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) 2002-2015, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* http://www.opensource.org/licenses/bsd-license.php
*/
package jline.internal;
import java.util.ArrayList;
import java.util.List;
import static jline.internal.Preconditions.checkNotNull;
/**
* Manages the JLine shutdown-hook thread and tasks to execute on shutdown.
*
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
* @since 2.7
*/
public class ShutdownHooks
{
public static final String JLINE_SHUTDOWNHOOK = "jline.shutdownhook";
private static final boolean enabled = Configuration.getBoolean(JLINE_SHUTDOWNHOOK, true);
private static final List<Task> tasks = new ArrayList<Task>();
private static Thread hook;
public static synchronized <T extends Task> T add(final T task) {
checkNotNull(task);
// If not enabled ignore
if (!enabled) {
Log.debug("Shutdown-hook is disabled; not installing: ", task);
return task;
}
// Install the hook thread if needed
if (hook == null) {
hook = addHook(new Thread("JLine Shutdown Hook")
{
@Override
public void run() {
runTasks();
}
});
}
// Track the task
Log.debug("Adding shutdown-hook task: ", task);
tasks.add(task);
return task;
}
private static synchronized void runTasks() {
Log.debug("Running all shutdown-hook tasks");
// Iterate through copy of tasks list
for (Task task : tasks.toArray(new Task[tasks.size()])) {
Log.debug("Running task: ", task);
try {
task.run();
}
catch (Throwable e) {
Log.warn("Task failed", e);
}
}
tasks.clear();
}
private static Thread addHook(final Thread thread) {
Log.debug("Registering shutdown-hook: ", thread);
try {
Runtime.getRuntime().addShutdownHook(thread);
}
catch (AbstractMethodError e) {
// JDK 1.3+ only method. Bummer.
Log.debug("Failed to register shutdown-hook", e);
}
return thread;
}
public static synchronized void remove(final Task task) {
checkNotNull(task);
// ignore if not enabled or hook never installed
if (!enabled || hook == null) {
return;
}
// Drop the task
tasks.remove(task);
// If there are no more tasks, then remove the hook thread
if (tasks.isEmpty()) {
removeHook(hook);
hook = null;
}
}
private static void removeHook(final Thread thread) {
Log.debug("Removing shutdown-hook: ", thread);
try {
Runtime.getRuntime().removeShutdownHook(thread);
}
catch (AbstractMethodError e) {
// JDK 1.3+ only method. Bummer.
Log.debug("Failed to remove shutdown-hook", e);
}
catch (IllegalStateException e) {
// The VM is shutting down, not a big deal; ignore
}
}
/**
* Essentially a {@link Runnable} which allows running to throw an exception.
*/
public static interface Task
{
void run() throws Exception;
}
} | kaulkie/jline2 | src/main/java/jline/internal/ShutdownHooks.java | Java | bsd-3-clause | 3,503 |
// t0288.cc
// "ambiguous function template instantiation"
// 2005-08-03: This appears to be fixed by the switch to
// the new mtype module.
namespace std
{
template < class _CharT > struct char_traits;
}
typedef int ptrdiff_t;
extern "C"
{
typedef struct __locale_struct
{
}
*__locale_t;
};
typedef struct __pthread_attr_s
{
}
pthread_barrierattr_t;
namespace std
{
typedef ptrdiff_t streamsize;
template < typename _CharT, typename _Traits =
char_traits < _CharT > >class basic_ios;
template < typename _CharT, typename _Traits =
char_traits < _CharT > >class basic_streambuf;
}
extern "C++"
{
namespace std
{
class exception
{
};
}
}
namespace std
{
template < typename _CharT, typename _Traits > class basic_streambuf
{
public:typedef _CharT char_type;
typedef _Traits traits_type;
typedef basic_streambuf < char_type, traits_type > __streambuf_type;
friend streamsize __copy_streambufs <> (basic_ios < char_type,
traits_type > &__ios,
__streambuf_type * __sbin,
__streambuf_type * __sbout);
};
template < typename _CharT,
typename _Traits > streamsize __copy_streambufs (basic_ios < _CharT,
_Traits > &__ios,
basic_streambuf < _CharT,
_Traits > *__sbin,
basic_streambuf < _CharT,
_Traits > *__sbout)
{
try
{
}
catch (exception & __fail)
{
}
}
extern template streamsize __copy_streambufs (basic_ios < wchar_t > &,
basic_streambuf < wchar_t > *,
basic_streambuf < wchar_t >
*);
}
| BackupTheBerlios/codemorpher-svn | trunk/elsa/elsa/in/t0288.cc | C++ | bsd-3-clause | 1,589 |
/*
Copyright (c) 2014, Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "device/common/nn_workload_data.h"
#include "device/cpu/api_internal/nn_device_interface_0_internal.h"
#include "layer_normalization_avx2.h"
#include <immintrin.h>
#include <string.h>
#include <thread>
#include <vector>
#include "device/cpu/api_internal/data_helper.h"
// NN_CODE_UNREACHABLE signal to supporting compiler that specific location in code cannot be reached
#if defined _MSC_VER
# define NN_UNREACHABLE_CODE __assume(0)
#endif
#if defined __GNUC__
# if (__GNUC__ * 100 + __GNUC_MINOR__) >= 405
# define NN_UNREACHABLE_CODE __builtin_unreachable()
# else
# define NN_UNREACHABLE_CODE
# endif
#endif
#if defined __clang__
# if __has_builtin(__builtin_unreachable)
# define NN_UNREACHABLE_CODE __builtin_unreachable()
# else
# define NN_UNREACHABLE_CODE
# endif
#endif
// SIMD width for this implementation
const auto C_simd_width = sizeof(__m256) / sizeof(float);
static const auto C_max_acc = 12u;
static const auto C_batch_size = C_simd_width;
static const auto C_data_stride = C_batch_size * C_max_acc;
namespace layer {
///////////////////////////////////////////////////////////////////////////////////////////////////
// forward implementation
template<uint32_t T_SIZE>
void normalization_compute_block_linear_single(
float* &input_ptr,
float* &output_ptr,
const __m256 coeff_a,
const __m256 coeff_b)
{
// We are not using table of registers and unroll pragmas
// due to compiler which have issues with register allocation
// and needs special, obvious treatment. Template immediate
// arguments matching will remove all conditions in this code.
__m256 acc0, acc1, acc2, acc3, acc4,
acc5, acc6, acc7, acc8, acc9,
acc10, acc11, acc12, acc13, acc14, acc15;
// Load inputs.
if (T_SIZE >= 1) acc0 = _mm256_loadu_ps(input_ptr + 0 * C_batch_size);
if (T_SIZE >= 2) acc1 = _mm256_loadu_ps(input_ptr + 1 * C_batch_size);
if (T_SIZE >= 3) acc2 = _mm256_loadu_ps(input_ptr + 2 * C_batch_size);
if (T_SIZE >= 4) acc3 = _mm256_loadu_ps(input_ptr + 3 * C_batch_size);
if (T_SIZE >= 5) acc4 = _mm256_loadu_ps(input_ptr + 4 * C_batch_size);
if (T_SIZE >= 6) acc5 = _mm256_loadu_ps(input_ptr + 5 * C_batch_size);
if (T_SIZE >= 7) acc6 = _mm256_loadu_ps(input_ptr + 6 * C_batch_size);
if (T_SIZE >= 8) acc7 = _mm256_loadu_ps(input_ptr + 7 * C_batch_size);
if (T_SIZE >= 9) acc8 = _mm256_loadu_ps(input_ptr + 8 * C_batch_size);
if (T_SIZE >= 10) acc9 = _mm256_loadu_ps(input_ptr + 9 * C_batch_size);
if (T_SIZE >= 11) acc10 = _mm256_loadu_ps(input_ptr + 10 * C_batch_size);
if (T_SIZE >= 12) acc11 = _mm256_loadu_ps(input_ptr + 11 * C_batch_size);
if (T_SIZE >= 13) acc12 = _mm256_loadu_ps(input_ptr + 12 * C_batch_size);
if (T_SIZE >= 14) acc13 = _mm256_loadu_ps(input_ptr + 13 * C_batch_size);
if (T_SIZE >= 15) acc14 = _mm256_loadu_ps(input_ptr + 14 * C_batch_size);
// Perform a*x + b
if (T_SIZE >= 1) acc0 = _mm256_fmadd_ps(coeff_a, acc0, coeff_b);
if (T_SIZE >= 2) acc1 = _mm256_fmadd_ps(coeff_a, acc1, coeff_b);
if (T_SIZE >= 3) acc2 = _mm256_fmadd_ps(coeff_a, acc2, coeff_b);
if (T_SIZE >= 4) acc3 = _mm256_fmadd_ps(coeff_a, acc3, coeff_b);
if (T_SIZE >= 5) acc4 = _mm256_fmadd_ps(coeff_a, acc4, coeff_b);
if (T_SIZE >= 6) acc5 = _mm256_fmadd_ps(coeff_a, acc5, coeff_b);
if (T_SIZE >= 7) acc6 = _mm256_fmadd_ps(coeff_a, acc6, coeff_b);
if (T_SIZE >= 8) acc7 = _mm256_fmadd_ps(coeff_a, acc7, coeff_b);
if (T_SIZE >= 9) acc8 = _mm256_fmadd_ps(coeff_a, acc8, coeff_b);
if (T_SIZE >= 10) acc9 = _mm256_fmadd_ps(coeff_a, acc9, coeff_b);
if (T_SIZE >= 11) acc10 = _mm256_fmadd_ps(coeff_a, acc10, coeff_b);
if (T_SIZE >= 12) acc11 = _mm256_fmadd_ps(coeff_a, acc11, coeff_b);
if (T_SIZE >= 13) acc12 = _mm256_fmadd_ps(coeff_a, acc12, coeff_b);
if (T_SIZE >= 14) acc13 = _mm256_fmadd_ps(coeff_a, acc13, coeff_b);
if (T_SIZE >= 15) acc14 = _mm256_fmadd_ps(coeff_a, acc14, coeff_b);
// Store results.
if (T_SIZE >= 1) _mm256_storeu_ps(output_ptr + 0 * C_batch_size, acc0);
if (T_SIZE >= 2) _mm256_storeu_ps(output_ptr + 1 * C_batch_size, acc1);
if (T_SIZE >= 3) _mm256_storeu_ps(output_ptr + 2 * C_batch_size, acc2);
if (T_SIZE >= 4) _mm256_storeu_ps(output_ptr + 3 * C_batch_size, acc3);
if (T_SIZE >= 5) _mm256_storeu_ps(output_ptr + 4 * C_batch_size, acc4);
if (T_SIZE >= 6) _mm256_storeu_ps(output_ptr + 5 * C_batch_size, acc5);
if (T_SIZE >= 7) _mm256_storeu_ps(output_ptr + 6 * C_batch_size, acc6);
if (T_SIZE >= 8) _mm256_storeu_ps(output_ptr + 7 * C_batch_size, acc7);
if (T_SIZE >= 9) _mm256_storeu_ps(output_ptr + 8 * C_batch_size, acc8);
if (T_SIZE >= 10) _mm256_storeu_ps(output_ptr + 9 * C_batch_size, acc9);
if (T_SIZE >= 11) _mm256_storeu_ps(output_ptr + 10 * C_batch_size, acc10);
if (T_SIZE >= 12) _mm256_storeu_ps(output_ptr + 11 * C_batch_size, acc11);
if (T_SIZE >= 13) _mm256_storeu_ps(output_ptr + 12 * C_batch_size, acc12);
if (T_SIZE >= 14) _mm256_storeu_ps(output_ptr + 13 * C_batch_size, acc13);
if (T_SIZE >= 15) _mm256_storeu_ps(output_ptr + 14 * C_batch_size, acc14);
input_ptr += T_SIZE*C_batch_size;
output_ptr += T_SIZE*C_batch_size;
}
void normalization_elementwise_linear_f32::run_normalization_work_item_linear_single_batch8(
const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) {
const auto input_width = input_view->parent->lengths.t[NN_DATA_COORD_x];
const auto output_width = output_view->view_end.t[NN_DATA_COORD_x] - output_view->view_begin.t[NN_DATA_COORD_x] + 1;
const auto num_full_blocks = output_width / C_max_acc;
const auto partial_block_size = output_width % C_max_acc;
const auto output_view_offset = output_view->view_begin.t[NN_DATA_COORD_x] * C_batch_size;
const auto input_view_offset = input_view->view_begin.t[NN_DATA_COORD_x] * C_batch_size;
auto input_buffer = &static_cast<float*>(input_view->parent->data_buffer)[input_view_offset];
auto output_buffer = &static_cast<float*>(output_view->parent->data_buffer)[output_view_offset];
const __m256 coeff_a = _mm256_set1_ps(alpha);
const __m256 coeff_b = _mm256_set1_ps(beta);
{
for (auto block = 0u; block < num_full_blocks; ++block)
{
// Run computation.
normalization_compute_block_linear_single<C_max_acc>(input_buffer, output_buffer, coeff_a, coeff_b);
}
switch (partial_block_size)
{
case 0: break;
case 1: normalization_compute_block_linear_single< 1>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 2: normalization_compute_block_linear_single< 2>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 3: normalization_compute_block_linear_single< 3>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 4: normalization_compute_block_linear_single< 4>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 5: normalization_compute_block_linear_single< 5>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 6: normalization_compute_block_linear_single< 6>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 7: normalization_compute_block_linear_single< 7>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 8: normalization_compute_block_linear_single< 8>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 9: normalization_compute_block_linear_single< 9>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 10: normalization_compute_block_linear_single<10>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 11: normalization_compute_block_linear_single<11>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 12: normalization_compute_block_linear_single<12>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 13: normalization_compute_block_linear_single<13>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 14: normalization_compute_block_linear_single<14>(input_buffer, output_buffer, coeff_a, coeff_b); break;
default: NN_UNREACHABLE_CODE;
}
}
}
void normalization_elementwise_linear_f32::run_normalization_work_item_linear_single_batch8X(
const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) {
const auto BatchSize = output_view->parent->lengths.t[NN_DATA_COORD_n];
const auto NoBatches = BatchSize / C_batch_size;
const auto input_width = input_view->parent->lengths.t[NN_DATA_COORD_x] * BatchSize;
const auto output_width = (output_view->view_end.t[NN_DATA_COORD_x] - output_view->view_begin.t[NN_DATA_COORD_x] + 1) * BatchSize;
const auto num_full_blocks = (output_width / C_simd_width) / C_max_acc;
const auto partial_block_size = (output_width / C_simd_width ) % C_max_acc;
const auto output_view_offset = output_view->view_begin.t[NN_DATA_COORD_x] * BatchSize;
const auto input_view_offset = input_view->view_begin.t[NN_DATA_COORD_x] * BatchSize;
//for (auto itrB = 0; itrB < BatchSize / C_batch_size; ++itrB)
{
auto input_buffer = &static_cast<float*>(input_view->parent->data_buffer)[input_view_offset];
auto output_buffer = &static_cast<float*>(output_view->parent->data_buffer)[output_view_offset];
const __m256 coeff_a = _mm256_set1_ps(alpha);
const __m256 coeff_b = _mm256_set1_ps(beta);
for (auto block = 0u; block < num_full_blocks; ++block)
{
// Run computation.
normalization_compute_block_linear_single<C_max_acc>(input_buffer, output_buffer, coeff_a, coeff_b);
}
switch (partial_block_size)
{
case 0: break;
case 1: normalization_compute_block_linear_single< 1>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 2: normalization_compute_block_linear_single< 2>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 3: normalization_compute_block_linear_single< 3>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 4: normalization_compute_block_linear_single< 4>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 5: normalization_compute_block_linear_single< 5>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 6: normalization_compute_block_linear_single< 6>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 7: normalization_compute_block_linear_single< 7>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 8: normalization_compute_block_linear_single< 8>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 9: normalization_compute_block_linear_single< 9>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 10: normalization_compute_block_linear_single<10>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 11: normalization_compute_block_linear_single<11>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 12: normalization_compute_block_linear_single<12>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 13: normalization_compute_block_linear_single<13>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 14: normalization_compute_block_linear_single<14>(input_buffer, output_buffer, coeff_a, coeff_b); break;
default: NN_UNREACHABLE_CODE;
}
}
}
template<uint32_t T_NUM_ITERATIONS>
void normalization_compute_subsimd_linear_single(
float* &input_ptr,
float* &output_ptr,
const float coeff_a,
const float coeff_b)
{
for (auto iteration = 0u; iteration < T_NUM_ITERATIONS; ++iteration)
{
*output_ptr = (*input_ptr) * coeff_a + coeff_b;
++input_ptr;
++output_ptr;
}
}
void normalization_elementwise_linear_f32::run_normalization_work_item_linear_single_latency(
const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) {
const auto input_width = input_view->parent->lengths.t[NN_DATA_COORD_x];
const auto output_width = output_view->view_end.t[NN_DATA_COORD_x] - output_view->view_begin.t[NN_DATA_COORD_x] + 1;
const auto num_full_blocks = output_width / C_data_stride;
const auto partial_block_size = (output_width / C_simd_width) % C_max_acc;
const auto subsimd_block_size = output_width % C_simd_width;
const auto output_view_offset = output_view->view_begin.t[NN_DATA_COORD_x];
const auto input_view_offset = input_view->view_begin.t[NN_DATA_COORD_x];
auto input_buffer = &static_cast<float*>(input_view->parent->data_buffer)[input_view_offset];
auto output_buffer = &static_cast<float*>(output_view->parent->data_buffer)[output_view_offset];
const __m256 coeff_a = _mm256_set1_ps(alpha);
const __m256 coeff_b = _mm256_set1_ps(beta);
for (auto block = 0u; block < num_full_blocks; ++block)
{
// Run computation.
normalization_compute_block_linear_single<C_max_acc>(input_buffer, output_buffer, coeff_a, coeff_b);
}
switch (partial_block_size)
{
case 0: break;
case 1: normalization_compute_block_linear_single< 1>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 2: normalization_compute_block_linear_single< 2>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 3: normalization_compute_block_linear_single< 3>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 4: normalization_compute_block_linear_single< 4>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 5: normalization_compute_block_linear_single< 5>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 6: normalization_compute_block_linear_single< 6>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 7: normalization_compute_block_linear_single< 7>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 8: normalization_compute_block_linear_single< 8>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 9: normalization_compute_block_linear_single< 9>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 10: normalization_compute_block_linear_single<10>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 11: normalization_compute_block_linear_single<11>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 12: normalization_compute_block_linear_single<12>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 13: normalization_compute_block_linear_single<13>(input_buffer, output_buffer, coeff_a, coeff_b); break;
case 14: normalization_compute_block_linear_single<14>(input_buffer, output_buffer, coeff_a, coeff_b); break;
default: NN_UNREACHABLE_CODE;
}
switch (subsimd_block_size)
{
case 0: break;
case 1: normalization_compute_subsimd_linear_single<1>(input_buffer, output_buffer, alpha, beta); break;
case 2: normalization_compute_subsimd_linear_single<2>(input_buffer, output_buffer, alpha, beta); break;
case 3: normalization_compute_subsimd_linear_single<3>(input_buffer, output_buffer, alpha, beta); break;
case 4: normalization_compute_subsimd_linear_single<4>(input_buffer, output_buffer, alpha, beta); break;
case 5: normalization_compute_subsimd_linear_single<5>(input_buffer, output_buffer, alpha, beta); break;
case 6: normalization_compute_subsimd_linear_single<6>(input_buffer, output_buffer, alpha, beta); break;
case 7: normalization_compute_subsimd_linear_single<7>(input_buffer, output_buffer, alpha, beta); break;
default: NN_UNREACHABLE_CODE;
}
}
void normalization_elementwise_linear_f32::choose_normalization_work_item_linear_single_batching_mode(
const nn::workload_data<float> *input_view, nn::workload_data<float> *output_view) {
auto batch_size = input_view->parent->lengths.t[NN_DATA_COORD_n];
switch (batch_size)
{
case 1:
run_normalization_work_item_linear_single_latency(input_view, output_view);
break;
case 8:
run_normalization_work_item_linear_single_batch8(input_view, output_view);
break;
case 16:
case 24:
case 32:
case 48:
run_normalization_work_item_linear_single_batch8X(input_view, output_view);
break;
default:
break;
}
}
struct normalization_elementwise_linear_f32_request_handle {
normalization_elementwise_linear_f32 *primitive;
const nn::workload_data<float> *input_view;
nn::workload_data<float> *output_view;
};
void unpack_1d_normalization_callback_handle(
void* void_handle)
{
auto handle = reinterpret_cast<normalization_elementwise_linear_f32_request_handle *>(void_handle);
handle->primitive->choose_normalization_work_item_linear_single_batching_mode(handle->input_view,
handle->output_view);
}
void normalization_elementwise_linear_f32::run_multithreaded_1d_normalization_work_item(
const nn::workload_data<float> *input, nn::workload_data<float> *output) {
auto num_hardware_threads = std::min(static_cast<decltype(device->thread_pool.get_num_threads())>(18), device->thread_pool.get_num_threads());
const auto item_view_length =
output->view_end.t[NN_DATA_COORD_x] - output->view_begin.t[NN_DATA_COORD_x] + 1;
const auto items_per_thread = item_view_length / num_hardware_threads;
const auto items_modulo = item_view_length % num_hardware_threads;
// Check if we have enough data to cover all threads.
if (items_per_thread == 0 && items_modulo < 2)
{
// Its tiny data - just do it single threaded way.
choose_normalization_work_item_linear_single_batching_mode(input, output);
}
else
{
// Not all threads will be used.
if (items_per_thread == 0)
num_hardware_threads = items_modulo;
// Full cores utilization version.
std::vector<normalization_elementwise_linear_f32_request_handle> request_handles(num_hardware_threads);
std::vector<const nn::workload_data<float> *> input_views(num_hardware_threads);
std::vector<nn::workload_data<float> *> output_views(num_hardware_threads);
uint32_t* thread_items_sums = static_cast<uint32_t*>(alloca(num_hardware_threads * sizeof(uint32_t)));
if (thread_items_sums == nullptr) throw std::bad_alloc();
// Distribute elements more evenly.
auto elements_left = items_modulo;
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
thread_items_sums[thread_id] = items_per_thread;
if (elements_left)
{
++thread_items_sums[thread_id];
--elements_left;
}
}
// Now create table of thread sums.
auto thread_sum = 0u;
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
thread_sum += thread_items_sums[thread_id];
thread_items_sums[thread_id] = thread_sum;
}
// Fill slave work items.
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
auto work_begin = 0u;
if (thread_id > 0u)
work_begin = thread_items_sums[thread_id - 1];
auto work_end = thread_items_sums[thread_id] - 1;
// Replace nn_workload_datas pointers with views.
nn_workload_data_coords_t nn_view_begin =
{
0,
work_begin,
0,
0,
0,
0
};
nn_workload_data_coords_t nn_view_end =
{
input->get_length(NN_DATA_COORD_n) - 1,
work_end,
input->get_length(NN_DATA_COORD_y) - 1,
input->get_length(NN_DATA_COORD_z) - 1,
input->get_length(NN_DATA_COORD_p) - 1,
input->get_length(NN_DATA_COORD_q) - 1
};
input_views[thread_id] = new nn::workload_data<float>(*input, nn_view_begin, nn_view_end);
output_views[thread_id] = new nn::workload_data<float>(*output, nn_view_begin, nn_view_end);
}
// Run threads.
std::vector<nn_multithreaded_request> job(num_hardware_threads);
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
request_handles[thread_id].primitive = this;
request_handles[thread_id].input_view = input_views[thread_id];
request_handles[thread_id].output_view = output_views[thread_id];
job[thread_id].callback = unpack_1d_normalization_callback_handle;
job[thread_id].request_handle = &request_handles[thread_id];
}
// Wait for all sub threads.
device->thread_pool.push_job(job);
// Cleanup dynamic memory.
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
delete input_views[thread_id];
delete output_views[thread_id];
}
}
}
void normalization_elementwise_linear_f32::forward(const nn::workload_data<float> *input,
nn::workload_data<float> *output) {
nn_workload_data_coords_t in_out_view_coords =
{
input->parent->lengths.t[NN_DATA_COORD_n],
input->parent->buffer_size / static_cast<uint32_t>(sizeof(float)) / input->parent->lengths.t[NN_DATA_COORD_n],
1,
1,
1,
1
};
nn_workload_data_layout_t in_out_view_layout = nn::workload_data<float>::layout.nxyzpq;
nn::workload_data<float>* input_view = new nn::workload_data<float>(NN_WORKLOAD_DATA_TAG_UNKNOWN, input->parent->data_buffer, in_out_view_coords, in_out_view_layout);
nn::workload_data<float>* output_view = new nn::workload_data<float>(NN_WORKLOAD_DATA_TAG_UNKNOWN, output->parent->data_buffer, in_out_view_coords, in_out_view_layout);
if (device->thread_pool.get_num_threads() > 1)
{
run_multithreaded_1d_normalization_work_item(input_view, output_view);
}
else
{
choose_normalization_work_item_linear_single_batching_mode(input_view, output_view);
}
delete output_view;
delete input_view;
}
void normalization_elementwise_linear_f32::forward(const std::vector<const nn_workload_data_t *> &inputs, const std::vector<const nn_workload_data_t *> ¶meters, const std::vector<nn_workload_data_t *> &outputs)
{
assert(inputs.size() == 1);
assert(parameters.size() == 0);
assert(outputs.size() == 1);
forward(reinterpret_cast<const nn::workload_data<float> *>(inputs[0]),
reinterpret_cast<nn::workload_data<float> *>(outputs[0]));
}
__m256 _inner_mm256_invpow075_ps(__m256 arg)
{
__m256i e = _mm256_slli_epi32(
_mm256_sub_epi32(
_mm256_and_si256(
_mm256_castps_si256(arg),
_mm256_set1_epi32(0x7f800000)),
_mm256_set1_epi32(0x3f800000)),
1);
__m256 p0 = _mm256_castsi256_ps(
_mm256_srli_epi32(
_mm256_add_epi32(
_mm256_mullo_epi32(
_mm256_srai_epi32(
_mm256_and_si256(
e,
_mm256_set1_epi32(0xfc000000)),
2),
_mm256_set1_epi32(-3)),
_mm256_set1_epi32(0x7f000000)),
1));
__m256 p1 = _mm256_blendv_ps(
_mm256_set1_ps(0.59460355750136053335874998528f),
_mm256_set1_ps(1.0f),
_mm256_castsi256_ps(
_mm256_cmpeq_epi32(
_mm256_and_si256(
e,
_mm256_set1_epi32(1<<24)),
_mm256_set1_epi32(0))));
__m256 p2 = _mm256_blendv_ps(
_mm256_set1_ps(0.35355339059327376220042218105f),
_mm256_set1_ps(1.0f),
_mm256_castsi256_ps(
_mm256_cmpeq_epi32(
_mm256_and_si256(
e,
_mm256_set1_epi32(2<<24)),
_mm256_set1_epi32(0))));
arg = _mm256_castsi256_ps(
_mm256_or_si256(
_mm256_and_si256(
_mm256_castps_si256(arg),
_mm256_set1_epi32(0x007fffff)),
_mm256_set1_epi32(0x3f800000)));
__m256 intermediate_result;
intermediate_result = _mm256_fmadd_ps(arg, _mm256_set1_ps(-0.06251362156237f), _mm256_set1_ps(0.56657226995864f));
intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(-2.12314847503624f));
intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(4.22879355263332f));
intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(-4.79039952143706f));
intermediate_result = _mm256_fmadd_ps(arg, intermediate_result, _mm256_set1_ps(3.18069569544757f));
intermediate_result =
_mm256_mul_ps(
_mm256_mul_ps(
p0,
p1),
_mm256_mul_ps(
p2,
intermediate_result));
return intermediate_result;
}
void normalization_response_across_maps_f32::run_3d_normalization_work_item(const nn::workload_data<float> *input_view,
nn::workload_data<float> *output_view) {
const auto input_column_size = input_view->parent->lengths.t[NN_DATA_COORD_z];
const auto input_row_size = input_view->parent->lengths.t[NN_DATA_COORD_x] * input_column_size;
const auto input_batch_size = input_view->parent->lengths.t[NN_DATA_COORD_y] * input_row_size;
const auto output_column_size = output_view->parent->lengths.t[NN_DATA_COORD_z];
const auto output_row_size = output_view->parent->lengths.t[NN_DATA_COORD_x] * output_column_size;
const auto output_batch_size = output_view->parent->lengths.t[NN_DATA_COORD_y] * output_row_size;
auto input_buffer = static_cast<float*>(input_view->parent->data_buffer);
auto output_buffer = static_cast<float*>(output_view->parent->data_buffer);
// Const data.
const uint32_t permutation_mask[8] = { 1, 2, 3, 4, 5, 6, 7, 0 };
uint32_t first_load_mask[8] = { 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000 };
uint32_t last_load_mask[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
const auto neighbourhood = n / 2;
for (uint32_t neighbour = 0; neighbour < neighbourhood; ++neighbour)
{
first_load_mask[neighbour] ^= 0x80000000;
last_load_mask[neighbour] ^= 0x80000000;
}
// Permuters and masks.
const __m256i forward_permuter = _mm256_loadu_si256((__m256i*)permutation_mask);
const __m256i first_masker = _mm256_loadu_si256((__m256i*)first_load_mask);
const __m256i last_masker = _mm256_loadu_si256((__m256i*)last_load_mask);
for (uint32_t batch = input_view->view_begin.t[NN_DATA_COORD_n]; batch <= input_view->view_end.t[NN_DATA_COORD_n]; ++batch)
{
for (uint32_t row = input_view->view_begin.t[NN_DATA_COORD_y], out_row = output_view->view_begin.t[NN_DATA_COORD_y];
row <= input_view->view_end.t[NN_DATA_COORD_y];
++row, ++out_row)
{
for (uint32_t column = input_view->view_begin.t[NN_DATA_COORD_x], out_column = output_view->view_begin.t[NN_DATA_COORD_x];
column <= input_view->view_end.t[NN_DATA_COORD_x];
++column, ++out_column)
{
const auto input_address = &input_buffer[batch*input_batch_size + row*input_row_size + column*input_column_size];
const auto output_address = &output_buffer[batch*output_batch_size + out_row*output_row_size + out_column*output_column_size];
// Prepare first data chunk.
__m256 source_tmp = _mm256_maskload_ps(input_address - neighbourhood, first_masker);
source_tmp = _mm256_mul_ps(source_tmp, source_tmp);
for (uint32_t feature_map = input_view->view_begin.t[NN_DATA_COORD_z], out_feature_map = output_view->view_begin.t[NN_DATA_COORD_z];
feature_map <= input_view->view_end.t[NN_DATA_COORD_z];
feature_map += C_simd_width, out_feature_map += C_simd_width)
{
// Initialize accumulator.
__m256 acc = _mm256_setzero_ps();
// Move previous saved chunk to first and load new one as a next.
__m256 source_first = source_tmp;
__m256 source_second =
(feature_map + C_simd_width <= input_view->view_end.t[NN_DATA_COORD_z])
? _mm256_loadu_ps(input_address + feature_map - neighbourhood + C_simd_width)
: _mm256_maskload_ps(input_address + feature_map - neighbourhood + C_simd_width, last_masker);
// Square of new chunk and save for next iteration.
source_tmp = source_second = _mm256_mul_ps(source_second, source_second);
// Required for final computation.
__m256 source_raw = _mm256_loadu_ps(input_address + feature_map);
// Forward permute - five times.
for (int i = 0; i < n; ++i)
{
acc = _mm256_add_ps(source_first, acc);
source_first = _mm256_permutevar8x32_ps(source_first, forward_permuter);
source_second = _mm256_permutevar8x32_ps(source_second, forward_permuter);
source_first = _mm256_blend_ps(source_first, source_second, 0x80);
}
// Do k + alpha * acc.
acc = _mm256_fmadd_ps(acc, _mm256_set1_ps(alpha), _mm256_set1_ps(k));
// Magic happens here. (acc^-0.75)
acc = _inner_mm256_invpow075_ps(acc);
// Multiply with input data.
acc = _mm256_mul_ps(acc, source_raw);
// Save data.
_mm256_storeu_ps(output_address + out_feature_map, acc);
}
}
}
}
}
struct normalization_response_across_maps_f32_request_handle {
normalization_response_across_maps_f32 *primitive;
const nn::workload_data<float> *input_view;
nn::workload_data<float> *output_view;
};
struct normalization_response_across_maps_f32_backward_request_handle {
normalization_response_across_maps_f32 *primitive;
const nn::workload_data<float> *forward_input;
const nn::workload_data<float> *forward_output;
const nn::workload_data<float> *backward_input;
nn::workload_data<float> *backward_output;
};
void unpack_3d_normalization_callback_handle(
void* void_handle)
{
auto handle = reinterpret_cast<normalization_response_across_maps_f32_request_handle *>(void_handle);
handle->primitive->run_3d_normalization_work_item(handle->input_view, handle->output_view);
}
void unpack_3d_normalization_callback_handle_backward(
void* void_handle)
{
auto handle = reinterpret_cast<normalization_response_across_maps_f32_backward_request_handle *>(void_handle);
handle->primitive->backward(handle->forward_input, handle->forward_output, handle->backward_input, handle->backward_output);
}
void normalization_response_across_maps_f32::dispatch_backward(
const nn::workload_data<float> *forward_input,
const nn::workload_data<float> *forward_output,
const nn::workload_data<float> *backward_input,
nn::workload_data<float> *backward_output)
{
const auto num_batch_items =
(backward_output->view_end.t[NN_DATA_COORD_n] - backward_output->view_begin.t[NN_DATA_COORD_n] + 1);
const auto total_workers = num_batch_items;
if (device->thread_pool.get_num_threads() < 2 || total_workers < 2)
{
// Its tiny data or there is only one thread available - just do it singlethreaded way.
backward(forward_input, forward_output, backward_input, backward_output);
}
else
{
// Full cores utilization version.
std::vector<nn::workload_data<float> *> backprop_output_delta_views(total_workers);
// Fill slave work items.
for (auto batch_item = 0u; batch_item < num_batch_items; ++batch_item)
{
auto item_in_pool = batch_item;
// Replace nn_workload_datas pointers with views.
nn_workload_data_coords_t output_view_begin =
{
batch_item,
0,
0,
0,
0,
0
};
nn_workload_data_coords_t output_view_end =
{
batch_item,
backward_output->get_length(NN_DATA_COORD_x) - 1,
backward_output->get_length(NN_DATA_COORD_y) - 1,
backward_output->get_length(NN_DATA_COORD_z) - 1,
backward_output->get_length(NN_DATA_COORD_p) - 1,
backward_output->get_length(NN_DATA_COORD_q) - 1
};
backprop_output_delta_views[item_in_pool] =
new nn::workload_data<float>(*backward_output, output_view_begin, output_view_end);
}
// Run threads.
std::vector<nn_multithreaded_request> job(total_workers);
std::vector<normalization_response_across_maps_f32_backward_request_handle> request_handles(total_workers);
for (auto item_in_pool = 0u; item_in_pool < total_workers; ++item_in_pool)
{
request_handles[item_in_pool].primitive = this;
request_handles[item_in_pool].forward_input = forward_input;
request_handles[item_in_pool].forward_output = forward_output;
request_handles[item_in_pool].backward_input = backward_input;
request_handles[item_in_pool].backward_output = backprop_output_delta_views[item_in_pool];
job[item_in_pool].callback = unpack_3d_normalization_callback_handle_backward;
job[item_in_pool].request_handle = &request_handles[item_in_pool];
}
// Wait for all sub threads.
device->thread_pool.push_job(job);
// Cleanup dynamic memory.
for (auto item_in_pool = 0u; item_in_pool < total_workers; ++item_in_pool)
{
delete backprop_output_delta_views[item_in_pool];
}
}
}
void normalization_response_across_maps_f32::run_multithreaded_3d_normalization_work_item(
const nn::workload_data<float> *input, nn::workload_data<float> *output) {
auto num_hardware_threads = std::min(device->thread_pool.get_num_threads(), max_threads);
const auto item_view_length =
output->view_end.t[NN_DATA_COORD_y] - output->view_begin.t[NN_DATA_COORD_y] + 1;
const auto items_per_thread = item_view_length / num_hardware_threads;
const auto items_modulo = item_view_length % num_hardware_threads;
// Check if we have enough data to cover all threads.
if (items_per_thread == 0 && items_modulo < 2)
{
// Its tiny data - just do it singlethreaded way.
run_3d_normalization_work_item(input, output);
}
else
{
// Full cores utilization version.
// Not all threads will be used.
if (items_per_thread == 0)
num_hardware_threads = items_modulo;
std::vector<normalization_response_across_maps_f32_request_handle> request_handles(num_hardware_threads);
std::vector<const nn::workload_data<float> *> input_views(num_hardware_threads);
std::vector<nn::workload_data<float> *> output_views(num_hardware_threads);
uint32_t* thread_items_sums = static_cast<uint32_t*>(alloca(num_hardware_threads * sizeof(uint32_t)));
if (thread_items_sums == nullptr) throw std::bad_alloc();
// Distribute elements more evenly.
auto elements_left = items_modulo;
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
thread_items_sums[thread_id] = items_per_thread;
if (elements_left)
{
++thread_items_sums[thread_id];
--elements_left;
}
}
// Now create table of thread sums.
auto thread_sum = 0u;
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
thread_sum += thread_items_sums[thread_id];
thread_items_sums[thread_id] = thread_sum;
}
// Fill slave work items.
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
auto work_begin = 0u;
if (thread_id > 0u)
work_begin = thread_items_sums[thread_id - 1];
auto work_end = thread_items_sums[thread_id] - 1;
// Replace nn_workload_datas pointers with views.
nn_workload_data_coords_t nn_view_begin =
{
0,
0,
work_begin,
0,
0,
0
};
nn_workload_data_coords_t nn_view_end =
{
input->get_length(NN_DATA_COORD_n) - 1,
input->get_length(NN_DATA_COORD_x) - 1,
work_end,
input->get_length(NN_DATA_COORD_z) - 1,
input->get_length(NN_DATA_COORD_p) - 1,
input->get_length(NN_DATA_COORD_q) - 1
};
input_views[thread_id] = new nn::workload_data<float>(*input, nn_view_begin, nn_view_end);
output_views[thread_id] = new nn::workload_data<float>(*output, nn_view_begin, nn_view_end);
}
// Run threads.
std::vector<nn_multithreaded_request> job(num_hardware_threads);
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
request_handles[thread_id].primitive = this;
request_handles[thread_id].input_view = input_views[thread_id];
request_handles[thread_id].output_view = output_views[thread_id];
job[thread_id].callback = unpack_3d_normalization_callback_handle;
job[thread_id].request_handle = &request_handles[thread_id];
}
// Wait for all sub threads.
device->thread_pool.push_job(job);
// Cleanup dynamic memory.
for (auto thread_id = 0u; thread_id < num_hardware_threads; ++thread_id)
{
delete input_views[thread_id];
delete output_views[thread_id];
}
}
}
void normalization_response_across_maps_f32::forward(const nn::workload_data<float> *input,
nn::workload_data<float> *output) {
if (device->thread_pool.get_num_threads() > 1) {
run_multithreaded_3d_normalization_work_item(input, output);
}
else {
run_3d_normalization_work_item(input, output);
}
}
void normalization_response_across_maps_f32::forward(const std::vector<const nn_workload_data_t *> &inputs, const std::vector<const nn_workload_data_t *> ¶meters, const std::vector<nn_workload_data_t *> &outputs)
{
assert(inputs.size() == 1);
assert(parameters.size() == 0);
assert(outputs.size() == 1);
forward(reinterpret_cast<const nn::workload_data<float> *>(inputs[0]),
reinterpret_cast<nn::workload_data<float> *>(outputs[0]));
}
__m256 _internal_mm256_pow2_ps(__m256 arg)
{
__m256i e = _mm256_sub_epi32(_mm256_cvttps_epi32(arg), _mm256_and_si256(_mm256_castps_si256(_mm256_cmp_ps(arg, _mm256_setzero_ps(), _CMP_LT_OQ)), _mm256_set1_epi32(1)));
arg = _mm256_sub_ps(arg, _mm256_cvtepi32_ps(e));
arg =
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
arg
, _mm256_set1_ps(0.00021871895714413f)
, _mm256_set1_ps(0.00123905464987147f))
, arg
, _mm256_set1_ps(0.00968412797528994f))
, arg
, _mm256_set1_ps(0.0554807914042966f))
, arg
, _mm256_set1_ps(0.240230343637606f))
, arg
, _mm256_set1_ps(0.693146963375785f))
, arg
, _mm256_set1_ps(0.999999999869321f));
__m256 res = _mm256_castsi256_ps(_mm256_slli_epi32(_mm256_add_epi32(e, _mm256_set1_epi32(127)), 23));
res = _mm256_mul_ps(res, arg);
return res;
}
__m256 _internal_mm256_log2_ps(__m256 input)
{
__m256i tmp = _mm256_castps_si256(input);
__m256i e = _mm256_and_si256(tmp, _mm256_set1_epi32(0xff800000));
input = _mm256_castsi256_ps(_mm256_or_si256(_mm256_xor_si256(tmp, e), _mm256_set1_epi32(0x40000000)));
e = _mm256_srai_epi32(_mm256_sub_epi32(e, _mm256_set1_epi32(0x3f900000)), 23);
input =
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
input
, _mm256_set1_ps(-3.92272173215165e-4f)
, _mm256_set1_ps(8.44188448699613e-3f))
, input
, _mm256_set1_ps(-7.80873452751869e-2f))
, input
, _mm256_set1_ps(4.06812574432218e-1f))
, input
, _mm256_set1_ps(-1.32744857721956f))
, input
, _mm256_set1_ps(3.04806680788937f))
, input
, _mm256_set1_ps(-2.03647726245336f));
return _mm256_add_ps(input, _mm256_cvtepi32_ps(e));
}
__m256 _internal_generic_mm256_pow_ps(__m256 base, __m256 exponent)
{
return _internal_mm256_pow2_ps(_mm256_mul_ps(_internal_mm256_log2_ps(base), exponent));
}
__m256 _internal_2_33_mm256_pow_ps(__m256 base)
{
auto x = _mm256_castsi256_ps(_mm256_or_si256(_mm256_and_si256(_mm256_castps_si256(base), _mm256_set1_epi32(0x007fffff)), _mm256_set1_epi32(0x3f800000)));
auto e4 = _mm256_sub_epi32(_mm256_srai_epi32(_mm256_and_si256(_mm256_castps_si256(base), _mm256_set1_epi32(0x7f800000)), 21), _mm256_set1_epi32(508));
auto e4_3i = _mm256_srai_epi32(_mm256_add_epi32(_mm256_mullo_epi32(e4, _mm256_set1_epi32(0x5555)), _mm256_set1_epi32(0x1000)), 16);
auto e4_3f = _mm256_sub_epi32(e4, _mm256_mullo_epi32(e4_3i, _mm256_set1_epi32(3)));
auto e0 = _mm256_add_ps(_mm256_set1_ps(1.0f), _mm256_castsi256_ps(_mm256_and_si256(_mm256_cmpgt_epi32(e4_3f, _mm256_set1_epi32(0)), _mm256_castps_si256(_mm256_set1_ps(0.2599210498948731647672106072782f)))));
auto e1 = _mm256_add_ps(_mm256_set1_ps(1.0f), _mm256_castsi256_ps(_mm256_and_si256(_mm256_cmpgt_epi32(e4_3f, _mm256_set1_epi32(1)), _mm256_castps_si256(_mm256_set1_ps(0.2599210498948731647672106072782f)))));
auto e = _mm256_mul_ps(_mm256_mul_ps(_mm256_castsi256_ps(_mm256_slli_epi32(_mm256_add_epi32(e4_3i, _mm256_set1_epi32(127)), 23)), e0), e1);
x =
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
_mm256_fmadd_ps(
x
, _mm256_set1_ps(-6.13621063256050e-4f)
, _mm256_set1_ps(2.81846524230542e-3f))
, x
, _mm256_set1_ps(7.23755774062622e-3f))
, x
, _mm256_set1_ps(-9.05150071637931e-2f))
, x
, _mm256_set1_ps(4.30600295045482e-1f))
, x
, _mm256_set1_ps(7.04368603164122e-1f))
, x
, _mm256_set1_ps(-5.38962929654863e-2f));
return _mm256_mul_ps(_mm256_mul_ps(x, e), base);
}
enum EXP_APPROX
{
APPROX_GENERIC,
APPROX_2_33
};
template<EXP_APPROX T_approx> __m256 _internal_mm256_pow_ps (__m256 base, __m256 exponent);
template<> __m256 _internal_mm256_pow_ps<APPROX_GENERIC>(__m256 base, __m256 exponent) {return _internal_generic_mm256_pow_ps(base, exponent);}
template<> __m256 _internal_mm256_pow_ps<APPROX_2_33> (__m256 base, __m256 exponent) {return _internal_2_33_mm256_pow_ps(base);}
template<EXP_APPROX T_approx>
void backward_inner_template(
const nn::workload_data<float> *forward_input,
const nn::workload_data<float> *forward_output,
const nn::workload_data<float> *backward_input,
nn::workload_data<float> *backward_output,
const uint32_t n,
const float alpha,
const float beta)
{
const uint32_t range = (n - 1) / 2;
const auto forward_input_buffer = reinterpret_cast<float*>(forward_input->parent->data_buffer);
const auto forward_output_buffer = reinterpret_cast<float*>(forward_output->parent->data_buffer);
const auto backward_input_buffer = reinterpret_cast<float*>(backward_input->parent->data_buffer);
const auto backward_output_buffer = reinterpret_cast<float*>(backward_output->parent->data_buffer);
const auto input_depth = forward_input->parent->lengths.t[NN_DATA_COORD_z];
const auto input_width = forward_input->parent->lengths.t[NN_DATA_COORD_x];
const auto input_height = forward_input->parent->lengths.t[NN_DATA_COORD_y];
const auto output_depth = forward_output->parent->lengths.t[NN_DATA_COORD_z];
const auto output_width = forward_output->parent->lengths.t[NN_DATA_COORD_x];
const auto output_height = forward_output->parent->lengths.t[NN_DATA_COORD_y];
assert(input_depth == output_depth);
__m256i mask;
const __m256 alpha_vec = _mm256_set1_ps(alpha);
const __m256 beta_vec = _mm256_set1_ps(beta);
const __m256 const_vec = _mm256_set1_ps(-2.0f);
const __m256 pow_vec = _mm256_set1_ps(1.0f + 1.0f / beta);
uint32_t* initial_load_mask = reinterpret_cast<uint32_t*>(alloca((output_depth + n - 1) * sizeof(float)));
uint32_t load_mask[C_simd_width];
uint32_t load_mask_id = 0;
for(uint32_t i = 0; i < range; ++i, ++load_mask_id)
initial_load_mask[load_mask_id] = 0;
for(uint32_t i = 0; i < input_depth; ++i, ++load_mask_id)
initial_load_mask[load_mask_id] = 0xFFFFFFFF;
for(uint32_t i = 0; i < range; ++i, ++load_mask_id)
initial_load_mask[load_mask_id] = 0;
for (uint32_t batch = backward_output->view_begin.t[NN_DATA_COORD_n]; batch <= backward_output->view_end.t[NN_DATA_COORD_n]; ++batch)
{
for (uint32_t row = backward_output->view_begin.t[NN_DATA_COORD_y];
row <= backward_output->view_end.t[NN_DATA_COORD_y];
++row)
{
for (uint32_t column = backward_output->view_begin.t[NN_DATA_COORD_x];
column <= backward_output->view_end.t[NN_DATA_COORD_x];
++column)
{
const auto forward_input_ptr = forward_input_buffer
+ column * input_depth
+ row * input_depth * input_width
+ batch * input_depth * input_width * input_height;
const auto forward_output_ptr = forward_output_buffer
+ column * output_depth
+ row * output_depth * output_width
+ batch * output_depth * output_width * output_height;
const auto backward_input_ptr = backward_input_buffer
+ column * output_depth
+ row * output_depth * output_width
+ batch * output_depth * output_width * output_height;
#pragma forceinline recursive
for (uint32_t in_feature_map = backward_output->view_begin.t[NN_DATA_COORD_z];
in_feature_map <= backward_output->view_end.t[NN_DATA_COORD_z];
in_feature_map += C_simd_width)
{
__m256 derivative_accumulator = _mm256_setzero_ps();
for (int32_t out_feature_map = (int32_t)in_feature_map - (int32_t)range;
out_feature_map <= (int32_t)in_feature_map + (int32_t)range;
++out_feature_map)
{
const __m256i mask = _mm256_loadu_si256((__m256i*)(initial_load_mask + out_feature_map + range));
const __m256 n_out = _mm256_maskload_ps(forward_input_ptr + out_feature_map, mask);
const __m256 a_out = _mm256_maskload_ps(forward_output_ptr + out_feature_map, mask);
const __m256 n_in = _mm256_load_ps(forward_input_ptr + in_feature_map);
const __m256 error_in = _mm256_maskload_ps(backward_input_ptr + out_feature_map, mask);
// This code corresponds to:
// acc = -2.0f * alpha * beta * n_out * n_in * std::pow(a_out / n_out, 1.0f + 1.0f / beta);
__m256 acc = _mm256_mul_ps(
_mm256_mul_ps(
_internal_mm256_pow_ps<T_approx>(
_mm256_div_ps(a_out, n_out),
pow_vec),
n_in),
_mm256_mul_ps(
_mm256_mul_ps(const_vec, alpha_vec),
_mm256_mul_ps(beta_vec, n_out)));
acc = _mm256_and_ps(acc, _mm256_castsi256_ps(mask));
derivative_accumulator = _mm256_fmadd_ps(acc, error_in, derivative_accumulator);
}
{
const __m256i mask = _mm256_loadu_si256((__m256i*)(initial_load_mask + in_feature_map + range));
const __m256 n_out = _mm256_maskload_ps(forward_input_ptr + in_feature_map, mask);
const __m256 a_out = _mm256_maskload_ps(forward_output_ptr + in_feature_map, mask);
const __m256 error_in = _mm256_maskload_ps(backward_input_ptr + in_feature_map, mask);
__m256 acc = _mm256_and_ps(_mm256_div_ps(a_out, n_out), _mm256_castsi256_ps(mask));
derivative_accumulator = _mm256_fmadd_ps(acc, error_in, derivative_accumulator);
}
_mm256_store_ps( backward_output_buffer
+ in_feature_map
+ column * input_depth
+ row * input_depth * input_width
+ batch * input_depth * input_width * input_height
, derivative_accumulator);
}
}
}
}
}
void normalization_response_across_maps_f32::backward(
const nn::workload_data<float> *forward_input,
const nn::workload_data<float> *forward_output,
const nn::workload_data<float> *backward_input,
nn::workload_data<float> *backward_output)
{
if(beta == 0.75f)
{
// Fast approximated exponent = 2.333f.
backward_inner_template<APPROX_2_33>(
forward_input,
forward_output,
backward_input,
backward_output,
n,
alpha,
beta);
}
else
{
// Generic case.
backward_inner_template<APPROX_GENERIC>(
forward_input,
forward_output,
backward_input,
backward_output,
n,
alpha,
beta);
}
}
void normalization_response_across_maps_f32::backward(const std::vector<nn_workload_data_t *> &inputs,
const std::vector<const nn_workload_data_t *> ¶meters,
const std::vector<const nn_workload_data_t *> &outputs) {
assert(inputs.size() == 1);
assert(outputs.size() == 1);
const nn::workload_data<float> backward_input(outputs[0]->parent->delta_buffer, outputs[0]->parent->lengths, outputs[0]->parent->layout);
nn::workload_data<float> backward_output(inputs[0]->parent->delta_buffer, inputs[0]->parent->lengths, inputs[0]->parent->layout);
dispatch_backward(reinterpret_cast<const nn::workload_data<float> *>(inputs[0]),
reinterpret_cast<const nn::workload_data<float> *>(outputs[0]),
&backward_input,
&backward_output);
}
void wrapper_normalization_work_item_backward(nn_workload_item *const work_item) {
switch (work_item->forward_item->arguments.forward_normalization.normalization.mode) {
case NN_NORMALIZATION_MODE_LINEAR_SINGLE: {
assert(0); // Not yet implemented.
break;
}
case NN_NORMALIZATION_MODE_RESPONSE_ACROSS_MAPS: {
auto primitive = static_cast<normalization_response_across_maps_f32 *>(work_item->forward_item->primitive);
primitive->dispatch_backward(
reinterpret_cast<nn::workload_data<float> *>(work_item->forward_item->input[0].get_data_view()),
reinterpret_cast<nn::workload_data<float> *>(work_item->forward_item->output[0]),
reinterpret_cast<nn::workload_data<float> *>(work_item->input[0].get_data_view()),
reinterpret_cast<nn::workload_data<float> *>(work_item->output[0]));
break;
}
default: {
assert(0);
break;
}
}
}
normalization_elementwise_linear_f32::normalization_elementwise_linear_f32(float alpha,
float beta,
size_t image_size_x,
size_t image_size_y,
size_t image_size_z,
size_t batch_size,
nn_device_internal *device)
: primitive_zxyn_f32_base(batch_size, image_size_z, image_size_x, image_size_y, image_size_z, 0, 0, 0, 0, device),
normalization_mode(NN_NORMALIZATION_MODE_LINEAR_SINGLE),
alpha(alpha),
beta(beta) {}
size_t normalization_elementwise_linear_f32::get_required_input_w() { return output_size_x; }
size_t normalization_elementwise_linear_f32::get_required_input_h() { return output_size_y; }
bool normalization_elementwise_linear_f32::validate_input(size_t index, nn_workload_data_t *data)
{
switch (index) {
case 0:
return nn::data_helper<NN_WORKLOAD_DATA_TAG_ZXYN, float>::validate<false>(
data, get_required_input_w(), get_required_input_h(), input_size_z, batch_size, 0, 0, 0, 0);
}
throw std::invalid_argument("index out of range");
}
normalization_response_across_maps_f32::normalization_response_across_maps_f32(float alpha,
float beta,
uint32_t k,
uint32_t n,
size_t image_size_x,
size_t image_size_y,
size_t image_size_z,
size_t batch_size,
size_t output_padding_left,
size_t output_padding_right,
size_t output_padding_top,
size_t output_padding_bottom,
nn_device_internal *device)
: primitive_zxyn_f32_base(batch_size,
image_size_z,
image_size_x,
image_size_y,
image_size_z,
output_padding_left,
output_padding_right,
output_padding_top,
output_padding_bottom,
device),
normalization_mode(NN_NORMALIZATION_MODE_LINEAR_SINGLE),
alpha(alpha),
beta(beta),
k(k),
n(n) {}
size_t normalization_response_across_maps_f32::get_required_input_w() { return output_size_x; }
size_t normalization_response_across_maps_f32::get_required_input_h() { return output_size_y; }
bool normalization_response_across_maps_f32::validate_input(size_t index, nn_workload_data_t *data)
{
switch (index) {
case 0:
return nn::data_helper<NN_WORKLOAD_DATA_TAG_ZXYN, float>::validate<true>(
data, get_required_input_w(), get_required_input_h(), input_size_z, batch_size, 0, 0, 0, 0);
}
throw std::invalid_argument("index out of range");
}
} // namespace layer
nn_primitive_handle_t NN_API_CALL_CONVENTION
nn_primitives_normalization_elementwise_linear_f32_create_0(nn_device_t *device, /* IDLF device handle */
float alpha, /* multiplier */
float beta, /* offset */
size_t image_size_x, /* image width */
size_t image_size_y, /* image height */
size_t image_size_z, /* number of feature maps */
size_t batch_size, /* size of input batch */
NN_API_STATUS *status /* NN_API_STATUS_OK on success */) {
SET_STATUS(NN_API_STATUS_OK);
return new layer::normalization_elementwise_linear_f32(alpha,
beta,
image_size_x,
image_size_y,
image_size_z,
batch_size,
reinterpret_cast<nn_device_internal *>(device));
}
nn_primitive_handle_t NN_API_CALL_CONVENTION nn_primitives_normalization_response_across_maps_f32_create_0(
nn_device_t *device, /* IDLF device handle */
float alpha, /* sum scale */
float beta, /* sum power */
uint32_t k, /* square sum weight */
uint32_t n, /* size of moving window on the feature maps */
size_t image_size_x, /* image width */
size_t image_size_y, /* image height */
size_t image_size_z, /* number of feature maps */
size_t batch_size, /* size of input batch */
const nn_primitives_normalization_response_across_maps_hints_t *hints,
NN_API_STATUS *status /* NN_API_STATUS_OK on success */) {
SET_STATUS(NN_API_STATUS_OK);
std::remove_const<std::remove_pointer<decltype(hints)>::type>::type hints_ = {};
if (hints != nullptr)
hints_ = *hints;
return new layer::normalization_response_across_maps_f32(alpha,
beta,
k,
n,
image_size_x,
image_size_y,
image_size_z,
batch_size,
hints_.output_padding.left,
hints_.output_padding.right,
hints_.output_padding.top,
hints_.output_padding.bottom,
reinterpret_cast<nn_device_internal *>(device));
}
| MatrixPlayer/idlf | device/cpu/core/layer_normalization_avx2.cpp | C++ | bsd-3-clause | 63,958 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
__ace_shadowed__.define('ace/mode/ruby', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/ruby_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/folding/coffee'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var RubyHighlightRules = require("./ruby_highlight_rules").RubyHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var FoldMode = require("./folding/coffee").FoldMode;
var Mode = function() {
this.HighlightRules = RubyHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "#";
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[]\s*$/);
var startingClassOrMethod = line.match(/^\s*(class|def|module)\s.*$/);
var startingDoBlock = line.match(/.*do(\s*|\s+\|.*\|\s*)$/);
var startingConditional = line.match(/^\s*(if|else)\s*/)
if (match || startingClassOrMethod || startingDoBlock || startingConditional) {
indent += tab;
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return /^\s+end$/.test(line + input) || /^\s+}$/.test(line + input) || /^\s+else$/.test(line + input);
};
this.autoOutdent = function(state, doc, row) {
var indent = this.$getIndent(doc.getLine(row));
var tab = doc.getTabString();
if (indent.slice(-tab.length) == tab)
doc.remove(new Range(row, indent.length-tab.length, row, indent.length));
};
this.$id = "ace/mode/ruby";
}).call(Mode.prototype);
exports.Mode = Mode;
});
__ace_shadowed__.define('ace/mode/ruby_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var constantOtherSymbol = exports.constantOtherSymbol = {
token : "constant.other.symbol.ruby", // symbol
regex : "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?"
};
var qString = exports.qString = {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
};
var qqString = exports.qqString = {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
};
var tString = exports.tString = {
token : "string", // backtick string
regex : "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]"
};
var constantNumericHex = exports.constantNumericHex = {
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b"
};
var constantNumericFloat = exports.constantNumericFloat = {
token : "constant.numeric", // float
regex : "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b"
};
var RubyHighlightRules = function() {
var builtinFunctions = (
"abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" +
"assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" +
"assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" +
"assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" +
"assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|" +
"assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|" +
"attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" +
"caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" +
"exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" +
"gsub!|get_via_redirect|host!|https?|https!|include|Integer|lambda|link_to|" +
"link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" +
"p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" +
"raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|" +
"set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" +
"throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" +
"render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" +
"content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" +
"fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|" +
"time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" +
"select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" +
"file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" +
"protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|" +
"send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|" +
"validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|" +
"validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" +
"authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" +
"filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" +
"translate|localize|extract_locale_from_tld|caches_page|expire_page|caches_action|expire_action|" +
"cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" +
"has_many|has_one|belongs_to|has_and_belongs_to_many"
);
var keywords = (
"alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" +
"__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" +
"redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield"
);
var buildinConstants = (
"true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" +
"RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING"
);
var builtinVariables = (
"\$DEBUG|\$defout|\$FILENAME|\$LOAD_PATH|\$SAFE|\$stdin|\$stdout|\$stderr|\$VERBOSE|" +
"$!|root_url|flash|session|cookies|params|request|response|logger|self"
);
var keywordMapper = this.$keywords = this.createKeywordMapper({
"keyword": keywords,
"constant.language": buildinConstants,
"variable.language": builtinVariables,
"support.function": builtinFunctions,
"invalid.deprecated": "debugger" // TODO is this a remnant from js mode?
}, "identifier");
this.$rules = {
"start" : [
{
token : "comment",
regex : "#.*$"
}, {
token : "comment", // multi line comment
regex : "^=begin(?:$|\\s.*$)",
next : "comment"
}, {
token : "string.regexp",
regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
},
qString,
qqString,
tString,
{
token : "text", // namespaces aren't symbols
regex : "::"
}, {
token : "variable.instance", // instance variable
regex : "@{1,2}[a-zA-Z_\\d]+"
}, {
token : "support.class", // class name
regex : "[A-Z][a-zA-Z_\\d]+"
},
constantOtherSymbol,
constantNumericHex,
constantNumericFloat,
{
token : "constant.language.boolean",
regex : "(?:true|false)\\b"
}, {
token : keywordMapper,
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "punctuation.separator.key-value",
regex : "=>"
}, {
stateName: "heredoc",
onMatch : function(value, currentState, stack) {
var next = value[2] == '-' ? "indentedHeredoc" : "heredoc";
var tokens = value.split(this.splitRegex);
stack.push(next, tokens[3]);
return [
{type:"constant", value: tokens[1]},
{type:"string", value: tokens[2]},
{type:"support.class", value: tokens[3]},
{type:"string", value: tokens[4]}
];
},
regex : "(<<-?)(['\"`]?)([\\w]+)(['\"`]?)",
rules: {
heredoc: [{
onMatch: function(value, currentState, stack) {
if (value === stack[1]) {
stack.shift();
stack.shift();
this.next = stack[0] || "start";
return "support.class";
}
this.next = "";
return "string";
},
regex: ".*$",
next: "start"
}],
indentedHeredoc: [{
token: "string",
regex: "^ +"
}, {
onMatch: function(value, currentState, stack) {
if (value === stack[1]) {
stack.shift();
stack.shift();
this.next = stack[0] || "start";
return "support.class";
}
this.next = "";
return "string";
},
regex: ".*$",
next: "start"
}]
}
}, {
regex : "$",
token : "empty",
next : function(currentState, stack) {
if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc")
return stack[0];
return currentState;
}
}, {
token : "keyword.operator",
regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"
}, {
token : "paren.lparen",
regex : "[[({]"
}, {
token : "paren.rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : "^=end(?:$|\\s.*$)",
next : "start"
}, {
token : "comment", // comment spanning whole line
regex : ".+"
}
]
};
this.normalizeRules();
};
oop.inherits(RubyHighlightRules, TextHighlightRules);
exports.RubyHighlightRules = RubyHighlightRules;
});
__ace_shadowed__.define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
__ace_shadowed__.define('ace/mode/folding/coffee', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(require, exports, module) {
var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.getFoldWidgetRange = function(session, foldStyle, row) {
var range = this.indentationBlock(session, row);
if (range)
return range;
var re = /\S/;
var line = session.getLine(row);
var startLevel = line.search(re);
if (startLevel == -1 || line[startLevel] != "#")
return;
var startColumn = line.length;
var maxRow = session.getLength();
var startRow = row;
var endRow = row;
while (++row < maxRow) {
line = session.getLine(row);
var level = line.search(re);
if (level == -1)
continue;
if (line[level] != "#")
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
var indent = line.search(/\S/);
var next = session.getLine(row + 1);
var prev = session.getLine(row - 1);
var prevIndent = prev.search(/\S/);
var nextIndent = next.search(/\S/);
if (indent == -1) {
session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : "";
return "";
}
if (prevIndent == -1) {
if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") {
session.foldWidgets[row - 1] = "";
session.foldWidgets[row + 1] = "";
return "start";
}
} else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") {
if (session.getLine(row - 2).search(/\S/) == -1) {
session.foldWidgets[row - 1] = "start";
session.foldWidgets[row + 1] = "";
return "";
}
}
if (prevIndent!= -1 && prevIndent < indent)
session.foldWidgets[row - 1] = "start";
else
session.foldWidgets[row - 1] = "";
if (indent < nextIndent)
return "start";
else
return "";
};
}).call(FoldMode.prototype);
});
| kang/ace-builds | textarea/src/mode-ruby.js | JavaScript | bsd-3-clause | 17,646 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Currently this file is only used for the uninstall prompt. The install prompt
// code is in extension_install_prompt2_gtk.cc.
#include "chrome/browser/extensions/extension_uninstall_dialog.h"
#include <gtk/gtk.h>
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/gtk/browser_window_gtk.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "ui/base/gtk/gtk_hig_constants.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/gtk_util.h"
namespace {
// Left or right margin.
const int kPanelHorizMargin = 13;
// GTK implementation of the uninstall dialog.
class ExtensionUninstallDialogGtk : public ExtensionUninstallDialog {
public:
ExtensionUninstallDialogGtk(Browser* browser, Delegate* delegate);
virtual ~ExtensionUninstallDialogGtk() OVERRIDE;
private:
virtual void Show() OVERRIDE;
CHROMEGTK_CALLBACK_1(ExtensionUninstallDialogGtk, void, OnResponse, int);
GtkWidget* dialog_;
};
ExtensionUninstallDialogGtk::ExtensionUninstallDialogGtk(
Browser* browser, ExtensionUninstallDialog::Delegate* delegate)
: ExtensionUninstallDialog(browser, delegate),
dialog_(NULL) {}
void ExtensionUninstallDialogGtk::Show() {
BrowserWindow* browser_window = browser_->window();
if (!browser_window) {
delegate_->ExtensionUninstallCanceled();
return;
}
// Build the dialog.
dialog_ = gtk_dialog_new_with_buttons(
l10n_util::GetStringUTF8(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE).c_str(),
browser_window->GetNativeWindow(),
GTK_DIALOG_MODAL,
GTK_STOCK_CANCEL,
GTK_RESPONSE_CLOSE,
l10n_util::GetStringUTF8(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON).c_str(),
GTK_RESPONSE_ACCEPT,
NULL);
#if !GTK_CHECK_VERSION(2, 22, 0)
gtk_dialog_set_has_separator(GTK_DIALOG(dialog_), FALSE);
#endif
// Create a two column layout.
GtkWidget* content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog_));
gtk_box_set_spacing(GTK_BOX(content_area), ui::kContentAreaSpacing);
GtkWidget* icon_hbox = gtk_hbox_new(FALSE, ui::kContentAreaSpacing);
gtk_box_pack_start(GTK_BOX(content_area), icon_hbox, TRUE, TRUE, 0);
// Put Icon in the left column.
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(*icon_.bitmap());
GtkWidget* icon = gtk_image_new_from_pixbuf(pixbuf);
g_object_unref(pixbuf);
gtk_box_pack_start(GTK_BOX(icon_hbox), icon, TRUE, TRUE, 0);
// Create a new vbox for the right column.
GtkWidget* right_column_area = gtk_vbox_new(FALSE, 0);
gtk_box_pack_start(GTK_BOX(icon_hbox), right_column_area, TRUE, TRUE, 0);
std::string heading_text = l10n_util::GetStringFUTF8(
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING, UTF8ToUTF16(extension_->name()));
GtkWidget* heading_label = gtk_label_new(heading_text.c_str());
gtk_misc_set_alignment(GTK_MISC(heading_label), 0.0, 0.5);
gtk_box_pack_start(GTK_BOX(right_column_area), heading_label, TRUE, TRUE, 0);
g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this);
gtk_window_set_resizable(GTK_WINDOW(dialog_), FALSE);
gtk_widget_show_all(dialog_);
}
ExtensionUninstallDialogGtk::~ExtensionUninstallDialogGtk() {
delegate_ = NULL;
if (dialog_) {
gtk_widget_destroy(dialog_);
dialog_ = NULL;
}
}
void ExtensionUninstallDialogGtk::OnResponse(
GtkWidget* dialog, int response_id) {
CHECK_EQ(dialog_, dialog);
gtk_widget_destroy(dialog_);
dialog_ = NULL;
if (delegate_) {
if (response_id == GTK_RESPONSE_ACCEPT)
delegate_->ExtensionUninstallAccepted();
else
delegate_->ExtensionUninstallCanceled();
}
}
} // namespace
// static
// Platform specific implementation of the uninstall dialog show method.
ExtensionUninstallDialog* ExtensionUninstallDialog::Create(
Browser* browser, Delegate* delegate) {
return new ExtensionUninstallDialogGtk(browser, delegate);
}
| junmin-zhu/chromium-rivertrail | chrome/browser/ui/gtk/extensions/extension_uninstall_dialog_gtk.cc | C++ | bsd-3-clause | 4,153 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#include "components/nacl/common/nacl_types.h"
#include "ipc/ipc_platform_file.h"
namespace nacl {
NaClStartParams::NaClStartParams()
: nexe_file(IPC::InvalidPlatformFileForTransit()),
irt_handle(IPC::InvalidPlatformFileForTransit()),
#if defined(OS_MACOSX)
mac_shm_fd(IPC::InvalidPlatformFileForTransit()),
#endif
#if defined(OS_POSIX)
debug_stub_server_bound_socket(IPC::InvalidPlatformFileForTransit()),
#endif
validation_cache_enabled(false),
enable_debug_stub(false),
process_type(kUnknownNaClProcessType),
crash_info_shmem_handle(base::SharedMemory::NULLHandle()) {
}
NaClStartParams::~NaClStartParams() {
}
NaClResourcePrefetchResult::NaClResourcePrefetchResult()
: file(IPC::InvalidPlatformFileForTransit()) {
}
NaClResourcePrefetchResult::NaClResourcePrefetchResult(
const IPC::PlatformFileForTransit& file,
const base::FilePath& file_path_metadata,
const std::string& file_key)
: file(file), file_path_metadata(file_path_metadata), file_key(file_key) {
}
NaClResourcePrefetchResult::~NaClResourcePrefetchResult() {
}
NaClResourcePrefetchRequest::NaClResourcePrefetchRequest() {
}
NaClResourcePrefetchRequest::NaClResourcePrefetchRequest(
const std::string& file_key,
const std::string& resource_url)
: file_key(file_key),
resource_url(resource_url) {
}
NaClResourcePrefetchRequest::~NaClResourcePrefetchRequest() {
}
NaClLaunchParams::NaClLaunchParams()
: nexe_file(IPC::InvalidPlatformFileForTransit()),
nexe_token_lo(0),
nexe_token_hi(0),
render_view_id(0),
permission_bits(0),
process_type(kUnknownNaClProcessType) {
}
NaClLaunchParams::NaClLaunchParams(
const std::string& manifest_url,
const IPC::PlatformFileForTransit& nexe_file,
uint64_t nexe_token_lo,
uint64_t nexe_token_hi,
const std::vector<NaClResourcePrefetchRequest>&
resource_prefetch_request_list,
int render_view_id,
uint32_t permission_bits,
bool uses_nonsfi_mode,
NaClAppProcessType process_type)
: manifest_url(manifest_url),
nexe_file(nexe_file),
nexe_token_lo(nexe_token_lo),
nexe_token_hi(nexe_token_hi),
resource_prefetch_request_list(resource_prefetch_request_list),
render_view_id(render_view_id),
permission_bits(permission_bits),
uses_nonsfi_mode(uses_nonsfi_mode),
process_type(process_type) {}
NaClLaunchParams::~NaClLaunchParams() {
}
NaClLaunchResult::NaClLaunchResult()
: ppapi_ipc_channel_handle(),
trusted_ipc_channel_handle(),
plugin_pid(base::kNullProcessId),
plugin_child_id(0),
crash_info_shmem_handle(base::SharedMemory::NULLHandle()) {
}
NaClLaunchResult::NaClLaunchResult(
const IPC::ChannelHandle& ppapi_ipc_channel_handle,
const IPC::ChannelHandle& trusted_ipc_channel_handle,
const IPC::ChannelHandle& manifest_service_ipc_channel_handle,
base::ProcessId plugin_pid,
int plugin_child_id,
base::SharedMemoryHandle crash_info_shmem_handle)
: ppapi_ipc_channel_handle(ppapi_ipc_channel_handle),
trusted_ipc_channel_handle(trusted_ipc_channel_handle),
manifest_service_ipc_channel_handle(manifest_service_ipc_channel_handle),
plugin_pid(plugin_pid),
plugin_child_id(plugin_child_id),
crash_info_shmem_handle(crash_info_shmem_handle) {
}
NaClLaunchResult::~NaClLaunchResult() {
}
} // namespace nacl
| hujiajie/chromium-crosswalk | components/nacl/common/nacl_types.cc | C++ | bsd-3-clause | 3,616 |
// Copyright (c) 2006, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: Satoru Takabayashi
// Stack-footprint reduction work done by Raksit Ashok
//
// Implementation note:
//
// We don't use heaps but only use stacks. We want to reduce the
// stack consumption so that the symbolizer can run on small stacks.
//
// Here are some numbers collected with GCC 4.1.0 on x86:
// - sizeof(Elf32_Sym) = 16
// - sizeof(Elf32_Shdr) = 40
// - sizeof(Elf64_Sym) = 24
// - sizeof(Elf64_Shdr) = 64
//
// This implementation is intended to be async-signal-safe but uses
// some functions which are not guaranteed to be so, such as memchr()
// and memmove(). We assume they are async-signal-safe.
//
// Additional header can be specified by the GLOG_BUILD_CONFIG_INCLUDE
// macro to add platform specific defines (e.g. OS_OPENBSD).
#ifdef GLOG_BUILD_CONFIG_INCLUDE
#include GLOG_BUILD_CONFIG_INCLUDE
#endif // GLOG_BUILD_CONFIG_INCLUDE
#include "build/build_config.h"
#include "utilities.h"
#if defined(HAVE_SYMBOLIZE)
#include <string.h>
#include <algorithm>
#include <limits>
#include "symbolize.h"
#include "demangle.h"
_START_GOOGLE_NAMESPACE_
// We don't use assert() since it's not guaranteed to be
// async-signal-safe. Instead we define a minimal assertion
// macro. So far, we don't need pretty printing for __FILE__, etc.
// A wrapper for abort() to make it callable in ? :.
static int AssertFail() {
abort();
return 0; // Should not reach.
}
#define SAFE_ASSERT(expr) ((expr) ? 0 : AssertFail())
static SymbolizeCallback g_symbolize_callback = NULL;
void InstallSymbolizeCallback(SymbolizeCallback callback) {
g_symbolize_callback = callback;
}
static SymbolizeOpenObjectFileCallback g_symbolize_open_object_file_callback =
NULL;
void InstallSymbolizeOpenObjectFileCallback(
SymbolizeOpenObjectFileCallback callback) {
g_symbolize_open_object_file_callback = callback;
}
// This function wraps the Demangle function to provide an interface
// where the input symbol is demangled in-place.
// To keep stack consumption low, we would like this function to not
// get inlined.
static ATTRIBUTE_NOINLINE void DemangleInplace(char *out, int out_size) {
char demangled[256]; // Big enough for sane demangled symbols.
if (Demangle(out, demangled, sizeof(demangled))) {
// Demangling succeeded. Copy to out if the space allows.
size_t len = strlen(demangled);
if (len + 1 <= (size_t)out_size) { // +1 for '\0'.
SAFE_ASSERT(len < sizeof(demangled));
memmove(out, demangled, len + 1);
}
}
}
_END_GOOGLE_NAMESPACE_
#if defined(__ELF__)
#if defined(HAVE_DLFCN_H)
#include <dlfcn.h>
#endif
#if BUILDFLAG(IS_OPENBSD)
#include <sys/exec_elf.h>
#else
#include <elf.h>
#endif
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "symbolize.h"
#include "config.h"
#include "glog/raw_logging.h"
// Re-runs fn until it doesn't cause EINTR.
#define NO_INTR(fn) do {} while ((fn) < 0 && errno == EINTR)
_START_GOOGLE_NAMESPACE_
// Read up to "count" bytes from "offset" in the file pointed by file
// descriptor "fd" into the buffer starting at "buf" while handling short reads
// and EINTR. On success, return the number of bytes read. Otherwise, return
// -1.
ssize_t ReadFromOffset(const int fd,
void* buf,
const size_t count,
const off_t offset) {
SAFE_ASSERT(fd >= 0);
SAFE_ASSERT(count <= std::numeric_limits<ssize_t>::max());
char *buf0 = reinterpret_cast<char *>(buf);
ssize_t num_bytes = 0;
while (num_bytes < count) {
ssize_t len;
NO_INTR(len = pread(fd, buf0 + num_bytes, count - num_bytes,
offset + num_bytes));
if (len < 0) { // There was an error other than EINTR.
return -1;
}
if (len == 0) { // Reached EOF.
break;
}
num_bytes += len;
}
SAFE_ASSERT(num_bytes <= count);
return num_bytes;
}
// Try reading exactly "count" bytes from "offset" bytes in a file
// pointed by "fd" into the buffer starting at "buf" while handling
// short reads and EINTR. On success, return true. Otherwise, return
// false.
static bool ReadFromOffsetExact(const int fd, void *buf,
const size_t count, const off_t offset) {
ssize_t len = ReadFromOffset(fd, buf, count, offset);
return len == count;
}
// Returns elf_header.e_type if the file pointed by fd is an ELF binary.
static int FileGetElfType(const int fd) {
ElfW(Ehdr) elf_header;
if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
return -1;
}
if (memcmp(elf_header.e_ident, ELFMAG, SELFMAG) != 0) {
return -1;
}
return elf_header.e_type;
}
// Read the section headers in the given ELF binary, and if a section
// of the specified type is found, set the output to this section header
// and return true. Otherwise, return false.
// To keep stack consumption low, we would like this function to not get
// inlined.
static ATTRIBUTE_NOINLINE bool
GetSectionHeaderByType(const int fd, ElfW(Half) sh_num, const off_t sh_offset,
ElfW(Word) type, ElfW(Shdr) *out) {
// Read at most 16 section headers at a time to save read calls.
ElfW(Shdr) buf[16];
for (int i = 0; i < sh_num;) {
const ssize_t num_bytes_left = (sh_num - i) * sizeof(buf[0]);
const ssize_t num_bytes_to_read =
(sizeof(buf) > num_bytes_left) ? num_bytes_left : sizeof(buf);
const ssize_t len = ReadFromOffset(fd, buf, num_bytes_to_read,
sh_offset + i * sizeof(buf[0]));
if (len == -1) {
return false;
}
SAFE_ASSERT(len % sizeof(buf[0]) == 0);
const ssize_t num_headers_in_buf = len / sizeof(buf[0]);
SAFE_ASSERT(num_headers_in_buf <= sizeof(buf) / sizeof(buf[0]));
for (int j = 0; j < num_headers_in_buf; ++j) {
if (buf[j].sh_type == type) {
*out = buf[j];
return true;
}
}
i += num_headers_in_buf;
}
return false;
}
// There is no particular reason to limit section name to 63 characters,
// but there has (as yet) been no need for anything longer either.
const int kMaxSectionNameLen = 64;
// name_len should include terminating '\0'.
bool GetSectionHeaderByName(int fd, const char *name, size_t name_len,
ElfW(Shdr) *out) {
ElfW(Ehdr) elf_header;
if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
return false;
}
ElfW(Shdr) shstrtab;
off_t shstrtab_offset = (elf_header.e_shoff +
elf_header.e_shentsize * elf_header.e_shstrndx);
if (!ReadFromOffsetExact(fd, &shstrtab, sizeof(shstrtab), shstrtab_offset)) {
return false;
}
for (int i = 0; i < elf_header.e_shnum; ++i) {
off_t section_header_offset = (elf_header.e_shoff +
elf_header.e_shentsize * i);
if (!ReadFromOffsetExact(fd, out, sizeof(*out), section_header_offset)) {
return false;
}
char header_name[kMaxSectionNameLen];
if (sizeof(header_name) < name_len) {
RAW_LOG(WARNING, "Section name '%s' is too long (%" PRIuS "); "
"section will not be found (even if present).", name, name_len);
// No point in even trying.
return false;
}
off_t name_offset = shstrtab.sh_offset + out->sh_name;
ssize_t n_read = ReadFromOffset(fd, &header_name, name_len, name_offset);
if (n_read == -1) {
return false;
} else if (n_read != name_len) {
// Short read -- name could be at end of file.
continue;
}
if (memcmp(header_name, name, name_len) == 0) {
return true;
}
}
return false;
}
// Read a symbol table and look for the symbol containing the
// pc. Iterate over symbols in a symbol table and look for the symbol
// containing "pc". On success, return true and write the symbol name
// to out. Otherwise, return false.
// To keep stack consumption low, we would like this function to not get
// inlined.
static ATTRIBUTE_NOINLINE bool
FindSymbol(uint64_t pc, const int fd, char *out, int out_size,
uint64_t symbol_offset, const ElfW(Shdr) *strtab,
const ElfW(Shdr) *symtab) {
if (symtab == NULL) {
return false;
}
const int num_symbols = symtab->sh_size / symtab->sh_entsize;
for (int i = 0; i < num_symbols;) {
off_t offset = symtab->sh_offset + i * symtab->sh_entsize;
// If we are reading Elf64_Sym's, we want to limit this array to
// 32 elements (to keep stack consumption low), otherwise we can
// have a 64 element Elf32_Sym array.
#if __WORDSIZE == 64
#define NUM_SYMBOLS 32
#else
#define NUM_SYMBOLS 64
#endif
// Read at most NUM_SYMBOLS symbols at once to save read() calls.
ElfW(Sym) buf[NUM_SYMBOLS];
int num_symbols_to_read = std::min(NUM_SYMBOLS, num_symbols - i);
const ssize_t len =
ReadFromOffset(fd, &buf, sizeof(buf[0]) * num_symbols_to_read, offset);
SAFE_ASSERT(len % sizeof(buf[0]) == 0);
const ssize_t num_symbols_in_buf = len / sizeof(buf[0]);
SAFE_ASSERT(num_symbols_in_buf <= num_symbols_to_read);
for (int j = 0; j < num_symbols_in_buf; ++j) {
const ElfW(Sym)& symbol = buf[j];
uint64_t start_address = symbol.st_value;
start_address += symbol_offset;
uint64_t end_address = start_address + symbol.st_size;
if (symbol.st_value != 0 && // Skip null value symbols.
symbol.st_shndx != 0 && // Skip undefined symbols.
start_address <= pc && pc < end_address) {
ssize_t len1 = ReadFromOffset(fd, out, out_size,
strtab->sh_offset + symbol.st_name);
if (len1 <= 0 || memchr(out, '\0', out_size) == NULL) {
memset(out, 0, out_size);
return false;
}
return true; // Obtained the symbol name.
}
}
i += num_symbols_in_buf;
}
return false;
}
// Get the symbol name of "pc" from the file pointed by "fd". Process
// both regular and dynamic symbol tables if necessary. On success,
// write the symbol name to "out" and return true. Otherwise, return
// false.
static bool GetSymbolFromObjectFile(const int fd,
uint64_t pc,
char* out,
int out_size,
uint64_t base_address) {
// Read the ELF header.
ElfW(Ehdr) elf_header;
if (!ReadFromOffsetExact(fd, &elf_header, sizeof(elf_header), 0)) {
return false;
}
ElfW(Shdr) symtab, strtab;
// Consult a regular symbol table first.
if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff,
SHT_SYMTAB, &symtab)) {
if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff +
symtab.sh_link * sizeof(symtab))) {
return false;
}
if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) {
return true; // Found the symbol in a regular symbol table.
}
}
// If the symbol is not found, then consult a dynamic symbol table.
if (GetSectionHeaderByType(fd, elf_header.e_shnum, elf_header.e_shoff,
SHT_DYNSYM, &symtab)) {
if (!ReadFromOffsetExact(fd, &strtab, sizeof(strtab), elf_header.e_shoff +
symtab.sh_link * sizeof(symtab))) {
return false;
}
if (FindSymbol(pc, fd, out, out_size, base_address, &strtab, &symtab)) {
return true; // Found the symbol in a dynamic symbol table.
}
}
return false;
}
// Thin wrapper around a file descriptor so that the file descriptor
// gets closed for sure.
FileDescriptor::FileDescriptor(int fd) : fd_(fd) {}
FileDescriptor::~FileDescriptor() {
if (fd_ >= 0) {
close(fd_);
}
}
namespace {
// Helper class for reading lines from file.
//
// Note: we don't use ProcMapsIterator since the object is big (it has
// a 5k array member) and uses async-unsafe functions such as sscanf()
// and snprintf().
class LineReader {
public:
explicit LineReader(int fd, char *buf, int buf_len, off_t offset)
: fd_(fd),
buf_(buf),
buf_len_(buf_len),
offset_(offset),
bol_(buf),
eol_(buf),
eod_(buf) {}
// Read '\n'-terminated line from file. On success, modify "bol"
// and "eol", then return true. Otherwise, return false.
//
// Note: if the last line doesn't end with '\n', the line will be
// dropped. It's an intentional behavior to make the code simple.
bool ReadLine(const char **bol, const char **eol) {
if (BufferIsEmpty()) { // First time.
const ssize_t num_bytes = ReadFromOffset(fd_, buf_, buf_len_, offset_);
if (num_bytes <= 0) { // EOF or error.
return false;
}
offset_ += num_bytes;
eod_ = buf_ + num_bytes;
bol_ = buf_;
} else {
bol_ = eol_ + 1; // Advance to the next line in the buffer.
SAFE_ASSERT(bol_ <= eod_); // "bol_" can point to "eod_".
if (!HasCompleteLine()) {
const int incomplete_line_length = eod_ - bol_;
// Move the trailing incomplete line to the beginning.
memmove(buf_, bol_, incomplete_line_length);
// Read text from file and append it.
char * const append_pos = buf_ + incomplete_line_length;
const int capacity_left = buf_len_ - incomplete_line_length;
const ssize_t num_bytes =
ReadFromOffset(fd_, append_pos, capacity_left, offset_);
if (num_bytes <= 0) { // EOF or error.
return false;
}
offset_ += num_bytes;
eod_ = append_pos + num_bytes;
bol_ = buf_;
}
}
eol_ = FindLineFeed();
if (eol_ == NULL) { // '\n' not found. Malformed line.
return false;
}
*eol_ = '\0'; // Replace '\n' with '\0'.
*bol = bol_;
*eol = eol_;
return true;
}
// Beginning of line.
const char *bol() {
return bol_;
}
// End of line.
const char *eol() {
return eol_;
}
private:
explicit LineReader(const LineReader&);
void operator=(const LineReader&);
char *FindLineFeed() {
return reinterpret_cast<char *>(memchr(bol_, '\n', eod_ - bol_));
}
bool BufferIsEmpty() {
return buf_ == eod_;
}
bool HasCompleteLine() {
return !BufferIsEmpty() && FindLineFeed() != NULL;
}
const int fd_;
char * const buf_;
const int buf_len_;
off_t offset_;
char *bol_;
char *eol_;
const char *eod_; // End of data in "buf_".
};
} // namespace
// Place the hex number read from "start" into "*hex". The pointer to
// the first non-hex character or "end" is returned.
static char *GetHex(const char *start, const char *end, uint64_t *hex) {
*hex = 0;
const char *p;
for (p = start; p < end; ++p) {
int ch = *p;
if ((ch >= '0' && ch <= '9') ||
(ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f')) {
*hex = (*hex << 4) | (ch < 'A' ? ch - '0' : (ch & 0xF) + 9);
} else { // Encountered the first non-hex character.
break;
}
}
SAFE_ASSERT(p <= end);
return const_cast<char *>(p);
}
// Searches for the object file (from /proc/self/maps) that contains
// the specified pc. If found, sets |start_address| to the start address
// of where this object file is mapped in memory, sets the module base
// address into |base_address|, copies the object file name into
// |out_file_name|, and attempts to open the object file. If the object
// file is opened successfully, returns the file descriptor. Otherwise,
// returns -1. |out_file_name_size| is the size of the file name buffer
// (including the null-terminator).
ATTRIBUTE_NOINLINE int OpenObjectFileContainingPcAndGetStartAddress(
uint64_t pc,
uint64_t& start_address,
uint64_t& end_address,
uint64_t& base_address,
char* out_file_name,
int out_file_name_size) {
int object_fd;
int maps_fd;
NO_INTR(maps_fd = open("/proc/self/maps", O_RDONLY));
FileDescriptor wrapped_maps_fd(maps_fd);
if (wrapped_maps_fd.get() < 0) {
return -1;
}
int mem_fd;
NO_INTR(mem_fd = open("/proc/self/mem", O_RDONLY));
FileDescriptor wrapped_mem_fd(mem_fd);
if (wrapped_mem_fd.get() < 0) {
return -1;
}
// Iterate over maps and look for the map containing the pc. Then
// look into the symbol tables inside.
char buf[1024]; // Big enough for line of sane /proc/self/maps
int num_maps = 0;
LineReader reader(wrapped_maps_fd.get(), buf, sizeof(buf), 0);
while (true) {
num_maps++;
const char *cursor;
const char *eol;
if (!reader.ReadLine(&cursor, &eol)) { // EOF or malformed line.
return -1;
}
// Start parsing line in /proc/self/maps. Here is an example:
//
// 08048000-0804c000 r-xp 00000000 08:01 2142121 /bin/cat
//
// We want start address (08048000), end address (0804c000), flags
// (r-xp) and file name (/bin/cat).
// Read start address.
cursor = GetHex(cursor, eol, &start_address);
if (cursor == eol || *cursor != '-') {
return -1; // Malformed line.
}
++cursor; // Skip '-'.
// Read end address.
cursor = GetHex(cursor, eol, &end_address);
if (cursor == eol || *cursor != ' ') {
return -1; // Malformed line.
}
++cursor; // Skip ' '.
// Read flags. Skip flags until we encounter a space or eol.
const char * const flags_start = cursor;
while (cursor < eol && *cursor != ' ') {
++cursor;
}
// We expect at least four letters for flags (ex. "r-xp").
if (cursor == eol || cursor < flags_start + 4) {
return -1; // Malformed line.
}
// Determine the base address by reading ELF headers in process memory.
ElfW(Ehdr) ehdr;
// Skip non-readable maps.
if (flags_start[0] == 'r' &&
ReadFromOffsetExact(mem_fd, &ehdr, sizeof(ElfW(Ehdr)), start_address) &&
memcmp(ehdr.e_ident, ELFMAG, SELFMAG) == 0) {
switch (ehdr.e_type) {
case ET_EXEC:
base_address = 0;
break;
case ET_DYN:
// Find the segment containing file offset 0. This will correspond
// to the ELF header that we just read. Normally this will have
// virtual address 0, but this is not guaranteed. We must subtract
// the virtual address from the address where the ELF header was
// mapped to get the base address.
//
// If we fail to find a segment for file offset 0, use the address
// of the ELF header as the base address.
base_address = start_address;
for (unsigned i = 0; i != ehdr.e_phnum; ++i) {
ElfW(Phdr) phdr;
if (ReadFromOffsetExact(
mem_fd, &phdr, sizeof(phdr),
start_address + ehdr.e_phoff + i * sizeof(phdr)) &&
phdr.p_type == PT_LOAD && phdr.p_offset == 0) {
base_address = start_address - phdr.p_vaddr;
break;
}
}
break;
default:
// ET_REL or ET_CORE. These aren't directly executable, so they don't
// affect the base address.
break;
}
}
// Check start and end addresses.
if (!(start_address <= pc && pc < end_address)) {
continue; // We skip this map. PC isn't in this map.
}
// Check flags. We are only interested in "r*x" maps.
if (flags_start[0] != 'r' || flags_start[2] != 'x') {
continue; // We skip this map.
}
++cursor; // Skip ' '.
// Read file offset.
uint64_t file_offset;
cursor = GetHex(cursor, eol, &file_offset);
if (cursor == eol || *cursor != ' ') {
return -1; // Malformed line.
}
++cursor; // Skip ' '.
// Skip to file name. "cursor" now points to dev. We need to
// skip at least two spaces for dev and inode.
int num_spaces = 0;
while (cursor < eol) {
if (*cursor == ' ') {
++num_spaces;
} else if (num_spaces >= 2) {
// The first non-space character after skipping two spaces
// is the beginning of the file name.
break;
}
++cursor;
}
if (cursor == eol) {
return -1; // Malformed line.
}
// Finally, "cursor" now points to file name of our interest.
NO_INTR(object_fd = open(cursor, O_RDONLY));
if (object_fd < 0) {
// Failed to open object file. Copy the object file name to
// |out_file_name|.
strncpy(out_file_name, cursor, out_file_name_size);
// Making sure |out_file_name| is always null-terminated.
out_file_name[out_file_name_size - 1] = '\0';
return -1;
}
return object_fd;
}
}
// POSIX doesn't define any async-signal safe function for converting
// an integer to ASCII. We'll have to define our own version.
// itoa_r() converts a (signed) integer to ASCII. It returns "buf", if the
// conversion was successful or NULL otherwise. It never writes more than "sz"
// bytes. Output will be truncated as needed, and a NUL character is always
// appended.
// NOTE: code from sandbox/linux/seccomp-bpf/demo.cc.
char* itoa_r(intptr_t i, char* buf, size_t sz, int base, size_t padding) {
// Make sure we can write at least one NUL byte.
size_t n = 1;
if (n > sz)
return NULL;
if (base < 2 || base > 16) {
buf[0] = '\000';
return NULL;
}
char *start = buf;
uintptr_t j = i;
// Handle negative numbers (only for base 10).
if (i < 0 && base == 10) {
// This does "j = -i" while avoiding integer overflow.
j = static_cast<uintptr_t>(-(i + 1)) + 1;
// Make sure we can write the '-' character.
if (++n > sz) {
buf[0] = '\000';
return NULL;
}
*start++ = '-';
}
// Loop until we have converted the entire number. Output at least one
// character (i.e. '0').
char *ptr = start;
do {
// Make sure there is still enough space left in our output buffer.
if (++n > sz) {
buf[0] = '\000';
return NULL;
}
// Output the next digit.
*ptr++ = "0123456789abcdef"[j % base];
j /= base;
if (padding > 0)
padding--;
} while (j > 0 || padding > 0);
// Terminate the output with a NUL character.
*ptr = '\000';
// Conversion to ASCII actually resulted in the digits being in reverse
// order. We can't easily generate them in forward order, as we can't tell
// the number of characters needed until we are done converting.
// So, now, we reverse the string (except for the possible "-" sign).
while (--ptr > start) {
char ch = *ptr;
*ptr = *start;
*start++ = ch;
}
return buf;
}
// Safely appends string |source| to string |dest|. Never writes past the
// buffer size |dest_size| and guarantees that |dest| is null-terminated.
static void SafeAppendString(const char* source, char* dest, int dest_size) {
int dest_string_length = strlen(dest);
SAFE_ASSERT(dest_string_length < dest_size);
dest += dest_string_length;
dest_size -= dest_string_length;
strncpy(dest, source, dest_size);
// Making sure |dest| is always null-terminated.
dest[dest_size - 1] = '\0';
}
// Converts a 64-bit value into a hex string, and safely appends it to |dest|.
// Never writes past the buffer size |dest_size| and guarantees that |dest| is
// null-terminated.
static void SafeAppendHexNumber(uint64_t value, char* dest, int dest_size) {
// 64-bit numbers in hex can have up to 16 digits.
char buf[17] = {'\0'};
SafeAppendString(itoa_r(value, buf, sizeof(buf), 16, 0), dest, dest_size);
}
// The implementation of our symbolization routine. If it
// successfully finds the symbol containing "pc" and obtains the
// symbol name, returns true and write the symbol name to "out".
// Otherwise, returns false. If Callback function is installed via
// InstallSymbolizeCallback(), the function is also called in this function,
// and "out" is used as its output.
// To keep stack consumption low, we would like this function to not
// get inlined.
static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
int out_size) {
uint64_t pc0 = reinterpret_cast<uintptr_t>(pc);
uint64_t start_address = 0;
uint64_t end_address = 0;
uint64_t base_address = 0;
int object_fd = -1;
if (out_size < 1) {
return false;
}
out[0] = '\0';
SafeAppendString("(", out, out_size);
if (g_symbolize_open_object_file_callback) {
object_fd = g_symbolize_open_object_file_callback(pc0, start_address,
base_address, out + 1,
out_size - 1);
} else {
object_fd = OpenObjectFileContainingPcAndGetStartAddress(
pc0, start_address, base_address, end_address, out + 1, out_size - 1);
}
FileDescriptor wrapped_object_fd(object_fd);
#if defined(PRINT_UNSYMBOLIZED_STACK_TRACES)
{
#else
// Check whether a file name was returned.
if (object_fd < 0) {
#endif
if (out[1]) {
// The object file containing PC was determined successfully however the
// object file was not opened successfully. This is still considered
// success because the object file name and offset are known and tools
// like asan_symbolize.py can be used for the symbolization.
out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated.
SafeAppendString("+0x", out, out_size);
SafeAppendHexNumber(pc0 - base_address, out, out_size);
SafeAppendString(")", out, out_size);
return true;
}
// Failed to determine the object file containing PC. Bail out.
return false;
}
int elf_type = FileGetElfType(wrapped_object_fd.get());
if (elf_type == -1) {
return false;
}
if (g_symbolize_callback) {
// Run the call back if it's installed.
// Note: relocation (and much of the rest of this code) will be
// wrong for prelinked shared libraries and PIE executables.
uint64_t relocation = (elf_type == ET_DYN) ? start_address : 0;
int num_bytes_written = g_symbolize_callback(wrapped_object_fd.get(),
pc, out, out_size,
relocation);
if (num_bytes_written > 0) {
out += num_bytes_written;
out_size -= num_bytes_written;
}
}
if (!GetSymbolFromObjectFile(wrapped_object_fd.get(), pc0,
out, out_size, base_address)) {
if (out[1] && !g_symbolize_callback) {
// The object file containing PC was opened successfully however the
// symbol was not found. The object may have been stripped. This is still
// considered success because the object file name and offset are known
// and tools like asan_symbolize.py can be used for the symbolization.
out[out_size - 1] = '\0'; // Making sure |out| is always null-terminated.
SafeAppendString("+0x", out, out_size);
SafeAppendHexNumber(pc0 - base_address, out, out_size);
SafeAppendString(")", out, out_size);
return true;
}
return false;
}
// Symbolization succeeded. Now we try to demangle the symbol.
DemangleInplace(out, out_size);
return true;
}
_END_GOOGLE_NAMESPACE_
#elif BUILDFLAG(IS_APPLE) && defined(HAVE_DLADDR)
#include <dlfcn.h>
#include <string.h>
_START_GOOGLE_NAMESPACE_
static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
int out_size) {
Dl_info info;
if (dladdr(pc, &info)) {
if ((int)strlen(info.dli_sname) < out_size) {
strcpy(out, info.dli_sname);
// Symbolization succeeded. Now we try to demangle the symbol.
DemangleInplace(out, out_size);
return true;
}
}
return false;
}
_END_GOOGLE_NAMESPACE_
#elif defined(OS_WINDOWS) || defined(OS_CYGWIN)
#include <windows.h>
#include <dbghelp.h>
#ifdef _MSC_VER
#pragma comment(lib, "dbghelp")
#endif
_START_GOOGLE_NAMESPACE_
class SymInitializer {
public:
HANDLE process;
bool ready;
SymInitializer() : process(NULL), ready(false) {
// Initialize the symbol handler.
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680344(v=vs.85).aspx
process = GetCurrentProcess();
// Defer symbol loading.
// We do not request undecorated symbols with SYMOPT_UNDNAME
// because the mangling library calls UnDecorateSymbolName.
SymSetOptions(SYMOPT_DEFERRED_LOADS);
if (SymInitialize(process, NULL, true)) {
ready = true;
}
}
~SymInitializer() {
SymCleanup(process);
// We do not need to close `HANDLE process` because it's a "pseudo handle."
}
private:
SymInitializer(const SymInitializer&);
SymInitializer& operator=(const SymInitializer&);
};
static ATTRIBUTE_NOINLINE bool SymbolizeAndDemangle(void *pc, char *out,
int out_size) {
const static SymInitializer symInitializer;
if (!symInitializer.ready) {
return false;
}
// Resolve symbol information from address.
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680578(v=vs.85).aspx
char buf[sizeof(SYMBOL_INFO) + MAX_SYM_NAME];
SYMBOL_INFO *symbol = reinterpret_cast<SYMBOL_INFO *>(buf);
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
symbol->MaxNameLen = MAX_SYM_NAME;
// We use the ANSI version to ensure the string type is always `char *`.
// This could break if a symbol has Unicode in it.
BOOL ret = SymFromAddr(symInitializer.process,
reinterpret_cast<DWORD64>(pc), 0, symbol);
if (ret == 1 && static_cast<int>(symbol->NameLen) < out_size) {
// `NameLen` does not include the null terminating character.
strncpy(out, symbol->Name, static_cast<size_t>(symbol->NameLen) + 1);
out[static_cast<size_t>(symbol->NameLen)] = '\0';
// Symbolization succeeded. Now we try to demangle the symbol.
DemangleInplace(out, out_size);
return true;
}
return false;
}
_END_GOOGLE_NAMESPACE_
#else
# error BUG: HAVE_SYMBOLIZE was wrongly set
#endif
_START_GOOGLE_NAMESPACE_
bool Symbolize(void *pc, char *out, int out_size) {
SAFE_ASSERT(out_size >= 0);
return SymbolizeAndDemangle(pc, out, out_size);
}
_END_GOOGLE_NAMESPACE_
#else /* HAVE_SYMBOLIZE */
#include <assert.h>
#include "config.h"
_START_GOOGLE_NAMESPACE_
// TODO: Support other environments.
bool Symbolize(void *pc, char *out, int out_size) {
assert(0);
return false;
}
_END_GOOGLE_NAMESPACE_
#endif
| chromium/chromium | base/third_party/symbolize/symbolize.cc | C++ | bsd-3-clause | 32,173 |
from django.utils.six.moves import http_client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import Permission
from django_webtest import WebTest
from purl import URL
from oscar.core.compat import get_user_model
User = get_user_model()
def add_permissions(user, permissions):
"""
Grant permissions to the passed user
:param permissions: e.g. ['partner.dashboard_access']
"""
for permission in permissions:
app_label, __, codename = permission.partition('.')
perm = Permission.objects.get(content_type__app_label=app_label,
codename=codename)
user.user_permissions.add(perm)
class WebTestCase(WebTest):
is_staff = False
is_anonymous = False
is_superuser = False
username = 'testuser'
email = 'testuser@buymore.com'
password = 'somefancypassword'
permissions = []
def setUp(self):
self.user = None
if not self.is_anonymous:
self.user = self.create_user(
self.username, self.email, self.password)
self.user.is_staff = self.is_staff
add_permissions(self.user, self.permissions)
self.user.save()
def create_user(self, username=None, email=None, password=None):
"""
Create a user for use in a test.
As usernames are optional in newer versions of Django, it only sets it
if exists.
"""
kwargs = {'email': email, 'password': password}
if 'username' in User._meta.get_all_field_names():
kwargs['username'] = username
return User.objects.create_user(**kwargs)
def get(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.get(url, **kwargs)
def post(self, url, **kwargs):
kwargs.setdefault('user', self.user)
return self.app.post(url, **kwargs)
# Custom assertions
def assertIsRedirect(self, response, expected_url=None):
self.assertTrue(response.status_code in (
http_client.FOUND, http_client.MOVED_PERMANENTLY))
if expected_url:
location = URL.from_string(response['Location'])
self.assertEqual(expected_url, location.path())
def assertRedirectsTo(self, response, url_name):
self.assertTrue(str(response.status_code).startswith('3'))
location = response.headers['Location']
redirect_path = location.replace('http://localhost:80', '')
self.assertEqual(reverse(url_name), redirect_path)
def assertNoAccess(self, response):
self.assertContext(response)
self.assertTrue(response.status_code in (http_client.NOT_FOUND,
http_client.FORBIDDEN))
def assertRedirectUrlName(self, response, name, kwargs=None):
self.assertIsRedirect(response)
location = response['Location'].replace('http://testserver', '')
self.assertEqual(location, reverse(name, kwargs=kwargs))
def assertIsOk(self, response):
self.assertEqual(http_client.OK, response.status_code)
def assertContext(self, response):
self.assertTrue(response.context is not None,
'No context was returned')
def assertInContext(self, response, key):
self.assertContext(response)
self.assertTrue(key in response.context,
"Context should contain a variable '%s'" % key)
| jinnykoo/christmas | src/oscar/test/testcases.py | Python | bsd-3-clause | 3,477 |
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
namespace Kooboo.CMS.Common.Runtime.Mvc
{
public class MvcDependencyAttributeFilterProvider : FilterAttributeFilterProvider
{
private readonly IEngine _engine;
/// <summary>
/// Initializes a new instance of the <see cref="NinjectFilterAttributeFilterProvider"/> class.
/// </summary>
/// <param name="kernel">The kernel.</param>
public MvcDependencyAttributeFilterProvider(IEngine engine)
{
this._engine = engine;
}
/// <summary>
/// Gets the controller attributes.
/// </summary>
/// <param name="controllerContext">The controller context.</param>
/// <param name="actionDescriptor">The action descriptor.</param>
/// <returns>The filters defined by attributes</returns>
protected override IEnumerable<FilterAttribute> GetControllerAttributes(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor)
{
var attributes = base.GetControllerAttributes(controllerContext, actionDescriptor);
foreach (var attribute in attributes)
{
this._engine.InjectProperties(attribute);
}
return attributes;
}
/// <summary>
/// Gets the action attributes.
/// </summary>
/// <param name="controllerContext">The controller context.</param>
/// <param name="actionDescriptor">The action descriptor.</param>
/// <returns>The filters defined by attributes.</returns>
protected override IEnumerable<FilterAttribute> GetActionAttributes(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor)
{
var attributes = base.GetActionAttributes(controllerContext, actionDescriptor);
foreach (var attribute in attributes)
{
this._engine.InjectProperties(attribute);
}
return attributes;
}
}
}
| lingxyd/CMS | Kooboo.CMS/Kooboo.CMS.Common/Runtime/Mvc/MvcDependencyAttributeFilterProvider.cs | C# | bsd-3-clause | 2,292 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Fscc
{
/// <summary>
/// the response packet of FSCTL_PIPE_TRANSCEIVE
/// </summary>
public class FsccFsctlPipeTransceiveResponsePacket : FsccStandardPacket<FSCTL_PIPE_TRANSCEIVE>
{
#region Properties
/// <summary>
/// the command of fscc packet
/// </summary>
public override uint Command
{
get
{
return (uint)FsControlCommand.FSCTL_PIPE_TRANSCEIVE;
}
}
#endregion
#region Constructors
/// <summary>
/// default constructor
/// </summary>
public FsccFsctlPipeTransceiveResponsePacket()
: base()
{
}
#endregion
#region Marshaling and Unmarshaling Methods
/// <summary>
/// marshaling this packet to bytes.
/// </summary>
/// <returns>the bytes of this packet </returns>
public override byte[] ToBytes()
{
byte[] payload;
if (this.Payload.Data == null || this.Payload.Data.Length == 0)
{
payload = new byte[0];
}
else
{
payload = new byte[this.Payload.Data.Length];
Array.Copy(this.Payload.Data, payload, payload.Length);
}
return payload;
}
/// <summary>
/// unmarshaling packet from bytes
/// </summary>
/// <param name = "packetBytes">the bytes of packet </param>
public override void FromBytes(byte[] packetBytes)
{
byte[] payload;
if (packetBytes == null || packetBytes.Length == 0)
{
payload = new byte[0];
}
else
{
payload = new byte[packetBytes.Length];
Array.Copy(packetBytes, payload, packetBytes.Length);
}
FSCTL_PIPE_TRANSCEIVE transceivePayload = new FSCTL_PIPE_TRANSCEIVE();
transceivePayload.Data = payload;
this.Payload = transceivePayload;
}
#endregion
}
}
| dongruiqing/WindowsProtocolTestSuites | ProtoSDK/MS-FSCC/Messages/FsccFsctlPipeTransceiveResponsePacket.cs | C# | mit | 2,384 |
<?php
declare(strict_types=1);
/*
* This file is part of PHP CS Fixer.
*
* (c) Fabien Potencier <fabien@symfony.com>
* Dariusz Rumiński <dariusz.ruminski@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace PhpCsFixer\Tests\RuleSet\Sets;
/**
* @internal
*
* @covers \PhpCsFixer\RuleSet\Sets\PHPUnit60MigrationRiskySet
*/
final class PHPUnit60MigrationRiskySetTest extends AbstractSetTest
{
}
| gharlan/PHP-CS-Fixer | tests/RuleSet/Sets/PHPUnit60MigrationRiskySetTest.php | PHP | mit | 496 |
package org.knowm.xchange.dsx.dto.trade;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Map;
import org.knowm.xchange.dsx.dto.DSXReturn;
/** @author Mikhail Wall */
public class DSXOrderHistoryReturn extends DSXReturn<Map<Long, DSXOrderHistoryResult>> {
public DSXOrderHistoryReturn(
@JsonProperty("success") boolean success,
@JsonProperty("return") Map<Long, DSXOrderHistoryResult> value,
@JsonProperty("error") String error) {
super(success, value, error);
}
}
| chrisrico/XChange | xchange-dsx/src/main/java/org/knowm/xchange/dsx/dto/trade/DSXOrderHistoryReturn.java | Java | mit | 517 |
<?php
namespace Sabre\CardDAV;
use Sabre\HTTP;
use Sabre\DAV;
require_once 'Sabre/HTTP/ResponseMock.php';
class MultiGetTest extends AbstractPluginTest {
function testMultiGet() {
$request = HTTP\Sapi::createFromServerArray([
'REQUEST_METHOD' => 'REPORT',
'REQUEST_URI' => '/addressbooks/user1/book1',
]);
$request->setBody(
'<?xml version="1.0"?>
<c:addressbook-multiget xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
<d:prop>
<d:getetag />
<c:address-data />
</d:prop>
<d:href>/addressbooks/user1/book1/card1</d:href>
</c:addressbook-multiget>'
);
$response = new HTTP\ResponseMock();
$this->server->httpRequest = $request;
$this->server->httpResponse = $response;
$this->server->exec();
$this->assertEquals(207, $response->status, 'Incorrect status code. Full response body:' . $response->body);
// using the client for parsing
$client = new DAV\Client(['baseUri' => '/']);
$result = $client->parseMultiStatus($response->body);
$this->assertEquals([
'/addressbooks/user1/book1/card1' => [
200 => [
'{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD") . '"',
'{urn:ietf:params:xml:ns:carddav}address-data' => "BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD",
]
]
], $result);
}
function testMultiGetVCard4() {
$request = HTTP\Sapi::createFromServerArray([
'REQUEST_METHOD' => 'REPORT',
'REQUEST_URI' => '/addressbooks/user1/book1',
]);
$request->setBody(
'<?xml version="1.0"?>
<c:addressbook-multiget xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:carddav">
<d:prop>
<d:getetag />
<c:address-data content-type="text/vcard" version="4.0" />
</d:prop>
<d:href>/addressbooks/user1/book1/card1</d:href>
</c:addressbook-multiget>'
);
$response = new HTTP\ResponseMock();
$this->server->httpRequest = $request;
$this->server->httpResponse = $response;
$this->server->exec();
$this->assertEquals(207, $response->status, 'Incorrect status code. Full response body:' . $response->body);
// using the client for parsing
$client = new DAV\Client(['baseUri' => '/']);
$result = $client->parseMultiStatus($response->body);
$prodId = "PRODID:-//Sabre//Sabre VObject " . \Sabre\VObject\Version::VERSION . "//EN";
$this->assertEquals([
'/addressbooks/user1/book1/card1' => [
200 => [
'{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD") . '"',
'{urn:ietf:params:xml:ns:carddav}address-data' => "BEGIN:VCARD\r\nVERSION:4.0\r\n$prodId\r\nUID:12345\r\nEND:VCARD\r\n",
]
]
], $result);
}
}
| wave72/hubzilla-dev | vendor/sabre/dav/tests/Sabre/CardDAV/MultiGetTest.php | PHP | mit | 3,074 |
<?php
namespace Kunstmaan\NodeBundle\Twig;
use Kunstmaan\NodeBundle\Helper\URLHelper;
class UrlReplaceTwigExtension extends \Twig_Extension
{
/**
* @var URLHelper
*/
private $urlHelper;
/**
* @param URLHelper $urlHelper
*/
public function __construct(URLHelper $urlHelper)
{
$this->urlHelper = $urlHelper;
}
/**
* @return array
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('replace_url', array($this, 'replaceUrl'))
);
}
public function replaceUrl($text)
{
return $this->urlHelper->replaceUrl($text);
}
}
| webtown-php/KunstmaanBundlesCMS | src/Kunstmaan/NodeBundle/Twig/UrlReplaceTwigExtension.php | PHP | mit | 664 |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Protocols.TestTools.StackSdk.Messages.Marshaling
{
/// <summary>
/// Token
/// </summary>
public class Token : IToken
{
private string text;
private TokenType type;
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Token type</param>
public Token(TokenType type)
{
this.type = type;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Token type</param>
/// <param name="text">Token text</param>
public Token(TokenType type, string text)
{
this.type = type;
this.text = text;
}
/// <summary>
/// Token text
/// </summary>
public string Text
{
get
{
return text;
}
set
{
text = value;
}
}
/// <summary>
/// Token type
/// </summary>
public virtual TokenType Type
{
get
{
return type;
}
set
{
this.type = value;
}
}
}
}
| dongruiqing/WindowsProtocolTestSuites | ProtoSDK/Messages/messagecommon/Token.cs | C# | mit | 1,525 |
#include "wrapper_common.h"
#include "cblas.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
Capability is supported if >0
Actual number can be increased over time to indicate
extensions/revisions (that do not break compatibility)
*/
DLLEXPORT int query_capability(const int capability)
{
switch (capability)
{
// SANITY CHECKS
case 0: return 0;
case 1: return -1;
// PLATFORM
case 8:
#ifdef _M_IX86
return 1;
#else
return 0;
#endif
case 9:
#ifdef _M_X64
return 1;
#else
return 0;
#endif
case 10:
#ifdef _M_IA64
return 1;
#else
return 0;
#endif
// COMMON/SHARED
case 64: return 1; // revision
case 66: return 1; // threading control
// LINEAR ALGEBRA
case 128: return 1; // basic dense linear algebra (major - breaking)
case 129: return 0; // basic dense linear algebra (minor - non-breaking)
default: return 0; // unknown or not supported
}
}
DLLEXPORT void set_max_threads(const blasint num_threads)
{
openblas_set_num_threads(num_threads);
}
DLLEXPORT char* get_build_config()
{
return openblas_get_config();
}
DLLEXPORT char* get_cpu_core()
{
return openblas_get_corename();
}
DLLEXPORT int get_parallel_type()
{
return openblas_get_parallel();
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
| albertp007/mathnet-numerics | src/NativeProviders/OpenBLAS/capabilities.cpp | C++ | mit | 1,308 |
'use strict';
// Load modules
const Http = require('http');
const Stream = require('stream');
// Declare internals
const internals = {};
exports = module.exports = class Response extends Http.ServerResponse {
constructor(req, onEnd) {
super({ method: req.method, httpVersionMajor: 1, httpVersionMinor: 1 });
this._shot = { headers: null, trailers: {}, payloadChunks: [] };
this._headers = {}; // This forces node@8 to always render the headers
this.assignSocket(internals.nullSocket());
this.once('finish', () => {
const res = internals.payload(this);
res.raw.req = req;
process.nextTick(() => onEnd(res));
});
}
writeHead() {
const result = super.writeHead.apply(this, arguments);
this._shot.headers = Object.assign({}, this._headers); // Should be .getHeaders() since node v7.7
// Add raw headers
['Date', 'Connection', 'Transfer-Encoding'].forEach((name) => {
const regex = new RegExp('\\r\\n' + name + ': ([^\\r]*)\\r\\n');
const field = this._header.match(regex);
if (field) {
this._shot.headers[name.toLowerCase()] = field[1];
}
});
return result;
}
write(data, encoding, callback) {
super.write(data, encoding, callback);
this._shot.payloadChunks.push(new Buffer(data, encoding));
return true; // Write always returns false when disconnected
}
end(data, encoding, callback) {
if (data) {
this.write(data, encoding);
}
super.end(callback);
this.emit('finish');
}
destroy() {
}
addTrailers(trailers) {
for (const key in trailers) {
this._shot.trailers[key.toLowerCase().trim()] = trailers[key].toString().trim();
}
}
};
internals.payload = function (response) {
// Prepare response object
const res = {
raw: {
res: response
},
headers: response._shot.headers,
statusCode: response.statusCode,
statusMessage: response.statusMessage,
trailers: {}
};
// Prepare payload and trailers
const rawBuffer = Buffer.concat(response._shot.payloadChunks);
res.rawPayload = rawBuffer;
res.payload = rawBuffer.toString();
res.trailers = response._shot.trailers;
return res;
};
// Throws away all written data to prevent response from buffering payload
internals.nullSocket = function () {
return new Stream.Writable({
write(chunk, encoding, callback) {
setImmediate(callback);
}
});
};
| shikun2014010800/manga | web/backend/node_modules/shot/lib/response.js | JavaScript | mit | 2,749 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Request represents an HTTP request.
*
* The methods dealing with URL accept / return a raw path (% encoded):
* * getBasePath
* * getBaseUrl
* * getPathInfo
* * getRequestUri
* * getUri
* * getUriForPath
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @api
*/
class Request
{
const HEADER_CLIENT_IP = 'client_ip';
const HEADER_CLIENT_HOST = 'client_host';
const HEADER_CLIENT_PROTO = 'client_proto';
const HEADER_CLIENT_PORT = 'client_port';
const METHOD_HEAD = 'HEAD';
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_PATCH = 'PATCH';
const METHOD_DELETE = 'DELETE';
const METHOD_PURGE = 'PURGE';
const METHOD_OPTIONS = 'OPTIONS';
const METHOD_TRACE = 'TRACE';
const METHOD_CONNECT = 'CONNECT';
protected static $trustedProxies = array();
/**
* @var string[]
*/
protected static $trustedHostPatterns = array();
/**
* @var string[]
*/
protected static $trustedHosts = array();
/**
* Names for headers that can be trusted when
* using trusted proxies.
*
* The default names are non-standard, but widely used
* by popular reverse proxies (like Apache mod_proxy or Amazon EC2).
*/
protected static $trustedHeaders = array(
self::HEADER_CLIENT_IP => 'X_FORWARDED_FOR',
self::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST',
self::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
self::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT',
);
protected static $httpMethodParameterOverride = false;
/**
* Custom parameters.
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*
* @api
*/
public $attributes;
/**
* Request body parameters ($_POST).
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*
* @api
*/
public $request;
/**
* Query string parameters ($_GET).
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*
* @api
*/
public $query;
/**
* Server and execution environment parameters ($_SERVER).
*
* @var \Symfony\Component\HttpFoundation\ServerBag
*
* @api
*/
public $server;
/**
* Uploaded files ($_FILES).
*
* @var \Symfony\Component\HttpFoundation\FileBag
*
* @api
*/
public $files;
/**
* Cookies ($_COOKIE).
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*
* @api
*/
public $cookies;
/**
* Headers (taken from the $_SERVER).
*
* @var \Symfony\Component\HttpFoundation\HeaderBag
*
* @api
*/
public $headers;
/**
* @var string
*/
protected $content;
/**
* @var array
*/
protected $languages;
/**
* @var array
*/
protected $charsets;
/**
* @var array
*/
protected $encodings;
/**
* @var array
*/
protected $acceptableContentTypes;
/**
* @var string
*/
protected $pathInfo;
/**
* @var string
*/
protected $requestUri;
/**
* @var string
*/
protected $baseUrl;
/**
* @var string
*/
protected $basePath;
/**
* @var string
*/
protected $method;
/**
* @var string
*/
protected $format;
/**
* @var \Symfony\Component\HttpFoundation\Session\SessionInterface
*/
protected $session;
/**
* @var string
*/
protected $locale;
/**
* @var string
*/
protected $defaultLocale = 'en';
/**
* @var array
*/
protected static $formats;
protected static $requestFactory;
/**
* Constructor.
*
* @param array $query The GET parameters
* @param array $request The POST parameters
* @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
* @param array $cookies The COOKIE parameters
* @param array $files The FILES parameters
* @param array $server The SERVER parameters
* @param string $content The raw body data
*
* @api
*/
public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
$this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
}
/**
* Sets the parameters for this request.
*
* This method also re-initializes all properties.
*
* @param array $query The GET parameters
* @param array $request The POST parameters
* @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
* @param array $cookies The COOKIE parameters
* @param array $files The FILES parameters
* @param array $server The SERVER parameters
* @param string $content The raw body data
*
* @api
*/
public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
$this->request = new ParameterBag($request);
$this->query = new ParameterBag($query);
$this->attributes = new ParameterBag($attributes);
$this->cookies = new ParameterBag($cookies);
$this->files = new FileBag($files);
$this->server = new ServerBag($server);
$this->headers = new HeaderBag($this->server->getHeaders());
$this->content = $content;
$this->languages = null;
$this->charsets = null;
$this->encodings = null;
$this->acceptableContentTypes = null;
$this->pathInfo = null;
$this->requestUri = null;
$this->baseUrl = null;
$this->basePath = null;
$this->method = null;
$this->format = null;
}
/**
* Creates a new request with values from PHP's super globals.
*
* @return Request A new request
*
* @api
*/
public static function createFromGlobals()
{
// With the php's bug #66606, the php's built-in web server
// stores the Content-Type and Content-Length header values in
// HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH fields.
$server = $_SERVER;
if ('cli-server' === php_sapi_name()) {
if (array_key_exists('HTTP_CONTENT_LENGTH', $_SERVER)) {
$server['CONTENT_LENGTH'] = $_SERVER['HTTP_CONTENT_LENGTH'];
}
if (array_key_exists('HTTP_CONTENT_TYPE', $_SERVER)) {
$server['CONTENT_TYPE'] = $_SERVER['HTTP_CONTENT_TYPE'];
}
}
$request = self::createRequestFromFactory($_GET, $_POST, array(), $_COOKIE, $_FILES, $server);
if (0 === strpos($request->headers->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
&& in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))
) {
parse_str($request->getContent(), $data);
$request->request = new ParameterBag($data);
}
return $request;
}
/**
* Creates a Request based on a given URI and configuration.
*
* The information contained in the URI always take precedence
* over the other information (server and parameters).
*
* @param string $uri The URI
* @param string $method The HTTP method
* @param array $parameters The query (GET) or request (POST) parameters
* @param array $cookies The request cookies ($_COOKIE)
* @param array $files The request files ($_FILES)
* @param array $server The server parameters ($_SERVER)
* @param string $content The raw body data
*
* @return Request A Request instance
*
* @api
*/
public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
{
$server = array_replace(array(
'SERVER_NAME' => 'localhost',
'SERVER_PORT' => 80,
'HTTP_HOST' => 'localhost',
'HTTP_USER_AGENT' => 'Symfony/2.X',
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'REMOTE_ADDR' => '127.0.0.1',
'SCRIPT_NAME' => '',
'SCRIPT_FILENAME' => '',
'SERVER_PROTOCOL' => 'HTTP/1.1',
'REQUEST_TIME' => time(),
), $server);
$server['PATH_INFO'] = '';
$server['REQUEST_METHOD'] = strtoupper($method);
$components = parse_url($uri);
if (isset($components['host'])) {
$server['SERVER_NAME'] = $components['host'];
$server['HTTP_HOST'] = $components['host'];
}
if (isset($components['scheme'])) {
if ('https' === $components['scheme']) {
$server['HTTPS'] = 'on';
$server['SERVER_PORT'] = 443;
} else {
unset($server['HTTPS']);
$server['SERVER_PORT'] = 80;
}
}
if (isset($components['port'])) {
$server['SERVER_PORT'] = $components['port'];
$server['HTTP_HOST'] = $server['HTTP_HOST'].':'.$components['port'];
}
if (isset($components['user'])) {
$server['PHP_AUTH_USER'] = $components['user'];
}
if (isset($components['pass'])) {
$server['PHP_AUTH_PW'] = $components['pass'];
}
if (!isset($components['path'])) {
$components['path'] = '/';
}
switch (strtoupper($method)) {
case 'POST':
case 'PUT':
case 'DELETE':
if (!isset($server['CONTENT_TYPE'])) {
$server['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
}
// no break
case 'PATCH':
$request = $parameters;
$query = array();
break;
default:
$request = array();
$query = $parameters;
break;
}
$queryString = '';
if (isset($components['query'])) {
parse_str(html_entity_decode($components['query']), $qs);
if ($query) {
$query = array_replace($qs, $query);
$queryString = http_build_query($query, '', '&');
} else {
$query = $qs;
$queryString = $components['query'];
}
} elseif ($query) {
$queryString = http_build_query($query, '', '&');
}
$server['REQUEST_URI'] = $components['path'].('' !== $queryString ? '?'.$queryString : '');
$server['QUERY_STRING'] = $queryString;
return self::createRequestFromFactory($query, $request, array(), $cookies, $files, $server, $content);
}
/**
* Sets a callable able to create a Request instance.
*
* This is mainly useful when you need to override the Request class
* to keep BC with an existing system. It should not be used for any
* other purpose.
*
* @param callable|null $callable A PHP callable
*/
public static function setFactory($callable)
{
self::$requestFactory = $callable;
}
/**
* Clones a request and overrides some of its parameters.
*
* @param array $query The GET parameters
* @param array $request The POST parameters
* @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
* @param array $cookies The COOKIE parameters
* @param array $files The FILES parameters
* @param array $server The SERVER parameters
*
* @return Request The duplicated request
*
* @api
*/
public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
{
$dup = clone $this;
if ($query !== null) {
$dup->query = new ParameterBag($query);
}
if ($request !== null) {
$dup->request = new ParameterBag($request);
}
if ($attributes !== null) {
$dup->attributes = new ParameterBag($attributes);
}
if ($cookies !== null) {
$dup->cookies = new ParameterBag($cookies);
}
if ($files !== null) {
$dup->files = new FileBag($files);
}
if ($server !== null) {
$dup->server = new ServerBag($server);
$dup->headers = new HeaderBag($dup->server->getHeaders());
}
$dup->languages = null;
$dup->charsets = null;
$dup->encodings = null;
$dup->acceptableContentTypes = null;
$dup->pathInfo = null;
$dup->requestUri = null;
$dup->baseUrl = null;
$dup->basePath = null;
$dup->method = null;
$dup->format = null;
if (!$dup->get('_format') && $this->get('_format')) {
$dup->attributes->set('_format', $this->get('_format'));
}
if (!$dup->getRequestFormat(null)) {
$dup->setRequestFormat($this->getRequestFormat(null));
}
return $dup;
}
/**
* Clones the current request.
*
* Note that the session is not cloned as duplicated requests
* are most of the time sub-requests of the main one.
*/
public function __clone()
{
$this->query = clone $this->query;
$this->request = clone $this->request;
$this->attributes = clone $this->attributes;
$this->cookies = clone $this->cookies;
$this->files = clone $this->files;
$this->server = clone $this->server;
$this->headers = clone $this->headers;
}
/**
* Returns the request as a string.
*
* @return string The request
*/
public function __toString()
{
try {
$content = $this->getContent();
} catch (\LogicException $e) {
return trigger_error($e, E_USER_ERROR);
}
return
sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
$this->headers."\r\n".
$content;
}
/**
* Overrides the PHP global variables according to this request instance.
*
* It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE.
* $_FILES is never overridden, see rfc1867
*
* @api
*/
public function overrideGlobals()
{
$this->server->set('QUERY_STRING', static::normalizeQueryString(http_build_query($this->query->all(), null, '&')));
$_GET = $this->query->all();
$_POST = $this->request->all();
$_SERVER = $this->server->all();
$_COOKIE = $this->cookies->all();
foreach ($this->headers->all() as $key => $value) {
$key = strtoupper(str_replace('-', '_', $key));
if (in_array($key, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) {
$_SERVER[$key] = implode(', ', $value);
} else {
$_SERVER['HTTP_'.$key] = implode(', ', $value);
}
}
$request = array('g' => $_GET, 'p' => $_POST, 'c' => $_COOKIE);
$requestOrder = ini_get('request_order') ?: ini_get('variables_order');
$requestOrder = preg_replace('#[^cgp]#', '', strtolower($requestOrder)) ?: 'gp';
$_REQUEST = array();
foreach (str_split($requestOrder) as $order) {
$_REQUEST = array_merge($_REQUEST, $request[$order]);
}
}
/**
* Sets a list of trusted proxies.
*
* You should only list the reverse proxies that you manage directly.
*
* @param array $proxies A list of trusted proxies
*
* @api
*/
public static function setTrustedProxies(array $proxies)
{
self::$trustedProxies = $proxies;
}
/**
* Gets the list of trusted proxies.
*
* @return array An array of trusted proxies.
*/
public static function getTrustedProxies()
{
return self::$trustedProxies;
}
/**
* Sets a list of trusted host patterns.
*
* You should only list the hosts you manage using regexs.
*
* @param array $hostPatterns A list of trusted host patterns
*/
public static function setTrustedHosts(array $hostPatterns)
{
self::$trustedHostPatterns = array_map(function ($hostPattern) {
return sprintf('#%s#i', $hostPattern);
}, $hostPatterns);
// we need to reset trusted hosts on trusted host patterns change
self::$trustedHosts = array();
}
/**
* Gets the list of trusted host patterns.
*
* @return array An array of trusted host patterns.
*/
public static function getTrustedHosts()
{
return self::$trustedHostPatterns;
}
/**
* Sets the name for trusted headers.
*
* The following header keys are supported:
*
* * Request::HEADER_CLIENT_IP: defaults to X-Forwarded-For (see getClientIp())
* * Request::HEADER_CLIENT_HOST: defaults to X-Forwarded-Host (see getHost())
* * Request::HEADER_CLIENT_PORT: defaults to X-Forwarded-Port (see getPort())
* * Request::HEADER_CLIENT_PROTO: defaults to X-Forwarded-Proto (see getScheme() and isSecure())
*
* Setting an empty value allows to disable the trusted header for the given key.
*
* @param string $key The header key
* @param string $value The header name
*
* @throws \InvalidArgumentException
*/
public static function setTrustedHeaderName($key, $value)
{
if (!array_key_exists($key, self::$trustedHeaders)) {
throw new \InvalidArgumentException(sprintf('Unable to set the trusted header name for key "%s".', $key));
}
self::$trustedHeaders[$key] = $value;
}
/**
* Gets the trusted proxy header name.
*
* @param string $key The header key
*
* @return string The header name
*
* @throws \InvalidArgumentException
*/
public static function getTrustedHeaderName($key)
{
if (!array_key_exists($key, self::$trustedHeaders)) {
throw new \InvalidArgumentException(sprintf('Unable to get the trusted header name for key "%s".', $key));
}
return self::$trustedHeaders[$key];
}
/**
* Normalizes a query string.
*
* It builds a normalized query string, where keys/value pairs are alphabetized,
* have consistent escaping and unneeded delimiters are removed.
*
* @param string $qs Query string
*
* @return string A normalized query string for the Request
*/
public static function normalizeQueryString($qs)
{
if ('' == $qs) {
return '';
}
$parts = array();
$order = array();
foreach (explode('&', $qs) as $param) {
if ('' === $param || '=' === $param[0]) {
// Ignore useless delimiters, e.g. "x=y&".
// Also ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway.
// PHP also does not include them when building _GET.
continue;
}
$keyValuePair = explode('=', $param, 2);
// GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded).
// PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str. This is why we use urldecode and then normalize to
// RFC 3986 with rawurlencode.
$parts[] = isset($keyValuePair[1]) ?
rawurlencode(urldecode($keyValuePair[0])).'='.rawurlencode(urldecode($keyValuePair[1])) :
rawurlencode(urldecode($keyValuePair[0]));
$order[] = urldecode($keyValuePair[0]);
}
array_multisort($order, SORT_ASC, $parts);
return implode('&', $parts);
}
/**
* Enables support for the _method request parameter to determine the intended HTTP method.
*
* Be warned that enabling this feature might lead to CSRF issues in your code.
* Check that you are using CSRF tokens when required.
* If the HTTP method parameter override is enabled, an html-form with method "POST" can be altered
* and used to send a "PUT" or "DELETE" request via the _method request parameter.
* If these methods are not protected against CSRF, this presents a possible vulnerability.
*
* The HTTP method can only be overridden when the real HTTP method is POST.
*/
public static function enableHttpMethodParameterOverride()
{
self::$httpMethodParameterOverride = true;
}
/**
* Checks whether support for the _method request parameter is enabled.
*
* @return bool True when the _method request parameter is enabled, false otherwise
*/
public static function getHttpMethodParameterOverride()
{
return self::$httpMethodParameterOverride;
}
/**
* Gets a "parameter" value.
*
* This method is mainly useful for libraries that want to provide some flexibility.
*
* Order of precedence: GET, PATH, POST
*
* Avoid using this method in controllers:
*
* * slow
* * prefer to get from a "named" source
*
* It is better to explicitly get request parameters from the appropriate
* public property instead (query, attributes, request).
*
* @param string $key the key
* @param mixed $default the default value
* @param bool $deep is parameter deep in multidimensional array
*
* @return mixed
*/
public function get($key, $default = null, $deep = false)
{
if ($this !== $result = $this->query->get($key, $this, $deep)) {
return $result;
}
if ($this !== $result = $this->attributes->get($key, $this, $deep)) {
return $result;
}
if ($this !== $result = $this->request->get($key, $this, $deep)) {
return $result;
}
return $default;
}
/**
* Gets the Session.
*
* @return SessionInterface|null The session
*
* @api
*/
public function getSession()
{
return $this->session;
}
/**
* Whether the request contains a Session which was started in one of the
* previous requests.
*
* @return bool
*
* @api
*/
public function hasPreviousSession()
{
// the check for $this->session avoids malicious users trying to fake a session cookie with proper name
return $this->hasSession() && $this->cookies->has($this->session->getName());
}
/**
* Whether the request contains a Session object.
*
* This method does not give any information about the state of the session object,
* like whether the session is started or not. It is just a way to check if this Request
* is associated with a Session instance.
*
* @return bool true when the Request contains a Session object, false otherwise
*
* @api
*/
public function hasSession()
{
return null !== $this->session;
}
/**
* Sets the Session.
*
* @param SessionInterface $session The Session
*
* @api
*/
public function setSession(SessionInterface $session)
{
$this->session = $session;
}
/**
* Returns the client IP addresses.
*
* In the returned array the most trusted IP address is first, and the
* least trusted one last. The "real" client IP address is the last one,
* but this is also the least trusted one. Trusted proxies are stripped.
*
* Use this method carefully; you should use getClientIp() instead.
*
* @return array The client IP addresses
*
* @see getClientIp()
*/
public function getClientIps()
{
$ip = $this->server->get('REMOTE_ADDR');
if (!$this->isFromTrustedProxy()) {
return array($ip);
}
if (!self::$trustedHeaders[self::HEADER_CLIENT_IP] || !$this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) {
return array($ip);
}
$clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
$clientIps[] = $ip; // Complete the IP chain with the IP the request actually came from
$ip = $clientIps[0]; // Fallback to this when the client IP falls into the range of trusted proxies
// Eliminate all IPs from the forwarded IP chain which are trusted proxies
foreach ($clientIps as $key => $clientIp) {
// Remove port on IPv4 address (unfortunately, it does happen)
if (preg_match('{((?:\d+\.){3}\d+)\:\d+}', $clientIp, $match)) {
$clientIps[$key] = $clientIp = $match[1];
}
if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
unset($clientIps[$key]);
}
}
// Now the IP chain contains only untrusted proxies and the client IP
return $clientIps ? array_reverse($clientIps) : array($ip);
}
/**
* Returns the client IP address.
*
* This method can read the client IP address from the "X-Forwarded-For" header
* when trusted proxies were set via "setTrustedProxies()". The "X-Forwarded-For"
* header value is a comma+space separated list of IP addresses, the left-most
* being the original client, and each successive proxy that passed the request
* adding the IP address where it received the request from.
*
* If your reverse proxy uses a different header name than "X-Forwarded-For",
* ("Client-Ip" for instance), configure it via "setTrustedHeaderName()" with
* the "client-ip" key.
*
* @return string The client IP address
*
* @see getClientIps()
* @see http://en.wikipedia.org/wiki/X-Forwarded-For
*
* @api
*/
public function getClientIp()
{
$ipAddresses = $this->getClientIps();
return $ipAddresses[0];
}
/**
* Returns current script name.
*
* @return string
*
* @api
*/
public function getScriptName()
{
return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
}
/**
* Returns the path being requested relative to the executed script.
*
* The path info always starts with a /.
*
* Suppose this request is instantiated from /mysite on localhost:
*
* * http://localhost/mysite returns an empty string
* * http://localhost/mysite/about returns '/about'
* * http://localhost/mysite/enco%20ded returns '/enco%20ded'
* * http://localhost/mysite/about?var=1 returns '/about'
*
* @return string The raw path (i.e. not urldecoded)
*
* @api
*/
public function getPathInfo()
{
if (null === $this->pathInfo) {
$this->pathInfo = $this->preparePathInfo();
}
return $this->pathInfo;
}
/**
* Returns the root path from which this request is executed.
*
* Suppose that an index.php file instantiates this request object:
*
* * http://localhost/index.php returns an empty string
* * http://localhost/index.php/page returns an empty string
* * http://localhost/web/index.php returns '/web'
* * http://localhost/we%20b/index.php returns '/we%20b'
*
* @return string The raw path (i.e. not urldecoded)
*
* @api
*/
public function getBasePath()
{
if (null === $this->basePath) {
$this->basePath = $this->prepareBasePath();
}
return $this->basePath;
}
/**
* Returns the root URL from which this request is executed.
*
* The base URL never ends with a /.
*
* This is similar to getBasePath(), except that it also includes the
* script filename (e.g. index.php) if one exists.
*
* @return string The raw URL (i.e. not urldecoded)
*
* @api
*/
public function getBaseUrl()
{
if (null === $this->baseUrl) {
$this->baseUrl = $this->prepareBaseUrl();
}
return $this->baseUrl;
}
/**
* Gets the request's scheme.
*
* @return string
*
* @api
*/
public function getScheme()
{
return $this->isSecure() ? 'https' : 'http';
}
/**
* Returns the port on which the request is made.
*
* This method can read the client port from the "X-Forwarded-Port" header
* when trusted proxies were set via "setTrustedProxies()".
*
* The "X-Forwarded-Port" header must contain the client port.
*
* If your reverse proxy uses a different header name than "X-Forwarded-Port",
* configure it via "setTrustedHeaderName()" with the "client-port" key.
*
* @return string
*
* @api
*/
public function getPort()
{
if ($this->isFromTrustedProxy()) {
if (self::$trustedHeaders[self::HEADER_CLIENT_PORT] && $port = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PORT])) {
return $port;
}
if (self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && 'https' === $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO], 'http')) {
return 443;
}
}
if ($host = $this->headers->get('HOST')) {
if ($host[0] === '[') {
$pos = strpos($host, ':', strrpos($host, ']'));
} else {
$pos = strrpos($host, ':');
}
if (false !== $pos) {
return (int) substr($host, $pos + 1);
}
return 'https' === $this->getScheme() ? 443 : 80;
}
return $this->server->get('SERVER_PORT');
}
/**
* Returns the user.
*
* @return string|null
*/
public function getUser()
{
return $this->headers->get('PHP_AUTH_USER');
}
/**
* Returns the password.
*
* @return string|null
*/
public function getPassword()
{
return $this->headers->get('PHP_AUTH_PW');
}
/**
* Gets the user info.
*
* @return string A user name and, optionally, scheme-specific information about how to gain authorization to access the server
*/
public function getUserInfo()
{
$userinfo = $this->getUser();
$pass = $this->getPassword();
if ('' != $pass) {
$userinfo .= ":$pass";
}
return $userinfo;
}
/**
* Returns the HTTP host being requested.
*
* The port name will be appended to the host if it's non-standard.
*
* @return string
*
* @api
*/
public function getHttpHost()
{
$scheme = $this->getScheme();
$port = $this->getPort();
if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
return $this->getHost();
}
return $this->getHost().':'.$port;
}
/**
* Returns the requested URI (path and query string).
*
* @return string The raw URI (i.e. not URI decoded)
*
* @api
*/
public function getRequestUri()
{
if (null === $this->requestUri) {
$this->requestUri = $this->prepareRequestUri();
}
return $this->requestUri;
}
/**
* Gets the scheme and HTTP host.
*
* If the URL was called with basic authentication, the user
* and the password are not added to the generated string.
*
* @return string The scheme and HTTP host
*/
public function getSchemeAndHttpHost()
{
return $this->getScheme().'://'.$this->getHttpHost();
}
/**
* Generates a normalized URI (URL) for the Request.
*
* @return string A normalized URI (URL) for the Request
*
* @see getQueryString()
*
* @api
*/
public function getUri()
{
if (null !== $qs = $this->getQueryString()) {
$qs = '?'.$qs;
}
return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
}
/**
* Generates a normalized URI for the given path.
*
* @param string $path A path to use instead of the current one
*
* @return string The normalized URI for the path
*
* @api
*/
public function getUriForPath($path)
{
return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
}
/**
* Generates the normalized query string for the Request.
*
* It builds a normalized query string, where keys/value pairs are alphabetized
* and have consistent escaping.
*
* @return string|null A normalized query string for the Request
*
* @api
*/
public function getQueryString()
{
$qs = static::normalizeQueryString($this->server->get('QUERY_STRING'));
return '' === $qs ? null : $qs;
}
/**
* Checks whether the request is secure or not.
*
* This method can read the client port from the "X-Forwarded-Proto" header
* when trusted proxies were set via "setTrustedProxies()".
*
* The "X-Forwarded-Proto" header must contain the protocol: "https" or "http".
*
* If your reverse proxy uses a different header name than "X-Forwarded-Proto"
* ("SSL_HTTPS" for instance), configure it via "setTrustedHeaderName()" with
* the "client-proto" key.
*
* @return bool
*
* @api
*/
public function isSecure()
{
if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_PROTO] && $proto = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_PROTO])) {
return in_array(strtolower(current(explode(',', $proto))), array('https', 'on', 'ssl', '1'));
}
$https = $this->server->get('HTTPS');
return !empty($https) && 'off' !== strtolower($https);
}
/**
* Returns the host name.
*
* This method can read the client port from the "X-Forwarded-Host" header
* when trusted proxies were set via "setTrustedProxies()".
*
* The "X-Forwarded-Host" header must contain the client host name.
*
* If your reverse proxy uses a different header name than "X-Forwarded-Host",
* configure it via "setTrustedHeaderName()" with the "client-host" key.
*
* @return string
*
* @throws \UnexpectedValueException when the host name is invalid
*
* @api
*/
public function getHost()
{
if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_HOST] && $host = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_HOST])) {
$elements = explode(',', $host);
$host = $elements[count($elements) - 1];
} elseif (!$host = $this->headers->get('HOST')) {
if (!$host = $this->server->get('SERVER_NAME')) {
$host = $this->server->get('SERVER_ADDR', '');
}
}
// trim and remove port number from host
// host is lowercase as per RFC 952/2181
$host = strtolower(preg_replace('/:\d+$/', '', trim($host)));
// as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
// check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
// use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) {
throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host));
}
if (count(self::$trustedHostPatterns) > 0) {
// to avoid host header injection attacks, you should provide a list of trusted host patterns
if (in_array($host, self::$trustedHosts)) {
return $host;
}
foreach (self::$trustedHostPatterns as $pattern) {
if (preg_match($pattern, $host)) {
self::$trustedHosts[] = $host;
return $host;
}
}
throw new \UnexpectedValueException(sprintf('Untrusted Host "%s"', $host));
}
return $host;
}
/**
* Sets the request method.
*
* @param string $method
*
* @api
*/
public function setMethod($method)
{
$this->method = null;
$this->server->set('REQUEST_METHOD', $method);
}
/**
* Gets the request "intended" method.
*
* If the X-HTTP-Method-Override header is set, and if the method is a POST,
* then it is used to determine the "real" intended HTTP method.
*
* The _method request parameter can also be used to determine the HTTP method,
* but only if enableHttpMethodParameterOverride() has been called.
*
* The method is always an uppercased string.
*
* @return string The request method
*
* @api
*
* @see getRealMethod()
*/
public function getMethod()
{
if (null === $this->method) {
$this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
if ('POST' === $this->method) {
if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) {
$this->method = strtoupper($method);
} elseif (self::$httpMethodParameterOverride) {
$this->method = strtoupper($this->request->get('_method', $this->query->get('_method', 'POST')));
}
}
}
return $this->method;
}
/**
* Gets the "real" request method.
*
* @return string The request method
*
* @see getMethod()
*/
public function getRealMethod()
{
return strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
}
/**
* Gets the mime type associated with the format.
*
* @param string $format The format
*
* @return string The associated mime type (null if not found)
*
* @api
*/
public function getMimeType($format)
{
if (null === static::$formats) {
static::initializeFormats();
}
return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
}
/**
* Gets the format associated with the mime type.
*
* @param string $mimeType The associated mime type
*
* @return string|null The format (null if not found)
*
* @api
*/
public function getFormat($mimeType)
{
if (false !== $pos = strpos($mimeType, ';')) {
$mimeType = substr($mimeType, 0, $pos);
}
if (null === static::$formats) {
static::initializeFormats();
}
foreach (static::$formats as $format => $mimeTypes) {
if (in_array($mimeType, (array) $mimeTypes)) {
return $format;
}
}
}
/**
* Associates a format with mime types.
*
* @param string $format The format
* @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
*
* @api
*/
public function setFormat($format, $mimeTypes)
{
if (null === static::$formats) {
static::initializeFormats();
}
static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
}
/**
* Gets the request format.
*
* Here is the process to determine the format:
*
* * format defined by the user (with setRequestFormat())
* * _format request parameter
* * $default
*
* @param string $default The default format
*
* @return string The request format
*
* @api
*/
public function getRequestFormat($default = 'html')
{
if (null === $this->format) {
$this->format = $this->get('_format', $default);
}
return $this->format;
}
/**
* Sets the request format.
*
* @param string $format The request format.
*
* @api
*/
public function setRequestFormat($format)
{
$this->format = $format;
}
/**
* Gets the format associated with the request.
*
* @return string|null The format (null if no content type is present)
*
* @api
*/
public function getContentType()
{
return $this->getFormat($this->headers->get('CONTENT_TYPE'));
}
/**
* Sets the default locale.
*
* @param string $locale
*
* @api
*/
public function setDefaultLocale($locale)
{
$this->defaultLocale = $locale;
if (null === $this->locale) {
$this->setPhpDefaultLocale($locale);
}
}
/**
* Get the default locale.
*
* @return string
*/
public function getDefaultLocale()
{
return $this->defaultLocale;
}
/**
* Sets the locale.
*
* @param string $locale
*
* @api
*/
public function setLocale($locale)
{
$this->setPhpDefaultLocale($this->locale = $locale);
}
/**
* Get the locale.
*
* @return string
*/
public function getLocale()
{
return null === $this->locale ? $this->defaultLocale : $this->locale;
}
/**
* Checks if the request method is of specified type.
*
* @param string $method Uppercase request method (GET, POST etc).
*
* @return bool
*/
public function isMethod($method)
{
return $this->getMethod() === strtoupper($method);
}
/**
* Checks whether the method is safe or not.
*
* @return bool
*
* @api
*/
public function isMethodSafe()
{
return in_array($this->getMethod(), array('GET', 'HEAD'));
}
/**
* Returns the request body content.
*
* @param bool $asResource If true, a resource will be returned
*
* @return string|resource The request body content or a resource to read the body stream.
*
* @throws \LogicException
*/
public function getContent($asResource = false)
{
if (PHP_VERSION_ID < 50600 && (false === $this->content || (true === $asResource && null !== $this->content))) {
throw new \LogicException('getContent() can only be called once when using the resource return type and PHP below 5.6.');
}
if (true === $asResource) {
$this->content = false;
return fopen('php://input', 'rb');
}
if (null === $this->content) {
$this->content = file_get_contents('php://input');
}
return $this->content;
}
/**
* Gets the Etags.
*
* @return array The entity tags
*/
public function getETags()
{
return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
}
/**
* @return bool
*/
public function isNoCache()
{
return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
}
/**
* Returns the preferred language.
*
* @param array $locales An array of ordered available locales
*
* @return string|null The preferred locale
*
* @api
*/
public function getPreferredLanguage(array $locales = null)
{
$preferredLanguages = $this->getLanguages();
if (empty($locales)) {
return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
}
if (!$preferredLanguages) {
return $locales[0];
}
$extendedPreferredLanguages = array();
foreach ($preferredLanguages as $language) {
$extendedPreferredLanguages[] = $language;
if (false !== $position = strpos($language, '_')) {
$superLanguage = substr($language, 0, $position);
if (!in_array($superLanguage, $preferredLanguages)) {
$extendedPreferredLanguages[] = $superLanguage;
}
}
}
$preferredLanguages = array_values(array_intersect($extendedPreferredLanguages, $locales));
return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
}
/**
* Gets a list of languages acceptable by the client browser.
*
* @return array Languages ordered in the user browser preferences
*
* @api
*/
public function getLanguages()
{
if (null !== $this->languages) {
return $this->languages;
}
$languages = AcceptHeader::fromString($this->headers->get('Accept-Language'))->all();
$this->languages = array();
foreach ($languages as $lang => $acceptHeaderItem) {
if (false !== strpos($lang, '-')) {
$codes = explode('-', $lang);
if ('i' === $codes[0]) {
// Language not listed in ISO 639 that are not variants
// of any listed language, which can be registered with the
// i-prefix, such as i-cherokee
if (count($codes) > 1) {
$lang = $codes[1];
}
} else {
for ($i = 0, $max = count($codes); $i < $max; ++$i) {
if ($i === 0) {
$lang = strtolower($codes[0]);
} else {
$lang .= '_'.strtoupper($codes[$i]);
}
}
}
}
$this->languages[] = $lang;
}
return $this->languages;
}
/**
* Gets a list of charsets acceptable by the client browser.
*
* @return array List of charsets in preferable order
*
* @api
*/
public function getCharsets()
{
if (null !== $this->charsets) {
return $this->charsets;
}
return $this->charsets = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Charset'))->all());
}
/**
* Gets a list of encodings acceptable by the client browser.
*
* @return array List of encodings in preferable order
*/
public function getEncodings()
{
if (null !== $this->encodings) {
return $this->encodings;
}
return $this->encodings = array_keys(AcceptHeader::fromString($this->headers->get('Accept-Encoding'))->all());
}
/**
* Gets a list of content types acceptable by the client browser.
*
* @return array List of content types in preferable order
*
* @api
*/
public function getAcceptableContentTypes()
{
if (null !== $this->acceptableContentTypes) {
return $this->acceptableContentTypes;
}
return $this->acceptableContentTypes = array_keys(AcceptHeader::fromString($this->headers->get('Accept'))->all());
}
/**
* Returns true if the request is a XMLHttpRequest.
*
* It works if your JavaScript library sets an X-Requested-With HTTP header.
* It is known to work with common JavaScript frameworks:
*
* @link http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
*
* @return bool true if the request is an XMLHttpRequest, false otherwise
*
* @api
*/
public function isXmlHttpRequest()
{
return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}
/*
* The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
*
* Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
*
* Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
*/
protected function prepareRequestUri()
{
$requestUri = '';
if ($this->headers->has('X_ORIGINAL_URL')) {
// IIS with Microsoft Rewrite Module
$requestUri = $this->headers->get('X_ORIGINAL_URL');
$this->headers->remove('X_ORIGINAL_URL');
$this->server->remove('HTTP_X_ORIGINAL_URL');
$this->server->remove('UNENCODED_URL');
$this->server->remove('IIS_WasUrlRewritten');
} elseif ($this->headers->has('X_REWRITE_URL')) {
// IIS with ISAPI_Rewrite
$requestUri = $this->headers->get('X_REWRITE_URL');
$this->headers->remove('X_REWRITE_URL');
} elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
// IIS7 with URL Rewrite: make sure we get the unencoded URL (double slash problem)
$requestUri = $this->server->get('UNENCODED_URL');
$this->server->remove('UNENCODED_URL');
$this->server->remove('IIS_WasUrlRewritten');
} elseif ($this->server->has('REQUEST_URI')) {
$requestUri = $this->server->get('REQUEST_URI');
// HTTP proxy reqs setup request URI with scheme and host [and port] + the URL path, only use URL path
$schemeAndHttpHost = $this->getSchemeAndHttpHost();
if (strpos($requestUri, $schemeAndHttpHost) === 0) {
$requestUri = substr($requestUri, strlen($schemeAndHttpHost));
}
} elseif ($this->server->has('ORIG_PATH_INFO')) {
// IIS 5.0, PHP as CGI
$requestUri = $this->server->get('ORIG_PATH_INFO');
if ('' != $this->server->get('QUERY_STRING')) {
$requestUri .= '?'.$this->server->get('QUERY_STRING');
}
$this->server->remove('ORIG_PATH_INFO');
}
// normalize the request URI to ease creating sub-requests from this request
$this->server->set('REQUEST_URI', $requestUri);
return $requestUri;
}
/**
* Prepares the base URL.
*
* @return string
*/
protected function prepareBaseUrl()
{
$filename = basename($this->server->get('SCRIPT_FILENAME'));
if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
$baseUrl = $this->server->get('SCRIPT_NAME');
} elseif (basename($this->server->get('PHP_SELF')) === $filename) {
$baseUrl = $this->server->get('PHP_SELF');
} elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
$baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
} else {
// Backtrack up the script_filename to find the portion matching
// php_self
$path = $this->server->get('PHP_SELF', '');
$file = $this->server->get('SCRIPT_FILENAME', '');
$segs = explode('/', trim($file, '/'));
$segs = array_reverse($segs);
$index = 0;
$last = count($segs);
$baseUrl = '';
do {
$seg = $segs[$index];
$baseUrl = '/'.$seg.$baseUrl;
++$index;
} while ($last > $index && (false !== $pos = strpos($path, $baseUrl)) && 0 != $pos);
}
// Does the baseUrl have anything in common with the request_uri?
$requestUri = $this->getRequestUri();
if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, $baseUrl)) {
// full $baseUrl matches
return $prefix;
}
if ($baseUrl && false !== $prefix = $this->getUrlencodedPrefix($requestUri, rtrim(dirname($baseUrl), '/').'/')) {
// directory portion of $baseUrl matches
return rtrim($prefix, '/');
}
$truncatedRequestUri = $requestUri;
if (false !== $pos = strpos($requestUri, '?')) {
$truncatedRequestUri = substr($requestUri, 0, $pos);
}
$basename = basename($baseUrl);
if (empty($basename) || !strpos(rawurldecode($truncatedRequestUri), $basename)) {
// no match whatsoever; set it blank
return '';
}
// If using mod_rewrite or ISAPI_Rewrite strip the script filename
// out of baseUrl. $pos !== 0 makes sure it is not matching a value
// from PATH_INFO or QUERY_STRING
if (strlen($requestUri) >= strlen($baseUrl) && (false !== $pos = strpos($requestUri, $baseUrl)) && $pos !== 0) {
$baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
}
return rtrim($baseUrl, '/');
}
/**
* Prepares the base path.
*
* @return string base path
*/
protected function prepareBasePath()
{
$filename = basename($this->server->get('SCRIPT_FILENAME'));
$baseUrl = $this->getBaseUrl();
if (empty($baseUrl)) {
return '';
}
if (basename($baseUrl) === $filename) {
$basePath = dirname($baseUrl);
} else {
$basePath = $baseUrl;
}
if ('\\' === DIRECTORY_SEPARATOR) {
$basePath = str_replace('\\', '/', $basePath);
}
return rtrim($basePath, '/');
}
/**
* Prepares the path info.
*
* @return string path info
*/
protected function preparePathInfo()
{
$baseUrl = $this->getBaseUrl();
if (null === ($requestUri = $this->getRequestUri())) {
return '/';
}
$pathInfo = '/';
// Remove the query string from REQUEST_URI
if ($pos = strpos($requestUri, '?')) {
$requestUri = substr($requestUri, 0, $pos);
}
if (null !== $baseUrl && false === $pathInfo = substr($requestUri, strlen($baseUrl))) {
// If substr() returns false then PATH_INFO is set to an empty string
return '/';
} elseif (null === $baseUrl) {
return $requestUri;
}
return (string) $pathInfo;
}
/**
* Initializes HTTP request formats.
*/
protected static function initializeFormats()
{
static::$formats = array(
'html' => array('text/html', 'application/xhtml+xml'),
'txt' => array('text/plain'),
'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
'css' => array('text/css'),
'json' => array('application/json', 'application/x-json'),
'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
'rdf' => array('application/rdf+xml'),
'atom' => array('application/atom+xml'),
'rss' => array('application/rss+xml'),
'form' => array('application/x-www-form-urlencoded'),
);
}
/**
* Sets the default PHP locale.
*
* @param string $locale
*/
private function setPhpDefaultLocale($locale)
{
// if either the class Locale doesn't exist, or an exception is thrown when
// setting the default locale, the intl module is not installed, and
// the call can be ignored:
try {
if (class_exists('Locale', false)) {
\Locale::setDefault($locale);
}
} catch (\Exception $e) {
}
}
/*
* Returns the prefix as encoded in the string when the string starts with
* the given prefix, false otherwise.
*
* @param string $string The urlencoded string
* @param string $prefix The prefix not encoded
*
* @return string|false The prefix as it is encoded in $string, or false
*/
private function getUrlencodedPrefix($string, $prefix)
{
if (0 !== strpos(rawurldecode($string), $prefix)) {
return false;
}
$len = strlen($prefix);
if (preg_match(sprintf('#^(%%[[:xdigit:]]{2}|.){%d}#', $len), $string, $match)) {
return $match[0];
}
return false;
}
private static function createRequestFromFactory(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
{
if (self::$requestFactory) {
$request = call_user_func(self::$requestFactory, $query, $request, $attributes, $cookies, $files, $server, $content);
if (!$request instanceof Request) {
throw new \LogicException('The Request factory must return an instance of Symfony\Component\HttpFoundation\Request.');
}
return $request;
}
return new static($query, $request, $attributes, $cookies, $files, $server, $content);
}
private function isFromTrustedProxy()
{
return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'), self::$trustedProxies);
}
}
| thelastsoulja/Cpanet | vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Request.php | PHP | mit | 58,515 |
var chownr = require('chownr')
var tar = require('tar-stream')
var pump = require('pump')
var mkdirp = require('mkdirp')
var fs = require('fs')
var path = require('path')
var os = require('os')
var win32 = os.platform() === 'win32'
var noop = function () {}
var echo = function (name) {
return name
}
var normalize = !win32 ? echo : function (name) {
return name.replace(/\\/g, '/').replace(/[:?<>|]/g, '_')
}
var statAll = function (fs, stat, cwd, ignore, entries, sort) {
var queue = entries || ['.']
return function loop (callback) {
if (!queue.length) return callback()
var next = queue.shift()
var nextAbs = path.join(cwd, next)
stat(nextAbs, function (err, stat) {
if (err) return callback(err)
if (!stat.isDirectory()) return callback(null, next, stat)
fs.readdir(nextAbs, function (err, files) {
if (err) return callback(err)
if (sort) files.sort()
for (var i = 0; i < files.length; i++) {
if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i]))
}
callback(null, next, stat)
})
})
}
}
var strip = function (map, level) {
return function (header) {
header.name = header.name.split('/').slice(level).join('/')
var linkname = header.linkname
if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) {
header.linkname = linkname.split('/').slice(level).join('/')
}
return map(header)
}
}
exports.pack = function (cwd, opts) {
if (!cwd) cwd = '.'
if (!opts) opts = {}
var xfs = opts.fs || fs
var ignore = opts.ignore || opts.filter || noop
var map = opts.map || noop
var mapStream = opts.mapStream || echo
var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort)
var strict = opts.strict !== false
var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
var pack = opts.pack || tar.pack()
var finish = opts.finish || noop
if (opts.strip) map = strip(map, opts.strip)
if (opts.readable) {
dmode |= parseInt(555, 8)
fmode |= parseInt(444, 8)
}
if (opts.writable) {
dmode |= parseInt(333, 8)
fmode |= parseInt(222, 8)
}
var onsymlink = function (filename, header) {
xfs.readlink(path.join(cwd, filename), function (err, linkname) {
if (err) return pack.destroy(err)
header.linkname = normalize(linkname)
pack.entry(header, onnextentry)
})
}
var onstat = function (err, filename, stat) {
if (err) return pack.destroy(err)
if (!filename) {
if (opts.finalize !== false) pack.finalize()
return finish(pack)
}
if (stat.isSocket()) return onnextentry() // tar does not support sockets...
var header = {
name: normalize(filename),
mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask,
mtime: stat.mtime,
size: stat.size,
type: 'file',
uid: stat.uid,
gid: stat.gid
}
if (stat.isDirectory()) {
header.size = 0
header.type = 'directory'
header = map(header) || header
return pack.entry(header, onnextentry)
}
if (stat.isSymbolicLink()) {
header.size = 0
header.type = 'symlink'
header = map(header) || header
return onsymlink(filename, header)
}
// TODO: add fifo etc...
header = map(header) || header
if (!stat.isFile()) {
if (strict) return pack.destroy(new Error('unsupported type for ' + filename))
return onnextentry()
}
var entry = pack.entry(header, onnextentry)
if (!entry) return
var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header)
rs.on('error', function (err) { // always forward errors on destroy
entry.destroy(err)
})
pump(rs, entry)
}
var onnextentry = function (err) {
if (err) return pack.destroy(err)
statNext(onstat)
}
onnextentry()
return pack
}
var head = function (list) {
return list.length ? list[list.length - 1] : null
}
var processGetuid = function () {
return process.getuid ? process.getuid() : -1
}
var processUmask = function () {
return process.umask ? process.umask() : 0
}
exports.extract = function (cwd, opts) {
if (!cwd) cwd = '.'
if (!opts) opts = {}
var xfs = opts.fs || fs
var ignore = opts.ignore || opts.filter || noop
var map = opts.map || noop
var mapStream = opts.mapStream || echo
var own = opts.chown !== false && !win32 && processGetuid() === 0
var extract = opts.extract || tar.extract()
var stack = []
var now = new Date()
var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask()
var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0
var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0
var strict = opts.strict !== false
if (opts.strip) map = strip(map, opts.strip)
if (opts.readable) {
dmode |= parseInt(555, 8)
fmode |= parseInt(444, 8)
}
if (opts.writable) {
dmode |= parseInt(333, 8)
fmode |= parseInt(222, 8)
}
var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry
var top
while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop()
if (!top) return cb()
xfs.utimes(top[0], now, top[1], cb)
}
var utimes = function (name, header, cb) {
if (opts.utimes === false) return cb()
if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb)
if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link?
xfs.utimes(name, now, header.mtime, function (err) {
if (err) return cb(err)
utimesParent(name, cb)
})
}
var chperm = function (name, header, cb) {
var link = header.type === 'symlink'
var chmod = link ? xfs.lchmod : xfs.chmod
var chown = link ? xfs.lchown : xfs.chown
if (!chmod) return cb()
var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask
chmod(name, mode, function (err) {
if (err) return cb(err)
if (!own) return cb()
if (!chown) return cb()
chown(name, header.uid, header.gid, cb)
})
}
extract.on('entry', function (header, stream, next) {
header = map(header) || header
header.name = normalize(header.name)
var name = path.join(cwd, path.join('/', header.name))
if (ignore(name, header)) {
stream.resume()
return next()
}
var stat = function (err) {
if (err) return next(err)
utimes(name, header, function (err) {
if (err) return next(err)
if (win32) return next()
chperm(name, header, next)
})
}
var onsymlink = function () {
if (win32) return next() // skip symlinks on win for now before it can be tested
xfs.unlink(name, function () {
xfs.symlink(header.linkname, name, stat)
})
}
var onlink = function () {
if (win32) return next() // skip links on win for now before it can be tested
xfs.unlink(name, function () {
var srcpath = path.join(cwd, path.join('/', header.linkname))
xfs.link(srcpath, name, function (err) {
if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {
stream = xfs.createReadStream(srcpath)
return onfile()
}
stat(err)
})
})
}
var onfile = function () {
var ws = xfs.createWriteStream(name)
var rs = mapStream(stream, header)
ws.on('error', function (err) { // always forward errors on destroy
rs.destroy(err)
})
pump(rs, ws, function (err) {
if (err) return next(err)
ws.on('close', stat)
})
}
if (header.type === 'directory') {
stack.push([name, header.mtime])
return mkdirfix(name, {
fs: xfs, own: own, uid: header.uid, gid: header.gid
}, stat)
}
var dir = path.dirname(name)
validate(xfs, dir, path.join(cwd, '.'), function (err, valid) {
if (err) return next(err)
if (!valid) return next(new Error(dir + ' is not a valid path'))
mkdirfix(dir, {
fs: xfs, own: own, uid: header.uid, gid: header.gid
}, function (err) {
if (err) return next(err)
switch (header.type) {
case 'file': return onfile()
case 'link': return onlink()
case 'symlink': return onsymlink()
}
if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')'))
stream.resume()
next()
})
})
})
if (opts.finish) extract.on('finish', opts.finish)
return extract
}
function validate (fs, name, root, cb) {
if (name === root) return cb(null, true)
fs.lstat(name, function (err, st) {
if (err && err.code !== 'ENOENT') return cb(err)
if (err || st.isDirectory()) return validate(fs, path.join(name, '..'), root, cb)
cb(null, false)
})
}
function mkdirfix (name, opts, cb) {
mkdirp(name, {fs: opts.fs}, function (err, made) {
if (!err && made && opts.own) {
chownr(made, opts.uid, opts.gid, cb)
} else {
cb(err)
}
})
}
| february29/Learning | web/vue/AccountBook-Express/node_modules/.staging/tar-fs-f8fd0786/index.js | JavaScript | mit | 9,349 |
class AddProfileBackgroundFieldsToUser < ActiveRecord::Migration
def change
add_column :users, :show_profile_background, :boolean, default: true
add_column :users, :profile_background_photo_id, :integer
end
end
| arnkorty/photographer-io | db/migrate/20130731183731_add_profile_background_fields_to_user.rb | Ruby | mit | 223 |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2015, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link http://codeigniter.com
* @since Version 1.0.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Database Forge Class
*
* @category Database
* @author EllisLab Dev Team
* @link http://codeigniter.com/user_guide/database/
*/
abstract class CI_DB_forge {
/**
* Database object
*
* @var object
*/
protected $db;
/**
* Fields data
*
* @var array
*/
public $fields = array();
/**
* Keys data
*
* @var array
*/
public $keys = array();
/**
* Primary Keys data
*
* @var array
*/
public $primary_keys = array();
/**
* Database character set
*
* @var string
*/
public $db_char_set = '';
// --------------------------------------------------------------------
/**
* CREATE DATABASE statement
*
* @var string
*/
protected $_create_database = 'CREATE DATABASE %s';
/**
* DROP DATABASE statement
*
* @var string
*/
protected $_drop_database = 'DROP DATABASE %s';
/**
* CREATE TABLE statement
*
* @var string
*/
protected $_create_table = "%s %s (%s\n)";
/**
* CREATE TABLE IF statement
*
* @var string
*/
protected $_create_table_if = 'CREATE TABLE IF NOT EXISTS';
/**
* CREATE TABLE keys flag
*
* Whether table keys are created from within the
* CREATE TABLE statement.
*
* @var bool
*/
protected $_create_table_keys = FALSE;
/**
* DROP TABLE IF EXISTS statement
*
* @var string
*/
protected $_drop_table_if = 'DROP TABLE IF EXISTS';
/**
* RENAME TABLE statement
*
* @var string
*/
protected $_rename_table = 'ALTER TABLE %s RENAME TO %s;';
/**
* UNSIGNED support
*
* @var bool|array
*/
protected $_unsigned = TRUE;
/**
* NULL value representation in CREATE/ALTER TABLE statements
*
* @var string
*/
protected $_null = '';
/**
* DEFAULT value representation in CREATE/ALTER TABLE statements
*
* @var string
*/
protected $_default = ' DEFAULT ';
// --------------------------------------------------------------------
/**
* Class constructor
*
* @param object &$db Database object
* @return void
*/
public function __construct(&$db)
{
$this->db =& $db;
log_message('info', 'Database Forge Class Initialized');
}
// --------------------------------------------------------------------
/**
* Create database
*
* @param string $db_name
* @return bool
*/
public function create_database($db_name)
{
if ($this->_create_database === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
elseif ( ! $this->db->query(sprintf($this->_create_database, $db_name, $this->db->char_set, $this->db->dbcollat)))
{
return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE;
}
if ( ! empty($this->db->data_cache['db_names']))
{
$this->db->data_cache['db_names'][] = $db_name;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Drop database
*
* @param string $db_name
* @return bool
*/
public function drop_database($db_name)
{
if ($this->_drop_database === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
elseif ( ! $this->db->query(sprintf($this->_drop_database, $db_name)))
{
return ($this->db->db_debug) ? $this->db->display_error('db_unable_to_drop') : FALSE;
}
if ( ! empty($this->db->data_cache['db_names']))
{
$key = array_search(strtolower($db_name), array_map('strtolower', $this->db->data_cache['db_names']), TRUE);
if ($key !== FALSE)
{
unset($this->db->data_cache['db_names'][$key]);
}
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Add Key
*
* @param string $key
* @param bool $primary
* @return CI_DB_forge
*/
public function add_key($key, $primary = FALSE)
{
// DO NOT change this! This condition is only applicable
// for PRIMARY keys because you can only have one such,
// and therefore all fields you add to it will be included
// in the same, composite PRIMARY KEY.
//
// It's not the same for regular indexes.
if ($primary === TRUE && is_array($key))
{
foreach ($key as $one)
{
$this->add_key($one, $primary);
}
return $this;
}
if ($primary === TRUE)
{
$this->primary_keys[] = $key;
}
else
{
$this->keys[] = $key;
}
return $this;
}
// --------------------------------------------------------------------
/**
* Add Field
*
* @param array $field
* @return CI_DB_forge
*/
public function add_field($field)
{
if (is_string($field))
{
if ($field === 'id')
{
$this->add_field(array(
'id' => array(
'type' => 'INT',
'constraint' => 9,
'auto_increment' => TRUE
)
));
$this->add_key('id', TRUE);
}
else
{
if (strpos($field, ' ') === FALSE)
{
show_error('Field information is required for that operation.');
}
$this->fields[] = $field;
}
}
if (is_array($field))
{
$this->fields = array_merge($this->fields, $field);
}
return $this;
}
// --------------------------------------------------------------------
/**
* Create Table
*
* @param string $table Table name
* @param bool $if_not_exists Whether to add IF NOT EXISTS condition
* @param array $attributes Associative array of table attributes
* @return bool
*/
public function create_table($table, $if_not_exists = FALSE, array $attributes = array())
{
if ($table === '')
{
show_error('A table name is required for that operation.');
}
else
{
$table = $this->db->dbprefix.$table;
}
if (count($this->fields) === 0)
{
show_error('Field information is required.');
}
$sql = $this->_create_table($table, $if_not_exists, $attributes);
if (is_bool($sql))
{
$this->_reset();
if ($sql === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
}
if (($result = $this->db->query($sql)) !== FALSE)
{
empty($this->db->data_cache['table_names']) OR $this->db->data_cache['table_names'][] = $table;
// Most databases don't support creating indexes from within the CREATE TABLE statement
if ( ! empty($this->keys))
{
for ($i = 0, $sqls = $this->_process_indexes($table), $c = count($sqls); $i < $c; $i++)
{
$this->db->query($sqls[$i]);
}
}
}
$this->_reset();
return $result;
}
// --------------------------------------------------------------------
/**
* Create Table
*
* @param string $table Table name
* @param bool $if_not_exists Whether to add 'IF NOT EXISTS' condition
* @param array $attributes Associative array of table attributes
* @return mixed
*/
protected function _create_table($table, $if_not_exists, $attributes)
{
if ($if_not_exists === TRUE && $this->_create_table_if === FALSE)
{
if ($this->db->table_exists($table))
{
return TRUE;
}
else
{
$if_not_exists = FALSE;
}
}
$sql = ($if_not_exists)
? sprintf($this->_create_table_if, $this->db->escape_identifiers($table))
: 'CREATE TABLE';
$columns = $this->_process_fields(TRUE);
for ($i = 0, $c = count($columns); $i < $c; $i++)
{
$columns[$i] = ($columns[$i]['_literal'] !== FALSE)
? "\n\t".$columns[$i]['_literal']
: "\n\t".$this->_process_column($columns[$i]);
}
$columns = implode(',', $columns)
.$this->_process_primary_keys($table);
// Are indexes created from within the CREATE TABLE statement? (e.g. in MySQL)
if ($this->_create_table_keys === TRUE)
{
$columns .= $this->_process_indexes($table);
}
// _create_table will usually have the following format: "%s %s (%s\n)"
$sql = sprintf($this->_create_table.'%s',
$sql,
$this->db->escape_identifiers($table),
$columns,
$this->_create_table_attr($attributes)
);
return $sql;
}
// --------------------------------------------------------------------
/**
* CREATE TABLE attributes
*
* @param array $attributes Associative array of table attributes
* @return string
*/
protected function _create_table_attr($attributes)
{
$sql = '';
foreach (array_keys($attributes) as $key)
{
if (is_string($key))
{
$sql .= ' '.strtoupper($key).' '.$attributes[$key];
}
}
return $sql;
}
// --------------------------------------------------------------------
/**
* Drop Table
*
* @param string $table_name Table name
* @param bool $if_exists Whether to add an IF EXISTS condition
* @return bool
*/
public function drop_table($table_name, $if_exists = FALSE)
{
if ($table_name === '')
{
return ($this->db->db_debug) ? $this->db->display_error('db_table_name_required') : FALSE;
}
if (($query = $this->_drop_table($this->db->dbprefix.$table_name, $if_exists)) === TRUE)
{
return TRUE;
}
$query = $this->db->query($query);
// Update table list cache
if ($query && ! empty($this->db->data_cache['table_names']))
{
$key = array_search(strtolower($this->db->dbprefix.$table_name), array_map('strtolower', $this->db->data_cache['table_names']), TRUE);
if ($key !== FALSE)
{
unset($this->db->data_cache['table_names'][$key]);
}
}
return $query;
}
// --------------------------------------------------------------------
/**
* Drop Table
*
* Generates a platform-specific DROP TABLE string
*
* @param string $table Table name
* @param bool $if_exists Whether to add an IF EXISTS condition
* @return string
*/
protected function _drop_table($table, $if_exists)
{
$sql = 'DROP TABLE';
if ($if_exists)
{
if ($this->_drop_table_if === FALSE)
{
if ( ! $this->db->table_exists($table))
{
return TRUE;
}
}
else
{
$sql = sprintf($this->_drop_table_if, $this->db->escape_identifiers($table));
}
}
return $sql.' '.$this->db->escape_identifiers($table);
}
// --------------------------------------------------------------------
/**
* Rename Table
*
* @param string $table_name Old table name
* @param string $new_table_name New table name
* @return bool
*/
public function rename_table($table_name, $new_table_name)
{
if ($table_name === '' OR $new_table_name === '')
{
show_error('A table name is required for that operation.');
return FALSE;
}
elseif ($this->_rename_table === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
$result = $this->db->query(sprintf($this->_rename_table,
$this->db->escape_identifiers($this->db->dbprefix.$table_name),
$this->db->escape_identifiers($this->db->dbprefix.$new_table_name))
);
if ($result && ! empty($this->db->data_cache['table_names']))
{
$key = array_search(strtolower($this->db->dbprefix.$table_name), array_map('strtolower', $this->db->data_cache['table_names']), TRUE);
if ($key !== FALSE)
{
$this->db->data_cache['table_names'][$key] = $this->db->dbprefix.$new_table_name;
}
}
return $result;
}
// --------------------------------------------------------------------
/**
* Column Add
*
* @todo Remove deprecated $_after option in 3.1+
* @param string $table Table name
* @param array $field Column definition
* @param string $_after Column for AFTER clause (deprecated)
* @return bool
*/
public function add_column($table, $field, $_after = NULL)
{
// Work-around for literal column definitions
is_array($field) OR $field = array($field);
foreach (array_keys($field) as $k)
{
// Backwards-compatibility work-around for MySQL/CUBRID AFTER clause (remove in 3.1+)
if ($_after !== NULL && is_array($field[$k]) && ! isset($field[$k]['after']))
{
$field[$k]['after'] = $_after;
}
$this->add_field(array($k => $field[$k]));
}
$sqls = $this->_alter_table('ADD', $this->db->dbprefix.$table, $this->_process_fields());
$this->_reset();
if ($sqls === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
for ($i = 0, $c = count($sqls); $i < $c; $i++)
{
if ($this->db->query($sqls[$i]) === FALSE)
{
return FALSE;
}
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* Column Drop
*
* @param string $table Table name
* @param string $column_name Column name
* @return bool
*/
public function drop_column($table, $column_name)
{
$sql = $this->_alter_table('DROP', $this->db->dbprefix.$table, $column_name);
if ($sql === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
return $this->db->query($sql);
}
// --------------------------------------------------------------------
/**
* Column Modify
*
* @param string $table Table name
* @param string $field Column definition
* @return bool
*/
public function modify_column($table, $field)
{
// Work-around for literal column definitions
is_array($field) OR $field = array($field);
foreach (array_keys($field) as $k)
{
$this->add_field(array($k => $field[$k]));
}
if (count($this->fields) === 0)
{
show_error('Field information is required.');
}
$sqls = $this->_alter_table('CHANGE', $this->db->dbprefix.$table, $this->_process_fields());
$this->_reset();
if ($sqls === FALSE)
{
return ($this->db->db_debug) ? $this->db->display_error('db_unsupported_feature') : FALSE;
}
for ($i = 0, $c = count($sqls); $i < $c; $i++)
{
if ($this->db->query($sqls[$i]) === FALSE)
{
return FALSE;
}
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* ALTER TABLE
*
* @param string $alter_type ALTER type
* @param string $table Table name
* @param mixed $field Column definition
* @return string|string[]
*/
protected function _alter_table($alter_type, $table, $field)
{
$sql = 'ALTER TABLE '.$this->db->escape_identifiers($table).' ';
// DROP has everything it needs now.
if ($alter_type === 'DROP')
{
return $sql.'DROP COLUMN '.$this->db->escape_identifiers($field);
}
$sql .= ($alter_type === 'ADD')
? 'ADD '
: $alter_type.' COLUMN ';
$sqls = array();
for ($i = 0, $c = count($field); $i < $c; $i++)
{
$sqls[] = $sql
.($field[$i]['_literal'] !== FALSE ? $field[$i]['_literal'] : $this->_process_column($field[$i]));
}
return $sqls;
}
// --------------------------------------------------------------------
/**
* Process fields
*
* @param bool $create_table
* @return array
*/
protected function _process_fields($create_table = FALSE)
{
$fields = array();
foreach ($this->fields as $key => $attributes)
{
if (is_int($key) && ! is_array($attributes))
{
$fields[] = array('_literal' => $attributes);
continue;
}
$attributes = array_change_key_case($attributes, CASE_UPPER);
if ($create_table === TRUE && empty($attributes['TYPE']))
{
continue;
}
isset($attributes['TYPE']) && $this->_attr_type($attributes);
$field = array(
'name' => $key,
'new_name' => isset($attributes['NAME']) ? $attributes['NAME'] : NULL,
'type' => isset($attributes['TYPE']) ? $attributes['TYPE'] : NULL,
'length' => '',
'unsigned' => '',
'null' => '',
'unique' => '',
'default' => '',
'auto_increment' => '',
'_literal' => FALSE
);
isset($attributes['TYPE']) && $this->_attr_unsigned($attributes, $field);
if ($create_table === FALSE)
{
if (isset($attributes['AFTER']))
{
$field['after'] = $attributes['AFTER'];
}
elseif (isset($attributes['FIRST']))
{
$field['first'] = (bool) $attributes['FIRST'];
}
}
$this->_attr_default($attributes, $field);
if (isset($attributes['NULL']))
{
if ($attributes['NULL'] === TRUE)
{
$field['null'] = empty($this->_null) ? '' : ' '.$this->_null;
}
else
{
$field['null'] = ' NOT NULL';
}
}
elseif ($create_table === TRUE)
{
$field['null'] = ' NOT NULL';
}
$this->_attr_auto_increment($attributes, $field);
$this->_attr_unique($attributes, $field);
if (isset($attributes['COMMENT']))
{
$field['comment'] = $this->db->escape($attributes['COMMENT']);
}
if (isset($attributes['TYPE']) && ! empty($attributes['CONSTRAINT']))
{
switch (strtoupper($attributes['TYPE']))
{
case 'ENUM':
case 'SET':
$attributes['CONSTRAINT'] = $this->db->escape($attributes['CONSTRAINT']);
default:
$field['length'] = is_array($attributes['CONSTRAINT'])
? '('.implode(',', $attributes['CONSTRAINT']).')'
: '('.$attributes['CONSTRAINT'].')';
break;
}
}
$fields[] = $field;
}
return $fields;
}
// --------------------------------------------------------------------
/**
* Process column
*
* @param array $field
* @return string
*/
protected function _process_column($field)
{
return $this->db->escape_identifiers($field['name'])
.' '.$field['type'].$field['length']
.$field['unsigned']
.$field['default']
.$field['null']
.$field['auto_increment']
.$field['unique'];
}
// --------------------------------------------------------------------
/**
* Field attribute TYPE
*
* Performs a data type mapping between different databases.
*
* @param array &$attributes
* @return void
*/
protected function _attr_type(&$attributes)
{
// Usually overridden by drivers
}
// --------------------------------------------------------------------
/**
* Field attribute UNSIGNED
*
* Depending on the _unsigned property value:
*
* - TRUE will always set $field['unsigned'] to 'UNSIGNED'
* - FALSE will always set $field['unsigned'] to ''
* - array(TYPE) will set $field['unsigned'] to 'UNSIGNED',
* if $attributes['TYPE'] is found in the array
* - array(TYPE => UTYPE) will change $field['type'],
* from TYPE to UTYPE in case of a match
*
* @param array &$attributes
* @param array &$field
* @return void
*/
protected function _attr_unsigned(&$attributes, &$field)
{
if (empty($attributes['UNSIGNED']) OR $attributes['UNSIGNED'] !== TRUE)
{
return;
}
// Reset the attribute in order to avoid issues if we do type conversion
$attributes['UNSIGNED'] = FALSE;
if (is_array($this->_unsigned))
{
foreach (array_keys($this->_unsigned) as $key)
{
if (is_int($key) && strcasecmp($attributes['TYPE'], $this->_unsigned[$key]) === 0)
{
$field['unsigned'] = ' UNSIGNED';
return;
}
elseif (is_string($key) && strcasecmp($attributes['TYPE'], $key) === 0)
{
$field['type'] = $key;
return;
}
}
return;
}
$field['unsigned'] = ($this->_unsigned === TRUE) ? ' UNSIGNED' : '';
}
// --------------------------------------------------------------------
/**
* Field attribute DEFAULT
*
* @param array &$attributes
* @param array &$field
* @return void
*/
protected function _attr_default(&$attributes, &$field)
{
if ($this->_default === FALSE)
{
return;
}
if (array_key_exists('DEFAULT', $attributes))
{
if ($attributes['DEFAULT'] === NULL)
{
$field['default'] = empty($this->_null) ? '' : $this->_default.$this->_null;
// Override the NULL attribute if that's our default
$attributes['NULL'] = TRUE;
$field['null'] = empty($this->_null) ? '' : ' '.$this->_null;
}
else
{
$field['default'] = $this->_default.$this->db->escape($attributes['DEFAULT']);
}
}
}
// --------------------------------------------------------------------
/**
* Field attribute UNIQUE
*
* @param array &$attributes
* @param array &$field
* @return void
*/
protected function _attr_unique(&$attributes, &$field)
{
if ( ! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === TRUE)
{
$field['unique'] = ' UNIQUE';
}
}
// --------------------------------------------------------------------
/**
* Field attribute AUTO_INCREMENT
*
* @param array &$attributes
* @param array &$field
* @return void
*/
protected function _attr_auto_increment(&$attributes, &$field)
{
if ( ! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === TRUE && stripos($field['type'], 'int') !== FALSE)
{
$field['auto_increment'] = ' AUTO_INCREMENT';
}
}
// --------------------------------------------------------------------
/**
* Process primary keys
*
* @param string $table Table name
* @return string
*/
protected function _process_primary_keys($table)
{
$sql = '';
for ($i = 0, $c = count($this->primary_keys); $i < $c; $i++)
{
if ( ! isset($this->fields[$this->primary_keys[$i]]))
{
unset($this->primary_keys[$i]);
}
}
if (count($this->primary_keys) > 0)
{
$sql .= ",\n\tCONSTRAINT ".$this->db->escape_identifiers('pk_'.$table)
.' PRIMARY KEY('.implode(', ', $this->db->escape_identifiers($this->primary_keys)).')';
}
return $sql;
}
// --------------------------------------------------------------------
/**
* Process indexes
*
* @param string $table
* @return string
*/
protected function _process_indexes($table)
{
$sqls = array();
for ($i = 0, $c = count($this->keys); $i < $c; $i++)
{
if (is_array($this->keys[$i]))
{
for ($i2 = 0, $c2 = count($this->keys[$i]); $i2 < $c2; $i2++)
{
if ( ! isset($this->fields[$this->keys[$i][$i2]]))
{
unset($this->keys[$i][$i2]);
continue;
}
}
}
elseif ( ! isset($this->fields[$this->keys[$i]]))
{
unset($this->keys[$i]);
continue;
}
is_array($this->keys[$i]) OR $this->keys[$i] = array($this->keys[$i]);
$sqls[] = 'CREATE INDEX '.$this->db->escape_identifiers($table.'_'.implode('_', $this->keys[$i]))
.' ON '.$this->db->escape_identifiers($table)
.' ('.implode(', ', $this->db->escape_identifiers($this->keys[$i])).');';
}
return $sqls;
}
// --------------------------------------------------------------------
/**
* Reset
*
* Resets table creation vars
*
* @return void
*/
protected function _reset()
{
$this->fields = $this->keys = $this->primary_keys = array();
}
}
| wms-code/CodeIgniter-admin | system/database/DB_forge.php | PHP | mit | 23,953 |
"use strict";
// local import of the exported AngularPage class
var angularPage_1 = require('./angularPage');
// The jasmine typings are brought in via DefinitelyTyped ambient typings.
describe('angularjs homepage', function () {
it('should greet the named user', function () {
var angularHomepage = new angularPage_1.AngularHomepage();
angularHomepage.get();
angularHomepage.setName('Julie');
expect(angularHomepage.getGreeting()).toEqual('Hello Julie!');
});
});
| bhavateja/Developer-Test-Angular-JS-Web-App | node_modules/protractor/built/spec/install/node_modules/protractor/exampleTypescript/specPageObjects.js | JavaScript | mit | 505 |
/*
* Copyright (c) 2012, 2013, 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.
*/
/*
* This file is available under and governed by the GNU General Public
* License version 2 only, as published by the Free Software Foundation.
* However, the following notice accompanied the original version of this
* file:
*
* Copyright (c) 2007-2012, Stephen Colebourne & Michael Nascimento Santos
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of JSR-310 nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package java.time;
import static java.time.temporal.ChronoField.ERA;
import static java.time.temporal.ChronoField.YEAR;
import static java.time.temporal.ChronoField.YEAR_OF_ERA;
import static java.time.temporal.ChronoUnit.CENTURIES;
import static java.time.temporal.ChronoUnit.DECADES;
import static java.time.temporal.ChronoUnit.ERAS;
import static java.time.temporal.ChronoUnit.MILLENNIA;
import static java.time.temporal.ChronoUnit.YEARS;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.time.chrono.Chronology;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.format.SignStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQueries;
import java.time.temporal.TemporalQuery;
import java.time.temporal.TemporalUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.time.temporal.ValueRange;
import java.util.Objects;
/**
* A year in the ISO-8601 calendar system, such as {@code 2007}.
* <p>
* {@code Year} is an immutable date-time object that represents a year.
* Any field that can be derived from a year can be obtained.
* <p>
* <b>Note that years in the ISO chronology only align with years in the
* Gregorian-Julian system for modern years. Parts of Russia did not switch to the
* modern Gregorian/ISO rules until 1920.
* As such, historical years must be treated with caution.</b>
* <p>
* This class does not store or represent a month, day, time or time-zone.
* For example, the value "2007" can be stored in a {@code Year}.
* <p>
* Years represented by this class follow the ISO-8601 standard and use
* the proleptic numbering system. Year 1 is preceded by year 0, then by year -1.
* <p>
* The ISO-8601 calendar system is the modern civil calendar system used today
* in most of the world. It is equivalent to the proleptic Gregorian calendar
* system, in which today's rules for leap years are applied for all time.
* For most applications written today, the ISO-8601 rules are entirely suitable.
* However, any application that makes use of historical dates, and requires them
* to be accurate will find the ISO-8601 approach unsuitable.
*
* <p>
* This is a <a href="{@docRoot}/java/lang/doc-files/ValueBased.html">value-based</a>
* class; use of identity-sensitive operations (including reference equality
* ({@code ==}), identity hash code, or synchronization) on instances of
* {@code Year} may have unpredictable results and should be avoided.
* The {@code equals} method should be used for comparisons.
*
* @implSpec
* This class is immutable and thread-safe.
*
* @since 1.8
*/
public final class Year
implements Temporal, TemporalAdjuster, Comparable<Year>, Serializable {
/**
* The minimum supported year, '-999,999,999'.
*/
public static final int MIN_VALUE = -999_999_999;
/**
* The maximum supported year, '+999,999,999'.
*/
public static final int MAX_VALUE = 999_999_999;
/**
* Serialization version.
*/
private static final long serialVersionUID = -23038383694477807L;
/**
* Parser.
*/
private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
.appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.toFormatter();
/**
* The year being represented.
*/
private final int year;
//-----------------------------------------------------------------------
/**
* Obtains the current year from the system clock in the default time-zone.
* <p>
* This will query the {@link java.time.Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current year.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current year using the system clock and default time-zone, not null
*/
public static Year now() {
return now(Clock.systemDefaultZone());
}
/**
* Obtains the current year from the system clock in the specified time-zone.
* <p>
* This will query the {@link Clock#system(java.time.ZoneId) system clock} to obtain the current year.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @param zone the zone ID to use, not null
* @return the current year using the system clock, not null
*/
public static Year now(ZoneId zone) {
return now(Clock.system(zone));
}
/**
* Obtains the current year from the specified clock.
* <p>
* This will query the specified clock to obtain the current year.
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@link Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current year, not null
*/
public static Year now(Clock clock) {
final LocalDate now = LocalDate.now(clock); // called once
return Year.of(now.getYear());
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Year}.
* <p>
* This method accepts a year value from the proleptic ISO calendar system.
* <p>
* The year 2AD/CE is represented by 2.<br>
* The year 1AD/CE is represented by 1.<br>
* The year 1BC/BCE is represented by 0.<br>
* The year 2BC/BCE is represented by -1.<br>
*
* @param isoYear the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE}
* @return the year, not null
* @throws DateTimeException if the field is invalid
*/
public static Year of(int isoYear) {
YEAR.checkValidValue(isoYear);
return new Year(isoYear);
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Year} from a temporal object.
* <p>
* This obtains a year based on the specified temporal.
* A {@code TemporalAccessor} represents an arbitrary set of date and time information,
* which this factory converts to an instance of {@code Year}.
* <p>
* The conversion extracts the {@link ChronoField#YEAR year} field.
* The extraction is only permitted if the temporal object has an ISO
* chronology, or can be converted to a {@code LocalDate}.
* <p>
* This method matches the signature of the functional interface {@link TemporalQuery}
* allowing it to be used in queries via method reference, {@code Year::from}.
*
* @param temporal the temporal object to convert, not null
* @return the year, not null
* @throws DateTimeException if unable to convert to a {@code Year}
*/
public static Year from(TemporalAccessor temporal) {
if (temporal instanceof Year) {
return (Year) temporal;
}
Objects.requireNonNull(temporal, "temporal");
try {
if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) {
temporal = LocalDate.from(temporal);
}
return of(temporal.get(YEAR));
} catch (DateTimeException ex) {
throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " +
temporal + " of type " + temporal.getClass().getName(), ex);
}
}
//-----------------------------------------------------------------------
/**
* Obtains an instance of {@code Year} from a text string such as {@code 2007}.
* <p>
* The string must represent a valid year.
* Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.
*
* @param text the text to parse such as "2007", not null
* @return the parsed year, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static Year parse(CharSequence text) {
return parse(text, PARSER);
}
/**
* Obtains an instance of {@code Year} from a text string using a specific formatter.
* <p>
* The text is parsed using the formatter, returning a year.
*
* @param text the text to parse, not null
* @param formatter the formatter to use, not null
* @return the parsed year, not null
* @throws DateTimeParseException if the text cannot be parsed
*/
public static Year parse(CharSequence text, DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.parse(text, Year::from);
}
//-------------------------------------------------------------------------
/**
* Checks if the year is a leap year, according to the ISO proleptic
* calendar system rules.
* <p>
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without
* remainder. However, years divisible by 100, are not leap years, with
* the exception of years divisible by 400 which are.
* <p>
* For example, 1904 is a leap year it is divisible by 4.
* 1900 was not a leap year as it is divisible by 100, however 2000 was a
* leap year as it is divisible by 400.
* <p>
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*
* @param year the year to check
* @return true if the year is leap, false otherwise
*/
public static boolean isLeap(long year) {
return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
}
//-----------------------------------------------------------------------
/**
* Constructor.
*
* @param year the year to represent
*/
private Year(int year) {
this.year = year;
}
//-----------------------------------------------------------------------
/**
* Gets the year value.
* <p>
* The year returned by this method is proleptic as per {@code get(YEAR)}.
*
* @return the year, {@code MIN_VALUE} to {@code MAX_VALUE}
*/
public int getValue() {
return year;
}
//-----------------------------------------------------------------------
/**
* Checks if the specified field is supported.
* <p>
* This checks if this year can be queried for the specified field.
* If false, then calling the {@link #range(TemporalField) range},
* {@link #get(TemporalField) get} and {@link #with(TemporalField, long)}
* methods will throw an exception.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The supported fields are:
* <ul>
* <li>{@code YEAR_OF_ERA}
* <li>{@code YEAR}
* <li>{@code ERA}
* </ul>
* All other {@code ChronoField} instances will return false.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
* passing {@code this} as the argument.
* Whether the field is supported is determined by the field.
*
* @param field the field to check, null returns false
* @return true if the field is supported on this year, false if not
*/
@Override
public boolean isSupported(TemporalField field) {
if (field instanceof ChronoField) {
return field == YEAR || field == YEAR_OF_ERA || field == ERA;
}
return field != null && field.isSupportedBy(this);
}
/**
* Checks if the specified unit is supported.
* <p>
* This checks if the specified unit can be added to, or subtracted from, this date-time.
* If false, then calling the {@link #plus(long, TemporalUnit)} and
* {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
* <p>
* If the unit is a {@link ChronoUnit} then the query is implemented here.
* The supported units are:
* <ul>
* <li>{@code YEARS}
* <li>{@code DECADES}
* <li>{@code CENTURIES}
* <li>{@code MILLENNIA}
* <li>{@code ERAS}
* </ul>
* All other {@code ChronoUnit} instances will return false.
* <p>
* If the unit is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
* passing {@code this} as the argument.
* Whether the unit is supported is determined by the unit.
*
* @param unit the unit to check, null returns false
* @return true if the unit can be added/subtracted, false if not
*/
@Override
public boolean isSupported(TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
return unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS;
}
return unit != null && unit.isSupportedBy(this);
}
//-----------------------------------------------------------------------
/**
* Gets the range of valid values for the specified field.
* <p>
* The range object expresses the minimum and maximum valid values for a field.
* This year is used to enhance the accuracy of the returned range.
* If it is not possible to return the range, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return
* appropriate range instances.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
* passing {@code this} as the argument.
* Whether the range can be obtained is determined by the field.
*
* @param field the field to query the range for, not null
* @return the range of valid values for the field, not null
* @throws DateTimeException if the range for the field cannot be obtained
* @throws UnsupportedTemporalTypeException if the field is not supported
*/
@Override
public ValueRange range(TemporalField field) {
if (field == YEAR_OF_ERA) {
return (year <= 0 ? ValueRange.of(1, MAX_VALUE + 1) : ValueRange.of(1, MAX_VALUE));
}
return Temporal.super.range(field);
}
/**
* Gets the value of the specified field from this year as an {@code int}.
* <p>
* This queries this year for the value for the specified field.
* The returned value will always be within the valid range of values for the field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this year.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
* passing {@code this} as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param field the field to get, not null
* @return the value for the field
* @throws DateTimeException if a value for the field cannot be obtained or
* the value is outside the range of valid values for the field
* @throws UnsupportedTemporalTypeException if the field is not supported or
* the range of values exceeds an {@code int}
* @throws ArithmeticException if numeric overflow occurs
*/
@Override // override for Javadoc
public int get(TemporalField field) {
return range(field).checkValidIntValue(getLong(field), field);
}
/**
* Gets the value of the specified field from this year as a {@code long}.
* <p>
* This queries this year for the value for the specified field.
* If it is not possible to return the value, because the field is not supported
* or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the query is implemented here.
* The {@link #isSupported(TemporalField) supported fields} will return valid
* values based on this year.
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
* passing {@code this} as the argument. Whether the value can be obtained,
* and what the value represents, is determined by the field.
*
* @param field the field to get, not null
* @return the value for the field
* @throws DateTimeException if a value for the field cannot be obtained
* @throws UnsupportedTemporalTypeException if the field is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public long getLong(TemporalField field) {
if (field instanceof ChronoField) {
switch ((ChronoField) field) {
case YEAR_OF_ERA: return (year < 1 ? 1 - year : year);
case YEAR: return year;
case ERA: return (year < 1 ? 0 : 1);
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.getFrom(this);
}
//-----------------------------------------------------------------------
/**
* Checks if the year is a leap year, according to the ISO proleptic
* calendar system rules.
* <p>
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without
* remainder. However, years divisible by 100, are not leap years, with
* the exception of years divisible by 400 which are.
* <p>
* For example, 1904 is a leap year it is divisible by 4.
* 1900 was not a leap year as it is divisible by 100, however 2000 was a
* leap year as it is divisible by 400.
* <p>
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*
* @return true if the year is leap, false otherwise
*/
public boolean isLeap() {
return Year.isLeap(year);
}
/**
* Checks if the month-day is valid for this year.
* <p>
* This method checks whether this year and the input month and day form
* a valid date.
*
* @param monthDay the month-day to validate, null returns false
* @return true if the month and day are valid for this year
*/
public boolean isValidMonthDay(MonthDay monthDay) {
return monthDay != null && monthDay.isValidYear(year);
}
/**
* Gets the length of this year in days.
*
* @return the length of this year in days, 365 or 366
*/
public int length() {
return isLeap() ? 366 : 365;
}
//-----------------------------------------------------------------------
/**
* Returns an adjusted copy of this year.
* <p>
* This returns a {@code Year}, based on this one, with the year adjusted.
* The adjustment takes place using the specified adjuster strategy object.
* Read the documentation of the adjuster to understand what adjustment will be made.
* <p>
* The result of this method is obtained by invoking the
* {@link TemporalAdjuster#adjustInto(Temporal)} method on the
* specified adjuster passing {@code this} as the argument.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param adjuster the adjuster to use, not null
* @return a {@code Year} based on {@code this} with the adjustment made, not null
* @throws DateTimeException if the adjustment cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year with(TemporalAdjuster adjuster) {
return (Year) adjuster.adjustInto(this);
}
/**
* Returns a copy of this year with the specified field set to a new value.
* <p>
* This returns a {@code Year}, based on this one, with the value
* for the specified field changed.
* If it is not possible to set the value, because the field is not supported or for
* some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoField} then the adjustment is implemented here.
* The supported fields behave as follows:
* <ul>
* <li>{@code YEAR_OF_ERA} -
* Returns a {@code Year} with the specified year-of-era
* The era will be unchanged.
* <li>{@code YEAR} -
* Returns a {@code Year} with the specified year.
* This completely replaces the date and is equivalent to {@link #of(int)}.
* <li>{@code ERA} -
* Returns a {@code Year} with the specified era.
* The year-of-era will be unchanged.
* </ul>
* <p>
* In all cases, if the new value is outside the valid range of values for the field
* then a {@code DateTimeException} will be thrown.
* <p>
* All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoField}, then the result of this method
* is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
* passing {@code this} as the argument. In this case, the field determines
* whether and how to adjust the instant.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param field the field to set in the result, not null
* @param newValue the new value of the field in the result
* @return a {@code Year} based on {@code this} with the specified field set, not null
* @throws DateTimeException if the field cannot be set
* @throws UnsupportedTemporalTypeException if the field is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year with(TemporalField field, long newValue) {
if (field instanceof ChronoField) {
ChronoField f = (ChronoField) field;
f.checkValidValue(newValue);
switch (f) {
case YEAR_OF_ERA: return Year.of((int) (year < 1 ? 1 - newValue : newValue));
case YEAR: return Year.of((int) newValue);
case ERA: return (getLong(ERA) == newValue ? this : Year.of(1 - year));
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
return field.adjustInto(this, newValue);
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this year with the specified amount added.
* <p>
* This returns a {@code Year}, based on this one, with the specified amount added.
* The amount is typically {@link Period} but may be any other type implementing
* the {@link TemporalAmount} interface.
* <p>
* The calculation is delegated to the amount object by calling
* {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
* to implement the addition in any way it wishes, however it typically
* calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
* of the amount implementation to determine if it can be successfully added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToAdd the amount to add, not null
* @return a {@code Year} based on this year with the addition made, not null
* @throws DateTimeException if the addition cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year plus(TemporalAmount amountToAdd) {
return (Year) amountToAdd.addTo(this);
}
/**
* Returns a copy of this year with the specified amount added.
* <p>
* This returns a {@code Year}, based on this one, with the amount
* in terms of the unit added. If it is not possible to add the amount, because the
* unit is not supported or for some other reason, an exception is thrown.
* <p>
* If the field is a {@link ChronoUnit} then the addition is implemented here.
* The supported fields behave as follows:
* <ul>
* <li>{@code YEARS} -
* Returns a {@code Year} with the specified number of years added.
* This is equivalent to {@link #plusYears(long)}.
* <li>{@code DECADES} -
* Returns a {@code Year} with the specified number of decades added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 10.
* <li>{@code CENTURIES} -
* Returns a {@code Year} with the specified number of centuries added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 100.
* <li>{@code MILLENNIA} -
* Returns a {@code Year} with the specified number of millennia added.
* This is equivalent to calling {@link #plusYears(long)} with the amount
* multiplied by 1,000.
* <li>{@code ERAS} -
* Returns a {@code Year} with the specified number of eras added.
* Only two eras are supported so the amount must be one, zero or minus one.
* If the amount is non-zero then the year is changed such that the year-of-era
* is unchanged.
* </ul>
* <p>
* All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
* <p>
* If the field is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
* passing {@code this} as the argument. In this case, the unit determines
* whether and how to perform the addition.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToAdd the amount of the unit to add to the result, may be negative
* @param unit the unit of the amount to add, not null
* @return a {@code Year} based on this year with the specified amount added, not null
* @throws DateTimeException if the addition cannot be made
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year plus(long amountToAdd, TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
switch ((ChronoUnit) unit) {
case YEARS: return plusYears(amountToAdd);
case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10));
case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100));
case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000));
case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd));
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.addTo(this, amountToAdd);
}
/**
* Returns a copy of this year with the specified number of years added.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToAdd the years to add, may be negative
* @return a {@code Year} based on this year with the period added, not null
* @throws DateTimeException if the result exceeds the supported year range
*/
public Year plusYears(long yearsToAdd) {
if (yearsToAdd == 0) {
return this;
}
return of(YEAR.checkValidIntValue(year + yearsToAdd)); // overflow safe
}
//-----------------------------------------------------------------------
/**
* Returns a copy of this year with the specified amount subtracted.
* <p>
* This returns a {@code Year}, based on this one, with the specified amount subtracted.
* The amount is typically {@link Period} but may be any other type implementing
* the {@link TemporalAmount} interface.
* <p>
* The calculation is delegated to the amount object by calling
* {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
* to implement the subtraction in any way it wishes, however it typically
* calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
* of the amount implementation to determine if it can be successfully subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToSubtract the amount to subtract, not null
* @return a {@code Year} based on this year with the subtraction made, not null
* @throws DateTimeException if the subtraction cannot be made
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year minus(TemporalAmount amountToSubtract) {
return (Year) amountToSubtract.subtractFrom(this);
}
/**
* Returns a copy of this year with the specified amount subtracted.
* <p>
* This returns a {@code Year}, based on this one, with the amount
* in terms of the unit subtracted. If it is not possible to subtract the amount,
* because the unit is not supported or for some other reason, an exception is thrown.
* <p>
* This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
* See that method for a full description of how addition, and thus subtraction, works.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param amountToSubtract the amount of the unit to subtract from the result, may be negative
* @param unit the unit of the amount to subtract, not null
* @return a {@code Year} based on this year with the specified amount subtracted, not null
* @throws DateTimeException if the subtraction cannot be made
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Year minus(long amountToSubtract, TemporalUnit unit) {
return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
}
/**
* Returns a copy of this year with the specified number of years subtracted.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToSubtract the years to subtract, may be negative
* @return a {@code Year} based on this year with the period subtracted, not null
* @throws DateTimeException if the result exceeds the supported year range
*/
public Year minusYears(long yearsToSubtract) {
return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
}
//-----------------------------------------------------------------------
/**
* Queries this year using the specified query.
* <p>
* This queries this year using the specified query strategy object.
* The {@code TemporalQuery} object defines the logic to be used to
* obtain the result. Read the documentation of the query to understand
* what the result of this method will be.
* <p>
* The result of this method is obtained by invoking the
* {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
* specified query passing {@code this} as the argument.
*
* @param <R> the type of the result
* @param query the query to invoke, not null
* @return the query result, null may be returned (defined by the query)
* @throws DateTimeException if unable to query (defined by the query)
* @throws ArithmeticException if numeric overflow occurs (defined by the query)
*/
@SuppressWarnings("unchecked")
@Override
public <R> R query(TemporalQuery<R> query) {
if (query == TemporalQueries.chronology()) {
return (R) IsoChronology.INSTANCE;
} else if (query == TemporalQueries.precision()) {
return (R) YEARS;
}
return Temporal.super.query(query);
}
/**
* Adjusts the specified temporal object to have this year.
* <p>
* This returns a temporal object of the same observable type as the input
* with the year changed to be the same as this.
* <p>
* The adjustment is equivalent to using {@link Temporal#with(TemporalField, long)}
* passing {@link ChronoField#YEAR} as the field.
* If the specified temporal object does not use the ISO calendar system then
* a {@code DateTimeException} is thrown.
* <p>
* In most cases, it is clearer to reverse the calling pattern by using
* {@link Temporal#with(TemporalAdjuster)}:
* <pre>
* // these two lines are equivalent, but the second approach is recommended
* temporal = thisYear.adjustInto(temporal);
* temporal = temporal.with(thisYear);
* </pre>
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param temporal the target object to be adjusted, not null
* @return the adjusted object, not null
* @throws DateTimeException if unable to make the adjustment
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public Temporal adjustInto(Temporal temporal) {
if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) {
throw new DateTimeException("Adjustment only supported on ISO date-time");
}
return temporal.with(YEAR, year);
}
/**
* Calculates the amount of time until another year in terms of the specified unit.
* <p>
* This calculates the amount of time between two {@code Year}
* objects in terms of a single {@code TemporalUnit}.
* The start and end points are {@code this} and the specified year.
* The result will be negative if the end is before the start.
* The {@code Temporal} passed to this method is converted to a
* {@code Year} using {@link #from(TemporalAccessor)}.
* For example, the period in decades between two year can be calculated
* using {@code startYear.until(endYear, DECADES)}.
* <p>
* The calculation returns a whole number, representing the number of
* complete units between the two years.
* For example, the period in decades between 2012 and 2031
* will only be one decade as it is one year short of two decades.
* <p>
* There are two equivalent ways of using this method.
* The first is to invoke this method.
* The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
* <pre>
* // these two lines are equivalent
* amount = start.until(end, YEARS);
* amount = YEARS.between(start, end);
* </pre>
* The choice should be made based on which makes the code more readable.
* <p>
* The calculation is implemented in this method for {@link ChronoUnit}.
* The units {@code YEARS}, {@code DECADES}, {@code CENTURIES},
* {@code MILLENNIA} and {@code ERAS} are supported.
* Other {@code ChronoUnit} values will throw an exception.
* <p>
* If the unit is not a {@code ChronoUnit}, then the result of this method
* is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
* passing {@code this} as the first argument and the converted input temporal
* as the second argument.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param endExclusive the end date, exclusive, which is converted to a {@code Year}, not null
* @param unit the unit to measure the amount in, not null
* @return the amount of time between this year and the end year
* @throws DateTimeException if the amount cannot be calculated, or the end
* temporal cannot be converted to a {@code Year}
* @throws UnsupportedTemporalTypeException if the unit is not supported
* @throws ArithmeticException if numeric overflow occurs
*/
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
Year end = Year.from(endExclusive);
if (unit instanceof ChronoUnit) {
long yearsUntil = ((long) end.year) - year; // no overflow
switch ((ChronoUnit) unit) {
case YEARS: return yearsUntil;
case DECADES: return yearsUntil / 10;
case CENTURIES: return yearsUntil / 100;
case MILLENNIA: return yearsUntil / 1000;
case ERAS: return end.getLong(ERA) - getLong(ERA);
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.between(this, end);
}
/**
* Formats this year using the specified formatter.
* <p>
* This year will be passed to the formatter to produce a string.
*
* @param formatter the formatter to use, not null
* @return the formatted year string, not null
* @throws DateTimeException if an error occurs during printing
*/
public String format(DateTimeFormatter formatter) {
Objects.requireNonNull(formatter, "formatter");
return formatter.format(this);
}
//-----------------------------------------------------------------------
/**
* Combines this year with a day-of-year to create a {@code LocalDate}.
* <p>
* This returns a {@code LocalDate} formed from this year and the specified day-of-year.
* <p>
* The day-of-year value 366 is only valid in a leap year.
*
* @param dayOfYear the day-of-year to use, not null
* @return the local date formed from this year and the specified date of year, not null
* @throws DateTimeException if the day of year is zero or less, 366 or greater or equal
* to 366 and this is not a leap year
*/
public LocalDate atDay(int dayOfYear) {
return LocalDate.ofYearDay(year, dayOfYear);
}
/**
* Combines this year with a month to create a {@code YearMonth}.
* <p>
* This returns a {@code YearMonth} formed from this year and the specified month.
* All possible combinations of year and month are valid.
* <p>
* This method can be used as part of a chain to produce a date:
* <pre>
* LocalDate date = year.atMonth(month).atDay(day);
* </pre>
*
* @param month the month-of-year to use, not null
* @return the year-month formed from this year and the specified month, not null
*/
public YearMonth atMonth(Month month) {
return YearMonth.of(year, month);
}
/**
* Combines this year with a month to create a {@code YearMonth}.
* <p>
* This returns a {@code YearMonth} formed from this year and the specified month.
* All possible combinations of year and month are valid.
* <p>
* This method can be used as part of a chain to produce a date:
* <pre>
* LocalDate date = year.atMonth(month).atDay(day);
* </pre>
*
* @param month the month-of-year to use, from 1 (January) to 12 (December)
* @return the year-month formed from this year and the specified month, not null
* @throws DateTimeException if the month is invalid
*/
public YearMonth atMonth(int month) {
return YearMonth.of(year, month);
}
/**
* Combines this year with a month-day to create a {@code LocalDate}.
* <p>
* This returns a {@code LocalDate} formed from this year and the specified month-day.
* <p>
* A month-day of February 29th will be adjusted to February 28th in the resulting
* date if the year is not a leap year.
*
* @param monthDay the month-day to use, not null
* @return the local date formed from this year and the specified month-day, not null
*/
public LocalDate atMonthDay(MonthDay monthDay) {
return monthDay.atYear(year);
}
//-----------------------------------------------------------------------
/**
* Compares this year to another year.
* <p>
* The comparison is based on the value of the year.
* It is "consistent with equals", as defined by {@link Comparable}.
*
* @param other the other year to compare to, not null
* @return the comparator value, negative if less, positive if greater
*/
@Override
public int compareTo(Year other) {
return year - other.year;
}
/**
* Is this year after the specified year.
*
* @param other the other year to compare to, not null
* @return true if this is after the specified year
*/
public boolean isAfter(Year other) {
return year > other.year;
}
/**
* Is this year before the specified year.
*
* @param other the other year to compare to, not null
* @return true if this point is before the specified year
*/
public boolean isBefore(Year other) {
return year < other.year;
}
//-----------------------------------------------------------------------
/**
* Checks if this year is equal to another year.
* <p>
* The comparison is based on the time-line position of the years.
*
* @param obj the object to check, null returns false
* @return true if this is equal to the other year
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Year) {
return year == ((Year) obj).year;
}
return false;
}
/**
* A hash code for this year.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return year;
}
//-----------------------------------------------------------------------
/**
* Outputs this year as a {@code String}.
*
* @return a string representation of this year, not null
*/
@Override
public String toString() {
return Integer.toString(year);
}
//-----------------------------------------------------------------------
/**
* Writes the object using a
* <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>.
* @serialData
* <pre>
* out.writeByte(11); // identifies a Year
* out.writeInt(year);
* </pre>
*
* @return the instance of {@code Ser}, not null
*/
private Object writeReplace() {
return new Ser(Ser.YEAR_TYPE, this);
}
/**
* Defend against malicious streams.
*
* @throws InvalidObjectException always
*/
private void readObject(ObjectInputStream s) throws InvalidObjectException {
throw new InvalidObjectException("Deserialization via serialization delegate");
}
void writeExternal(DataOutput out) throws IOException {
out.writeInt(year);
}
static Year readExternal(DataInput in) throws IOException {
return Year.of(in.readInt());
}
}
| rokn/Count_Words_2015 | testing/openjdk2/jdk/src/share/classes/java/time/Year.java | Java | mit | 47,803 |
// ------------------------------------------------------------------------------
//The MIT License(MIT)
//Copyright(c) 2015 Office Developer
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
// ------------------------------------------------------------------------------
using System.Threading.Tasks;
using Microsoft.Online.Applications.Core.Authentication;
using Microsoft.Online.Applications.Core.Configuration;
namespace Microsoft.Online.Applications.Core
{
public class ServiceProvider : IServiceInfoProvider
{
public IAuthenticationProvider AuthenticationProvider { get; private set; }
public virtual Task<ServiceInformation> CreateServiceInfo(AppConfig appConfig, CredentialType credentialType)
{
var activeDirectoryServiceInfo = new AdalServiceInformation
{
ClientID = appConfig.ClientID,
ClientSecret = appConfig.ClientSecret,
Tenant = appConfig.TenantDomain,
ServiceResource = appConfig.ServiceResource
};
if (credentialType == CredentialType.Certificate)
{
activeDirectoryServiceInfo.AuthenticationProvider = this.AuthenticationProvider ?? new AdalCertificateAuthenticationProvider(activeDirectoryServiceInfo);
}
else
{
activeDirectoryServiceInfo.AuthenticationProvider = this.AuthenticationProvider ?? new AdalClientAuthenticationProvider(activeDirectoryServiceInfo);
}
return Task.FromResult<ServiceInformation>(activeDirectoryServiceInfo);
}
}
}
| jansenbe/PnP-Tools | Solutions/Tenant Information Portal/src/Microsoft.Online.Applications.Core/ServiceProvider.cs | C# | mit | 2,638 |
import answer from './answer';
var answer2 = answer;
export default answer2;
| lukeapage/rollup | test/function/statement-order/main.js | JavaScript | mit | 77 |
import { Quaternion } from '../math/Quaternion';
import { Vector3 } from '../math/Vector3';
import { Matrix4 } from '../math/Matrix4';
import { EventDispatcher } from './EventDispatcher';
import { Euler } from '../math/Euler';
import { Layers } from './Layers';
import { Matrix3 } from '../math/Matrix3';
import { _Math } from '../math/Math';
/**
* @author mrdoob / http://mrdoob.com/
* @author mikael emtinger / http://gomo.se/
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author elephantatwork / www.elephantatwork.ch
*/
var object3DId = 0;
function Object3D() {
Object.defineProperty( this, 'id', { value: object3DId ++ } );
this.uuid = _Math.generateUUID();
this.name = '';
this.type = 'Object3D';
this.parent = null;
this.children = [];
this.up = Object3D.DefaultUp.clone();
var position = new Vector3();
var rotation = new Euler();
var quaternion = new Quaternion();
var scale = new Vector3( 1, 1, 1 );
function onRotationChange() {
quaternion.setFromEuler( rotation, false );
}
function onQuaternionChange() {
rotation.setFromQuaternion( quaternion, undefined, false );
}
rotation.onChange( onRotationChange );
quaternion.onChange( onQuaternionChange );
Object.defineProperties( this, {
position: {
enumerable: true,
value: position
},
rotation: {
enumerable: true,
value: rotation
},
quaternion: {
enumerable: true,
value: quaternion
},
scale: {
enumerable: true,
value: scale
},
modelViewMatrix: {
value: new Matrix4()
},
normalMatrix: {
value: new Matrix3()
}
} );
this.matrix = new Matrix4();
this.matrixWorld = new Matrix4();
this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
this.matrixWorldNeedsUpdate = false;
this.layers = new Layers();
this.visible = true;
this.castShadow = false;
this.receiveShadow = false;
this.frustumCulled = true;
this.renderOrder = 0;
this.userData = {};
}
Object3D.DefaultUp = new Vector3( 0, 1, 0 );
Object3D.DefaultMatrixAutoUpdate = true;
Object.assign( Object3D.prototype, EventDispatcher.prototype, {
isObject3D: true,
onBeforeRender: function () {},
onAfterRender: function () {},
applyMatrix: function ( matrix ) {
this.matrix.multiplyMatrices( matrix, this.matrix );
this.matrix.decompose( this.position, this.quaternion, this.scale );
},
applyQuaternion: function ( q ) {
this.quaternion.premultiply( q );
return this;
},
setRotationFromAxisAngle: function ( axis, angle ) {
// assumes axis is normalized
this.quaternion.setFromAxisAngle( axis, angle );
},
setRotationFromEuler: function ( euler ) {
this.quaternion.setFromEuler( euler, true );
},
setRotationFromMatrix: function ( m ) {
// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
this.quaternion.setFromRotationMatrix( m );
},
setRotationFromQuaternion: function ( q ) {
// assumes q is normalized
this.quaternion.copy( q );
},
rotateOnAxis: function () {
// rotate object on axis in object space
// axis is assumed to be normalized
var q1 = new Quaternion();
return function rotateOnAxis( axis, angle ) {
q1.setFromAxisAngle( axis, angle );
this.quaternion.multiply( q1 );
return this;
};
}(),
rotateX: function () {
var v1 = new Vector3( 1, 0, 0 );
return function rotateX( angle ) {
return this.rotateOnAxis( v1, angle );
};
}(),
rotateY: function () {
var v1 = new Vector3( 0, 1, 0 );
return function rotateY( angle ) {
return this.rotateOnAxis( v1, angle );
};
}(),
rotateZ: function () {
var v1 = new Vector3( 0, 0, 1 );
return function rotateZ( angle ) {
return this.rotateOnAxis( v1, angle );
};
}(),
translateOnAxis: function () {
// translate object by distance along axis in object space
// axis is assumed to be normalized
var v1 = new Vector3();
return function translateOnAxis( axis, distance ) {
v1.copy( axis ).applyQuaternion( this.quaternion );
this.position.add( v1.multiplyScalar( distance ) );
return this;
};
}(),
translateX: function () {
var v1 = new Vector3( 1, 0, 0 );
return function translateX( distance ) {
return this.translateOnAxis( v1, distance );
};
}(),
translateY: function () {
var v1 = new Vector3( 0, 1, 0 );
return function translateY( distance ) {
return this.translateOnAxis( v1, distance );
};
}(),
translateZ: function () {
var v1 = new Vector3( 0, 0, 1 );
return function translateZ( distance ) {
return this.translateOnAxis( v1, distance );
};
}(),
localToWorld: function ( vector ) {
return vector.applyMatrix4( this.matrixWorld );
},
worldToLocal: function () {
var m1 = new Matrix4();
return function worldToLocal( vector ) {
return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
};
}(),
lookAt: function () {
// This method does not support objects with rotated and/or translated parent(s)
var m1 = new Matrix4();
return function lookAt( vector ) {
if ( this.isCamera ) {
m1.lookAt( this.position, vector, this.up );
} else {
m1.lookAt( vector, this.position, this.up );
}
this.quaternion.setFromRotationMatrix( m1 );
};
}(),
add: function ( object ) {
if ( arguments.length > 1 ) {
for ( var i = 0; i < arguments.length; i ++ ) {
this.add( arguments[ i ] );
}
return this;
}
if ( object === this ) {
console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
return this;
}
if ( ( object && object.isObject3D ) ) {
if ( object.parent !== null ) {
object.parent.remove( object );
}
object.parent = this;
object.dispatchEvent( { type: 'added' } );
this.children.push( object );
} else {
console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
}
return this;
},
remove: function ( object ) {
if ( arguments.length > 1 ) {
for ( var i = 0; i < arguments.length; i ++ ) {
this.remove( arguments[ i ] );
}
return this;
}
var index = this.children.indexOf( object );
if ( index !== - 1 ) {
object.parent = null;
object.dispatchEvent( { type: 'removed' } );
this.children.splice( index, 1 );
}
return this;
},
getObjectById: function ( id ) {
return this.getObjectByProperty( 'id', id );
},
getObjectByName: function ( name ) {
return this.getObjectByProperty( 'name', name );
},
getObjectByProperty: function ( name, value ) {
if ( this[ name ] === value ) return this;
for ( var i = 0, l = this.children.length; i < l; i ++ ) {
var child = this.children[ i ];
var object = child.getObjectByProperty( name, value );
if ( object !== undefined ) {
return object;
}
}
return undefined;
},
getWorldPosition: function ( optionalTarget ) {
var result = optionalTarget || new Vector3();
this.updateMatrixWorld( true );
return result.setFromMatrixPosition( this.matrixWorld );
},
getWorldQuaternion: function () {
var position = new Vector3();
var scale = new Vector3();
return function getWorldQuaternion( optionalTarget ) {
var result = optionalTarget || new Quaternion();
this.updateMatrixWorld( true );
this.matrixWorld.decompose( position, result, scale );
return result;
};
}(),
getWorldRotation: function () {
var quaternion = new Quaternion();
return function getWorldRotation( optionalTarget ) {
var result = optionalTarget || new Euler();
this.getWorldQuaternion( quaternion );
return result.setFromQuaternion( quaternion, this.rotation.order, false );
};
}(),
getWorldScale: function () {
var position = new Vector3();
var quaternion = new Quaternion();
return function getWorldScale( optionalTarget ) {
var result = optionalTarget || new Vector3();
this.updateMatrixWorld( true );
this.matrixWorld.decompose( position, quaternion, result );
return result;
};
}(),
getWorldDirection: function () {
var quaternion = new Quaternion();
return function getWorldDirection( optionalTarget ) {
var result = optionalTarget || new Vector3();
this.getWorldQuaternion( quaternion );
return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
};
}(),
raycast: function () {},
traverse: function ( callback ) {
callback( this );
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].traverse( callback );
}
},
traverseVisible: function ( callback ) {
if ( this.visible === false ) return;
callback( this );
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].traverseVisible( callback );
}
},
traverseAncestors: function ( callback ) {
var parent = this.parent;
if ( parent !== null ) {
callback( parent );
parent.traverseAncestors( callback );
}
},
updateMatrix: function () {
this.matrix.compose( this.position, this.quaternion, this.scale );
this.matrixWorldNeedsUpdate = true;
},
updateMatrixWorld: function ( force ) {
if ( this.matrixAutoUpdate ) this.updateMatrix();
if ( this.matrixWorldNeedsUpdate || force ) {
if ( this.parent === null ) {
this.matrixWorld.copy( this.matrix );
} else {
this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
}
this.matrixWorldNeedsUpdate = false;
force = true;
}
// update children
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].updateMatrixWorld( force );
}
},
toJSON: function ( meta ) {
// meta is '' when called from JSON.stringify
var isRootObject = ( meta === undefined || meta === '' );
var output = {};
// meta is a hash used to collect geometries, materials.
// not providing it implies that this is the root object
// being serialized.
if ( isRootObject ) {
// initialize meta obj
meta = {
geometries: {},
materials: {},
textures: {},
images: {}
};
output.metadata = {
version: 4.5,
type: 'Object',
generator: 'Object3D.toJSON'
};
}
// standard Object3D serialization
var object = {};
object.uuid = this.uuid;
object.type = this.type;
if ( this.name !== '' ) object.name = this.name;
if ( this.castShadow === true ) object.castShadow = true;
if ( this.receiveShadow === true ) object.receiveShadow = true;
if ( this.visible === false ) object.visible = false;
if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
object.matrix = this.matrix.toArray();
//
function serialize( library, element ) {
if ( library[ element.uuid ] === undefined ) {
library[ element.uuid ] = element.toJSON( meta );
}
return element.uuid;
}
if ( this.geometry !== undefined ) {
object.geometry = serialize( meta.geometries, this.geometry );
}
if ( this.material !== undefined ) {
if ( Array.isArray( this.material ) ) {
var uuids = [];
for ( var i = 0, l = this.material.length; i < l; i ++ ) {
uuids.push( serialize( meta.materials, this.material[ i ] ) );
}
object.material = uuids;
} else {
object.material = serialize( meta.materials, this.material );
}
}
//
if ( this.children.length > 0 ) {
object.children = [];
for ( var i = 0; i < this.children.length; i ++ ) {
object.children.push( this.children[ i ].toJSON( meta ).object );
}
}
if ( isRootObject ) {
var geometries = extractFromCache( meta.geometries );
var materials = extractFromCache( meta.materials );
var textures = extractFromCache( meta.textures );
var images = extractFromCache( meta.images );
if ( geometries.length > 0 ) output.geometries = geometries;
if ( materials.length > 0 ) output.materials = materials;
if ( textures.length > 0 ) output.textures = textures;
if ( images.length > 0 ) output.images = images;
}
output.object = object;
return output;
// extract data from the cache hash
// remove metadata on each item
// and return as array
function extractFromCache( cache ) {
var values = [];
for ( var key in cache ) {
var data = cache[ key ];
delete data.metadata;
values.push( data );
}
return values;
}
},
clone: function ( recursive ) {
return new this.constructor().copy( this, recursive );
},
copy: function ( source, recursive ) {
if ( recursive === undefined ) recursive = true;
this.name = source.name;
this.up.copy( source.up );
this.position.copy( source.position );
this.quaternion.copy( source.quaternion );
this.scale.copy( source.scale );
this.matrix.copy( source.matrix );
this.matrixWorld.copy( source.matrixWorld );
this.matrixAutoUpdate = source.matrixAutoUpdate;
this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
this.layers.mask = source.layers.mask;
this.visible = source.visible;
this.castShadow = source.castShadow;
this.receiveShadow = source.receiveShadow;
this.frustumCulled = source.frustumCulled;
this.renderOrder = source.renderOrder;
this.userData = JSON.parse( JSON.stringify( source.userData ) );
if ( recursive === true ) {
for ( var i = 0; i < source.children.length; i ++ ) {
var child = source.children[ i ];
this.add( child.clone() );
}
}
return this;
}
} );
export { Object3D };
| carlosanunes/three.js | src/core/Object3D.js | JavaScript | mit | 13,558 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class ConnectivitySource(Model):
"""Parameters that define the source of the connection.
All required parameters must be populated in order to send to Azure.
:param resource_id: Required. The ID of the resource from which a
connectivity check will be initiated.
:type resource_id: str
:param port: The source port from which a connectivity check will be
performed.
:type port: int
"""
_validation = {
'resource_id': {'required': True},
}
_attribute_map = {
'resource_id': {'key': 'resourceId', 'type': 'str'},
'port': {'key': 'port', 'type': 'int'},
}
def __init__(self, *, resource_id: str, port: int=None, **kwargs) -> None:
super(ConnectivitySource, self).__init__(**kwargs)
self.resource_id = resource_id
self.port = port
| lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2018_01_01/models/connectivity_source_py3.py | Python | mit | 1,352 |
require 'gmail_xoauth'
module Gmail
module Client
class XOAuth < Base
attr_reader :token
attr_reader :secret
attr_reader :consumer_key
attr_reader :consumer_secret
def initialize(username, options={})
@token = options.delete(:token)
@secret = options.delete(:secret)
@consumer_key = options.delete(:consumer_key)
@consumer_secret = options.delete(:consumer_secret)
super(username, options)
end
def login(raise_errors=false)
@imap and @logged_in = (login = @imap.authenticate('XOAUTH', username,
:consumer_key => consumer_key,
:consumer_secret => consumer_secret,
:token => token,
:token_secret => secret
)) && login.name == 'OK'
rescue Net::IMAP::NoResponseError => e
if raise_errors
message = "Couldn't login to given GMail account: #{username}"
message += " (#{e.response.data.text.strip})"
raise(AuthorizationError.new(e.response), message, e.backtrace)
end
end
def smtp_settings
[:smtp, {
:address => GMAIL_SMTP_HOST,
:port => GMAIL_SMTP_PORT,
:domain => mail_domain,
:user_name => username,
:password => {
:consumer_key => consumer_key,
:consumer_secret => consumer_secret,
:token => token,
:token_secret => secret
},
:authentication => :xoauth,
:enable_starttls_auto => true
}]
end
end # XOAuth
register :xoauth, XOAuth
end # Client
end # Gmail
| jamescallmebrent/gmail | lib/gmail/client/xoauth.rb | Ruby | mit | 1,692 |
// sensible server which advertises itself via Bonjour
// NODE INCLUDES
var dgram = require ("dgram");
var fs = require ("fs");
var http = require ("http");
var os = require ("os");
var url = require ("url");
// REGULAR JS INCLUDES
// assume that sensible.js lives in the same directory as our mainline
var code = fs.readFileSync (require ("path").dirname (process.argv [1]) + "/sensible.js");
eval (code.toString ());
// MAINLINE
sensible.ApplicationFactory.createApplication
(
function (inError)
{
if (inError)
{
console.error ("error during sensible application startup");
console.error (inError);
}
else
{
console.log ("sensible application startup");
}
}
);
// called just before sensible.Application.start()
sensible.node.Application.prototype.onBeforeStart = function (inCallback)
{
console.log ("node.Application.onBeforeStart()");
inCallback ();
}
// called just after sensible.Application.start()
sensible.node.Application.prototype.onAfterStart = function (inCallback)
{
console.log ("node.Application.onAfterStart()");
inCallback ();
}
| gbraad/sensible | apps/node/waiter/sensible-app.js | JavaScript | mit | 1,089 |
<?php
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
namespace Twilio\Rest\Preview\Understand\Assistant;
use Twilio\InstanceContext;
use Twilio\Options;
use Twilio\Values;
use Twilio\Version;
/**
* PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com.
*/
class QueryContext extends InstanceContext {
/**
* Initialize the QueryContext
*
* @param \Twilio\Version $version Version that contains the resource
* @param string $assistantSid The assistant_sid
* @param string $sid The sid
* @return \Twilio\Rest\Preview\Understand\Assistant\QueryContext
*/
public function __construct(Version $version, $assistantSid, $sid) {
parent::__construct($version);
// Path Solution
$this->solution = array('assistantSid' => $assistantSid, 'sid' => $sid, );
$this->uri = '/Assistants/' . rawurlencode($assistantSid) . '/Queries/' . rawurlencode($sid) . '';
}
/**
* Fetch a QueryInstance
*
* @return QueryInstance Fetched QueryInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function fetch() {
$params = Values::of(array());
$payload = $this->version->fetch(
'GET',
$this->uri,
$params
);
return new QueryInstance(
$this->version,
$payload,
$this->solution['assistantSid'],
$this->solution['sid']
);
}
/**
* Update the QueryInstance
*
* @param array|Options $options Optional Arguments
* @return QueryInstance Updated QueryInstance
* @throws TwilioException When an HTTP error occurs.
*/
public function update($options = array()) {
$options = new Values($options);
$data = Values::of(array('SampleSid' => $options['sampleSid'], 'Status' => $options['status'], ));
$payload = $this->version->update(
'POST',
$this->uri,
array(),
$data
);
return new QueryInstance(
$this->version,
$payload,
$this->solution['assistantSid'],
$this->solution['sid']
);
}
/**
* Deletes the QueryInstance
*
* @return boolean True if delete succeeds, false otherwise
* @throws TwilioException When an HTTP error occurs.
*/
public function delete() {
return $this->version->delete('delete', $this->uri);
}
/**
* Provide a friendly representation
*
* @return string Machine friendly representation
*/
public function __toString() {
$context = array();
foreach ($this->solution as $key => $value) {
$context[] = "$key=$value";
}
return '[Twilio.Preview.Understand.QueryContext ' . implode(' ', $context) . ']';
}
} | camperjz/trident | upgrade/files/9.0.0.RC8-9.0.0.RC9/files/plugins/Twilio/Rest/Preview/Understand/Assistant/QueryContext.php | PHP | mit | 3,065 |
<?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use dixonsatit\agencyTheme\assets\AgencyAsset;
/* @var $this \yii\web\View */
/* @var $content string */
AgencyAsset::register($this);
$directoryAsset = Yii::$app->assetManager->getPublishedUrl('@dixonsatit/agencyTheme/dist');
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body id="page-top" class="index">
<?php $this->beginBody() ?>
<?= $content ?>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
| dixonsatit/yii2-agency-theme | views/layouts/_base.php | PHP | mit | 819 |
//===-- X86ELFObjectWriter.cpp - X86 ELF Writer ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/X86FixupKinds.h"
#include "MCTargetDesc/X86MCTargetDesc.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCValue.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
namespace {
class X86ELFObjectWriter : public MCELFObjectTargetWriter {
public:
X86ELFObjectWriter(bool IsELF64, uint8_t OSABI, uint16_t EMachine);
virtual ~X86ELFObjectWriter();
protected:
virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
bool IsPCRel, bool IsRelocWithSymbol,
int64_t Addend) const;
};
}
X86ELFObjectWriter::X86ELFObjectWriter(bool IsELF64, uint8_t OSABI,
uint16_t EMachine)
: MCELFObjectTargetWriter(IsELF64, OSABI, EMachine,
// Only i386 uses Rel instead of RelA.
/*HasRelocationAddend*/ EMachine != ELF::EM_386) {}
X86ELFObjectWriter::~X86ELFObjectWriter()
{}
unsigned X86ELFObjectWriter::GetRelocType(const MCValue &Target,
const MCFixup &Fixup,
bool IsPCRel,
bool IsRelocWithSymbol,
int64_t Addend) const {
// determine the type of the relocation
MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
unsigned Type;
if (getEMachine() == ELF::EM_X86_64) {
if (IsPCRel) {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("invalid fixup kind!");
case FK_Data_8: Type = ELF::R_X86_64_PC64; break;
case FK_Data_4: Type = ELF::R_X86_64_PC32; break;
case FK_Data_2: Type = ELF::R_X86_64_PC16; break;
case FK_PCRel_8:
assert(Modifier == MCSymbolRefExpr::VK_None);
Type = ELF::R_X86_64_PC64;
break;
case X86::reloc_signed_4byte:
case X86::reloc_riprel_4byte_movq_load:
case X86::reloc_riprel_4byte:
case FK_PCRel_4:
switch (Modifier) {
default:
llvm_unreachable("Unimplemented");
case MCSymbolRefExpr::VK_None:
Type = ELF::R_X86_64_PC32;
break;
case MCSymbolRefExpr::VK_PLT:
Type = ELF::R_X86_64_PLT32;
break;
case MCSymbolRefExpr::VK_GOTPCREL:
Type = ELF::R_X86_64_GOTPCREL;
break;
case MCSymbolRefExpr::VK_GOTTPOFF:
Type = ELF::R_X86_64_GOTTPOFF;
break;
case MCSymbolRefExpr::VK_TLSGD:
Type = ELF::R_X86_64_TLSGD;
break;
case MCSymbolRefExpr::VK_TLSLD:
Type = ELF::R_X86_64_TLSLD;
break;
}
break;
case FK_PCRel_2:
assert(Modifier == MCSymbolRefExpr::VK_None);
Type = ELF::R_X86_64_PC16;
break;
case FK_PCRel_1:
assert(Modifier == MCSymbolRefExpr::VK_None);
Type = ELF::R_X86_64_PC8;
break;
}
} else {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("invalid fixup kind!");
case FK_Data_8: Type = ELF::R_X86_64_64; break;
case X86::reloc_signed_4byte:
switch (Modifier) {
default:
llvm_unreachable("Unimplemented");
case MCSymbolRefExpr::VK_None:
Type = ELF::R_X86_64_32S;
break;
case MCSymbolRefExpr::VK_GOT:
Type = ELF::R_X86_64_GOT32;
break;
case MCSymbolRefExpr::VK_GOTPCREL:
Type = ELF::R_X86_64_GOTPCREL;
break;
case MCSymbolRefExpr::VK_TPOFF:
Type = ELF::R_X86_64_TPOFF32;
break;
case MCSymbolRefExpr::VK_DTPOFF:
Type = ELF::R_X86_64_DTPOFF32;
break;
}
break;
case FK_Data_4:
Type = ELF::R_X86_64_32;
break;
case FK_Data_2: Type = ELF::R_X86_64_16; break;
case FK_PCRel_1:
case FK_Data_1: Type = ELF::R_X86_64_8; break;
}
}
} else if (getEMachine() == ELF::EM_386) {
if (IsPCRel) {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("invalid fixup kind!");
case X86::reloc_global_offset_table:
Type = ELF::R_386_GOTPC;
break;
case X86::reloc_signed_4byte:
case FK_PCRel_4:
case FK_Data_4:
switch (Modifier) {
default:
llvm_unreachable("Unimplemented");
case MCSymbolRefExpr::VK_None:
Type = ELF::R_386_PC32;
break;
case MCSymbolRefExpr::VK_PLT:
Type = ELF::R_386_PLT32;
break;
}
break;
}
} else {
switch ((unsigned)Fixup.getKind()) {
default: llvm_unreachable("invalid fixup kind!");
case X86::reloc_global_offset_table:
Type = ELF::R_386_GOTPC;
break;
// FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
// instead?
case X86::reloc_signed_4byte:
case FK_PCRel_4:
case FK_Data_4:
switch (Modifier) {
default:
llvm_unreachable("Unimplemented");
case MCSymbolRefExpr::VK_None:
Type = ELF::R_386_32;
break;
case MCSymbolRefExpr::VK_GOT:
Type = ELF::R_386_GOT32;
break;
case MCSymbolRefExpr::VK_GOTOFF:
Type = ELF::R_386_GOTOFF;
break;
case MCSymbolRefExpr::VK_TLSGD:
Type = ELF::R_386_TLS_GD;
break;
case MCSymbolRefExpr::VK_TPOFF:
Type = ELF::R_386_TLS_LE_32;
break;
case MCSymbolRefExpr::VK_INDNTPOFF:
Type = ELF::R_386_TLS_IE;
break;
case MCSymbolRefExpr::VK_NTPOFF:
Type = ELF::R_386_TLS_LE;
break;
case MCSymbolRefExpr::VK_GOTNTPOFF:
Type = ELF::R_386_TLS_GOTIE;
break;
case MCSymbolRefExpr::VK_TLSLDM:
Type = ELF::R_386_TLS_LDM;
break;
case MCSymbolRefExpr::VK_DTPOFF:
Type = ELF::R_386_TLS_LDO_32;
break;
case MCSymbolRefExpr::VK_GOTTPOFF:
Type = ELF::R_386_TLS_IE_32;
break;
}
break;
case FK_Data_2: Type = ELF::R_386_16; break;
case FK_PCRel_1:
case FK_Data_1: Type = ELF::R_386_8; break;
}
}
} else
llvm_unreachable("Unsupported ELF machine type.");
return Type;
}
MCObjectWriter *llvm::createX86ELFObjectWriter(raw_ostream &OS,
bool IsELF64,
uint8_t OSABI,
uint16_t EMachine) {
MCELFObjectTargetWriter *MOTW =
new X86ELFObjectWriter(IsELF64, OSABI, EMachine);
return createELFObjectWriter(MOTW, OS, /*IsLittleEndian=*/true);
}
| dbrumley/recfi | llvm-3.3/lib/Target/X86/MCTargetDesc/X86ELFObjectWriter.cpp | C++ | mit | 7,285 |
##
# = JavaScript Object Notation (JSON)
#
# JSON is a lightweight data-interchange format. It is easy for us
# humans to read and write. Plus, equally simple for machines to generate or parse.
# JSON is completely language agnostic, making it the ideal interchange format.
#
# Built on two universally available structures:
# 1. A collection of name/value pairs. Often referred to as an _object_, hash table, record, struct, keyed list, or associative array.
# 2. An orderd list of values. More commonly named as an _array_, vector, sequence, or list.
#
# To read more about JSON visit: http://json.org
#
# == Parsing JSON
#
# To parse a JSON string received by another application, or generated within
# your existing application:
#
# require 'json'
#
# my_hash = JSON.parse('{"hello": "goodbye"}')
# puts my_hash["hello"] => "goodbye"
#
# Notice the extra quotes <tt>''</tt> around the hash notation. Ruby expects
# the argument to be a string and can't convert objects like a hash or array.
#
# Ruby converts your string into a hash
#
# == Generating JSON
#
# Creating a JSON string for communication or serialization is
# just as simple.
#
# require 'json'
#
# my_hash = {:hello => "goodbye"}
# puts JSON.generate(my_hash) => "{\"hello\":\"goodbye\"}"
#
# Or an alternative way:
#
# require 'json'
# puts {:hello => "goodbye"}.to_json => "{\"hello\":\"goodbye\"}"
#
# <tt>JSON.generate</tt> only allows objects or arrays to be converted
# to JSON syntax. While <tt>to_json</tt> accepts many Ruby classes
# even though it only acts a method for serialization:
#
# require 'json'
#
# 1.to_json => "1"
#
require 'json/common'
module JSON
require 'json/version'
begin
require 'json/ext'
rescue LoadError
require 'json/pure'
end
end
| smgt/alfred-workflow-rubygems | vendor/json_pure/json.rb | Ruby | mit | 1,783 |
/**
* @fileoverview Restrict usage of duplicate imports.
* @author Simen Bekkhus
* @copyright 2016 Simen Bekkhus. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/**
* Returns the name of the module imported or re-exported.
*
* @param {ASTNode} node - A node to get.
* @returns {string} the name of the module, or empty string if no name.
*/
function getValue(node) {
if (node && node.source && node.source.value) {
return node.source.value.trim();
}
return "";
}
/**
* Checks if the name of the import or export exists in the given array, and reports if so.
*
* @param {RuleContext} context - The ESLint rule context object.
* @param {ASTNode} node - A node to get.
* @param {string} value - The name of the imported or exported module.
* @param {string[]} array - The array containing other imports or exports in the file.
* @param {string} message - A message to be reported after the name of the module
*
* @returns {void} No return value
*/
function checkAndReport(context, node, value, array, message) {
if (array.indexOf(value) !== -1) {
context.report({
node: node,
message: "'{{module}}' " + message,
data: {module: value}
});
}
}
/**
* @callback nodeCallback
* @param {ASTNode} node - A node to handle.
*/
/**
* Returns a function handling the imports of a given file
*
* @param {RuleContext} context - The ESLint rule context object.
* @param {boolean} includeExports - Whether or not to check for exports in addition to imports.
* @param {string[]} importsInFile - The array containing other imports in the file.
* @param {string[]} exportsInFile - The array containing other exports in the file.
*
* @returns {nodeCallback} A function passed to ESLint to handle the statement.
*/
function handleImports(context, includeExports, importsInFile, exportsInFile) {
return function(node) {
var value = getValue(node);
if (value) {
checkAndReport(context, node, value, importsInFile, "import is duplicated.");
if (includeExports) {
checkAndReport(context, node, value, exportsInFile, "import is duplicated as export.");
}
importsInFile.push(value);
}
};
}
/**
* Returns a function handling the exports of a given file
*
* @param {RuleContext} context - The ESLint rule context object.
* @param {string[]} importsInFile - The array containing other imports in the file.
* @param {string[]} exportsInFile - The array containing other exports in the file.
*
* @returns {nodeCallback} A function passed to ESLint to handle the statement.
*/
function handleExports(context, importsInFile, exportsInFile) {
return function(node) {
var value = getValue(node);
if (value) {
checkAndReport(context, node, value, exportsInFile, "export is duplicated.");
checkAndReport(context, node, value, importsInFile, "export is duplicated as import.");
exportsInFile.push(value);
}
};
}
module.exports = function(context) {
var includeExports = (context.options[0] || {}).includeExports,
importsInFile = [],
exportsInFile = [];
var handlers = {
"ImportDeclaration": handleImports(context, includeExports, importsInFile, exportsInFile)
};
if (includeExports) {
handlers.ExportNamedDeclaration = handleExports(context, importsInFile, exportsInFile);
handlers.ExportAllDeclaration = handleExports(context, importsInFile, exportsInFile);
}
return handlers;
};
module.exports.schema = [{
"type": "object",
"properties": {
"includeExports": {
"type": "boolean"
}
},
"additionalProperties": false
}];
| sauceSquatch/we_are_razorfish_experience | node_modules/eslint/lib/rules/no-duplicate-imports.js | JavaScript | mit | 4,014 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.core.util;
import com.sun.jna.Library;
import com.sun.jna.Native;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
/**
* Process manager for *nix like system.
*
* @author andrew00x
*/
class UnixProcessManager extends ProcessManager {
/*
At the moment tested on linux only.
*/
private static final Logger LOG = LoggerFactory.getLogger(UnixProcessManager.class);
private static final CLibrary C_LIBRARY;
private static final Field PID_FIELD;
static {
CLibrary lib = null;
Field pidField = null;
if (SystemInfo.isUnix()) {
try {
lib = ((CLibrary)Native.loadLibrary("c", CLibrary.class));
} catch (Exception e) {
LOG.error("Cannot load native library", e);
}
try {
pidField = Thread.currentThread().getContextClassLoader().loadClass("java.lang.UNIXProcess").getDeclaredField("pid");
pidField.setAccessible(true);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
C_LIBRARY = lib;
PID_FIELD = pidField;
}
private static interface CLibrary extends Library {
// kill -l
int SIGKILL = 9;
int SIGTERM = 15;
int kill(int pid, int signal);
String strerror(int errno);
int system(String cmd);
}
private static final Pattern UNIX_PS_TABLE_PATTERN = Pattern.compile("\\s+");
@Override
public void kill(Process process) {
if (C_LIBRARY != null) {
killTree(getPid(process));
} else {
throw new IllegalStateException("Can't kill process. Not unix system?");
}
}
private void killTree(int pid) {
final int[] children = getChildProcesses(pid);
LOG.debug("PID: {}, child PIDs: {}", pid, children);
if (children.length > 0) {
for (int cpid : children) {
killTree(cpid); // kill process tree recursively
}
}
int r = C_LIBRARY.kill(pid, CLibrary.SIGKILL); // kill origin process
LOG.debug("kill {}", pid);
if (r != 0) {
if (LOG.isDebugEnabled()) {
LOG.debug("kill for {} returns {}, strerror '{}'", pid, r, C_LIBRARY.strerror(r));
}
}
}
private int[] getChildProcesses(final int myPid) {
final String ps = "ps -e -o ppid,pid,comm"; /* PPID, PID, COMMAND */
final List<Integer> children = new ArrayList<>();
final StringBuilder error = new StringBuilder();
final LineConsumer stdout = new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
if (line != null && !line.isEmpty()) {
final String[] tokens = UNIX_PS_TABLE_PATTERN.split(line.trim());
if (tokens.length == 3 /* PPID, PID, COMMAND */) {
int ppid;
try {
ppid = Integer.parseInt(tokens[0]);
} catch (NumberFormatException e) {
// May be first line from process table: 'PPID PID COMMAND'. Skip it.
return;
}
if (ppid == myPid) {
int pid = Integer.parseInt(tokens[1]);
children.add(pid);
}
}
}
}
@Override
public void close() throws IOException {
}
};
final LineConsumer stderr = new LineConsumer() {
@Override
public void writeLine(String line) throws IOException {
if (error.length() > 0) {
error.append('\n');
}
error.append(line);
}
@Override
public void close() throws IOException {
}
};
try {
ProcessUtil.process(Runtime.getRuntime().exec(ps), stdout, stderr);
} catch (IOException e) {
throw new IllegalStateException(e);
}
if (error.length() > 0) {
throw new IllegalStateException("can't get child processes: " + error.toString());
}
final int size = children.size();
final int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = children.get(i);
}
return result;
}
@Override
public boolean isAlive(Process process) {
return process.isAlive();
}
int getPid(Process process) {
if (PID_FIELD != null) {
try {
return ((Number)PID_FIELD.get(process)).intValue();
} catch (IllegalAccessException e) {
throw new IllegalStateException("Can't get process' pid. Not unix system?", e);
}
} else {
throw new IllegalStateException("Can't get process' pid. Not unix system?");
}
}
@Override
int system(String command) {
return C_LIBRARY.system(command);
}
}
| gazarenkov/che-sketch | core/che-core-api-core/src/main/java/org/eclipse/che/api/core/util/UnixProcessManager.java | Java | epl-1.0 | 5,909 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ui.toolbar;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.RootPanel;
/**
* This Lock Layer for Popup Menu uses as root for for Popup Menus and uses for closing all visible popups when user clicked outside one of
* them.
*
* @author Vitaliy Guliy
*/
public class MenuLockLayer extends AbsolutePanel {
/** Lock Layer uses for locking of screen. Uses for hiding popups. */
private class LockLayer extends AbsolutePanel {
public LockLayer() {
sinkEvents(Event.ONMOUSEDOWN);
}
@Override
public void onBrowserEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
close();
break;
}
}
}
/** Callback which is uses for closing Popup menu. */
private CloseMenuHandler closeMenuCallback;
private int topOffset = 20;
/** Create Menu Lock Layer. */
public MenuLockLayer() {
this(null, 0);
}
/**
* Create Menu Lock Layer.
*
* @param closeMenuCallback
* - callback which is uses for
*/
public MenuLockLayer(CloseMenuHandler closeMenuCallback) {
this(closeMenuCallback, 0);
}
public MenuLockLayer(CloseMenuHandler closeMenuCallback, int topOffset) {
this.closeMenuCallback = closeMenuCallback;
this.topOffset = topOffset;
getElement().setId("menu-lock-layer-id");
RootPanel.get().add(this, 0, topOffset);
getElement().getStyle().setProperty("right", "0px");
getElement().getStyle().setProperty("bottom", "0px");
getElement().getStyle().setProperty("zIndex", (Integer.MAX_VALUE - 5) + "");
AbsolutePanel blockMouseEventsPanel = new LockLayer();
blockMouseEventsPanel.setStyleName("exo-lockLayer");
blockMouseEventsPanel.getElement().getStyle().setProperty("position", "absolute");
blockMouseEventsPanel.getElement().getStyle().setProperty("left", "0px");
blockMouseEventsPanel.getElement().getStyle().setProperty("top", "0px");
blockMouseEventsPanel.getElement().getStyle().setProperty("right", "0px");
blockMouseEventsPanel.getElement().getStyle().setProperty("bottom", "0px");
add(blockMouseEventsPanel);
}
public void close() {
removeFromParent();
if (closeMenuCallback != null) {
closeMenuCallback.onCloseMenu();
}
}
public int getTopOffset() {
return topOffset;
}
}
| gazarenkov/che-sketch | ide/che-core-ide-ui/src/main/java/org/eclipse/che/ide/ui/toolbar/MenuLockLayer.java | Java | epl-1.0 | 3,234 |
package backtype.storm.state;
import java.util.List;
public interface ISynchronizeOutputCollector {
void add(int streamId, Object id, List<Object> tuple);
}
| revans2/storm | storm-core/src/jvm/backtype/storm/state/ISynchronizeOutputCollector.java | Java | epl-1.0 | 167 |
/*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.core.rest;
import javax.ws.rs.core.UriBuilder;
/**
* Helps to deliver context of RESTful request to components.
*
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
*/
public interface ServiceContext {
/**
* Get UriBuilder which already contains base URI of RESTful application and URL pattern of RESTful service that produces this
* instance.
*/
UriBuilder getServiceUriBuilder();
/** Get UriBuilder which already contains base URI of RESTful application. */
UriBuilder getBaseUriBuilder();
}
| gazarenkov/che-sketch | core/che-core-api-core/src/main/java/org/eclipse/che/api/core/rest/ServiceContext.java | Java | epl-1.0 | 1,098 |
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.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, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Ouro
SD%Complete: 85
SDComment: No model for submerging. Currently just invisible.
SDCategory: Temple of Ahn'Qiraj
EndScriptData */
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "temple_of_ahnqiraj.h"
enum Spells
{
SPELL_SWEEP = 26103,
SPELL_SANDBLAST = 26102,
SPELL_GROUND_RUPTURE = 26100,
SPELL_BIRTH = 26262, // The Birth Animation
SPELL_DIRTMOUND_PASSIVE = 26092
};
class boss_ouro : public CreatureScript
{
public:
boss_ouro() : CreatureScript("boss_ouro") { }
CreatureAI* GetAI(Creature* creature) const
{
return new boss_ouroAI (creature);
}
struct boss_ouroAI : public ScriptedAI
{
boss_ouroAI(Creature* creature) : ScriptedAI(creature) {}
uint32 Sweep_Timer;
uint32 SandBlast_Timer;
uint32 Submerge_Timer;
uint32 Back_Timer;
uint32 ChangeTarget_Timer;
uint32 Spawn_Timer;
bool Enrage;
bool Submerged;
void Reset()
{
Sweep_Timer = urand(5000, 10000);
SandBlast_Timer = urand(20000, 35000);
Submerge_Timer = urand(90000, 150000);
Back_Timer = urand(30000, 45000);
ChangeTarget_Timer = urand(5000, 8000);
Spawn_Timer = urand(10000, 20000);
Enrage = false;
Submerged = false;
}
void EnterCombat(Unit* /*who*/)
{
DoCast(me->GetVictim(), SPELL_BIRTH);
}
void UpdateAI(uint32 diff)
{
//Return since we have no target
if (!UpdateVictim())
return;
//Sweep_Timer
if (!Submerged && Sweep_Timer <= diff)
{
DoCast(me->GetVictim(), SPELL_SWEEP);
Sweep_Timer = urand(15000, 30000);
} else Sweep_Timer -= diff;
//SandBlast_Timer
if (!Submerged && SandBlast_Timer <= diff)
{
DoCast(me->GetVictim(), SPELL_SANDBLAST);
SandBlast_Timer = urand(20000, 35000);
} else SandBlast_Timer -= diff;
//Submerge_Timer
if (!Submerged && Submerge_Timer <= diff)
{
//Cast
me->HandleEmoteCommand(EMOTE_ONESHOT_SUBMERGE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->setFaction(35);
DoCast(me, SPELL_DIRTMOUND_PASSIVE);
Submerged = true;
Back_Timer = urand(30000, 45000);
} else Submerge_Timer -= diff;
//ChangeTarget_Timer
if (Submerged && ChangeTarget_Timer <= diff)
{
Unit* target = NULL;
target = SelectTarget(SELECT_TARGET_RANDOM, 0);
if (target)
DoTeleportTo(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ());
ChangeTarget_Timer = urand(10000, 20000);
} else ChangeTarget_Timer -= diff;
//Back_Timer
if (Submerged && Back_Timer <= diff)
{
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->setFaction(14);
DoCast(me->GetVictim(), SPELL_GROUND_RUPTURE);
Submerged = false;
Submerge_Timer = urand(60000, 120000);
} else Back_Timer -= diff;
DoMeleeAttackIfReady();
}
};
};
void AddSC_boss_ouro()
{
new boss_ouro();
}
| Sakratus/TC-Cata | src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_ouro.cpp | C++ | gpl-2.0 | 4,415 |
/* -*- c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Copyright(C) 2010 Tetsuro IKEDA
Copyright(C) 2010-2013 Kentoku SHIBA
Copyright(C) 2011-2017 Kouhei Sutou <kou@clear-code.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA
*/
#include <mrn_mysql.h>
#include <mrn_windows.hpp>
#include <mrn_table.hpp>
#include <mrn_macro.hpp>
#include <mrn_current_thread.hpp>
MRN_BEGIN_DECLS
MRN_API my_bool last_insert_grn_id_init(UDF_INIT *init, UDF_ARGS *args, char *message)
{
if (args->arg_count != 0) {
strcpy(message, "last_insert_grn_id must not have arguments");
return 1;
}
init->maybe_null = 0;
return 0;
}
MRN_API longlong last_insert_grn_id(UDF_INIT *init, UDF_ARGS *args, char *is_null, char *error)
{
THD *thd = current_thd;
st_mrn_slot_data *slot_data = mrn_get_slot_data(thd, false);
if (slot_data == NULL) {
return 0;
}
longlong last_insert_record_id = slot_data->last_insert_record_id;
return last_insert_record_id;
}
MRN_API void last_insert_grn_id_deinit(UDF_INIT *init)
{
}
MRN_END_DECLS
| MariaDB/server | storage/mroonga/udf/mrn_udf_last_insert_grn_id.cpp | C++ | gpl-2.0 | 1,726 |
<?php
/**
* @version $Id$
* @package JSNExtension
* @subpackage TPLFramework
* @author JoomlaShine Team <support@joomlashine.com>
* @copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved.
* @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*
* Websites: http://www.joomlashine.com
* Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$utils = JSNTplUtils::getInstance();
// Get all fieldset in XML
$fieldSets = $adminFormXml->fields->fieldset;
// Set appropriate wrapper class
$wrapperClass = 'jsn-joomla' . JSNTplHelper::getJoomlaVersion(1, false);
// Get template details
$template = JSNTplTemplateRecognization::detect($this->data->template);
// Prepare template name for link generation
$templateName = 'jsn-' . strtolower($template->name);
// Generate template introduction link
$templateLink = "http://www.joomlashine.com/joomla-templates/{$templateName}.html";
// Process template edition
$edition = $this->templateEdition->getEdition();
if ($edition == 'FREE')
{
$editionClass = 'jsn-free-edition';
}
else
{
$editionClass = 'jsn-pro-edition';
}
// Get next template edition
$nextEdition = str_replace('PRO ', '', $this->templateEdition->getNextEdition());
// Get installed template version
$version = JSNTplHelper::getTemplateVersion($this->data->template);
// Get list of JoomlaShine template for cross promotion
$promotion = $nextEdition == 'STANDARD' ? true : false;
if ($promotion)
{
$config = JFactory::getConfig();
$cache = $config->get('tmp_path') . '/jsn_templates.json';
if ( ! @is_file($cache) || ! @is_readable($cache) || time() - filemtime($cache) > 86400)
{
try
{
$jsn_templates = JSNTplHttpRequest::get(
'http://demo.joomlashine.com/products-intro/assets/json/showlist-templates-' . ($nextEdition == 'STANDARD' ? 'free' : 'pro') . '.json',
$cache
);
$jsn_templates = $jsn_templates['body'];
}
catch (Exception $e)
{
// Disable cross promotion
$promotion = false;
}
}
else
{
$jsn_templates = JFile::read($cache);
}
if ($jsn_templates = json_decode($jsn_templates))
{
$jsn_templates = $jsn_templates->showlist->images->image;
}
else
{
$promotion = false;
}
}
$jversion = new JVersion();
$megamenu = (string) $this->templateXml->megamenu;
// Migrate megamenu data
if ($megamenu == 'yes')
{
if (version_compare($jversion->getShortVersion(), '3.0', ">="))
{
include_once JSN_PATH_TPLFRAMEWORK_MEGAMENU_LIBRARIES . '/helpers/megamenu.php';
JSNTplMMHelperMegamenu::migrate();
}
}
$plgTplBrand = $utils->checkPlgJSNBrand();
$showUpgradeButton = 1;
$showChangelog = 1;
$showThumbnailLink = 1;
$showCopyrightContent = 1;
$replaceFooterContent = 0;
$replaceGettingStartedContent = 0;
$replacedGettingStartedContent = '';
$replacedFooterContent = '';
if ($plgTplBrand)
{
$dispatcher = JEventDispatcher::getInstance();
$rload = JPluginHelper::importPlugin('system', 'jsnbrand');
if ($rload === true)
{
$showUpgradeButton = $dispatcher->trigger('showTplUpgradeButton');
$showUpgradeButton = (int) $showUpgradeButton[0];
$showChangelog = $dispatcher->trigger('showTplChangelog');
$showChangelog = (int) $showChangelog[0];
$showThumbnailLink = $dispatcher->trigger('showTplThumbnailLink');
$showThumbnailLink = (int) $showThumbnailLink[0];
$showCopyrightContent = $dispatcher->trigger('showTplCopyrightContent');
$showCopyrightContent = (int) $showCopyrightContent[0];
$replaceFooterContent = $dispatcher->trigger('replaceTplFooterContent');
$replaceFooterContent = (int) $replaceFooterContent[0];
$replacedFooterContent = $dispatcher->trigger('getTplFooterContent');
$replacedFooterContent = (string) $replacedFooterContent[0];
$replaceGettingStartedContent = $dispatcher->trigger('replaceTplGettingStartedContent');
$replaceGettingStartedContent = (int) $replaceGettingStartedContent[0];
$replacedGettingStartedContent = $dispatcher->trigger('getTplGettingStartedContent');
$replacedGettingStartedContent = (string) $replacedGettingStartedContent[0];
}
}
if (!$showThumbnailLink)
{
$templateLink = '#';
}
?>
<div class="jsn-master"><div id="jsn-template-config" class="jsn-bootstrap <?php echo $wrapperClass ?> <?php echo $editionClass ?>">
<form action="" method="POST" name="adminForm" id="style-form">
<input type="hidden" name="task" />
<input type="hidden" id="jsn-tpl-style-id" value="<?php echo JFactory::getApplication()->input->getInt('id', 0); ?>" />
<input type="hidden" id="jsn-tpl-edition" value="<?php echo strtolower(trim($edition)); ?>" />
<input type="hidden" id="jsn-tpl-name" value="<?php echo strtolower(trim($this->data->template)); ?>" />
<input type="hidden" id="jsn-tpl-token" value="<?php echo JSession::getFormToken(); ?>" />
<input type="hidden" name="customized" value="<?php echo @count($this->data->params) ? 'yes' : 'no'; ?>" />
<?php echo JHtml::_('form.token'); ?>
<div id="jsn-template-toolbar">
<label for="jform_title pull-left"><?php echo JText::_('JSN_TPLFW_FIELD_TITLE_LABEL') ?></label>
<?php echo $this->templateForm->getInput('title') ?>
<label for="jform_template pull-left"><?php echo JText::_('COM_TEMPLATES_FIELD_TEMPLATE_LABEL') ?></label>
<?php echo $this->templateForm->getInput('template') ?>
<label for="jform_home pull-left"><?php echo JText::_('COM_TEMPLATES_FIELD_HOME_LABEL') ?></label>
<?php echo $this->templateForm->getInput('home') ?>
<?php echo $this->templateForm->getInput('client_id') ?>
<div class="clearfix"></div>
</div>
<div id="jsn-template-config-tabs" class="jsn-hide form-horizontal">
<ul id="jsn-main-nav">
<li>
<a href="#getting-started">
<i class="icon-home icon-black"></i>
<?php echo JText::_('JSN_TPLFW_GETTING_STARTED') ?>
</a>
</li>
<?php foreach ($fieldSets as $fieldSet): ?>
<?php
$valid = false;
if (isset($fieldSet['joomlaVersion']))
{
if (version_compare($jversion->getShortVersion(), (string) $fieldSet['joomlaVersion'], ">="))
{
$valid = true;
}
}
else
{
$valid = true;
}
?>
<?php if ($valid) : ?>
<?php
if ((string) $fieldSet['name'] == 'jsn-megamenu' && $megamenu != 'yes')
{
continue;
}
?>
<?php $class = isset($fieldSet['pro']) && $fieldSet['pro'] == 'true' ? 'jsn-pro-tab' : '' ?>
<li class="<?php echo $class ?>">
<a href="#<?php echo $fieldSet['name'] ?>">
<?php if (isset($fieldSet['icon'])): ?>
<i class="<?php echo $fieldSet['icon'] ?>"></i>
<?php endif ?>
<?php echo JText::_($fieldSet['label']) ?>
<?php if (isset($fieldSet['pro']) && $fieldSet['pro'] == 'true'): ?>
<span class="label label-important label-pro">PRO</span>
<?php endif ?>
</a>
</li>
<?php endif ?>
<?php endforeach ?>
<li><a href="#menu-assignment"><i class="icon-checkbox"></i> <?php echo JText::_('JSN_TPLFW_MENU_ASSIGNMENT') ?></a></li>
</ul>
<div id="jsn-template-maintenance" class="btn-group pull-right">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
<?php echo JText::_('JSN_TPLFW_MAINTENANCE'); ?>
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a id="jsn-template-maintenance-backup-params" href="<?php echo JRoute::_('index.php?widget=maintenance&action=backup&template=' . $this->data->template) . '&styleId=' . $this->data->id; ?>"><?php echo JText::_('JSN_TPLFW_MAINTENANCE_BACKUP'); ?></a></li>
<li><a id="jsn-template-maintenance-restore-params" href="<?php echo JRoute::_('index.php?widget=maintenance&action=restore&template=' . $this->data->template) . '&styleId=' . $this->data->id; ?>"><?php echo JText::_('JSN_TPLFW_MAINTENANCE_RESTORE'); ?></a></li>
</ul>
</div>
<div class="row-fluid" id="getting-started">
<?php include JSN_PATH_TPLFRAMEWORK_LIBRARIES . '/template/tmpl/default_home.php' ?>
</div>
<?php foreach ($fieldSets as $xmlFieldSet): ?>
<?php
$valid = false;
if (isset($xmlFieldSet['joomlaVersion']))
{
if (version_compare($jversion->getShortVersion(), (string) $xmlFieldSet['joomlaVersion'], ">="))
{
$valid = true;
}
}
else
{
$valid = true;
}
?>
<?php if ($valid) : ?>
<?php
if ((string) $xmlFieldSet['name'] == 'jsn-megamenu' && $megamenu != 'yes')
{
continue;
}
?>
<div id="<?php echo $xmlFieldSet['name'] ?>">
<?php if (isset($xmlFieldSet['pro']) && $xmlFieldSet['pro'] == 'true' && $this->templateEdition->getEdition() == 'FREE'): ?>
<div class="jsn-section-pro alert alert-block">
<p class="pull-left"><?php echo JText::_('JSN_TPLFW_FEATURES_AVAILABLE_IN_PRO') ?></p>
<?php if ($showUpgradeButton) {?>
<a href="javascript:void(0)" class="jsn-upgrade-link btn pull-right"><?php echo JText::_('JSN_TPLFW_UPGRADE_NOW') ?></a>
<?php } ?>
<div class="clearfix"></div>
</div>
<?php endif ?>
<?php if (isset($xmlFieldSet['twoColumns']) && $xmlFieldSet['twoColumns'] == 'true'): ?>
<?php include JSN_PATH_TPLFRAMEWORK_LIBRARIES . '/template/tmpl/default_layout.php' ?>
<?php else: ?>
<?php foreach ($xmlFieldSet->children() as $field): ?>
<?php $nodeName = strtolower($field->getName()) ?>
<?php if ($nodeName == 'field'): ?>
<?php $input = $this->adminForm->getField($field['name'], 'jsn') ?>
<?php if (trim($field['label']) != '') : ?>
<div class="control-group">
<div class="control-label">
<label for="<?php echo $input->id ?>" rel="tipsy" title="<?php echo JText::_($field['label'] . '_DESC') ?>">
<?php echo JText::_($field['label']) ?>
</label>
</div>
<div class="controls">
<?php echo str_replace('%TEMPLATE%', $this->data->template, $input->input) ?>
</div>
</div>
<?php else : ?>
<div>
<?php echo str_replace('%TEMPLATE%', $this->data->template, $input->input) ?>
</div>
<?php endif; ?>
<?php elseif ($nodeName == 'fieldset'): ?>
<fieldset class="<?php echo $field['name'] ?>">
<legend><?php echo JText::_($field['label']) ?></legend>
<?php foreach ($field->children() as $innerField): ?>
<?php $input = $this->adminForm->getField($innerField['name'], 'jsn') ?>
<?php if (trim($innerField['label']) != '') : ?>
<div class="control-group">
<div class="control-label">
<label for="<?php echo $input->id ?>" rel="tipsy" title="<?php echo JText::_($innerField['label'] . '_DESC') ?>">
<?php echo JText::_($innerField['label']) ?>
</label>
</div>
<div class="controls">
<?php echo str_replace('%TEMPLATE%', $this->data->template, $input->input) ?>
</div>
</div>
<?php else : ?>
<div>
<?php echo str_replace('%TEMPLATE%', $this->data->template, $input->input) ?>
</div>
<?php endif; ?>
<?php endforeach ?>
</fieldset>
<?php endif ?>
<?php endforeach ?>
<?php endif ?>
</div>
<?php endif ?>
<?php endforeach ?>
<div id="menu-assignment">
<?php include JSN_PATH_TPLFRAMEWORK_LIBRARIES . '/template/tmpl/default_assignment.php' ?>
</div>
</div>
</form>
<?php if ($promotion) : ?>
<div id="see-other-products">
<h2 class="jsn-section-header">
<?php echo JText::_('JSN_TPLFW_SEE_OTHER_PRODUCTS') ?>
<ul class="jsn-list-horizontal pull-right">
<li>
<a
class="jsn-icon24 jsn-icon-social jsn-icon-facebook"
href="http://www.facebook.com/joomlashine"
title="<?php echo JText::_('JSN_TPLFW_CONNECT_WITH_US_ON_FACEBOOK') ?>"
target="_blank">
</a>
</li>
<li>
<a
class="jsn-icon24 jsn-icon-social jsn-icon-twitter"
href="http://www.twitter.com/joomlashine"
title="<?php echo JText::_('JSN_TPLFW_FOLLOW_US_ON_TWITTER') ?>"
target="_blank">
</a>
</li>
<li>
<a
class="jsn-icon24 jsn-icon-social jsn-icon-youtube"
href="http://www.youtube.com/joomlashine"
title="<?php echo JText::_('JSN_TPLFW_WATCH_US_ON_YOUTUBE') ?>"
target="_blank">
</a>
</li>
</ul>
</h2>
<div class="clearbreak"></div>
<div class="bxslider">
<?php foreach ($jsn_templates as $item) :
$download = 'javascript:void(0)';
$title = 'Joomla Templates by JoomlaShine.com';
if (preg_match('#/jsn-([a-z0-9]+)\.#i', $item->image, $m))
{
$download = 'http://www.joomlashine.com/joomla-templates/jsn-' . $m[1] . '-download.html';
$title = 'JSN ' . ucfirst($m[1]);
} ?>
<a <?php echo 'href="http://demo.joomlashine.com/products-intro/' . $item->image . '" title="' . $title . '" data-demo="' . $item->link . '" data-download="' . $download . '" rel="cross-promo"'; ?>>
<img src="http://demo.joomlashine.com/products-intro/<?php echo $item->thumbnail; ?>" />
</a>
<?php endforeach; ?>
</div>
<input type="hidden" name="visited" value="" />
<script type="text/javascript">
(function($) {
$(document).ready(function() {
var promotion = $('.bxslider'); slicesPerView = parseInt(promotion.innerWidth() / 250);
promotion.bxSlider({
hideControlOnEnd: true,
adaptiveHeight: true,
pager: false,
slideWidth: 250,
slideMargin: 10,
minSlides: slicesPerView,
maxSlides: slicesPerView,
});
$('.bxslider > a').colorbox({
rel: 'cross-promo',
onComplete: function(event) {
// Set title
$('#colorbox #cboxCurrent').html($(event.el).attr('title'));
// Set buttons
$('#colorbox #cboxTitle').html(
'<div class="jsn-master"><div class="jsn-bootstrap">'
+
'<a href="' + $(event.el).attr('data-demo') + '" class="btn btn-primary" target="_blank"><?php echo JText::_('JSN_TPLFW_DEMO'); ?></a>'
+
'<a href="' + $(event.el).attr('data-download') + '" class="btn btn-success" target="_blank"><?php echo JText::_('JSN_TPLFW_DOWNLOAD'); ?></a>'
+
'</div></div>'
);
},
});
});
})(jQuery);
</script>
</div>
<?php endif; ?>
<div class="modal hide" id="jsn_pro_edition_only_modal">
<div class="modal-body">
<p><?php echo JText::_('JSN_TPLFW_PRO_EDITION_ONLY'); ?></p>
</div>
<div class="modal-footer">
<a class="btn btn-primary jsn-upgrade-link" href="javascript:void(0)" onclick="jQuery(this).parent().parent().addClass('hide');"><?php echo JText::_('JSN_TPLFW_UPGRADE_NOW'); ?></a>
<a class="btn" href="javascript:void(0)" onclick="jQuery(this).parent().parent().addClass('hide');"><?php echo JText::_('JSN_TPLFW_CLOSE'); ?></a>
</div>
</div>
<div class="jsn-form-validation-failed jsn-box-shadow-medium alert alert-error hide">
<span></span>
<a href="javascript:void(0);" title="<?php echo JText::_('JSN_TPLFW_CLOSE'); ?>" class="close" onclick="jQuery(this).parent().addClass('hide');">×</a>
</div>
</div></div>
<div class="jsn-master">
<div class="jsn-page-footer jsn-bootstrap" id="jsn-footer">
<?php if ($replaceFooterContent) { ?>
<?php echo $replacedFooterContent; ?>
<?php } else { ?>
<div class="pull-left">
<ul class="jsn-footer-menu">
<li class="first">
<a target="_blank" href="http://www.joomlashine.com/joomla-templates/<?php echo $templateName ?>-docs.zip"><?php echo JText::_('JSN_TPLFW_DOCUMENTATION'); ?></a>
</li>
<li>
<a target="_blank" href="http://www.joomlashine.com/contact-us/get-support.html"><?php echo JText::_('JSN_TPLFW_SUPPORT'); ?></a>
</li>
<li class="jsn-iconbar">
<strong>Keep in touch:</strong>
<a href="http://www.facebook.com/joomlashine" target="_blank" title="Find us on Facebook"><i class="jsn-icon16 jsn-icon-social jsn-icon-facebook"></i></a><a href="http://www.twitter.com/joomlashine" target="_blank" title="Follow us on Twitter"><i "="" class="jsn-icon16 jsn-icon-social jsn-icon-twitter"></i></a><a href="http://www.youtube.com/joomlashine" target="_blank" title="Watch us on YouTube"><i "="" class="jsn-icon16 jsn-icon-social jsn-icon-youtube"></i></a>
</li>
</ul>
<ul class="jsn-footer-menu">
<li class="first">
<a target="_blank" href="<?php echo $templateLink ?>"><?php echo JText::_($template->name) ?> <?php echo $edition ?> v<?php echo $version ?></a> by <a target="_blank" href="http://www.joomlashine.com">JoomlaShine.com</a>
<?php if ($nextEdition) : ?>
<a class="label label-important jsn-upgrade-link" href="javascript:void()"><strong class="jsn-text-attention"><?php echo JText::_($nextEdition == 'STANDARD' ? 'JSN_TPLFW_UPGRADE_TO_PRO' : 'JSN_TPLFW_UPGRADE_TO_PRO_UNLIMITED'); ?></strong></a>
<?php endif; ?>
</li>
<li class="jsn-outdated-version" id="jsn-global-check-version-result" style="display:none">
<span class="jsn-global-outdated-version"><?php echo JText::_('JSN_TPLFW_UPDATE_AVAILABLE'); ?></span>
<a class="label label-important jsn-update-link" data-target="template" href="javascript:void(0)"><?php echo JText::_('JSN_TPLFW_UPDATE_NOW'); ?></a>
</li>
</ul>
</div>
<div class="pull-right">
<ul class="jsn-footer-menu">
<li class="jsn-iconbar first">
<a href="http://www.joomlashine.com/joomla-extensions/jsn-poweradmin.html" target="_blank" title="JSN PowerAdmin - Manage Joomla websites with ease and joy">
<i class="jsn-icon32 jsn-icon-products jsn-icon-poweradmin"></i>
</a>
<a href="http://www.joomlashine.com/joomla-extensions/jsn-imageshow.html" target="_blank" title="JSN ImageShow - One Joomla gallery extension for all image presentation needs">
<i class="jsn-icon32 jsn-icon-products jsn-icon-imageshow"></i>
</a>
<a href="http://www.joomlashine.com/joomla-extensions/jsn-uniform.html" target="_blank" title="JSN UniForm - The most easy, yet sophisticated Joomla form builder extension">
<i class="jsn-icon32 jsn-icon-products jsn-icon-uniform"></i>
</a>
<a href="http://www.joomlashine.com/joomla-extensions/jsn-mobilize.html" target="_blank" title="JSN Mobilize - Painless mobile site creator">
<i class="jsn-icon32 jsn-icon-products jsn-icon-mobilize"></i>
</a>
<a href="http://www.joomlashine.com/joomla-extensions/jsn-pagebuilder.html" target="_blank" title="JSN PageBuilder - Easiest way to build Joomla pages">
<i class="jsn-icon32 jsn-icon-products jsn-icon-pagebuilder"></i>
</a>
<a href="http://www.joomlashine.com/joomla-extensions/jsn-easyslider.html" target="_blank" title="JSN EasySlider - Multipurpose content slider with super user-friendly interface">
<i class="jsn-icon32 jsn-icon-products jsn-icon-easyslider"></i>
</a>
</li>
</ul>
</div>
<?php } ?>
<div class="clearbreak"></div>
</div>
</div>
<!-- Hidden form for saving/restoring template parameters -->
<form id="jsn-template-maintenance-restore-params-form" method="post" enctype="multipart/form-data" target="jsn-silent-save" class="hide">
<input type="file" name="backup-upload" />
</form>
<iframe id="jsn-silent-save" name="jsn-silent-save" class="hide" src="about:blank"></iframe>
<script type="text/javascript">
(function($) {
$(document).ready(function() {
$(".jsn-modal-overlay,.jsn-modal-indicator").remove();
$("body").append($("<div/>", {
"class":"jsn-modal-overlay",
"style":"z-index: 1000; display: inline;"
})).append($("<div/>", {
"class":"jsn-modal-indicator",
"style":"display:block"
})).addClass("jsn-loading-page");
$(".jsn-modal-overlay,.jsn-modal-indicator").delay(1200).queue(function () {
$(this).remove();
$("#jsn-template-config-tabs").removeClass("jsn-hide");
});
});
// Setup tabs
$('#jsn-template-config-tabs').tabs();
// Setup form validation
new $.JSNFormValidation({
lang: {
JSN_TPLFW_INVALID_VALUE_TYPE: '<?php echo JText::_('JSN_TPLFW_INVALID_VALUE_TYPE'); ?>',
JSN_TPLFW_ERROR_FORM_VALIDATION_FAILED: '<?php echo JText::_('JSN_TPLFW_ERROR_FORM_VALIDATION_FAILED'); ?>',
JSN_TPLFW_SYSTEM_CUSTOM_ASSETS_INVALID: '<?php echo JText::_('JSN_TPLFW_SYSTEM_CUSTOM_ASSETS_INVALID'); ?>'
}
});
})(jQuery);
</script>
| k-yar/jadis | plugins/system/jsntplframework/libraries/joomlashine/template/tmpl/default.php | PHP | gpl-2.0 | 20,799 |
/*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* Copyright (c) 2011 Helge Bahmann
* Copyright (c) 2013 Tim Blechmann
* Copyright (c) 2014 Andrey Semashev
*/
/*!
* \file atomic/detail/atomic_template.hpp
*
* This header contains interface definition of \c atomic template.
*/
#ifndef BOOST_ATOMIC_DETAIL_ATOMIC_TEMPLATE_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_ATOMIC_TEMPLATE_HPP_INCLUDED_
#include <cstddef>
#include <boost/cstdint.hpp>
#include <boost/assert.hpp>
#include <boost/atomic/detail/config.hpp>
#include <boost/atomic/detail/bitwise_cast.hpp>
#include <boost/atomic/detail/operations_fwd.hpp>
#include <boost/atomic/detail/type_traits/is_signed.hpp>
#include <boost/atomic/detail/type_traits/is_integral.hpp>
#include <boost/atomic/detail/type_traits/is_function.hpp>
#include <boost/atomic/detail/type_traits/conditional.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#if defined(BOOST_MSVC)
#pragma warning(push)
// 'boost::atomics::atomic<T>' : multiple assignment operators specified
#pragma warning(disable: 4522)
#endif
/*
* IMPLEMENTATION NOTE: All interface functions MUST be declared with BOOST_FORCEINLINE,
* see comment for convert_memory_order_to_gcc in ops_gcc_atomic.hpp.
*/
namespace boost {
namespace atomics {
namespace detail {
BOOST_FORCEINLINE BOOST_CONSTEXPR memory_order deduce_failure_order(memory_order order) BOOST_NOEXCEPT
{
return order == memory_order_acq_rel ? memory_order_acquire : (order == memory_order_release ? memory_order_relaxed : order);
}
BOOST_FORCEINLINE BOOST_CONSTEXPR bool cas_failure_order_must_not_be_stronger_than_success_order(memory_order success_order, memory_order failure_order) BOOST_NOEXCEPT
{
// 15 == (memory_order_seq_cst | memory_order_consume), see memory_order.hpp
// Given the enum values we can test the strength of memory order requirements with this single condition.
return (failure_order & 15u) <= (success_order & 15u);
}
template< typename T, bool IsFunction = boost::atomics::detail::is_function< T >::value >
struct classify_pointer
{
typedef void* type;
};
template< typename T >
struct classify_pointer< T, true >
{
typedef void type;
};
template< typename T, bool IsInt = boost::atomics::detail::is_integral< T >::value >
struct classify
{
typedef void type;
};
template< typename T >
struct classify< T, true > { typedef int type; };
template< typename T >
struct classify< T*, false > { typedef typename classify_pointer< T >::type type; };
template< >
struct classify< void*, false > { typedef void type; };
template< >
struct classify< const void*, false > { typedef void type; };
template< >
struct classify< volatile void*, false > { typedef void type; };
template< >
struct classify< const volatile void*, false > { typedef void type; };
template< typename T, typename U >
struct classify< T U::*, false > { typedef void type; };
template< bool >
struct boolean_constant {};
typedef boolean_constant< true > true_constant;
typedef boolean_constant< false > false_constant;
template< typename T, typename Kind >
class base_atomic;
//! General template. Implementation for user-defined types, such as structs and enums, and pointers to non-object types
template< typename T >
class base_atomic< T, void >
{
public:
typedef T value_type;
protected:
typedef atomics::detail::operations< storage_size_of< value_type >::value, false > operations;
typedef typename boost::atomics::detail::conditional< sizeof(value_type) <= sizeof(void*), value_type, value_type const& >::type value_arg_type;
public:
typedef typename operations::storage_type storage_type;
private:
typedef boolean_constant< sizeof(value_type) == sizeof(storage_type) > value_matches_storage;
protected:
typename operations::aligned_storage_type m_storage;
public:
BOOST_FORCEINLINE explicit base_atomic(value_arg_type v = value_type()) BOOST_NOEXCEPT : m_storage(atomics::detail::bitwise_cast< storage_type >(v))
{
}
BOOST_FORCEINLINE void store(value_arg_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return atomics::detail::bitwise_cast< value_type >(operations::load(m_storage.value, order));
}
BOOST_FORCEINLINE value_type exchange(value_arg_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::exchange(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
return compare_exchange_strong_impl(expected, desired, success_order, failure_order, value_matches_storage());
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_arg_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
return compare_exchange_weak_impl(expected, desired, success_order, failure_order, value_matches_storage());
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_arg_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
private:
BOOST_FORCEINLINE bool compare_exchange_strong_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, true_constant) volatile BOOST_NOEXCEPT
{
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
return compare_exchange_strong_impl(expected, desired, success_order, failure_order, false_constant());
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, false_constant) volatile BOOST_NOEXCEPT
{
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
}
BOOST_FORCEINLINE bool compare_exchange_weak_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, true_constant) volatile BOOST_NOEXCEPT
{
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
return compare_exchange_weak_impl(expected, desired, success_order, failure_order, false_constant());
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak_impl(value_type& expected, value_arg_type desired, memory_order success_order, memory_order failure_order, false_constant) volatile BOOST_NOEXCEPT
{
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
}
};
//! Implementation for integers
template< typename T >
class base_atomic< T, int >
{
public:
typedef T value_type;
typedef T difference_type;
protected:
typedef atomics::detail::operations< storage_size_of< value_type >::value, boost::atomics::detail::is_signed< T >::value > operations;
typedef value_type value_arg_type;
public:
typedef typename operations::storage_type storage_type;
protected:
typename operations::aligned_storage_type m_storage;
public:
BOOST_DEFAULTED_FUNCTION(base_atomic(), {})
BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : m_storage(v) {}
BOOST_FORCEINLINE void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, static_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return static_cast< value_type >(operations::load(m_storage.value, order));
}
BOOST_FORCEINLINE value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_add(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_sub(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::exchange(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = static_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = static_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE value_type fetch_and(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_and(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type fetch_or(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_or(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type fetch_xor(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return static_cast< value_type >(operations::fetch_xor(m_storage.value, static_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE value_type operator++(int) volatile BOOST_NOEXCEPT
{
return fetch_add(1);
}
BOOST_FORCEINLINE value_type operator++() volatile BOOST_NOEXCEPT
{
return fetch_add(1) + 1;
}
BOOST_FORCEINLINE value_type operator--(int) volatile BOOST_NOEXCEPT
{
return fetch_sub(1);
}
BOOST_FORCEINLINE value_type operator--() volatile BOOST_NOEXCEPT
{
return fetch_sub(1) - 1;
}
BOOST_FORCEINLINE value_type operator+=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_add(v) + v;
}
BOOST_FORCEINLINE value_type operator-=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_sub(v) - v;
}
BOOST_FORCEINLINE value_type operator&=(value_type v) volatile BOOST_NOEXCEPT
{
return fetch_and(v) & v;
}
BOOST_FORCEINLINE value_type operator|=(value_type v) volatile BOOST_NOEXCEPT
{
return fetch_or(v) | v;
}
BOOST_FORCEINLINE value_type operator^=(value_type v) volatile BOOST_NOEXCEPT
{
return fetch_xor(v) ^ v;
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
};
//! Implementation for bool
template< >
class base_atomic< bool, int >
{
public:
typedef bool value_type;
protected:
typedef atomics::detail::operations< 1u, false > operations;
typedef value_type value_arg_type;
public:
typedef operations::storage_type storage_type;
protected:
operations::aligned_storage_type m_storage;
public:
BOOST_DEFAULTED_FUNCTION(base_atomic(), {})
BOOST_CONSTEXPR explicit base_atomic(value_type v) BOOST_NOEXCEPT : m_storage(v) {}
BOOST_FORCEINLINE void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, static_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return !!operations::load(m_storage.value, order);
}
BOOST_FORCEINLINE value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return !!operations::exchange(m_storage.value, static_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = !!old_value;
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), static_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = static_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, static_cast< storage_type >(desired), success_order, failure_order);
expected = !!old_value;
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
};
//! Implementation for pointers to object types
template< typename T >
class base_atomic< T*, void* >
{
public:
typedef T* value_type;
typedef std::ptrdiff_t difference_type;
protected:
typedef atomics::detail::operations< storage_size_of< value_type >::value, false > operations;
typedef value_type value_arg_type;
public:
typedef typename operations::storage_type storage_type;
protected:
typename operations::aligned_storage_type m_storage;
public:
BOOST_DEFAULTED_FUNCTION(base_atomic(), {})
BOOST_FORCEINLINE explicit base_atomic(value_type const& v) BOOST_NOEXCEPT : m_storage(atomics::detail::bitwise_cast< storage_type >(v))
{
}
BOOST_FORCEINLINE void store(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_consume);
BOOST_ASSERT(order != memory_order_acquire);
BOOST_ASSERT(order != memory_order_acq_rel);
operations::store(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order);
}
BOOST_FORCEINLINE value_type load(memory_order order = memory_order_seq_cst) const volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(order != memory_order_release);
BOOST_ASSERT(order != memory_order_acq_rel);
return atomics::detail::bitwise_cast< value_type >(operations::load(m_storage.value, order));
}
BOOST_FORCEINLINE value_type fetch_add(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::fetch_add(m_storage.value, static_cast< storage_type >(v * sizeof(T)), order));
}
BOOST_FORCEINLINE value_type fetch_sub(difference_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::fetch_sub(m_storage.value, static_cast< storage_type >(v * sizeof(T)), order));
}
BOOST_FORCEINLINE value_type exchange(value_type v, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return atomics::detail::bitwise_cast< value_type >(operations::exchange(m_storage.value, atomics::detail::bitwise_cast< storage_type >(v), order));
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_strong(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_strong(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_strong(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_strong(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order success_order, memory_order failure_order) volatile BOOST_NOEXCEPT
{
BOOST_ASSERT(failure_order != memory_order_release);
BOOST_ASSERT(failure_order != memory_order_acq_rel);
BOOST_ASSERT(cas_failure_order_must_not_be_stronger_than_success_order(success_order, failure_order));
#if defined(BOOST_ATOMIC_DETAIL_STORAGE_TYPE_MAY_ALIAS)
return operations::compare_exchange_weak(m_storage.value, reinterpret_cast< storage_type& >(expected), atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
#else
storage_type old_value = atomics::detail::bitwise_cast< storage_type >(expected);
const bool res = operations::compare_exchange_weak(m_storage.value, old_value, atomics::detail::bitwise_cast< storage_type >(desired), success_order, failure_order);
expected = atomics::detail::bitwise_cast< value_type >(old_value);
return res;
#endif
}
BOOST_FORCEINLINE bool compare_exchange_weak(value_type& expected, value_type desired, memory_order order = memory_order_seq_cst) volatile BOOST_NOEXCEPT
{
return compare_exchange_weak(expected, desired, order, atomics::detail::deduce_failure_order(order));
}
BOOST_FORCEINLINE value_type operator++(int) volatile BOOST_NOEXCEPT
{
return fetch_add(1);
}
BOOST_FORCEINLINE value_type operator++() volatile BOOST_NOEXCEPT
{
return fetch_add(1) + 1;
}
BOOST_FORCEINLINE value_type operator--(int) volatile BOOST_NOEXCEPT
{
return fetch_sub(1);
}
BOOST_FORCEINLINE value_type operator--() volatile BOOST_NOEXCEPT
{
return fetch_sub(1) - 1;
}
BOOST_FORCEINLINE value_type operator+=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_add(v) + v;
}
BOOST_FORCEINLINE value_type operator-=(difference_type v) volatile BOOST_NOEXCEPT
{
return fetch_sub(v) - v;
}
BOOST_DELETED_FUNCTION(base_atomic(base_atomic const&))
BOOST_DELETED_FUNCTION(base_atomic& operator=(base_atomic const&))
};
} // namespace detail
template< typename T >
class atomic :
public atomics::detail::base_atomic< T, typename atomics::detail::classify< T >::type >
{
private:
typedef atomics::detail::base_atomic< T, typename atomics::detail::classify< T >::type > base_type;
typedef typename base_type::value_arg_type value_arg_type;
public:
typedef typename base_type::value_type value_type;
typedef typename base_type::storage_type storage_type;
public:
static BOOST_CONSTEXPR_OR_CONST bool is_always_lock_free = base_type::operations::is_always_lock_free;
public:
BOOST_DEFAULTED_FUNCTION(atomic(), BOOST_NOEXCEPT {})
// NOTE: The constructor is made explicit because gcc 4.7 complains that
// operator=(value_arg_type) is considered ambiguous with operator=(atomic const&)
// in assignment expressions, even though conversion to atomic<> is less preferred
// than conversion to value_arg_type.
BOOST_FORCEINLINE explicit BOOST_CONSTEXPR atomic(value_arg_type v) BOOST_NOEXCEPT : base_type(v) {}
BOOST_FORCEINLINE value_type operator= (value_arg_type v) volatile BOOST_NOEXCEPT
{
this->store(v);
return v;
}
BOOST_FORCEINLINE operator value_type() const volatile BOOST_NOEXCEPT
{
return this->load();
}
BOOST_FORCEINLINE bool is_lock_free() const volatile BOOST_NOEXCEPT
{
// C++17 requires all instances of atomic<> return a value consistent with is_always_lock_free here
return is_always_lock_free;
}
BOOST_FORCEINLINE storage_type& storage() BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_FORCEINLINE storage_type volatile& storage() volatile BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_FORCEINLINE storage_type const& storage() const BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_FORCEINLINE storage_type const volatile& storage() const volatile BOOST_NOEXCEPT { return this->m_storage.value; }
BOOST_DELETED_FUNCTION(atomic(atomic const&))
BOOST_DELETED_FUNCTION(atomic& operator= (atomic const&))
BOOST_DELETED_FUNCTION(atomic& operator= (atomic const&) volatile)
};
template< typename T >
BOOST_CONSTEXPR_OR_CONST bool atomic< T >::is_always_lock_free;
typedef atomic< char > atomic_char;
typedef atomic< unsigned char > atomic_uchar;
typedef atomic< signed char > atomic_schar;
typedef atomic< uint8_t > atomic_uint8_t;
typedef atomic< int8_t > atomic_int8_t;
typedef atomic< unsigned short > atomic_ushort;
typedef atomic< short > atomic_short;
typedef atomic< uint16_t > atomic_uint16_t;
typedef atomic< int16_t > atomic_int16_t;
typedef atomic< unsigned int > atomic_uint;
typedef atomic< int > atomic_int;
typedef atomic< uint32_t > atomic_uint32_t;
typedef atomic< int32_t > atomic_int32_t;
typedef atomic< unsigned long > atomic_ulong;
typedef atomic< long > atomic_long;
typedef atomic< uint64_t > atomic_uint64_t;
typedef atomic< int64_t > atomic_int64_t;
#ifdef BOOST_HAS_LONG_LONG
typedef atomic< boost::ulong_long_type > atomic_ullong;
typedef atomic< boost::long_long_type > atomic_llong;
#endif
typedef atomic< void* > atomic_address;
typedef atomic< bool > atomic_bool;
typedef atomic< wchar_t > atomic_wchar_t;
#if !defined(BOOST_NO_CXX11_CHAR16_T)
typedef atomic< char16_t > atomic_char16_t;
#endif
#if !defined(BOOST_NO_CXX11_CHAR32_T)
typedef atomic< char32_t > atomic_char32_t;
#endif
typedef atomic< int_least8_t > atomic_int_least8_t;
typedef atomic< uint_least8_t > atomic_uint_least8_t;
typedef atomic< int_least16_t > atomic_int_least16_t;
typedef atomic< uint_least16_t > atomic_uint_least16_t;
typedef atomic< int_least32_t > atomic_int_least32_t;
typedef atomic< uint_least32_t > atomic_uint_least32_t;
typedef atomic< int_least64_t > atomic_int_least64_t;
typedef atomic< uint_least64_t > atomic_uint_least64_t;
typedef atomic< int_fast8_t > atomic_int_fast8_t;
typedef atomic< uint_fast8_t > atomic_uint_fast8_t;
typedef atomic< int_fast16_t > atomic_int_fast16_t;
typedef atomic< uint_fast16_t > atomic_uint_fast16_t;
typedef atomic< int_fast32_t > atomic_int_fast32_t;
typedef atomic< uint_fast32_t > atomic_uint_fast32_t;
typedef atomic< int_fast64_t > atomic_int_fast64_t;
typedef atomic< uint_fast64_t > atomic_uint_fast64_t;
typedef atomic< intmax_t > atomic_intmax_t;
typedef atomic< uintmax_t > atomic_uintmax_t;
typedef atomic< std::size_t > atomic_size_t;
typedef atomic< std::ptrdiff_t > atomic_ptrdiff_t;
#if defined(BOOST_HAS_INTPTR_T)
typedef atomic< intptr_t > atomic_intptr_t;
typedef atomic< uintptr_t > atomic_uintptr_t;
#endif
} // namespace atomics
} // namespace boost
#if defined(BOOST_MSVC)
#pragma warning(pop)
#endif
#endif // BOOST_ATOMIC_DETAIL_ATOMIC_TEMPLATE_HPP_INCLUDED_
| jack8z/TODOP | third_party/boost_1_65_1/boost/atomic/detail/atomic_template.hpp | C++ | gpl-2.0 | 30,415 |
/*
* Copyright (C) 2011,2012,2013,2014 Samuel Audet
*
* This file is part of JavaCPP.
*
* JavaCPP 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 (subject to the "Classpath" exception
* as provided in the LICENSE.txt file that accompanied this code).
*
* JavaCPP 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 JavaCPP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.googlecode.javacpp;
import com.googlecode.javacpp.annotation.Adapter;
import com.googlecode.javacpp.annotation.Allocator;
import com.googlecode.javacpp.annotation.ArrayAllocator;
import com.googlecode.javacpp.annotation.ByPtr;
import com.googlecode.javacpp.annotation.ByPtrPtr;
import com.googlecode.javacpp.annotation.ByPtrRef;
import com.googlecode.javacpp.annotation.ByRef;
import com.googlecode.javacpp.annotation.ByVal;
import com.googlecode.javacpp.annotation.Cast;
import com.googlecode.javacpp.annotation.Const;
import com.googlecode.javacpp.annotation.Convention;
import com.googlecode.javacpp.annotation.Function;
import com.googlecode.javacpp.annotation.Index;
import com.googlecode.javacpp.annotation.MemberGetter;
import com.googlecode.javacpp.annotation.MemberSetter;
import com.googlecode.javacpp.annotation.Name;
import com.googlecode.javacpp.annotation.Namespace;
import com.googlecode.javacpp.annotation.NoDeallocator;
import com.googlecode.javacpp.annotation.NoException;
import com.googlecode.javacpp.annotation.NoOffset;
import com.googlecode.javacpp.annotation.Opaque;
import com.googlecode.javacpp.annotation.Platform;
import com.googlecode.javacpp.annotation.Raw;
import com.googlecode.javacpp.annotation.ValueGetter;
import com.googlecode.javacpp.annotation.ValueSetter;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
/**
* The Generator is where all the C++ source code that we need gets generated.
* It has not been designed in any meaningful way since the requirements were
* not well understood. It is basically a prototype and is really quite a mess.
* Now that we understand better what we need, it could use some refactoring.
* <p>
* When attempting to understand what the Generator does, try to run experiments
* and inspect the generated code: It is quite readable.
* <p>
* Moreover, although Generator is the one ultimately doing something with the
* various annotations it relies on, it was easier to describe the behavior its
* meant to have with them as part of the documentation of the annotations, so
* we can refer to them to understand more about how Generator should work:
*
* @see Adapter
* @see Allocator
* @see ArrayAllocator
* @see ByPtr
* @see ByPtrPtr
* @see ByPtrRef
* @see ByRef
* @see ByVal
* @see Cast
* @see Const
* @see Convention
* @see Function
* @see Index
* @see MemberGetter
* @see MemberSetter
* @see Name
* @see Namespace
* @see NoDeallocator
* @see NoException
* @see NoOffset
* @see Opaque
* @see Platform
* @see Raw
* @see ValueGetter
* @see ValueSetter
*
* @author Samuel Audet
*/
public class Generator implements Closeable {
public Generator(Logger logger, Loader.ClassProperties properties) {
this.logger = logger;
this.properties = properties;
}
static class IndexedSet<E> extends LinkedHashMap<E,Integer> implements Iterable<E> {
public int index(E e) {
Integer i = get(e);
if (i == null) {
put(e, i = size());
}
return i;
}
public Iterator<E> iterator() {
return keySet().iterator();
}
}
static final String JNI_VERSION = "JNI_VERSION_1_4";
static final List<Class> baseClasses = Arrays.asList(new Class[] {
Pointer.class,
//FunctionPointer.class,
BytePointer.class,
ShortPointer.class,
IntPointer.class,
LongPointer.class,
FloatPointer.class,
DoublePointer.class,
CharPointer.class,
PointerPointer.class,
BoolPointer.class,
CLongPointer.class,
SizeTPointer.class });
final Logger logger;
final Loader.ClassProperties properties;
PrintWriter out, out2;
IndexedSet<String> callbacks;
IndexedSet<Class> functions, deallocators, arrayDeallocators, jclasses, jclassesInit;
HashMap<Class,LinkedList<String>> members;
boolean mayThrowExceptions, usesAdapters;
public boolean generate(String sourceFilename, String headerFilename,
String classPath, Class<?> ... classes) throws FileNotFoundException {
// first pass using a null writer to fill up the IndexedSet objects
out = new PrintWriter(new Writer() {
@Override public void write(char[] cbuf, int off, int len) { }
@Override public void flush() { }
@Override public void close() { }
});
out2 = null;
callbacks = new IndexedSet<String>();
functions = new IndexedSet<Class>();
deallocators = new IndexedSet<Class>();
arrayDeallocators = new IndexedSet<Class>();
jclasses = new IndexedSet<Class>();
jclassesInit = new IndexedSet<Class>();
members = new HashMap<Class,LinkedList<String>>();
mayThrowExceptions = false;
usesAdapters = false;
if (classes(true, true, classPath, classes)) {
// second pass with a real writer
out = new PrintWriter(sourceFilename);
if (headerFilename != null) {
out2 = new PrintWriter(headerFilename);
}
return classes(mayThrowExceptions, usesAdapters, classPath, classes);
} else {
return false;
}
}
public void close() {
if (out != null) {
out.close();
}
if (out2 != null) {
out2.close();
}
}
boolean classes(boolean handleExceptions, boolean defineAdapters, String classPath, Class<?> ... classes) {
String version = Generator.class.getPackage().getImplementationVersion();
if (version == null) {
version = "unknown";
}
String warning = "// Generated by JavaCPP version " + version;
out.println(warning);
out.println();
if (out2 != null) {
out2.println(warning);
out2.println();
}
for (String s : properties.get("platform.define")) {
out.println("#define " + s);
}
out.println();
out.println("#ifdef __APPLE__");
out.println(" #define _JAVASOFT_JNI_MD_H_");
out.println();
out.println(" #define JNIEXPORT __attribute__((visibility(\"default\")))");
out.println(" #define JNIIMPORT");
out.println(" #define JNICALL");
out.println();
out.println(" typedef int jint;");
out.println(" typedef long long jlong;");
out.println(" typedef signed char jbyte;");
out.println("#endif");
out.println("#ifdef _WIN32");
out.println(" #define _JAVASOFT_JNI_MD_H_");
out.println();
out.println(" #define JNIEXPORT __declspec(dllexport)");
out.println(" #define JNIIMPORT __declspec(dllimport)");
out.println(" #define JNICALL __stdcall");
out.println();
out.println(" typedef int jint;");
out.println(" typedef long long jlong;");
out.println(" typedef signed char jbyte;");
out.println("#endif");
out.println("#include <jni.h>");
if (out2 != null) {
out2.println("#include <jni.h>");
}
out.println("#ifdef ANDROID");
out.println(" #include <android/log.h>");
out.println("#elif defined(__APPLE__) && defined(__OBJC__)");
out.println(" #include <TargetConditionals.h>");
out.println(" #include <Foundation/Foundation.h>");
out.println("#endif");
out.println("#if defined(ANDROID) || TARGET_OS_IPHONE");
out.println(" #define NewWeakGlobalRef(obj) NewGlobalRef(obj)");
out.println(" #define DeleteWeakGlobalRef(obj) DeleteGlobalRef(obj)");
out.println("#endif");
out.println();
out.println("#include <stddef.h>");
out.println("#ifndef _WIN32");
out.println(" #include <stdint.h>");
out.println("#endif");
out.println("#include <stdio.h>");
out.println("#include <stdlib.h>");
out.println("#include <string.h>");
out.println("#include <exception>");
out.println("#include <new>");
out.println();
out.println("#define jlong_to_ptr(a) ((void*)(uintptr_t)(a))");
out.println("#define ptr_to_jlong(a) ((jlong)(uintptr_t)(a))");
out.println();
out.println("#if defined(_MSC_VER)");
out.println(" #define JavaCPP_noinline __declspec(noinline)");
out.println(" #define JavaCPP_hidden /* hidden by default */");
out.println("#elif defined(__GNUC__)");
out.println(" #define JavaCPP_noinline __attribute__((noinline))");
out.println(" #define JavaCPP_hidden __attribute__((visibility(\"hidden\")))");
out.println("#else");
out.println(" #define JavaCPP_noinline");
out.println(" #define JavaCPP_hidden");
out.println("#endif");
out.println();
List[] include = { properties.get("platform.include"),
properties.get("platform.cinclude") };
for (int i = 0; i < include.length; i++) {
if (include[i] != null && include[i].size() > 0) {
if (i == 1) {
out.println("extern \"C\" {");
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("extern \"C\" {");
out2.println("#endif");
}
}
for (String s : (List<String>)include[i]) {
String line = "#include ";
if (!s.startsWith("<") && !s.startsWith("\"")) {
line += '"';
}
line += s;
if (!s.endsWith(">") && !s.endsWith("\"")) {
line += '"';
}
out.println(line);
if (out2 != null) {
out2.println(line);
}
}
if (i == 1) {
out.println("}");
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("}");
out2.println("#endif");
}
}
out.println();
}
}
out.println("static JavaVM* JavaCPP_vm = NULL;");
out.println("static bool JavaCPP_haveAllocObject = false;");
out.println("static bool JavaCPP_haveNonvirtual = false;");
out.println("static const char* JavaCPP_classNames[" + jclasses.size() + "] = {");
Iterator<Class> classIterator = jclasses.iterator();
int maxMemberSize = 0;
while (classIterator.hasNext()) {
Class c = classIterator.next();
out.print(" \"" + c.getName().replace('.','/') + "\"");
if (classIterator.hasNext()) {
out.println(",");
}
LinkedList<String> m = members.get(c);
if (m != null && m.size() > maxMemberSize) {
maxMemberSize = m.size();
}
}
out.println(" };");
out.println("static jclass JavaCPP_classes[" + jclasses.size() + "] = { NULL };");
out.println("static jfieldID JavaCPP_addressFID = NULL;");
out.println("static jfieldID JavaCPP_positionFID = NULL;");
out.println("static jfieldID JavaCPP_limitFID = NULL;");
out.println("static jfieldID JavaCPP_capacityFID = NULL;");
out.println("static jmethodID JavaCPP_initMID = NULL;");
out.println("static jmethodID JavaCPP_toStringMID = NULL;");
out.println();
out.println("static inline void JavaCPP_log(const char* fmt, ...) {");
out.println(" va_list ap;");
out.println(" va_start(ap, fmt);");
out.println("#ifdef ANDROID");
out.println(" __android_log_vprint(ANDROID_LOG_ERROR, \"javacpp\", fmt, ap);");
out.println("#elif defined(__APPLE__) && defined(__OBJC__)");
out.println(" NSLogv([NSString stringWithUTF8String:fmt], ap);");
out.println("#else");
out.println(" vfprintf(stderr, fmt, ap);");
out.println(" fprintf(stderr, \"\\n\");");
out.println("#endif");
out.println(" va_end(ap);");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jclass JavaCPP_getClass(JNIEnv* env, int i) {");
out.println(" if (JavaCPP_classes[i] == NULL && env->PushLocalFrame(1) == 0) {");
out.println(" jclass cls = env->FindClass(JavaCPP_classNames[i]);");
out.println(" if (cls == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error loading class %s.\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" JavaCPP_classes[i] = (jclass)env->NewWeakGlobalRef(cls);");
out.println(" if (JavaCPP_classes[i] == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error creating global reference of class %s.\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" env->PopLocalFrame(NULL);");
out.println(" }");
out.println(" return JavaCPP_classes[i];");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jfieldID JavaCPP_getFieldID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jfieldID fid = env->GetFieldID(cls, name, sig);");
out.println(" if (fid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting field ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return fid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jmethodID JavaCPP_getMethodID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jmethodID mid = env->GetMethodID(cls, name, sig);");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting method ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return mid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jmethodID JavaCPP_getStaticMethodID(JNIEnv* env, int i, const char* name, const char* sig) {");
out.println(" jclass cls = JavaCPP_getClass(env, i);");
out.println(" if (cls == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" jmethodID mid = env->GetStaticMethodID(cls, name, sig);");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting static method ID of %s/%s\", JavaCPP_classNames[i], name);");
out.println(" return NULL;");
out.println(" }");
out.println(" return mid;");
out.println("}");
out.println();
out.println("static JavaCPP_noinline jobject JavaCPP_createPointer(JNIEnv* env, int i, jclass cls = NULL) {");
out.println(" if (cls == NULL && (cls = JavaCPP_getClass(env, i)) == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" if (JavaCPP_haveAllocObject) {");
out.println(" return env->AllocObject(cls);");
out.println(" } else {");
out.println(" jmethodID mid = env->GetMethodID(cls, \"<init>\", \"()V\");");
out.println(" if (mid == NULL || env->ExceptionCheck()) {");
out.println(" JavaCPP_log(\"Error getting default constructor of %s, while VM does not support AllocObject()\", JavaCPP_classNames[i]);");
out.println(" return NULL;");
out.println(" }");
out.println(" return env->NewObject(cls, mid);");
out.println(" }");
out.println("}");
out.println();
out.println("static JavaCPP_noinline void JavaCPP_initPointer(JNIEnv* env, jobject obj, const void* ptr, int size, void (*deallocator)(void*)) {");
out.println(" if (deallocator != NULL) {");
out.println(" jvalue args[3];");
out.println(" args[0].j = ptr_to_jlong(ptr);");
out.println(" args[1].i = size;");
out.println(" args[2].j = ptr_to_jlong(deallocator);");
out.println(" if (JavaCPP_haveNonvirtual) {");
out.println(" env->CallNonvirtualVoidMethodA(obj, JavaCPP_getClass(env, "
+ jclasses.index(Pointer.class) + "), JavaCPP_initMID, args);");
out.println(" } else {");
out.println(" env->CallVoidMethodA(obj, JavaCPP_initMID, args);");
out.println(" }");
out.println(" } else {");
out.println(" env->SetLongField(obj, JavaCPP_addressFID, ptr_to_jlong(ptr));");
out.println(" env->SetIntField(obj, JavaCPP_limitFID, size);");
out.println(" env->SetIntField(obj, JavaCPP_capacityFID, size);");
out.println(" }");
out.println("}");
out.println();
out.println("class JavaCPP_hidden JavaCPP_exception : public std::exception {");
out.println("public:");
out.println(" JavaCPP_exception(const char* str) throw() {");
out.println(" if (str == NULL) {");
out.println(" strcpy(msg, \"Unknown exception.\");");
out.println(" } else {");
out.println(" strncpy(msg, str, sizeof(msg));");
out.println(" msg[sizeof(msg) - 1] = 0;");
out.println(" }");
out.println(" }");
out.println(" virtual const char* what() const throw() { return msg; }");
out.println(" char msg[1024];");
out.println("};");
out.println();
if (handleExceptions) {
out.println("static JavaCPP_noinline jthrowable JavaCPP_handleException(JNIEnv* env, int i) {");
out.println(" jstring str = NULL;");
out.println(" try {");
out.println(" throw;");
out.println(" } catch (std::exception& e) {");
out.println(" str = env->NewStringUTF(e.what());");
out.println(" } catch (...) {");
out.println(" str = env->NewStringUTF(\"Unknown exception.\");");
out.println(" }");
out.println(" jmethodID mid = JavaCPP_getMethodID(env, i, \"<init>\", \"(Ljava/lang/String;)V\");");
out.println(" if (mid == NULL) {");
out.println(" return NULL;");
out.println(" }");
out.println(" return (jthrowable)env->NewObject(JavaCPP_getClass(env, i), mid, str);");
out.println("}");
out.println();
}
if (defineAdapters) {
out.println("#include <vector>");
out.println("template<typename P, typename T = P> class JavaCPP_hidden VectorAdapter {");
out.println("public:");
out.println(" VectorAdapter(const P* ptr, typename std::vector<T>::size_type size) : ptr((P*)ptr), size(size),");
out.println(" vec2(ptr ? std::vector<T>((P*)ptr, (P*)ptr + size) : std::vector<T>()), vec(vec2) { }");
out.println(" VectorAdapter(const std::vector<T>& vec) : ptr(0), size(0), vec2(vec), vec(vec2) { }");
out.println(" VectorAdapter( std::vector<T>& vec) : ptr(0), size(0), vec(vec) { }");
out.println(" void assign(P* ptr, typename std::vector<T>::size_type size) {");
out.println(" this->ptr = ptr;");
out.println(" this->size = size;");
out.println(" vec.assign(ptr, ptr + size);");
out.println(" }");
out.println(" static void deallocate(void* ptr) { delete[] (P*)ptr; }");
out.println(" operator P*() {");
out.println(" if (vec.size() > size) {");
out.println(" ptr = new (std::nothrow) P[vec.size()];");
out.println(" }");
out.println(" if (ptr) {");
out.println(" std::copy(vec.begin(), vec.end(), ptr);");
out.println(" }");
out.println(" size = vec.size();");
out.println(" return ptr;");
out.println(" }");
out.println(" operator const P*() { return &vec[0]; }");
out.println(" operator std::vector<T>&() { return vec; }");
out.println(" operator std::vector<T>*() { return ptr ? &vec : 0; }");
out.println(" P* ptr;");
out.println(" typename std::vector<T>::size_type size;");
out.println(" std::vector<T> vec2;");
out.println(" std::vector<T>& vec;");
out.println("};");
out.println();
out.println("#include <string>");
out.println("class JavaCPP_hidden StringAdapter {");
out.println("public:");
out.println(" StringAdapter(const char* ptr, size_t size) : ptr((char*)ptr), size(size),");
out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }");
out.println(" StringAdapter(const signed char* ptr, size_t size) : ptr((char*)ptr), size(size),");
out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }");
out.println(" StringAdapter(const unsigned char* ptr, size_t size) : ptr((char*)ptr), size(size),");
out.println(" str2(ptr ? (char*)ptr : \"\"), str(str2) { }");
out.println(" StringAdapter(const std::string& str) : ptr(0), size(0), str2(str), str(str2) { }");
out.println(" StringAdapter( std::string& str) : ptr(0), size(0), str(str) { }");
out.println(" void assign(char* ptr, size_t size) {");
out.println(" this->ptr = ptr;");
out.println(" this->size = size;");
out.println(" str.assign(ptr ? ptr : \"\");");
out.println(" }");
out.println(" static void deallocate(void* ptr) { free(ptr); }");
out.println(" operator char*() {");
out.println(" const char* c_str = str.c_str();");
out.println(" if (ptr == NULL || strcmp(c_str, ptr) != 0) {");
out.println(" ptr = strdup(c_str);");
out.println(" }");
out.println(" size = strlen(c_str) + 1;");
out.println(" return ptr;");
out.println(" }");
out.println(" operator signed char*() { return (signed char*)(operator char*)(); }");
out.println(" operator unsigned char*() { return (unsigned char*)(operator char*)(); }");
out.println(" operator const char*() { return str.c_str(); }");
out.println(" operator const signed char*() { return (signed char*)str.c_str(); }");
out.println(" operator const unsigned char*() { return (unsigned char*)str.c_str(); }");
out.println(" operator std::string&() { return str; }");
out.println(" operator std::string*() { return ptr ? &str : 0; }");
out.println(" char* ptr;");
out.println(" size_t size;");
out.println(" std::string str2;");
out.println(" std::string& str;");
out.println("};");
out.println();
}
if (!functions.isEmpty()) {
out.println("static JavaCPP_noinline void JavaCPP_detach(bool detach) {");
out.println(" if (detach && JavaCPP_vm->DetachCurrentThread() != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not detach the JavaVM from the current thread.\");");
out.println(" }");
out.println("}");
out.println();
out.println("static JavaCPP_noinline bool JavaCPP_getEnv(JNIEnv** env) {");
out.println(" bool attached = false;");
out.println(" JavaVM *vm = JavaCPP_vm;");
out.println(" if (vm == NULL) {");
if (out2 != null) {
out.println("#if !defined(ANDROID) && !TARGET_OS_IPHONE");
out.println(" int size = 1;");
out.println(" if (JNI_GetCreatedJavaVMs(&vm, 1, &size) != JNI_OK || size == 0) {");
out.println("#endif");
}
out.println(" JavaCPP_log(\"Could not get any created JavaVM.\");");
out.println(" *env = NULL;");
out.println(" return false;");
if (out2 != null) {
out.println("#if !defined(ANDROID) && !TARGET_OS_IPHONE");
out.println(" }");
out.println("#endif");
}
out.println(" }");
out.println(" if (vm->GetEnv((void**)env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" struct {");
out.println(" JNIEnv **env;");
out.println(" operator JNIEnv**() { return env; } // Android JNI");
out.println(" operator void**() { return (void**)env; } // standard JNI");
out.println(" } env2 = { env };");
out.println(" if (vm->AttachCurrentThread(env2, NULL) != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not attach the JavaVM to the current thread.\");");
out.println(" *env = NULL;");
out.println(" return false;");
out.println(" }");
out.println(" attached = true;");
out.println(" }");
out.println(" if (JavaCPP_vm == NULL) {");
out.println(" if (JNI_OnLoad(vm, NULL) < 0) {");
out.println(" JavaCPP_detach(attached);");
out.println(" *env = NULL;");
out.println(" return false;");
out.println(" }");
out.println(" }");
out.println(" return attached;");
out.println("}");
out.println();
}
for (Class c : functions) {
String[] typeName = cppTypeName(c);
String[] returnConvention = typeName[0].split("\\(");
returnConvention[1] = constValueTypeName(returnConvention[1]);
String parameterDeclaration = typeName[1].substring(1);
String instanceTypeName = functionClassName(c);
out.println("struct JavaCPP_hidden " + instanceTypeName + " {");
out.println(" " + instanceTypeName + "() : ptr(NULL), obj(NULL) { }");
out.println(" " + returnConvention[0] + "operator()" + parameterDeclaration + ";");
out.println(" " + typeName[0] + "ptr" + typeName[1] + ";");
out.println(" jobject obj; static jmethodID mid;");
out.println("};");
out.println("jmethodID " + instanceTypeName + "::mid = NULL;");
}
out.println();
for (String s : callbacks) {
out.println(s);
}
out.println();
for (Class c : deallocators) {
String name = "JavaCPP_" + mangle(c.getName());
out.print("static void " + name + "_deallocate(void *p) { ");
if (FunctionPointer.class.isAssignableFrom(c)) {
String typeName = functionClassName(c) + "*";
out.println("JNIEnv *e; bool a = JavaCPP_getEnv(&e); if (e != NULL) e->DeleteWeakGlobalRef((("
+ typeName + ")p)->obj); delete (" + typeName + ")p; JavaCPP_detach(a); }");
} else {
String[] typeName = cppTypeName(c);
out.println("delete (" + typeName[0] + typeName[1] + ")p; }");
}
}
for (Class c : arrayDeallocators) {
String name = "JavaCPP_" + mangle(c.getName());
String[] typeName = cppTypeName(c);
out.println("static void " + name + "_deallocateArray(void* p) { delete[] (" + typeName[0] + typeName[1] + ")p; }");
}
out.println();
out.println("extern \"C\" {");
if (out2 != null) {
out2.println();
out2.println("#ifdef __cplusplus");
out2.println("extern \"C\" {");
out2.println("#endif");
out2.println("JNIIMPORT int JavaCPP_init(int argc, const char *argv[]);");
out.println();
out.println("JNIEXPORT int JavaCPP_init(int argc, const char *argv[]) {");
out.println("#if defined(ANDROID) || TARGET_OS_IPHONE");
out.println(" return JNI_OK;");
out.println("#else");
out.println(" if (JavaCPP_vm != NULL) {");
out.println(" return JNI_OK;");
out.println(" }");
out.println(" int err;");
out.println(" JavaVM *vm;");
out.println(" JNIEnv *env;");
out.println(" int nOptions = 1 + (argc > 255 ? 255 : argc);");
out.println(" JavaVMOption options[256] = { { NULL } };");
out.println(" options[0].optionString = (char*)\"-Djava.class.path=" + classPath.replace('\\', '/') + "\";");
out.println(" for (int i = 1; i < nOptions && argv != NULL; i++) {");
out.println(" options[i].optionString = (char*)argv[i - 1];");
out.println(" }");
out.println(" JavaVMInitArgs vm_args = { " + JNI_VERSION + ", nOptions, options };");
out.println(" return (err = JNI_CreateJavaVM(&vm, (void**)&env, &vm_args)) == JNI_OK && vm != NULL && (err = JNI_OnLoad(vm, NULL)) >= 0 ? JNI_OK : err;");
out.println("#endif");
out.println("}");
}
out.println(); // XXX: JNI_OnLoad() should ideally be protected by some mutex
out.println("JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {");
out.println(" JNIEnv* env;");
out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnLoad().\");");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" if (JavaCPP_vm == vm) {");
out.println(" return env->GetVersion();");
out.println(" }");
out.println(" JavaCPP_vm = vm;");
out.println(" JavaCPP_haveAllocObject = env->functions->AllocObject != NULL;");
out.println(" JavaCPP_haveNonvirtual = env->functions->CallNonvirtualVoidMethodA != NULL;");
out.println(" const char* members[" + jclasses.size() + "][" + maxMemberSize + "] = {");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
out.print(" { ");
LinkedList<String> m = members.get(classIterator.next());
Iterator<String> memberIterator = m == null ? null : m.iterator();
while (memberIterator != null && memberIterator.hasNext()) {
out.print("\"" + memberIterator.next() + "\"");
if (memberIterator.hasNext()) {
out.print(", ");
}
}
out.print(" }");
if (classIterator.hasNext()) {
out.println(",");
}
}
out.println(" };");
out.println(" int offsets[" + jclasses.size() + "][" + maxMemberSize + "] = {");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
out.print(" { ");
Class c = classIterator.next();
LinkedList<String> m = members.get(c);
Iterator<String> memberIterator = m == null ? null : m.iterator();
while (memberIterator != null && memberIterator.hasNext()) {
String[] typeName = cppTypeName(c);
String valueTypeName = valueTypeName(typeName);
String memberName = memberIterator.next();
if ("sizeof".equals(memberName)) {
if ("void".equals(valueTypeName)) {
valueTypeName = "void*";
}
out.print("sizeof(" + valueTypeName + ")");
} else {
out.print("offsetof(" + valueTypeName + ", " + memberName + ")");
}
if (memberIterator.hasNext()) {
out.print(", ");
}
}
out.print(" }");
if (classIterator.hasNext()) {
out.println(",");
}
}
out.println(" };");
out.print(" int memberOffsetSizes[" + jclasses.size() + "] = { ");
classIterator = jclasses.iterator();
while (classIterator.hasNext()) {
LinkedList<String> m = members.get(classIterator.next());
out.print(m == null ? 0 : m.size());
if (classIterator.hasNext()) {
out.print(", ");
}
}
out.println(" };");
out.println(" jmethodID putMemberOffsetMID = JavaCPP_getStaticMethodID(env, " +
jclasses.index(Loader.class) + ", \"putMemberOffset\", \"(Ljava/lang/String;Ljava/lang/String;I)V\");");
out.println(" if (putMemberOffsetMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" for (int i = 0; i < " + jclasses.size() + " && !env->ExceptionCheck(); i++) {");
out.println(" for (int j = 0; j < memberOffsetSizes[i] && !env->ExceptionCheck(); j++) {");
out.println(" if (env->PushLocalFrame(2) == 0) {");
out.println(" jvalue args[3];");
out.println(" args[0].l = env->NewStringUTF(JavaCPP_classNames[i]);");
out.println(" args[1].l = env->NewStringUTF(members[i][j]);");
out.println(" args[2].i = offsets[i][j];");
out.println(" env->CallStaticVoidMethodA(JavaCPP_getClass(env, " +
jclasses.index(Loader.class) + "), putMemberOffsetMID, args);");
out.println(" env->PopLocalFrame(NULL);");
out.println(" }");
out.println(" }");
out.println(" }");
out.println(" JavaCPP_addressFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"address\", \"J\");");
out.println(" if (JavaCPP_addressFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_positionFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"position\", \"I\");");
out.println(" if (JavaCPP_positionFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_limitFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"limit\", \"I\");");
out.println(" if (JavaCPP_limitFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_capacityFID = JavaCPP_getFieldID(env, " +
jclasses.index(Pointer.class) + ", \"capacity\", \"I\");");
out.println(" if (JavaCPP_capacityFID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_initMID = JavaCPP_getMethodID(env, " +
jclasses.index(Pointer.class) + ", \"init\", \"(JIJ)V\");");
out.println(" if (JavaCPP_initMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
out.println(" JavaCPP_toStringMID = JavaCPP_getMethodID(env, " +
jclasses.index(Object.class) + ", \"toString\", \"()Ljava/lang/String;\");");
out.println(" if (JavaCPP_toStringMID == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
classIterator = jclassesInit.iterator();
while (classIterator.hasNext()) {
Class c = classIterator.next();
if (c == Pointer.class) {
continue;
}
out.println(" if (JavaCPP_getClass(env, " + jclasses.index(c) + ") == NULL) {");
out.println(" return JNI_ERR;");
out.println(" }");
}
out.println(" return env->GetVersion();");
out.println("}");
out.println();
if (out2 != null) {
out2.println("JNIIMPORT int JavaCPP_uninit();");
out2.println();
out.println("JNIEXPORT int JavaCPP_uninit() {");
out.println("#if defined(ANDROID) || TARGET_OS_IPHONE");
out.println(" return JNI_OK;");
out.println("#else");
out.println(" JavaVM *vm = JavaCPP_vm;");
out.println(" JNI_OnUnload(JavaCPP_vm, NULL);");
out.println(" return vm->DestroyJavaVM();");
out.println("#endif");
out.println("}");
}
out.println();
out.println("JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved) {");
out.println(" JNIEnv* env;");
out.println(" if (vm->GetEnv((void**)&env, " + JNI_VERSION + ") != JNI_OK) {");
out.println(" JavaCPP_log(\"Could not get JNIEnv for " + JNI_VERSION + " inside JNI_OnUnLoad().\");");
out.println(" return;");
out.println(" }");
out.println(" for (int i = 0; i < " + jclasses.size() + "; i++) {");
out.println(" env->DeleteWeakGlobalRef(JavaCPP_classes[i]);");
out.println(" JavaCPP_classes[i] = NULL;");
out.println(" }");
out.println(" JavaCPP_vm = NULL;");
out.println("}");
out.println();
for (Class<?> cls : baseClasses) {
methods(cls);
}
boolean didSomethingUseful = false;
for (Class<?> cls : classes) {
try {
didSomethingUseful |= methods(cls);
} catch (NoClassDefFoundError e) {
logger.warn("Could not generate code for class " + cls.getCanonicalName() + ": " + e);
}
}
out.println("}");
out.println();
if (out2 != null) {
out2.println("#ifdef __cplusplus");
out2.println("}");
out2.println("#endif");
}
return didSomethingUseful;
}
boolean methods(Class<?> cls) {
if (!checkPlatform(cls)) {
return false;
}
LinkedList<String> memberList = members.get(cls);
if (!cls.isAnnotationPresent(Opaque.class) &&
!FunctionPointer.class.isAssignableFrom(cls)) {
if (memberList == null) {
members.put(cls, memberList = new LinkedList<String>());
}
if (!memberList.contains("sizeof")) {
memberList.add("sizeof");
}
}
boolean didSomething = false;
for (Class<?> c : cls.getDeclaredClasses()) {
if (Pointer.class.isAssignableFrom(c) ||
Pointer.Deallocator.class.isAssignableFrom(c)) {
didSomething |= methods(c);
}
}
Method[] methods = cls.getDeclaredMethods();
boolean[] callbackAllocators = new boolean[methods.length];
Method functionMethod = functionMethod(cls, callbackAllocators);
boolean firstCallback = true;
for (int i = 0; i < methods.length; i++) {
String nativeName = mangle(cls.getName()) + "_" + mangle(methods[i].getName());
if (!checkPlatform(methods[i].getAnnotation(Platform.class))) {
continue;
}
MethodInformation methodInfo = methodInformation(methods[i]);
String callbackName = "JavaCPP_" + nativeName + "_callback";
if (callbackAllocators[i] && functionMethod == null) {
logger.warn("No callback method call() or apply() has been not declared in \"" +
cls.getCanonicalName() + "\". No code will be generated for callback allocator.");
continue;
} else if (callbackAllocators[i] || (methods[i].equals(functionMethod) && methodInfo == null)) {
functions.index(cls);
Name name = methods[i].getAnnotation(Name.class);
if (name != null && name.value().length > 0 && name.value()[0].length() > 0) {
callbackName = name.value()[0];
}
callback(cls, functionMethod, callbackName, firstCallback);
firstCallback = false;
didSomething = true;
}
if (methodInfo == null) {
continue;
}
if ((methodInfo.memberGetter || methodInfo.memberSetter) && !methodInfo.noOffset &&
memberList != null && !Modifier.isStatic(methodInfo.modifiers)) {
if (!memberList.contains(methodInfo.memberName[0])) {
memberList.add(methodInfo.memberName[0]);
}
}
didSomething = true;
out.print("JNIEXPORT " + jniTypeName(methodInfo.returnType) + " JNICALL Java_" + nativeName);
if (methodInfo.overloaded) {
out.print("__" + mangle(signature(methodInfo.parameterTypes)));
}
if (Modifier.isStatic(methodInfo.modifiers)) {
out.print("(JNIEnv* env, jclass cls");
} else {
out.print("(JNIEnv* env, jobject obj");
}
for (int j = 0; j < methodInfo.parameterTypes.length; j++) {
out.print(", " + jniTypeName(methodInfo.parameterTypes[j]) + " arg" + j);
}
out.println(") {");
if (callbackAllocators[i]) {
callbackAllocator(cls, callbackName);
continue;
} else if (!Modifier.isStatic(methodInfo.modifiers) && !methodInfo.allocator &&
!methodInfo.arrayAllocator && !methodInfo.deallocator) {
// get our "this" pointer
String[] typeName = cppTypeName(cls);
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
} else if (FunctionPointer.class.isAssignableFrom(cls)) {
functions.index(cls);
typeName[0] = functionClassName(cls) + "*";
typeName[1] = "";
}
out.println(" " + typeName[0] + " ptr" + typeName[1] + " = (" + typeName[0] +
typeName[1] + ")jlong_to_ptr(env->GetLongField(obj, JavaCPP_addressFID));");
out.println(" if (ptr == NULL) {");
out.println(" env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"This pointer address is NULL.\");");
out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;"));
out.println(" }");
if (FunctionPointer.class.isAssignableFrom(cls)) {
out.println(" if (ptr->ptr == NULL) {");
out.println(" env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"This function pointer address is NULL.\");");
out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;"));
out.println(" }");
}
if (!cls.isAnnotationPresent(Opaque.class)) {
out.println(" jint position = env->GetIntField(obj, JavaCPP_positionFID);");
out.println(" ptr += position;");
if (methodInfo.bufferGetter) {
out.println(" jint size = env->GetIntField(obj, JavaCPP_limitFID);");
out.println(" size -= position;");
}
}
}
parametersBefore(methodInfo);
String returnPrefix = returnBefore(methodInfo);
call(methodInfo, returnPrefix);
returnAfter(methodInfo);
parametersAfter(methodInfo);
if (methodInfo.throwsException != null) {
out.println(" if (exc != NULL) {");
out.println(" env->Throw(exc);");
out.println(" }");
}
if (methodInfo.returnType != void.class) {
out.println(" return rarg;");
}
out.println("}");
}
out.println();
return didSomething;
}
void parametersBefore(MethodInformation methodInfo) {
String adapterLine = "";
AdapterInformation prevAdapterInfo = null;
int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0;
for (int j = skipParameters; j < methodInfo.parameterTypes.length; j++) {
if (!methodInfo.parameterTypes[j].isPrimitive()) {
Annotation passBy = by(methodInfo, j);
String cast = cast(methodInfo, j);
String[] typeName = cppTypeName(methodInfo.parameterTypes[j]);
AdapterInformation adapterInfo = adapterInformation(false, methodInfo, j);
if (FunctionPointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
functions.index(methodInfo.parameterTypes[j]);
if (methodInfo.parameterTypes[j] == FunctionPointer.class) {
logger.warn("Method \"" + methodInfo.method + "\" has an abstract FunctionPointer parameter, " +
"but a concrete subclass is required. Compilation will most likely fail.");
}
typeName[0] = functionClassName(methodInfo.parameterTypes[j]) + "*";
typeName[1] = "";
}
if (typeName[0].length() == 0 || methodInfo.parameterRaw[j]) {
methodInfo.parameterRaw[j] = true;
typeName[0] = jniTypeName(methodInfo.parameterTypes[j]);
out.println(" " + typeName[0] + " ptr" + j + " = arg" + j + ";");
continue;
}
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
}
out.print(" " + typeName[0] + " ptr" + j + typeName[1] + " = ");
if (Pointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
out.println("arg" + j + " == NULL ? NULL : (" + typeName[0] + typeName[1] +
")jlong_to_ptr(env->GetLongField(arg" + j + ", JavaCPP_addressFID));");
if ((j == 0 && FunctionPointer.class.isAssignableFrom(methodInfo.cls) &&
methodInfo.cls.isAnnotationPresent(Namespace.class)) ||
passBy instanceof ByVal || passBy instanceof ByRef) {
// in the case of member ptr, ptr0 is our object pointer, which cannot be NULL
out.println(" if (ptr" + j + " == NULL) {");
out.println(" env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"Pointer address of argument " + j + " is NULL.\");");
out.println(" return" + (methodInfo.returnType == void.class ? ";" : " 0;"));
out.println(" }");
}
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j + " = arg" + j + " == NULL ? 0 : env->GetIntField(arg" + j +
", JavaCPP_limitFID);");
}
if (!methodInfo.parameterTypes[j].isAnnotationPresent(Opaque.class)) {
out.println(" jint position" + j + " = arg" + j + " == NULL ? 0 : env->GetIntField(arg" + j +
", JavaCPP_positionFID);");
out.println(" ptr" + j + " += position" + j + ";");
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" size" + j + " -= position" + j + ";");
}
}
} else if (methodInfo.parameterTypes[j] == String.class) {
out.println("arg" + j + " == NULL ? NULL : env->GetStringUTFChars(arg" + j + ", NULL);");
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j + " = 0;");
}
} else if (methodInfo.parameterTypes[j].isArray() &&
methodInfo.parameterTypes[j].getComponentType().isPrimitive()) {
out.print("arg" + j + " == NULL ? NULL : ");
String s = methodInfo.parameterTypes[j].getComponentType().getName();
if (methodInfo.valueGetter || methodInfo.valueSetter ||
methodInfo.memberGetter || methodInfo.memberSetter) {
out.println("(j" + s + "*)env->GetPrimitiveArrayCritical(arg" + j + ", NULL);");
} else {
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println("env->Get" + s + "ArrayElements(arg" + j + ", NULL);");
}
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j +
" = arg" + j + " == NULL ? 0 : env->GetArrayLength(arg" + j + ");");
}
} else if (Buffer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
out.println("arg" + j + " == NULL ? NULL : (" + typeName[0] + typeName[1] + ")env->GetDirectBufferAddress(arg" + j + ");");
if (adapterInfo != null || prevAdapterInfo != null) {
out.println(" jint size" + j +
" = arg" + j + " == NULL ? 0 : env->GetDirectBufferCapacity(arg" + j + ");");
}
} else {
out.println("arg" + j + ";");
logger.warn("Method \"" + methodInfo.method + "\" has an unsupported parameter of type \"" +
methodInfo.parameterTypes[j].getCanonicalName() + "\". Compilation will most likely fail.");
}
if (adapterInfo != null) {
usesAdapters = true;
adapterLine = " " + adapterInfo.name + " adapter" + j + "(";
prevAdapterInfo = adapterInfo;
}
if (prevAdapterInfo != null) {
if (!FunctionPointer.class.isAssignableFrom(methodInfo.cls)) {
// sometimes we need to use the Cast annotation for declaring functions only
adapterLine += cast;
}
adapterLine += "ptr" + j + ", size" + j;
if (--prevAdapterInfo.argc > 0) {
adapterLine += ", ";
}
}
if (prevAdapterInfo != null && prevAdapterInfo.argc <= 0) {
out.println(adapterLine + ");");
prevAdapterInfo = null;
}
}
}
}
String returnBefore(MethodInformation methodInfo) {
String returnPrefix = "";
if (methodInfo.returnType == void.class) {
if (methodInfo.allocator || methodInfo.arrayAllocator) {
if (methodInfo.cls != Pointer.class) {
out.println(" if (!env->IsSameObject(env->GetObjectClass(obj), JavaCPP_getClass(env, " +
jclasses.index(methodInfo.cls) + "))) {");
out.println(" return;");
out.println(" }");
}
String[] typeName = cppTypeName(methodInfo.cls);
returnPrefix = typeName[0] + " rptr" + typeName[1] + " = ";
}
} else {
String cast = cast(methodInfo.returnType, methodInfo.annotations);
String[] typeName = cppCastTypeName(methodInfo.returnType, methodInfo.annotations);
if (methodInfo.valueSetter || methodInfo.memberSetter || methodInfo.noReturnGetter) {
out.println(" jobject rarg = obj;");
} else if (methodInfo.returnType.isPrimitive()) {
out.println(" " + jniTypeName(methodInfo.returnType) + " rarg = 0;");
returnPrefix = typeName[0] + " rvalue" + typeName[1] + " = " + cast;
} else {
Annotation returnBy = by(methodInfo.annotations);
String valueTypeName = valueTypeName(typeName);
returnPrefix = "rptr = " + cast;
if (typeName[0].length() == 0 || methodInfo.returnRaw) {
methodInfo.returnRaw = true;
typeName[0] = jniTypeName(methodInfo.returnType);
out.println(" " + typeName[0] + " rarg = NULL;");
out.println(" " + typeName[0] + " rptr;");
} else if (Pointer.class.isAssignableFrom(methodInfo.returnType) ||
Buffer.class.isAssignableFrom(methodInfo.returnType) ||
(methodInfo.returnType.isArray() &&
methodInfo.returnType.getComponentType().isPrimitive())) {
if (FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) {
functions.index(methodInfo.returnType);
typeName[0] = functionClassName(methodInfo.returnType) + "*";
typeName[1] = "";
valueTypeName = valueTypeName(typeName);
returnPrefix = "if (rptr != NULL) rptr->ptr = ";
}
if (returnBy instanceof ByVal) {
returnPrefix += (noException(methodInfo.returnType, methodInfo.method) ?
"new (std::nothrow) " : "new ") + valueTypeName + typeName[1] + "(";
} else if (returnBy instanceof ByRef) {
returnPrefix += "&";
} else if (returnBy instanceof ByPtrPtr) {
if (cast.length() > 0) {
typeName[0] = typeName[0].substring(0, typeName[0].length()-1);
}
returnPrefix = "rptr = NULL; " + typeName[0] + "* rptrptr" + typeName[1] + " = " + cast;
} // else ByPtr || ByPtrRef
if (methodInfo.bufferGetter) {
out.println(" jobject rarg = NULL;");
out.println(" char* rptr;");
} else {
out.println(" " + jniTypeName(methodInfo.returnType) + " rarg = NULL;");
out.println(" " + typeName[0] + " rptr" + typeName[1] + ";");
}
if (FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) {
out.println(" rptr = new (std::nothrow) " + valueTypeName + ";");
}
} else if (methodInfo.returnType == String.class) {
out.println(" jstring rarg = NULL;");
out.println(" const char* rptr;");
if (returnBy instanceof ByRef) {
returnPrefix = "std::string rstr(";
} else {
returnPrefix += "(const char*)";
}
} else {
logger.warn("Method \"" + methodInfo.method + "\" has unsupported return type \"" +
methodInfo.returnType.getCanonicalName() + "\". Compilation will most likely fail.");
}
AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, methodInfo.annotations);
if (adapterInfo != null) {
usesAdapters = true;
returnPrefix = adapterInfo.name + " radapter(";
}
}
}
if (methodInfo.throwsException != null) {
out.println(" jthrowable exc = NULL;");
out.println(" try {");
}
return returnPrefix;
}
void call(MethodInformation methodInfo, String returnPrefix) {
String indent = methodInfo.throwsException != null ? " " : " ";
String prefix = "(";
String suffix = ")";
int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0;
boolean index = methodInfo.method.isAnnotationPresent(Index.class) ||
(methodInfo.pairedMethod != null &&
methodInfo.pairedMethod.isAnnotationPresent(Index.class));
if (methodInfo.deallocator) {
out.println(indent + "void* allocatedAddress = jlong_to_ptr(arg0);");
out.println(indent + "void (*deallocatorAddress)(void*) = (void(*)(void*))jlong_to_ptr(arg1);");
out.println(indent + "if (deallocatorAddress != NULL && allocatedAddress != NULL) {");
out.println(indent + " (*deallocatorAddress)(allocatedAddress);");
out.println(indent + "}");
return; // nothing else should be appended here for deallocator
} else if (methodInfo.valueGetter || methodInfo.valueSetter ||
methodInfo.memberGetter || methodInfo.memberSetter) {
boolean wantsPointer = false;
int k = methodInfo.parameterTypes.length-1;
if ((methodInfo.valueSetter || methodInfo.memberSetter) &&
!(by(methodInfo, k) instanceof ByRef) &&
adapterInformation(false, methodInfo, k) == null &&
methodInfo.parameterTypes[k] == String.class) {
// special considerations for char arrays as strings
out.print(indent + "strcpy((char*)");
wantsPointer = true;
prefix = ", ";
} else if (k >= 1 && methodInfo.parameterTypes[0].isArray() &&
methodInfo.parameterTypes[0].getComponentType().isPrimitive() &&
(methodInfo.parameterTypes[1] == int.class ||
methodInfo.parameterTypes[1] == long.class)) {
// special considerations for primitive arrays
out.print(indent + "memcpy(");
wantsPointer = true;
prefix = ", ";
if (methodInfo.memberGetter || methodInfo.valueGetter) {
out.print("ptr0 + arg1, ");
} else { // methodInfo.memberSetter || methodInfo.valueSetter
prefix += "ptr0 + arg1, ";
}
skipParameters = 2;
suffix = " * sizeof(*ptr0)" + suffix;
} else {
out.print(indent + returnPrefix);
prefix = methodInfo.valueGetter || methodInfo.memberGetter ? "" : " = ";
suffix = "";
}
if (Modifier.isStatic(methodInfo.modifiers)) {
out.print(cppScopeName(methodInfo));
} else if (methodInfo.memberGetter || methodInfo.memberSetter) {
if (index) {
out.print("(*ptr)");
prefix = "." + methodInfo.memberName[0] + prefix;
} else {
out.print("ptr->" + methodInfo.memberName[0]);
}
} else { // methodInfo.valueGetter || methodInfo.valueSetter
out.print(index ? "(*ptr)" : methodInfo.dim > 0 || wantsPointer ? "ptr" : "*ptr");
}
} else if (methodInfo.bufferGetter) {
out.print(indent + returnPrefix + "ptr");
prefix = "";
suffix = "";
} else { // function call
out.print(indent + returnPrefix);
if (FunctionPointer.class.isAssignableFrom(methodInfo.cls)) {
if (methodInfo.cls.isAnnotationPresent(Namespace.class)) {
out.print("(ptr0->*(ptr->ptr))");
skipParameters = 1;
} else {
out.print("(*ptr->ptr)");
}
} else if (methodInfo.allocator) {
String[] typeName = cppTypeName(methodInfo.cls);
String valueTypeName = valueTypeName(typeName);
if (methodInfo.cls == Pointer.class) {
// can't allocate a "void", so simply assign the argument instead
prefix = "";
suffix = "";
} else {
out.print((noException(methodInfo.cls, methodInfo.method) ?
"new (std::nothrow) " : "new ") + valueTypeName + typeName[1]);
if (methodInfo.arrayAllocator) {
prefix = "[";
suffix = "]";
}
}
} else if (Modifier.isStatic(methodInfo.modifiers)) {
out.print(cppScopeName(methodInfo));
} else {
if (index) {
out.print("(*ptr)");
prefix = "." + methodInfo.memberName[0] + prefix;
} else {
out.print("ptr->" + methodInfo.memberName[0]);
}
}
}
for (int j = skipParameters; j <= methodInfo.parameterTypes.length; j++) {
if (j == skipParameters + methodInfo.dim) {
if (methodInfo.memberName.length > 1) {
out.print(methodInfo.memberName[1]);
}
out.print(prefix);
if (methodInfo.withEnv) {
out.print(Modifier.isStatic(methodInfo.modifiers) ? "env, cls" : "env, obj");
if (methodInfo.parameterTypes.length - skipParameters - methodInfo.dim > 0) {
out.print(", ");
}
}
}
if (j == methodInfo.parameterTypes.length) {
break;
}
if (j < skipParameters + methodInfo.dim) {
// print array indices to access array members, or whatever
// the C++ operator does with them when the Index annotation is present
out.print("[");
}
Annotation passBy = by(methodInfo, j);
String cast = cast(methodInfo, j);
AdapterInformation adapterInfo = adapterInformation(false, methodInfo, j);
if (("(void*)".equals(cast) || "(void *)".equals(cast)) &&
methodInfo.parameterTypes[j] == long.class) {
out.print("jlong_to_ptr(arg" + j + ")");
} else if (methodInfo.parameterTypes[j].isPrimitive()) {
out.print(cast + "arg" + j);
} else if (adapterInfo != null) {
cast = adapterInfo.cast.trim();
if (cast.length() > 0 && !cast.startsWith("(") && !cast.endsWith(")")) {
cast = "(" + cast + ")";
}
out.print(cast + "adapter" + j);
j += adapterInfo.argc - 1;
} else if (FunctionPointer.class.isAssignableFrom(methodInfo.parameterTypes[j]) && passBy == null) {
out.print(cast + "(ptr" + j + " == NULL ? NULL : ptr" + j + "->ptr)");
} else if (passBy instanceof ByVal || (passBy instanceof ByRef &&
methodInfo.parameterTypes[j] != String.class)) {
out.print("*" + cast + "ptr" + j);
} else if (passBy instanceof ByPtrPtr) {
out.print(cast + "(arg" + j + " == NULL ? NULL : &ptr" + j + ")");
} else { // ByPtr || ByPtrRef || (ByRef && std::string)
out.print(cast + "ptr" + j);
}
if (j < skipParameters + methodInfo.dim) {
out.print("]");
} else if (j < methodInfo.parameterTypes.length - 1) {
out.print(", ");
}
}
out.print(suffix);
if (methodInfo.memberName.length > 2) {
out.print(methodInfo.memberName[2]);
}
if (by(methodInfo.annotations) instanceof ByRef &&
methodInfo.returnType == String.class) {
// special considerations for std::string
out.print(");\n" + indent + "rptr = rstr.c_str()");
}
}
void returnAfter(MethodInformation methodInfo) {
String indent = methodInfo.throwsException != null ? " " : " ";
String[] typeName = cppCastTypeName(methodInfo.returnType, methodInfo.annotations);
Annotation returnBy = by(methodInfo.annotations);
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, methodInfo.annotations);
String suffix = methodInfo.deallocator ? "" : ";";
if (!methodInfo.returnType.isPrimitive() && adapterInfo != null) {
suffix = ")" + suffix;
}
if ((Pointer.class.isAssignableFrom(methodInfo.returnType) ||
(methodInfo.returnType.isArray() &&
methodInfo.returnType.getComponentType().isPrimitive()) ||
Buffer.class.isAssignableFrom(methodInfo.returnType))) {
if (returnBy instanceof ByVal) {
suffix = ")" + suffix;
} else if (returnBy instanceof ByPtrPtr) {
out.println(suffix);
suffix = "";
out.println(indent + "if (rptrptr == NULL) {");
out.println(indent + " env->ThrowNew(JavaCPP_getClass(env, " +
jclasses.index(NullPointerException.class) + "), \"Return pointer address is NULL.\");");
out.println(indent + "} else {");
out.println(indent + " rptr = *rptrptr;");
out.println(indent + "}");
}
}
out.println(suffix);
if (methodInfo.returnType == void.class) {
if (methodInfo.allocator || methodInfo.arrayAllocator) {
out.println(indent + "jint rcapacity = " + (methodInfo.arrayAllocator ? "arg0;" : "1;"));
boolean noDeallocator = methodInfo.cls == Pointer.class ||
methodInfo.cls.isAnnotationPresent(NoDeallocator.class);
for (Annotation a : methodInfo.annotations) {
if (a instanceof NoDeallocator) {
noDeallocator = true;
break;
}
}
out.print(indent + "JavaCPP_initPointer(env, obj, rptr, rcapacity, ");
if (noDeallocator) {
out.println("NULL);");
} else if (methodInfo.arrayAllocator) {
out.println("&JavaCPP_" + mangle(methodInfo.cls.getName()) + "_deallocateArray);");
arrayDeallocators.index(methodInfo.cls);
} else {
out.println("&JavaCPP_" + mangle(methodInfo.cls.getName()) + "_deallocate);");
deallocators.index(methodInfo.cls);
}
}
} else {
if (methodInfo.valueSetter || methodInfo.memberSetter || methodInfo.noReturnGetter) {
// nothing
} else if (methodInfo.returnType.isPrimitive()) {
out.println(indent + "rarg = (" + jniTypeName(methodInfo.returnType) + ")rvalue;");
} else if (methodInfo.returnRaw) {
out.println(indent + "rarg = rptr;");
} else {
boolean needInit = false;
if (adapterInfo != null) {
out.println(indent + "rptr = radapter;");
if (methodInfo.returnType != String.class) {
out.println(indent + "jint rcapacity = (jint)radapter.size;");
out.println(indent + "void (*deallocator)(void*) = " +
(adapterInfo.constant ? "NULL;" : "&" + adapterInfo.name + "::deallocate;"));
}
needInit = true;
} else if (returnBy instanceof ByVal ||
FunctionPointer.class.isAssignableFrom(methodInfo.returnType)) {
out.println(indent + "jint rcapacity = 1;");
out.println(indent + "void (*deallocator)(void*) = &JavaCPP_" +
mangle(methodInfo.returnType.getName()) + "_deallocate;");
deallocators.index(methodInfo.returnType);
needInit = true;
}
if (Pointer.class.isAssignableFrom(methodInfo.returnType)) {
out.print(indent);
if (!(returnBy instanceof ByVal)) {
// check if we can reuse one of the Pointer objects from the arguments
if (Modifier.isStatic(methodInfo.modifiers) && methodInfo.parameterTypes.length > 0) {
for (int i = 0; i < methodInfo.parameterTypes.length; i++) {
String cast = cast(methodInfo, i);
if (Arrays.equals(methodInfo.parameterAnnotations[i], methodInfo.annotations)
&& methodInfo.parameterTypes[i] == methodInfo.returnType) {
out.println( "if (rptr == " + cast + "ptr" + i + ") {");
out.println(indent + " rarg = arg" + i + ";");
out.print(indent + "} else ");
}
}
} else if (!Modifier.isStatic(methodInfo.modifiers) && methodInfo.cls == methodInfo.returnType) {
out.println( "if (rptr == ptr) {");
out.println(indent + " rarg = obj;");
out.print(indent + "} else ");
}
}
out.println( "if (rptr != NULL) {");
out.println(indent + " rarg = JavaCPP_createPointer(env, " + jclasses.index(methodInfo.returnType) +
(methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? ", arg0);" : ");"));
if (needInit) {
out.println(indent + " JavaCPP_initPointer(env, rarg, rptr, rcapacity, deallocator);");
} else {
out.println(indent + " env->SetLongField(rarg, JavaCPP_addressFID, ptr_to_jlong(rptr));");
}
out.println(indent + "}");
} else if (methodInfo.returnType == String.class) {
out.println(indent + "if (rptr != NULL) {");
out.println(indent + " rarg = env->NewStringUTF(rptr);");
out.println(indent + "}");
} else if (methodInfo.returnType.isArray() &&
methodInfo.returnType.getComponentType().isPrimitive()) {
if (adapterInfo == null && !(returnBy instanceof ByVal)) {
out.println(indent + "jint rcapacity = rptr != NULL ? 1 : 0;");
}
String s = methodInfo.returnType.getComponentType().getName();
String S = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println(indent + "if (rptr != NULL) {");
out.println(indent + " rarg = env->New" + S + "Array(rcapacity);");
out.println(indent + " env->Set" + S + "ArrayRegion(rarg, 0, rcapacity, (j" + s + "*)rptr);");
out.println(indent + "}");
if (adapterInfo != null) {
out.println(indent + "if (deallocator != 0 && rptr != NULL) {");
out.println(indent + " (*(void(*)(void*))jlong_to_ptr(deallocator))((void*)rptr);");
out.println(indent + "}");
}
} else if (Buffer.class.isAssignableFrom(methodInfo.returnType)) {
if (methodInfo.bufferGetter) {
out.println(indent + "jint rcapacity = size;");
} else if (adapterInfo == null && !(returnBy instanceof ByVal)) {
out.println(indent + "jint rcapacity = rptr != NULL ? 1 : 0;");
}
out.println(indent + "if (rptr != NULL) {");
out.println(indent + " rarg = env->NewDirectByteBuffer((void*)rptr, rcapacity);");
out.println(indent + "}");
}
}
}
}
void parametersAfter(MethodInformation methodInfo) {
if (methodInfo.throwsException != null) {
mayThrowExceptions = true;
out.println(" } catch (...) {");
out.println(" exc = JavaCPP_handleException(env, " + jclasses.index(methodInfo.throwsException) + ");");
out.println(" }");
out.println();
}
int skipParameters = methodInfo.parameterTypes.length > 0 && methodInfo.parameterTypes[0] == Class.class ? 1 : 0;
for (int j = skipParameters; j < methodInfo.parameterTypes.length; j++) {
if (methodInfo.parameterRaw[j]) {
continue;
}
Annotation passBy = by(methodInfo, j);
String cast = cast(methodInfo, j);
String[] typeName = cppCastTypeName(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j]);
AdapterInformation adapterInfo = adapterInformation(true, methodInfo, j);
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
}
if (Pointer.class.isAssignableFrom(methodInfo.parameterTypes[j])) {
if (adapterInfo != null) {
for (int k = 0; k < adapterInfo.argc; k++) {
out.println(" " + typeName[0] + " rptr" + (j+k) + typeName[1] + " = " + cast + "adapter" + j + ";");
out.println(" jint rsize" + (j+k) + " = (jint)adapter" + j + ".size" + (k > 0 ? (k+1) + ";" : ";"));
out.println(" if (rptr" + (j+k) + " != " + cast + "ptr" + (j+k) + ") {");
out.println(" JavaCPP_initPointer(env, arg" + j + ", rptr" + (j+k) + ", rsize" + (j+k) + ", &" + adapterInfo.name + "::deallocate);");
out.println(" } else {");
out.println(" env->SetIntField(arg" + j + ", JavaCPP_limitFID, rsize" + (j+k) + " + position" + (j+k) + ");");
out.println(" }");
}
} else if ((passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) &&
!methodInfo.valueSetter && !methodInfo.memberSetter) {
if (!methodInfo.parameterTypes[j].isAnnotationPresent(Opaque.class)) {
out.println(" ptr" + j + " -= position" + j + ";");
}
out.println(" if (arg" + j + " != NULL) env->SetLongField(arg" + j +
", JavaCPP_addressFID, ptr_to_jlong(ptr" + j + "));");
}
} else if (methodInfo.parameterTypes[j] == String.class) {
out.println(" if (arg" + j + " != NULL) env->ReleaseStringUTFChars(arg" + j + ", ptr" + j + ");");
} else if (methodInfo.parameterTypes[j].isArray() &&
methodInfo.parameterTypes[j].getComponentType().isPrimitive()) {
out.print(" if (arg" + j + " != NULL) ");
if (methodInfo.valueGetter || methodInfo.valueSetter ||
methodInfo.memberGetter || methodInfo.memberSetter) {
out.println("env->ReleasePrimitiveArrayCritical(arg" + j + ", ptr" + j + ", 0);");
} else {
String s = methodInfo.parameterTypes[j].getComponentType().getName();
String S = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println("env->Release" + S + "ArrayElements(arg" + j + ", (j" + s + "*)ptr" + j + ", 0);");
}
}
}
}
void callback(Class<?> cls, Method callbackMethod, String callbackName, boolean needFunctor) {
Class<?> callbackReturnType = callbackMethod.getReturnType();
Class<?>[] callbackParameterTypes = callbackMethod.getParameterTypes();
Annotation[] callbackAnnotations = callbackMethod.getAnnotations();
Annotation[][] callbackParameterAnnotations = callbackMethod.getParameterAnnotations();
String instanceTypeName = functionClassName(cls);
String[] callbackTypeName = cppTypeName(cls);
String[] returnConvention = callbackTypeName[0].split("\\(");
returnConvention[1] = constValueTypeName(returnConvention[1]);
String parameterDeclaration = callbackTypeName[1].substring(1);
callbacks.index("static " + instanceTypeName + " " + callbackName + "_instance;");
jclassesInit.index(cls); // for custom class loaders
if (out2 != null) {
out2.println("JNIIMPORT " + returnConvention[0] + (returnConvention.length > 1 ?
returnConvention[1] : "") + callbackName + parameterDeclaration + ";");
}
out.println("JNIEXPORT " + returnConvention[0] + (returnConvention.length > 1 ?
returnConvention[1] : "") + callbackName + parameterDeclaration + " {");
out.print((callbackReturnType != void.class ? " return " : " ") + callbackName + "_instance(");
for (int j = 0; j < callbackParameterTypes.length; j++) {
out.print("arg" + j);
if (j < callbackParameterTypes.length - 1) {
out.print(", ");
}
}
out.println(");");
out.println("}");
if (!needFunctor) {
return;
}
out.println(returnConvention[0] + instanceTypeName + "::operator()" + parameterDeclaration + " {");
String returnPrefix = "";
if (callbackReturnType != void.class) {
out.println(" " + jniTypeName(callbackReturnType) + " rarg = 0;");
returnPrefix = "rarg = ";
if (callbackReturnType == String.class) {
returnPrefix += "(jstring)";
}
}
String callbackReturnCast = cast(callbackReturnType, callbackAnnotations);
Annotation returnBy = by(callbackAnnotations);
String[] returnTypeName = cppTypeName(callbackReturnType);
String returnValueTypeName = valueTypeName(returnTypeName);
AdapterInformation returnAdapterInfo = adapterInformation(false, returnValueTypeName, callbackAnnotations);
out.println(" jthrowable exc = NULL;");
out.println(" JNIEnv* env;");
out.println(" bool attached = JavaCPP_getEnv(&env);");
out.println(" if (env == NULL) {");
out.println(" goto end;");
out.println(" }");
out.println("{");
if (callbackParameterTypes.length > 0) {
out.println(" jvalue args[" + callbackParameterTypes.length + "];");
for (int j = 0; j < callbackParameterTypes.length; j++) {
if (callbackParameterTypes[j].isPrimitive()) {
out.println(" args[" + j + "]." +
signature(callbackParameterTypes[j]).toLowerCase() + " = (" +
jniTypeName(callbackParameterTypes[j]) + ")arg" + j + ";");
} else {
Annotation passBy = by(callbackParameterAnnotations[j]);
String[] typeName = cppTypeName(callbackParameterTypes[j]);
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapterInfo = adapterInformation(false, valueTypeName, callbackParameterAnnotations[j]);
boolean needInit = false;
if (adapterInfo != null) {
usesAdapters = true;
out.println(" " + adapterInfo.name + " adapter" + j + "(arg" + j + ");");
if (callbackParameterTypes[j] != String.class) {
out.println(" jint size" + j + " = (jint)adapter" + j + ".size;");
out.println(" void (*deallocator" + j + ")(void*) = &" + adapterInfo.name + "::deallocate;");
}
needInit = true;
} else if ((passBy instanceof ByVal && callbackParameterTypes[j] != Pointer.class) ||
FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) {
out.println(" jint size" + j + " = 1;");
out.println(" void (*deallocator" + j + ")(void*) = &JavaCPP_" +
mangle(callbackParameterTypes[j].getName()) + "_deallocate;");
deallocators.index(callbackParameterTypes[j]);
needInit = true;
}
if (Pointer.class.isAssignableFrom(callbackParameterTypes[j]) ||
Buffer.class.isAssignableFrom(callbackParameterTypes[j]) ||
(callbackParameterTypes[j].isArray() &&
callbackParameterTypes[j].getComponentType().isPrimitive())) {
if (FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) {
functions.index(callbackParameterTypes[j]);
typeName[0] = functionClassName(callbackParameterTypes[j]) + "*";
typeName[1] = "";
valueTypeName = valueTypeName(typeName);
}
out.println(" " + jniTypeName(callbackParameterTypes[j]) + " obj" + j + " = NULL;");
out.println(" " + typeName[0] + " ptr" + j + typeName[1] + " = NULL;");
if (FunctionPointer.class.isAssignableFrom(callbackParameterTypes[j])) {
out.println(" ptr" + j + " = new (std::nothrow) " + valueTypeName + ";");
out.println(" if (ptr" + j + " != NULL) {");
out.println(" ptr" + j + "->ptr = arg" + j + ";");
out.println(" }");
} else if (adapterInfo != null) {
out.println(" ptr" + j + " = adapter" + j + ";");
} else if (passBy instanceof ByVal && callbackParameterTypes[j] != Pointer.class) {
out.println(" ptr" + j + (noException(callbackParameterTypes[j], callbackMethod) ?
" = new (std::nothrow) " : " = new ") + valueTypeName + typeName[1] +
"(*(" + typeName[0] + typeName[1] + ")&arg" + j + ");");
} else if (passBy instanceof ByVal || passBy instanceof ByRef) {
out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")&arg" + j + ";");
} else if (passBy instanceof ByPtrPtr) {
out.println(" if (arg" + j + " == NULL) {");
out.println(" JavaCPP_log(\"Pointer address of argument " + j + " is NULL in callback for " + cls.getCanonicalName() + ".\");");
out.println(" } else {");
out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")*arg" + j + ";");
out.println(" }");
} else { // ByPtr || ByPtrRef
out.println(" ptr" + j + " = (" + typeName[0] + typeName[1] + ")arg" + j + ";");
}
}
if (Pointer.class.isAssignableFrom(callbackParameterTypes[j])) {
String s = " obj" + j + " = JavaCPP_createPointer(env, " + jclasses.index(callbackParameterTypes[j]) + ");";
jclassesInit.index(callbackParameterTypes[j]); // for custom class loaders
adapterInfo = adapterInformation(true, valueTypeName, callbackParameterAnnotations[j]);
if (adapterInfo != null || passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) {
out.println(s);
} else {
out.println(" if (ptr" + j + " != NULL) { ");
out.println(" " + s);
out.println(" }");
}
out.println(" if (obj" + j + " != NULL) { ");
if (needInit) {
out.println(" JavaCPP_initPointer(env, obj" + j + ", ptr" + j + ", size" + j + ", deallocator" + j + ");");
} else {
out.println(" env->SetLongField(obj" + j + ", JavaCPP_addressFID, ptr_to_jlong(ptr" + j + "));");
}
out.println(" }");
out.println(" args[" + j + "].l = obj" + j + ";");
} else if (callbackParameterTypes[j] == String.class) {
out.println(" jstring obj" + j + " = (const char*)" + (adapterInfo != null ? "adapter" : "arg") + j +
" == NULL ? NULL : env->NewStringUTF((const char*)" + (adapterInfo != null ? "adapter" : "arg") + j + ");");
out.println(" args[" + j + "].l = obj" + j + ";");
} else if (callbackParameterTypes[j].isArray() &&
callbackParameterTypes[j].getComponentType().isPrimitive()) {
if (adapterInfo == null) {
out.println(" jint size" + j + " = ptr" + j + " != NULL ? 1 : 0;");
}
String s = callbackParameterTypes[j].getComponentType().getName();
String S = Character.toUpperCase(s.charAt(0)) + s.substring(1);
out.println(" if (ptr" + j + " != NULL) {");
out.println(" obj" + j + " = env->New" + S + "Array(size"+ j + ");");
out.println(" env->Set" + S + "ArrayRegion(obj" + j + ", 0, size" + j + ", (j" + s + "*)ptr" + j + ");");
out.println(" }");
if (adapterInfo != null) {
out.println(" if (deallocator" + j + " != 0 && ptr" + j + " != NULL) {");
out.println(" (*(void(*)(void*))jlong_to_ptr(deallocator" + j + "))((void*)ptr" + j + ");");
out.println(" }");
}
} else if (Buffer.class.isAssignableFrom(callbackParameterTypes[j])) {
if (adapterInfo == null) {
out.println(" jint size" + j + " = ptr" + j + " != NULL ? 1 : 0;");
}
out.println(" if (ptr" + j + " != NULL) {");
out.println(" obj" + j + " = env->NewDirectByteBuffer((void*)ptr" + j + ", size" + j + ");");
out.println(" }");
} else {
logger.warn("Callback \"" + callbackMethod + "\" has unsupported parameter type \"" +
callbackParameterTypes[j].getCanonicalName() + "\". Compilation will most likely fail.");
}
}
}
}
out.println(" if (obj == NULL) {");
out.println(" obj = env->NewGlobalRef(JavaCPP_createPointer(env, " + jclasses.index(cls) + "));");
out.println(" if (obj == NULL) {");
out.println(" JavaCPP_log(\"Error creating global reference of " + cls.getCanonicalName() + " instance for callback.\");");
out.println(" } else {");
out.println(" env->SetLongField(obj, JavaCPP_addressFID, ptr_to_jlong(this));");
out.println(" }");
out.println(" ptr = &" + callbackName + ";");
out.println(" }");
out.println(" if (mid == NULL) {");
out.println(" mid = JavaCPP_getMethodID(env, " + jclasses.index(cls) + ", \"" + callbackMethod.getName() + "\", \"(" +
signature(callbackMethod.getParameterTypes()) + ")" + signature(callbackMethod.getReturnType()) + "\");");
out.println(" }");
out.println(" if (env->IsSameObject(obj, NULL)) {");
out.println(" JavaCPP_log(\"Function pointer object is NULL in callback for " + cls.getCanonicalName() + ".\");");
out.println(" } else if (mid == NULL) {");
out.println(" JavaCPP_log(\"Error getting method ID of function caller \\\"" + callbackMethod + "\\\" for callback.\");");
out.println(" } else {");
String s = "Object";
if (callbackReturnType.isPrimitive()) {
s = callbackReturnType.getName();
s = Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
out.println(" " + returnPrefix + "env->Call" + s + "MethodA(obj, mid, " + (callbackParameterTypes.length == 0 ? "NULL);" : "args);"));
out.println(" if ((exc = env->ExceptionOccurred()) != NULL) {");
out.println(" env->ExceptionClear();");
out.println(" }");
out.println(" }");
for (int j = 0; j < callbackParameterTypes.length; j++) {
if (Pointer.class.isAssignableFrom(callbackParameterTypes[j])) {
String[] typeName = cppTypeName(callbackParameterTypes[j]);
Annotation passBy = by(callbackParameterAnnotations[j]);
String cast = cast(callbackParameterTypes[j], callbackParameterAnnotations[j]);
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapterInfo = adapterInformation(true, valueTypeName, callbackParameterAnnotations[j]);
if ("void*".equals(typeName[0])) {
typeName[0] = "char*";
}
if (adapterInfo != null || passBy instanceof ByPtrPtr || passBy instanceof ByPtrRef) {
out.println(" " + typeName[0] + " rptr" + j + typeName[1] + " = (" +
typeName[0] + typeName[1] + ")jlong_to_ptr(env->GetLongField(obj" + j + ", JavaCPP_addressFID));");
if (adapterInfo != null) {
out.println(" jint rsize" + j + " = env->GetIntField(obj" + j + ", JavaCPP_limitFID);");
}
if (!callbackParameterTypes[j].isAnnotationPresent(Opaque.class)) {
out.println(" jint rposition" + j + " = env->GetIntField(obj" + j + ", JavaCPP_positionFID);");
out.println(" rptr" + j + " += rposition" + j + ";");
if (adapterInfo != null) {
out.println(" rsize" + j + " -= rposition" + j + ";");
}
}
if (adapterInfo != null) {
out.println(" adapter" + j + ".assign(rptr" + j + ", rsize" + j + ");");
} else if (passBy instanceof ByPtrPtr) {
out.println(" if (arg" + j + " != NULL) {");
out.println(" *arg" + j + " = *" + cast + "&rptr" + j + ";");
out.println(" }");
} else if (passBy instanceof ByPtrRef) {
out.println(" arg" + j + " = " + cast + "rptr" + j + ";");
}
}
}
if (!callbackParameterTypes[j].isPrimitive()) {
out.println(" env->DeleteLocalRef(obj" + j + ");");
}
}
out.println("}");
out.println("end:");
if (callbackReturnType != void.class) {
if ("void*".equals(returnTypeName[0])) {
returnTypeName[0] = "char*";
}
if (Pointer.class.isAssignableFrom(callbackReturnType)) {
out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : (" +
returnTypeName[0] + returnTypeName[1] + ")jlong_to_ptr(env->GetLongField(rarg, JavaCPP_addressFID));");
if (returnAdapterInfo != null) {
out.println(" jint rsize = rarg == NULL ? 0 : env->GetIntField(rarg, JavaCPP_limitFID);");
}
if (!callbackReturnType.isAnnotationPresent(Opaque.class)) {
out.println(" jint rposition = rarg == NULL ? 0 : env->GetIntField(rarg, JavaCPP_positionFID);");
out.println(" rptr += rposition;");
if (returnAdapterInfo != null) {
out.println(" rsize -= rposition;");
}
}
} else if (callbackReturnType == String.class) {
out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : env->GetStringUTFChars(rarg, NULL);");
if (returnAdapterInfo != null) {
out.println(" jint rsize = 0;");
}
} else if (Buffer.class.isAssignableFrom(callbackReturnType)) {
out.println(" " + returnTypeName[0] + " rptr" + returnTypeName[1] + " = rarg == NULL ? NULL : env->GetDirectBufferAddress(rarg);");
if (returnAdapterInfo != null) {
out.println(" jint rsize = rarg == NULL ? 0 : env->GetDirectBufferCapacity(rarg);");
}
} else if (!callbackReturnType.isPrimitive()) {
logger.warn("Callback \"" + callbackMethod + "\" has unsupported return type \"" +
callbackReturnType.getCanonicalName() + "\". Compilation will most likely fail.");
}
}
out.println(" if (exc != NULL) {");
out.println(" jstring str = (jstring)env->CallObjectMethod(exc, JavaCPP_toStringMID);");
out.println(" env->DeleteLocalRef(exc);");
out.println(" const char *msg = env->GetStringUTFChars(str, NULL);");
out.println(" JavaCPP_exception e(msg);");
out.println(" env->ReleaseStringUTFChars(str, msg);");
out.println(" env->DeleteLocalRef(str);");
out.println(" JavaCPP_detach(attached);");
out.println(" throw e;");
out.println(" } else {");
out.println(" JavaCPP_detach(attached);");
out.println(" }");
if (callbackReturnType != void.class) {
if (callbackReturnType.isPrimitive()) {
out.println(" return " + callbackReturnCast + "rarg;");
} else if (returnAdapterInfo != null) {
usesAdapters = true;
out.println(" return " + returnAdapterInfo.name + "(" + callbackReturnCast + "rptr, rsize);");
} else if (FunctionPointer.class.isAssignableFrom(callbackReturnType)) {
functions.index(callbackReturnType);
out.println(" return " + callbackReturnCast + "(rptr == NULL ? NULL : rptr->ptr);");
} else if (returnBy instanceof ByVal || returnBy instanceof ByRef) {
out.println(" if (rptr == NULL) {");
out.println(" JavaCPP_log(\"Return pointer address is NULL in callback for " + cls.getCanonicalName() + ".\");");
out.println(" static " + returnValueTypeName + " empty" + returnTypeName[1] + ";");
out.println(" return empty;");
out.println(" } else {");
out.println(" return *" + callbackReturnCast + "rptr;");
out.println(" }");
} else if (returnBy instanceof ByPtrPtr) {
out.println(" return " + callbackReturnCast + "&rptr;");
} else { // ByPtr || ByPtrRef
out.println(" return " + callbackReturnCast + "rptr;");
}
}
out.println("}");
}
void callbackAllocator(Class cls, String callbackName) {
// XXX: Here, we should actually allocate new trampolines on the heap somehow...
// For now it just bumps out from the global variable the last object that called this method
String instanceTypeName = functionClassName(cls);
out.println(" obj = env->NewWeakGlobalRef(obj);");
out.println(" if (obj == NULL) {");
out.println(" JavaCPP_log(\"Error creating global reference of " + cls.getCanonicalName() + " instance for callback.\");");
out.println(" return;");
out.println(" }");
out.println(" " + instanceTypeName + "* rptr = new (std::nothrow) " + instanceTypeName + ";");
out.println(" if (rptr != NULL) {");
out.println(" rptr->ptr = &" + callbackName + ";");
out.println(" rptr->obj = obj;");
out.println(" JavaCPP_initPointer(env, obj, rptr, 1, &JavaCPP_" + mangle(cls.getName()) + "_deallocate);");
deallocators.index(cls);
out.println(" " + callbackName + "_instance = *rptr;");
out.println(" }");
out.println("}");
}
boolean checkPlatform(Class<?> cls) {
com.googlecode.javacpp.annotation.Properties classProperties =
cls.getAnnotation(com.googlecode.javacpp.annotation.Properties.class);
if (classProperties != null) {
Class[] classes = classProperties.inherit();
if (classes != null) {
for (Class c : classes) {
if (checkPlatform(c)) {
return true;
}
}
}
Platform[] platforms = classProperties.value();
if (platforms != null) {
for (Platform p : platforms) {
if (checkPlatform(p)) {
return true;
}
}
}
} else if (checkPlatform(cls.getAnnotation(Platform.class))) {
return true;
}
return false;
}
boolean checkPlatform(Platform platform) {
if (platform == null) {
return true;
}
String platform2 = properties.getProperty("platform");
String[][] names = { platform.value(), platform.not() };
boolean[] matches = { false, false };
for (int i = 0; i < names.length; i++) {
for (String s : names[i]) {
if (platform2.startsWith(s)) {
matches[i] = true;
break;
}
}
}
if ((names[0].length == 0 || matches[0]) && (names[1].length == 0 || !matches[1])) {
return true;
}
return false;
}
static String functionClassName(Class<?> cls) {
Name name = cls.getAnnotation(Name.class);
return name != null ? name.value()[0] : "JavaCPP_" + mangle(cls.getName());
}
static Method functionMethod(Class<?> cls, boolean[] callbackAllocators) {
if (!FunctionPointer.class.isAssignableFrom(cls)) {
return null;
}
Method[] methods = cls.getDeclaredMethods();
Method functionMethod = null;
for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
int modifiers = methods[i].getModifiers();
Class[] parameterTypes = methods[i].getParameterTypes();
Class returnType = methods[i].getReturnType();
if (Modifier.isStatic(modifiers)) {
continue;
}
if (callbackAllocators != null && methodName.startsWith("allocate") &&
Modifier.isNative(modifiers) && returnType == void.class &&
parameterTypes.length == 0) {
// found a callback allocator method
callbackAllocators[i] = true;
} else if (methodName.startsWith("call") || methodName.startsWith("apply")) {
// found a function caller method and/or callback method
functionMethod = methods[i];
}
}
return functionMethod;
}
static class MethodInformation {
Class<?> cls;
Method method;
Annotation[] annotations;
int modifiers;
Class<?> returnType;
String name, memberName[];
int dim;
boolean[] parameterRaw;
Class<?>[] parameterTypes;
Annotation[][] parameterAnnotations;
boolean returnRaw, withEnv, overloaded, noOffset, deallocator, allocator, arrayAllocator,
bufferGetter, valueGetter, valueSetter, memberGetter, memberSetter, noReturnGetter;
Method pairedMethod;
Class<?> throwsException;
}
MethodInformation methodInformation(Method method) {
if (!Modifier.isNative(method.getModifiers())) {
return null;
}
MethodInformation info = new MethodInformation();
info.cls = method.getDeclaringClass();
info.method = method;
info.annotations = method.getAnnotations();
info.modifiers = method.getModifiers();
info.returnType = method.getReturnType();
info.name = method.getName();
Name name = method.getAnnotation(Name.class);
info.memberName = name != null ? name.value() : new String[] { info.name };
Index index = method.getAnnotation(Index.class);
info.dim = index != null ? index.value() : 0;
info.parameterTypes = method.getParameterTypes();
info.parameterAnnotations = method.getParameterAnnotations();
info.returnRaw = method.isAnnotationPresent(Raw.class);
info.withEnv = info.returnRaw ? method.getAnnotation(Raw.class).withEnv() : false;
info.parameterRaw = new boolean[info.parameterAnnotations.length];
for (int i = 0; i < info.parameterAnnotations.length; i++) {
for (int j = 0; j < info.parameterAnnotations[i].length; j++) {
if (info.parameterAnnotations[i][j] instanceof Raw) {
info.parameterRaw[i] = true;
info.withEnv |= ((Raw)info.parameterAnnotations[i][j]).withEnv();
}
}
}
boolean canBeGetter = info.returnType != void.class || (info.parameterTypes.length > 0 &&
info.parameterTypes[0].isArray() && info.parameterTypes[0].getComponentType().isPrimitive());
boolean canBeSetter = (info.returnType == void.class ||
info.returnType == info.cls) && info.parameterTypes.length > 0;
boolean canBeAllocator = !Modifier.isStatic(info.modifiers) && info.returnType == void.class;
boolean canBeArrayAllocator = canBeAllocator && info.parameterTypes.length == 1 &&
(info.parameterTypes[0] == int.class || info.parameterTypes[0] == long.class);
boolean valueGetter = false;
boolean valueSetter = false;
boolean memberGetter = false;
boolean memberSetter = false;
boolean noReturnGetter = false;
Method pairedMethod = null;
for (Method method2 : info.cls.getDeclaredMethods()) {
int modifiers2 = method2.getModifiers();
Class returnType2 = method2.getReturnType();
String methodName2 = method2.getName();
Class[] parameterTypes2 = method2.getParameterTypes();
Annotation[] annotations2 = method2.getAnnotations();
Annotation[][] parameterAnnotations2 = method2.getParameterAnnotations();
int skipParameters = info.parameterTypes.length > 0 && info.parameterTypes[0] == Class.class ? 1 : 0;
int skipParameters2 = parameterTypes2.length > 0 && parameterTypes2[0] == Class.class ? 1 : 0;
if (method.equals(method2) || !Modifier.isNative(modifiers2)) {
continue;
}
boolean canBeValueGetter = false;
boolean canBeValueSetter = false;
boolean canBeMemberGetter = false;
boolean canBeMemberSetter = false;
if (canBeGetter && "get".equals(info.name) && "put".equals(methodName2)) {
canBeValueGetter = true;
} else if (canBeSetter && "put".equals(info.name) && "get".equals(methodName2)) {
canBeValueSetter = true;
} else if (methodName2.equals(info.name)) {
info.overloaded = true;
canBeMemberGetter = canBeGetter;
canBeMemberSetter = canBeSetter;
for (int j = skipParameters; j < info.parameterTypes.length; j++) {
if (info.parameterTypes[j] != int.class && info.parameterTypes[j] != long.class) {
canBeMemberGetter = false;
if (j < info.parameterTypes.length - 1) {
canBeMemberSetter = false;
}
}
}
} else {
continue;
}
boolean sameIndexParameters = true;
for (int j = 0; j < info.parameterTypes.length - skipParameters && j < parameterTypes2.length - skipParameters2; j++) {
if (info.parameterTypes[j + skipParameters] != parameterTypes2[j + skipParameters2]) {
sameIndexParameters = false;
}
}
if (!sameIndexParameters) {
continue;
}
boolean parameterAsReturn = canBeValueGetter && info.parameterTypes.length > 0 &&
info.parameterTypes[0].isArray() && info.parameterTypes[0].getComponentType().isPrimitive();
boolean parameterAsReturn2 = canBeValueSetter && parameterTypes2.length > 0 &&
parameterTypes2[0].isArray() && parameterTypes2[0].getComponentType().isPrimitive();
if (canBeGetter && parameterTypes2.length - (parameterAsReturn ? 0 : 1) == info.parameterTypes.length - skipParameters
&& (parameterAsReturn ? info.parameterTypes[info.parameterTypes.length - 1] : info.returnType) ==
parameterTypes2[parameterTypes2.length - 1] && (returnType2 == void.class || returnType2 == info.cls)
&& (parameterAnnotations2[parameterAnnotations2.length - 1].length == 0
|| (Arrays.equals(parameterAnnotations2[parameterAnnotations2.length - 1], info.annotations)))) {
pairedMethod = method2;
valueGetter = canBeValueGetter;
memberGetter = canBeMemberGetter;
noReturnGetter = parameterAsReturn;
} else if (canBeSetter && info.parameterTypes.length - (parameterAsReturn2 ? 0 : 1) == parameterTypes2.length - skipParameters2
&& (parameterAsReturn2 ? parameterTypes2[parameterTypes2.length - 1] : returnType2) ==
info.parameterTypes[info.parameterTypes.length - 1] && (info.returnType == void.class || info.returnType == info.cls)
&& (info.parameterAnnotations[info.parameterAnnotations.length - 1].length == 0
|| (Arrays.equals(info.parameterAnnotations[info.parameterAnnotations.length - 1], annotations2)))) {
pairedMethod = method2;
valueSetter = canBeValueSetter;
memberSetter = canBeMemberSetter;
}
}
Annotation behavior = behavior(info.annotations);
if (canBeGetter && behavior instanceof ValueGetter) {
info.valueGetter = true;
info.noReturnGetter = noReturnGetter;
} else if (canBeSetter && behavior instanceof ValueSetter) {
info.valueSetter = true;
} else if (canBeGetter && behavior instanceof MemberGetter) {
info.memberGetter = true;
info.noReturnGetter = noReturnGetter;
} else if (canBeSetter && behavior instanceof MemberSetter) {
info.memberSetter = true;
} else if (canBeAllocator && behavior instanceof Allocator) {
info.allocator = true;
} else if (canBeArrayAllocator && behavior instanceof ArrayAllocator) {
info.allocator = info.arrayAllocator = true;
} else if (behavior == null) {
// try to guess the behavior of the method
if (info.returnType == void.class && "deallocate".equals(info.name) &&
!Modifier.isStatic(info.modifiers) && info.parameterTypes.length == 2 &&
info.parameterTypes[0] == long.class && info.parameterTypes[1] == long.class) {
info.deallocator = true;
} else if (canBeAllocator && "allocate".equals(info.name)) {
info.allocator = true;
} else if (canBeArrayAllocator && "allocateArray".equals(info.name)) {
info.allocator = info.arrayAllocator = true;
} else if (info.returnType.isAssignableFrom(ByteBuffer.class) && "asDirectBuffer".equals(info.name) &&
!Modifier.isStatic(info.modifiers) && info.parameterTypes.length == 0) {
info.bufferGetter = true;
} else if (valueGetter) {
info.valueGetter = true;
info.noReturnGetter = noReturnGetter;
info.pairedMethod = pairedMethod;
} else if (valueSetter) {
info.valueSetter = true;
info.pairedMethod = pairedMethod;
} else if (memberGetter) {
info.memberGetter = true;
info.noReturnGetter = noReturnGetter;
info.pairedMethod = pairedMethod;
} else if (memberSetter) {
info.memberSetter = true;
info.pairedMethod = pairedMethod;
}
} else if (!(behavior instanceof Function)) {
logger.warn("Method \"" + method + "\" cannot behave like a \"" +
behavior.annotationType().getSimpleName() + "\". No code will be generated.");
return null;
}
if (name == null && info.pairedMethod != null) {
name = info.pairedMethod.getAnnotation(Name.class);
if (name != null) {
info.memberName = name.value();
}
}
info.noOffset = info.cls.isAnnotationPresent(NoOffset.class) ||
method.isAnnotationPresent(NoOffset.class) ||
method.isAnnotationPresent(Index.class);
if (!info.noOffset && info.pairedMethod != null) {
info.noOffset = info.pairedMethod.isAnnotationPresent(NoOffset.class) ||
info.pairedMethod.isAnnotationPresent(Index.class);
}
if (info.parameterTypes.length == 0 || !info.parameterTypes[0].isArray()) {
if (info.valueGetter || info.memberGetter) {
info.dim = info.parameterTypes.length;
} else if (info.memberSetter || info.valueSetter) {
info.dim = info.parameterTypes.length-1;
}
}
info.throwsException = null;
if (!noException(info.cls, method)) {
if ((by(info.annotations) instanceof ByVal && !noException(info.returnType, method)) ||
!info.deallocator && !info.valueGetter && !info.valueSetter &&
!info.memberGetter && !info.memberSetter && !info.bufferGetter) {
Class<?>[] exceptions = method.getExceptionTypes();
info.throwsException = exceptions.length > 0 ? exceptions[0] : RuntimeException.class;
}
}
return info;
}
static boolean noException(Class<?> cls, Method method) {
boolean noException = baseClasses.contains(cls) ||
method.isAnnotationPresent(NoException.class);
while (!noException && cls != null) {
if (noException = cls.isAnnotationPresent(NoException.class)) {
break;
}
cls = cls.getDeclaringClass();
}
return noException;
}
static class AdapterInformation {
String name;
int argc;
String cast;
boolean constant;
}
AdapterInformation adapterInformation(boolean out, MethodInformation methodInfo, int j) {
if (out && (methodInfo.parameterTypes[j] == String.class || methodInfo.valueSetter || methodInfo.memberSetter)) {
return null;
}
String typeName = cast(methodInfo, j);
if (typeName != null && typeName.startsWith("(") && typeName.endsWith(")")) {
typeName = typeName.substring(1, typeName.length()-1);
}
if (typeName == null || typeName.length() == 0) {
typeName = cppCastTypeName(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j])[0];
}
String valueTypeName = valueTypeName(typeName);
AdapterInformation adapter = adapterInformation(out, valueTypeName, methodInfo.parameterAnnotations[j]);
if (adapter == null && methodInfo.pairedMethod != null && j == methodInfo.parameterTypes.length - 1 &&
(methodInfo.valueSetter || methodInfo.memberSetter)) {
adapter = adapterInformation(out, valueTypeName, methodInfo.pairedMethod.getAnnotations());
}
return adapter;
}
AdapterInformation adapterInformation(boolean out, String valueTypeName, Annotation ... annotations) {
AdapterInformation adapterInfo = null;
boolean constant = false;
String cast = "";
for (Annotation a : annotations) {
Adapter adapter = a instanceof Adapter ? (Adapter)a : a.annotationType().getAnnotation(Adapter.class);
if (adapter != null) {
adapterInfo = new AdapterInformation();
adapterInfo.name = adapter.value();
adapterInfo.argc = adapter.argc();
if (a != adapter) {
try {
Class cls = a.annotationType();
if (cls.isAnnotationPresent(Const.class)) {
constant = true;
}
try {
String value = cls.getDeclaredMethod("value").invoke(a).toString();
if (value != null && value.length() > 0) {
valueTypeName = value;
}
// else use inferred type
} catch (NoSuchMethodException e) {
// this adapter does not support a template type
valueTypeName = null;
}
Cast c = (Cast)cls.getAnnotation(Cast.class);
if (c != null && cast.length() == 0) {
cast = c.value()[0];
if (valueTypeName != null) {
cast += "< " + valueTypeName + " >";
}
if (c.value().length > 1) {
cast += c.value()[1];
}
}
} catch (Exception ex) {
logger.warn("Could not invoke the value() method on annotation \"" + a + "\": " + ex);
}
if (valueTypeName != null && valueTypeName.length() > 0) {
adapterInfo.name += "< " + valueTypeName + " >";
}
}
} else if (a instanceof Const) {
constant = true;
} else if (a instanceof Cast) {
Cast c = ((Cast)a);
if (c.value().length > 1) {
cast = c.value()[1];
}
}
}
if (adapterInfo != null) {
adapterInfo.cast = cast;
adapterInfo.constant = constant;
}
return out && constant ? null : adapterInfo;
}
String cast(MethodInformation methodInfo, int j) {
String cast = cast(methodInfo.parameterTypes[j], methodInfo.parameterAnnotations[j]);
if ((cast == null || cast.length() == 0) && j == methodInfo.parameterTypes.length-1 &&
(methodInfo.valueSetter || methodInfo.memberSetter) && methodInfo.pairedMethod != null) {
cast = cast(methodInfo.pairedMethod.getReturnType(), methodInfo.pairedMethod.getAnnotations());
}
return cast;
}
String cast(Class<?> type, Annotation ... annotations) {
String[] typeName = null;
for (Annotation a : annotations) {
if ((a instanceof Cast && ((Cast)a).value()[0].length() > 0) || a instanceof Const) {
typeName = cppCastTypeName(type, annotations);
break;
}
}
return typeName != null && typeName.length > 0 ? "(" + typeName[0] + typeName[1] + ")" : "";
}
Annotation by(MethodInformation methodInfo, int j) {
Annotation passBy = by(methodInfo.parameterAnnotations[j]);
if (passBy == null && methodInfo.pairedMethod != null &&
(methodInfo.valueSetter || methodInfo.memberSetter)) {
passBy = by(methodInfo.pairedMethod.getAnnotations());
}
return passBy;
}
Annotation by(Annotation ... annotations) {
Annotation byAnnotation = null;
for (Annotation a : annotations) {
if (a instanceof ByPtr || a instanceof ByPtrPtr || a instanceof ByPtrRef ||
a instanceof ByRef || a instanceof ByVal) {
if (byAnnotation != null) {
logger.warn("\"By\" annotation \"" + byAnnotation +
"\" already found. Ignoring superfluous annotation \"" + a + "\".");
} else {
byAnnotation = a;
}
}
}
return byAnnotation;
}
Annotation behavior(Annotation ... annotations) {
Annotation behaviorAnnotation = null;
for (Annotation a : annotations) {
if (a instanceof Function || a instanceof Allocator || a instanceof ArrayAllocator ||
a instanceof ValueSetter || a instanceof ValueGetter ||
a instanceof MemberGetter || a instanceof MemberSetter) {
if (behaviorAnnotation != null) {
logger.warn("Behavior annotation \"" + behaviorAnnotation +
"\" already found. Ignoring superfluous annotation \"" + a + "\".");
} else {
behaviorAnnotation = a;
}
}
}
return behaviorAnnotation;
}
static String constValueTypeName(String ... typeName) {
String type = typeName[0];
if (type.endsWith("*") || type.endsWith("&")) {
type = type.substring(0, type.length()-1);
}
return type;
}
static String valueTypeName(String ... typeName) {
String type = typeName[0];
if (type.startsWith("const ")) {
type = type.substring(6, type.length()-1);
} else if (type.endsWith("*") || type.endsWith("&")) {
type = type.substring(0, type.length()-1);
}
return type;
}
String[] cppAnnotationTypeName(Class<?> type, Annotation ... annotations) {
String[] typeName = cppCastTypeName(type, annotations);
String prefix = typeName[0];
String suffix = typeName[1];
boolean casted = false;
for (Annotation a : annotations) {
if ((a instanceof Cast && ((Cast)a).value()[0].length() > 0) || a instanceof Const) {
casted = true;
break;
}
}
Annotation by = by(annotations);
if (by instanceof ByVal) {
prefix = constValueTypeName(typeName);
} else if (by instanceof ByRef) {
prefix = constValueTypeName(typeName) + "&";
} else if (by instanceof ByPtrPtr && !casted) {
prefix = prefix + "*";
} else if (by instanceof ByPtrRef) {
prefix = prefix + "&";
} // else ByPtr
typeName[0] = prefix;
typeName[1] = suffix;
return typeName;
}
String[] cppCastTypeName(Class<?> type, Annotation ... annotations) {
String[] typeName = null;
boolean warning = false, adapter = false;
for (Annotation a : annotations) {
if (a instanceof Cast) {
warning = typeName != null;
String prefix = ((Cast)a).value()[0], suffix = "";
int parenthesis = prefix.indexOf(')');
if (parenthesis > 0) {
suffix = prefix.substring(parenthesis).trim();
prefix = prefix.substring(0, parenthesis).trim();
}
typeName = prefix.length() > 0 ? new String[] { prefix, suffix } : null;
} else if (a instanceof Const) {
if (warning = typeName != null) {
// prioritize @Cast
continue;
}
typeName = cppTypeName(type);
boolean[] b = ((Const)a).value();
if (b.length > 1 && b[1]) {
typeName[0] = valueTypeName(typeName) + " const *";
}
if (b.length > 0 && b[0]) {
typeName[0] = "const " + typeName[0];
}
Annotation by = by(annotations);
if (by instanceof ByPtrPtr) {
typeName[0] += "*";
} else if (by instanceof ByPtrRef) {
typeName[0] += "&";
}
} else if (a instanceof Adapter || a.annotationType().isAnnotationPresent(Adapter.class)) {
adapter = true;
}
}
if (warning && !adapter) {
logger.warn("Without \"Adapter\", \"Cast\" and \"Const\" annotations are mutually exclusive.");
}
if (typeName == null) {
typeName = cppTypeName(type);
}
return typeName;
}
String[] cppTypeName(Class<?> type) {
String prefix = "", suffix = "";
if (type == Buffer.class || type == Pointer.class) {
prefix = "void*";
} else if (type == byte[].class || type == ByteBuffer.class || type == BytePointer.class) {
prefix = "signed char*";
} else if (type == short[].class || type == ShortBuffer.class || type == ShortPointer.class) {
prefix = "short*";
} else if (type == int[].class || type == IntBuffer.class || type == IntPointer.class) {
prefix = "int*";
} else if (type == long[].class || type == LongBuffer.class || type == LongPointer.class) {
prefix = "jlong*";
} else if (type == float[].class || type == FloatBuffer.class || type == FloatPointer.class) {
prefix = "float*";
} else if (type == double[].class || type == DoubleBuffer.class || type == DoublePointer.class) {
prefix = "double*";
} else if (type == char[].class || type == CharBuffer.class || type == CharPointer.class) {
prefix = "unsigned short*";
} else if (type == boolean[].class) {
prefix = "unsigned char*";
} else if (type == PointerPointer.class) {
prefix = "void**";
} else if (type == String.class) {
prefix = "const char*";
} else if (type == byte.class) {
prefix = "signed char";
} else if (type == long.class) {
prefix = "jlong";
} else if (type == char.class) {
prefix = "unsigned short";
} else if (type == boolean.class) {
prefix = "unsigned char";
} else if (type.isPrimitive()) {
prefix = type.getName();
} else if (FunctionPointer.class.isAssignableFrom(type)) {
Method functionMethod = functionMethod(type, null);
if (functionMethod != null) {
Convention convention = type.getAnnotation(Convention.class);
String callingConvention = convention == null ? "" : convention.value() + " ";
Namespace namespace = type.getAnnotation(Namespace.class);
String spaceName = namespace == null ? "" : namespace.value();
if (spaceName.length() > 0 && !spaceName.endsWith("::")) {
spaceName += "::";
}
Class returnType = functionMethod.getReturnType();
Class[] parameterTypes = functionMethod.getParameterTypes();
Annotation[] annotations = functionMethod.getAnnotations();
Annotation[][] parameterAnnotations = functionMethod.getParameterAnnotations();
String[] returnTypeName = cppAnnotationTypeName(returnType, annotations);
AdapterInformation returnAdapterInfo = adapterInformation(false, valueTypeName(returnTypeName), annotations);
if (returnAdapterInfo != null && returnAdapterInfo.cast.length() > 0) {
prefix = returnAdapterInfo.cast;
} else {
prefix = returnTypeName[0] + returnTypeName[1];
}
prefix += " (" + callingConvention + spaceName + "*";
suffix = ")(";
if (namespace != null && !Pointer.class.isAssignableFrom(parameterTypes[0])) {
logger.warn("First parameter of caller method call() or apply() for member function pointer " +
type.getCanonicalName() + " is not a Pointer. Compilation will most likely fail.");
}
for (int j = namespace == null ? 0 : 1; j < parameterTypes.length; j++) {
String[] paramTypeName = cppAnnotationTypeName(parameterTypes[j], parameterAnnotations[j]);
AdapterInformation paramAdapterInfo = adapterInformation(false, valueTypeName(paramTypeName), parameterAnnotations[j]);
if (paramAdapterInfo != null && paramAdapterInfo.cast.length() > 0) {
suffix += paramAdapterInfo.cast + " arg" + j;
} else {
suffix += paramTypeName[0] + " arg" + j + paramTypeName[1];
}
if (j < parameterTypes.length - 1) {
suffix += ", ";
}
}
suffix += ")";
if (type.isAnnotationPresent(Const.class)) {
suffix += " const";
}
}
} else {
String scopedType = cppScopeName(type);
if (scopedType.length() > 0) {
prefix = scopedType + "*";
} else {
logger.warn("The class " + type.getCanonicalName() +
" does not map to any C++ type. Compilation will most likely fail.");
}
}
return new String[] { prefix, suffix };
}
static String cppScopeName(MethodInformation methodInfo) {
String scopeName = cppScopeName(methodInfo.cls);
Namespace namespace = methodInfo.method.getAnnotation(Namespace.class);
String spaceName = namespace == null ? "" : namespace.value();
if ((namespace != null && namespace.value().length() == 0) || spaceName.startsWith("::")) {
scopeName = ""; // user wants to reset namespace here
}
if (scopeName.length() > 0 && !scopeName.endsWith("::")) {
scopeName += "::";
}
scopeName += spaceName;
if (spaceName.length() > 0 && !spaceName.endsWith("::")) {
scopeName += "::";
}
return scopeName + methodInfo.memberName[0];
}
static String cppScopeName(Class<?> type) {
String scopeName = "";
while (type != null) {
Namespace namespace = type.getAnnotation(Namespace.class);
String spaceName = namespace == null ? "" : namespace.value();
if (Pointer.class.isAssignableFrom(type) && type != Pointer.class) {
Name name = type.getAnnotation(Name.class);
String s;
if (name == null) {
s = type.getName();
int i = s.lastIndexOf("$");
if (i < 0) {
i = s.lastIndexOf(".");
}
s = s.substring(i+1);
} else {
s = name.value()[0];
}
if (spaceName.length() > 0 && !spaceName.endsWith("::")) {
spaceName += "::";
}
spaceName += s;
}
if (scopeName.length() > 0 && !spaceName.endsWith("::")) {
spaceName += "::";
}
scopeName = spaceName + scopeName;
if ((namespace != null && namespace.value().length() == 0) || spaceName.startsWith("::")) {
// user wants to reset namespace here
break;
}
type = type.getDeclaringClass();
}
return scopeName;
}
static String jniTypeName(Class type) {
if (type == byte.class) {
return "jbyte";
} else if (type == short.class) {
return "jshort";
} else if (type == int.class) {
return "jint";
} else if (type == long.class) {
return "jlong";
} else if (type == float.class) {
return "jfloat";
} else if (type == double.class) {
return "jdouble";
} else if (type == char.class) {
return "jchar";
} else if (type == boolean.class) {
return "jboolean";
} else if (type == byte[].class) {
return "jbyteArray";
} else if (type == short[].class) {
return "jshortArray";
} else if (type == int[].class) {
return "jintArray";
} else if (type == long[].class) {
return "jlongArray";
} else if (type == float[].class) {
return "jfloatArray";
} else if (type == double[].class) {
return "jdoubleArray";
} else if (type == char[].class) {
return "jcharArray";
} else if (type == boolean[].class) {
return "jbooleanArray";
} else if (type.isArray()) {
return "jobjectArray";
} else if (type == String.class) {
return "jstring";
} else if (type == Class.class) {
return "jclass";
} else if (type == void.class) {
return "void";
} else {
return "jobject";
}
}
static String signature(Class ... types) {
StringBuilder signature = new StringBuilder(2*types.length);
for (Class type : types) {
if (type == byte.class) {
signature.append("B");
} else if (type == short.class) {
signature.append("S");
} else if (type == int.class) {
signature.append("I");
} else if (type == long.class) {
signature.append("J");
} else if (type == float.class) {
signature.append("F");
} else if (type == double.class) {
signature.append("D");
} else if (type == boolean.class) {
signature.append("Z");
} else if (type == char.class) {
signature.append("C");
} else if (type == void.class) {
signature.append("V");
} else if (type.isArray()) {
signature.append(type.getName().replace('.', '/'));
} else {
signature.append("L").append(type.getName().replace('.', '/')).append(";");
}
}
return signature.toString();
}
static String mangle(String name) {
StringBuilder mangledName = new StringBuilder(2*name.length());
for (int i = 0; i < name.length(); i++) {
char c = name.charAt(i);
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
mangledName.append(c);
} else if (c == '_') {
mangledName.append("_1");
} else if (c == ';') {
mangledName.append("_2");
} else if (c == '[') {
mangledName.append("_3");
} else if (c == '.' || c == '/') {
mangledName.append("_");
} else {
String code = Integer.toHexString(c);
mangledName.append("_0");
switch (code.length()) {
case 1: mangledName.append("0");
case 2: mangledName.append("0");
case 3: mangledName.append("0");
default: mangledName.append(code);
}
}
}
return mangledName.toString();
}
}
| tarzanking/javacpp | src/main/java/com/googlecode/javacpp/Generator.java | Java | gpl-2.0 | 138,100 |
// I18N constants
// LANG: "pl", ENCODING: UTF-8
// translated: Krzysztof Kotowicz koto@webworkers.pl
{
"Align": "Wyrównanie",
"All four sides": "Wszystkie 4 strony",
"Background": "Tło",
"Baseline": "Linia bazowa",
"Border": "Ramka",
"Borders": "Ramki",
"Bottom": "Dół",
"Style [CSS]": "Styl [CSS]",
"CSS Style": "Styl CSS",
"Caption": "Podpis",
"Cell Properties": "Właściwości komórki",
"Center": "Środek",
"Char": "Znak",
"Collapsed borders": "Ramki skolapsowane",
"Color": "Kolor",
"Description": "Opis",
"FG Color": "Kolor czcionek",
"Float": "Opływanie",
"Frames": "Ramki zewn.",
"Frame and borders": "Obramowania",
"Height": "Wysokość",
"How many columns would you like to merge?": "Ile kolumn chcesz scalić?",
"How many rows would you like to merge?": "Ile wierszy chcesz scalić?",
"Image URL": "URL obrazka",
"Justify": "Wyjustuj",
"Layout": "Layout",
"Left": "Lewo",
"Margin": "Margines",
"Middle": "Środek",
"No rules": "Bez wewnętrzych",
"No sides": "Bez ramek",
"None": "Brak",
"Padding": "Wcięcia",
"Please click into some cell": "Kliknij w jakąś komórkę",
"Right": "Prawo",
"Row Properties": "Właściwości wiersza",
"Rules will appear between all rows and columns": "Linie będą widoczne pomiędzy kolumnami i wierszami",
"Rules will appear between columns only": "Linie będą widoczne tylko pomiędzy kolumnami",
"Rules will appear between rows only": "Linie będą widoczne tylko pomiędzy wierszami",
"Rules": "Linie wewn.",
"Spacing and padding": "Spacjowanie",
"Spacing": "Odstęp",
"Summary": "Podsumowanie",
"Delete cell": "Usuń komórkę",
"Insert cell after": "Wstaw komórkę po",
"Insert cell before": "Wstaw komórkę przed",
"Merge cells": "Scal komórki",
"Cell properties": "Właściwości komórki",
"Split cell": "Rozdziel komórkę",
"Delete column": "Usuń kolumnę",
"Insert column after": "Wstaw kolumnę po",
"Insert column before": "Wstaw kolumnę przed",
"Split column": "Rozdziel kolumnę",
"Delete row": "Usuń wiersz",
"Insert row before": "Wstaw wiersz przed",
"Insert row after": "Wstaw wiersz po",
"Row properties": "Właściwości wiersza",
"Split row": "Rozdziel wiersz",
"Table properties": "Właściwości tabeli",
"Table Properties": "Właściwości tabeli",
"Text align": "Wyr. w poziomie",
"The bottom side only": "Tylko dolna linia",
"The left-hand side only": "Tylko lewa linia",
"The right and left sides only": "Lewa i prawa linia",
"The right-hand side only": "Tylko prawa linia",
"The top and bottom sides only": "Górna i dolna linia",
"The top side only": "Tylko górna linia",
"Top": "Góra",
"Unset color": "Usuń kolor",
"Vertical align": "Wyr. w pionie",
"Width": "Szerokość",
"HTMLArea cowardly refuses to delete the last cell in row.": "Nie możesz skasować ostatniej komórki w wierszu.",
"HTMLArea cowardly refuses to delete the last column in table.": "Nie możesz skasować ostatniej kolumny w tabeli.",
"HTMLArea cowardly refuses to delete the last row in table.": "Nie możesz skasować ostatniego wiersza w tabeli.",
"percent": "%",
"pixels": "pikseli",
"OK": "OK",
"Cancel": "Anuluj"
};
| claunia/qemudb | xinha/plugins/TableOperations/lang/pl.js | JavaScript | gpl-2.0 | 3,246 |
<?php
/**
* This module contains the XRDS parsing code.
*
* PHP versions 4 and 5
*
* LICENSE: See the COPYING file included in this distribution.
*
* @package OpenID
* @author JanRain, Inc. <openid@janrain.com>
* @copyright 2005-2008 Janrain, Inc.
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache
*/
/**
* Require the XPath implementation.
*/
require_once 'Auth/Yadis/XML.php';
/**
* This match mode means a given service must match ALL filters passed
* to the Auth_Yadis_XRDS::services() call.
*/
define('SERVICES_YADIS_MATCH_ALL', 101);
/**
* This match mode means a given service must match ANY filters (at
* least one) passed to the Auth_Yadis_XRDS::services() call.
*/
define('SERVICES_YADIS_MATCH_ANY', 102);
/**
* The priority value used for service elements with no priority
* specified.
*/
define('SERVICES_YADIS_MAX_PRIORITY', pow(2, 30));
/**
* XRD XML namespace
*/
define('Auth_Yadis_XMLNS_XRD_2_0', 'xri://$xrd*($v*2.0)');
/**
* XRDS XML namespace
*/
define('Auth_Yadis_XMLNS_XRDS', 'xri://$xrds');
function Auth_Yadis_getNSMap()
{
return array('xrds' => Auth_Yadis_XMLNS_XRDS,
'xrd' => Auth_Yadis_XMLNS_XRD_2_0);
}
/**
* @access private
*/
function Auth_Yadis_array_scramble($arr)
{
$result = array();
while (count($arr)) {
$index = array_rand($arr, 1);
$result[] = $arr[$index];
unset($arr[$index]);
}
return $result;
}
/**
* This class represents a <Service> element in an XRDS document.
* Objects of this type are returned by
* Auth_Yadis_XRDS::services() and
* Auth_Yadis_Yadis::services(). Each object corresponds directly
* to a <Service> element in the XRDS and supplies a
* getElements($name) method which you should use to inspect the
* element's contents. See {@link Auth_Yadis_Yadis} for more
* information on the role this class plays in Yadis discovery.
*
* @package OpenID
*/
class Auth_Yadis_Service {
/**
* Creates an empty service object.
*/
function Auth_Yadis_Service()
{
$this->element = null;
$this->parser = null;
}
/**
* Return the URIs in the "Type" elements, if any, of this Service
* element.
*
* @return array $type_uris An array of Type URI strings.
*/
function getTypes()
{
$t = array();
foreach ($this->getElements('xrd:Type') as $elem) {
$c = $this->parser->content($elem);
if ($c) {
$t[] = $c;
}
}
return $t;
}
function matchTypes($type_uris)
{
$result = array();
foreach ($this->getTypes() as $typ) {
if (in_array($typ, $type_uris)) {
$result[] = $typ;
}
}
return $result;
}
/**
* Return the URIs in the "URI" elements, if any, of this Service
* element. The URIs are returned sorted in priority order.
*
* @return array $uris An array of URI strings.
*/
function getURIs()
{
$uris = array();
$last = array();
foreach ($this->getElements('xrd:URI') as $elem) {
$uri_string = $this->parser->content($elem);
$attrs = $this->parser->attributes($elem);
if ($attrs &&
array_key_exists('priority', $attrs)) {
$priority = intval($attrs['priority']);
if (!array_key_exists($priority, $uris)) {
$uris[$priority] = array();
}
$uris[$priority][] = $uri_string;
} else {
$last[] = $uri_string;
}
}
$keys = array_keys($uris);
sort($keys);
// Rebuild array of URIs.
$result = array();
foreach ($keys as $k) {
$new_uris = Auth_Yadis_array_scramble($uris[$k]);
$result = array_merge($result, $new_uris);
}
$result = array_merge($result,
Auth_Yadis_array_scramble($last));
return $result;
}
/**
* Returns the "priority" attribute value of this <Service>
* element, if the attribute is present. Returns null if not.
*
* @return mixed $result Null or integer, depending on whether
* this Service element has a 'priority' attribute.
*/
function getPriority()
{
$attributes = $this->parser->attributes($this->element);
if (array_key_exists('priority', $attributes)) {
return intval($attributes['priority']);
}
return null;
}
/**
* Used to get XML elements from this object's <Service> element.
*
* This is what you should use to get all custom information out
* of this element. This is used by service filter functions to
* determine whether a service element contains specific tags,
* etc. NOTE: this only considers elements which are direct
* children of the <Service> element for this object.
*
* @param string $name The name of the element to look for
* @return array $list An array of elements with the specified
* name which are direct children of the <Service> element. The
* nodes returned by this function can be passed to $this->parser
* methods (see {@link Auth_Yadis_XMLParser}).
*/
function getElements($name)
{
return $this->parser->evalXPath($name, $this->element);
}
}
/*
* Return the expiration date of this XRD element, or None if no
* expiration was specified.
*
* @param $default The value to use as the expiration if no expiration
* was specified in the XRD.
*/
function Auth_Yadis_getXRDExpiration($xrd_element, $default=null)
{
$expires_element = $xrd_element->$parser->evalXPath('/xrd:Expires');
if ($expires_element === null) {
return $default;
} else {
$expires_string = $expires_element->text;
// Will raise ValueError if the string is not the expected
// format
$t = strptime($expires_string, "%Y-%m-%dT%H:%M:%SZ");
if ($t === false) {
return false;
}
// [int $hour [, int $minute [, int $second [,
// int $month [, int $day [, int $year ]]]]]]
return mktime($t['tm_hour'], $t['tm_min'], $t['tm_sec'],
$t['tm_mon'], $t['tm_day'], $t['tm_year']);
}
}
/**
* This class performs parsing of XRDS documents.
*
* You should not instantiate this class directly; rather, call
* parseXRDS statically:
*
* <pre> $xrds = Auth_Yadis_XRDS::parseXRDS($xml_string);</pre>
*
* If the XRDS can be parsed and is valid, an instance of
* Auth_Yadis_XRDS will be returned. Otherwise, null will be
* returned. This class is used by the Auth_Yadis_Yadis::discover
* method.
*
* @package OpenID
*/
class Auth_Yadis_XRDS {
/**
* Instantiate a Auth_Yadis_XRDS object. Requires an XPath
* instance which has been used to parse a valid XRDS document.
*/
function Auth_Yadis_XRDS(&$xmlParser, &$xrdNodes)
{
$this->parser =& $xmlParser;
$this->xrdNode = $xrdNodes[count($xrdNodes) - 1];
$this->allXrdNodes =& $xrdNodes;
$this->serviceList = array();
$this->_parse();
}
/**
* Parse an XML string (XRDS document) and return either a
* Auth_Yadis_XRDS object or null, depending on whether the
* XRDS XML is valid.
*
* @param string $xml_string An XRDS XML string.
* @return mixed $xrds An instance of Auth_Yadis_XRDS or null,
* depending on the validity of $xml_string
*/
function &parseXRDS($xml_string, $extra_ns_map = null)
{
$_null = null;
if (!$xml_string) {
return $_null;
}
$parser = Auth_Yadis_getXMLParser();
$ns_map = Auth_Yadis_getNSMap();
if ($extra_ns_map && is_array($extra_ns_map)) {
$ns_map = array_merge($ns_map, $extra_ns_map);
}
if (!($parser && $parser->init($xml_string, $ns_map))) {
return $_null;
}
// Try to get root element.
$root = $parser->evalXPath('/xrds:XRDS[1]');
if (!$root) {
return $_null;
}
if (is_array($root)) {
$root = $root[0];
}
$attrs = $parser->attributes($root);
if (array_key_exists('xmlns:xrd', $attrs) &&
$attrs['xmlns:xrd'] != Auth_Yadis_XMLNS_XRDS) {
return $_null;
} else if (array_key_exists('xmlns', $attrs) &&
preg_match('/xri/', $attrs['xmlns']) &&
$attrs['xmlns'] != Auth_Yadis_XMLNS_XRD_2_0) {
return $_null;
}
// Get the last XRD node.
$xrd_nodes = $parser->evalXPath('/xrds:XRDS[1]/xrd:XRD');
if (!$xrd_nodes) {
return $_null;
}
$xrds = new Auth_Yadis_XRDS($parser, $xrd_nodes);
return $xrds;
}
/**
* @access private
*/
function _addService($priority, $service)
{
$priority = intval($priority);
if (!array_key_exists($priority, $this->serviceList)) {
$this->serviceList[$priority] = array();
}
$this->serviceList[$priority][] = $service;
}
/**
* Creates the service list using nodes from the XRDS XML
* document.
*
* @access private
*/
function _parse()
{
$this->serviceList = array();
$services = $this->parser->evalXPath('xrd:Service', $this->xrdNode);
foreach ($services as $node) {
$s = new Auth_Yadis_Service();
$s->element = $node;
$s->parser =& $this->parser;
$priority = $s->getPriority();
if ($priority === null) {
$priority = SERVICES_YADIS_MAX_PRIORITY;
}
$this->_addService($priority, $s);
}
}
/**
* Returns a list of service objects which correspond to <Service>
* elements in the XRDS XML document for this object.
*
* Optionally, an array of filter callbacks may be given to limit
* the list of returned service objects. Furthermore, the default
* mode is to return all service objects which match ANY of the
* specified filters, but $filter_mode may be
* SERVICES_YADIS_MATCH_ALL if you want to be sure that the
* returned services match all the given filters. See {@link
* Auth_Yadis_Yadis} for detailed usage information on filter
* functions.
*
* @param mixed $filters An array of callbacks to filter the
* returned services, or null if all services are to be returned.
* @param integer $filter_mode SERVICES_YADIS_MATCH_ALL or
* SERVICES_YADIS_MATCH_ANY, depending on whether the returned
* services should match ALL or ANY of the specified filters,
* respectively.
* @return mixed $services An array of {@link
* Auth_Yadis_Service} objects if $filter_mode is a valid
* mode; null if $filter_mode is an invalid mode (i.e., not
* SERVICES_YADIS_MATCH_ANY or SERVICES_YADIS_MATCH_ALL).
*/
function services($filters = null,
$filter_mode = SERVICES_YADIS_MATCH_ANY)
{
$pri_keys = array_keys($this->serviceList);
sort($pri_keys, SORT_NUMERIC);
// If no filters are specified, return the entire service
// list, ordered by priority.
if (!$filters ||
(!is_array($filters))) {
$result = array();
foreach ($pri_keys as $pri) {
$result = array_merge($result, $this->serviceList[$pri]);
}
return $result;
}
// If a bad filter mode is specified, return null.
if (!in_array($filter_mode, array(SERVICES_YADIS_MATCH_ANY,
SERVICES_YADIS_MATCH_ALL))) {
return null;
}
// Otherwise, use the callbacks in the filter list to
// determine which services are returned.
$filtered = array();
foreach ($pri_keys as $priority_value) {
$service_obj_list = $this->serviceList[$priority_value];
foreach ($service_obj_list as $service) {
$matches = 0;
foreach ($filters as $filter) {
if (call_user_func_array($filter, array($service))) {
$matches++;
if ($filter_mode == SERVICES_YADIS_MATCH_ANY) {
$pri = $service->getPriority();
if ($pri === null) {
$pri = SERVICES_YADIS_MAX_PRIORITY;
}
if (!array_key_exists($pri, $filtered)) {
$filtered[$pri] = array();
}
$filtered[$pri][] = $service;
break;
}
}
}
if (($filter_mode == SERVICES_YADIS_MATCH_ALL) &&
($matches == count($filters))) {
$pri = $service->getPriority();
if ($pri === null) {
$pri = SERVICES_YADIS_MAX_PRIORITY;
}
if (!array_key_exists($pri, $filtered)) {
$filtered[$pri] = array();
}
$filtered[$pri][] = $service;
}
}
}
$pri_keys = array_keys($filtered);
sort($pri_keys, SORT_NUMERIC);
$result = array();
foreach ($pri_keys as $pri) {
$result = array_merge($result, $filtered[$pri]);
}
return $result;
}
}
?> | IYEO/Sweettaste | tmp/install_5680f69da1732/install_5680f6ab093c2/assets/yahoo-yos-social/lib/OpenID/Auth/Yadis/XRDS.php | PHP | gpl-2.0 | 14,321 |
/*
* Copyright (c) 2015, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.graalvm.compiler.nodes;
import java.util.List;
import org.graalvm.compiler.graph.NodeClass;
import jdk.vm.ci.meta.Assumptions;
import jdk.vm.ci.meta.ResolvedJavaMethod;
/**
* A {@link StructuredGraph} encoded in a compact binary representation as a byte[] array. See
* {@link GraphEncoder} for a description of the encoding format. Use {@link GraphDecoder} for
* decoding.
*/
public class EncodedGraph {
private final byte[] encoding;
private final long startOffset;
private final Object[] objects;
private final NodeClass<?>[] types;
private final Assumptions assumptions;
private final List<ResolvedJavaMethod> inlinedMethods;
/**
* The "table of contents" of the encoded graph, i.e., the mapping from orderId numbers to the
* offset in the encoded byte[] array. Used as a cache during decoding.
*/
protected long[] nodeStartOffsets;
public EncodedGraph(byte[] encoding, long startOffset, Object[] objects, NodeClass<?>[] types, Assumptions assumptions, List<ResolvedJavaMethod> inlinedMethods) {
this.encoding = encoding;
this.startOffset = startOffset;
this.objects = objects;
this.types = types;
this.assumptions = assumptions;
this.inlinedMethods = inlinedMethods;
}
public byte[] getEncoding() {
return encoding;
}
public long getStartOffset() {
return startOffset;
}
public Object[] getObjects() {
return objects;
}
public NodeClass<?>[] getNodeClasses() {
return types;
}
public Assumptions getAssumptions() {
return assumptions;
}
public List<ResolvedJavaMethod> getInlinedMethods() {
return inlinedMethods;
}
}
| YouDiSN/OpenJDK-Research | jdk9/hotspot/src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.nodes/src/org/graalvm/compiler/nodes/EncodedGraph.java | Java | gpl-2.0 | 2,807 |
//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2009 FURUHASHI Sadayuki
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef MSGPACK_TYPE_NIL_HPP
#define MSGPACK_TYPE_NIL_HPP
#include "msgpack/versioning.hpp"
#include "msgpack/adaptor/adaptor_base.hpp"
namespace msgpack {
/// @cond
MSGPACK_API_VERSION_NAMESPACE(v1) {
/// @endcond
namespace type {
struct nil_t { };
#if !defined(MSGPACK_DISABLE_LEGACY_NIL)
typedef nil_t nil;
#endif // !defined(MSGPACK_DISABLE_LEGACY_NIL)
inline bool operator<(nil_t const& lhs, nil_t const& rhs) {
return &lhs < &rhs;
}
inline bool operator==(nil_t const& lhs, nil_t const& rhs) {
return &lhs == &rhs;
}
} // namespace type
namespace adaptor {
template <>
struct convert<type::nil_t> {
msgpack::object const& operator()(msgpack::object const& o, type::nil_t&) const {
if(o.type != msgpack::type::NIL) { throw msgpack::type_error(); }
return o;
}
};
template <>
struct pack<type::nil_t> {
template <typename Stream>
msgpack::packer<Stream>& operator()(msgpack::packer<Stream>& o, const type::nil_t&) const {
o.pack_nil();
return o;
}
};
template <>
struct object<type::nil_t> {
void operator()(msgpack::object& o, type::nil_t) const {
o.type = msgpack::type::NIL;
}
};
template <>
struct object_with_zone<type::nil_t> {
void operator()(msgpack::object::with_zone& o, type::nil_t v) const {
static_cast<msgpack::object&>(o) << v;
}
};
} // namespace adaptor
template <>
inline void msgpack::object::as<void>() const
{
msgpack::type::nil_t v;
convert(v);
}
/// @cond
} // MSGPACK_API_VERSION_NAMESPACE(v1)
/// @endcond
} // namespace msgpack
#endif // MSGPACK_TYPE_NIL_HPP
| scraperwiki/pdf2msgpack | msgpack-c/include/msgpack/adaptor/nil.hpp | C++ | gpl-2.0 | 1,885 |
/* FCE Ultra - NES/Famicom Emulator
*
* Copyright notice for this file:
* Copyright (C) 2002 Xodnizel
*
* 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 "types.h"
#include "file.h"
#include "utils/endian.h"
#include "netplay.h"
#include "fceu.h"
#include "state.h"
#include "cheat.h"
#include "input.h"
#include "driver.h"
#include "utils/memory.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
//#include <unistd.h> //mbg merge 7/17/06 removed
#include <zlib.h>
int FCEUnetplay=0;
static uint8 netjoy[4]; // Controller cache.
static int numlocal;
static int netdivisor;
static int netdcount;
//NetError should only be called after a FCEUD_*Data function returned 0, in the function
//that called FCEUD_*Data, to prevent it from being called twice.
static void NetError(void)
{
FCEU_DispMessage("Network error/connection lost!",0);
FCEUD_NetworkClose();
}
void FCEUI_NetplayStop(void)
{
if(FCEUnetplay)
{
FCEUnetplay = 0;
FCEU_FlushGameCheats(0,1); //Don't save netplay cheats.
FCEU_LoadGameCheats(0); //Reload our original cheats.
}
else puts("Check your code!");
}
int FCEUI_NetplayStart(int nlocal, int divisor)
{
FCEU_FlushGameCheats(0, 0); //Save our pre-netplay cheats.
FCEU_LoadGameCheats(0); // Load them again, for pre-multiplayer action.
FCEUnetplay = 1;
memset(netjoy,0,sizeof(netjoy));
numlocal = nlocal;
netdivisor = divisor;
netdcount = 0;
return(1);
}
int FCEUNET_SendCommand(uint8 cmd, uint32 len)
{
//mbg merge 7/17/06 changed to alloca
//uint8 buf[numlocal + 1 + 4];
uint8 *buf = (uint8*)alloca(numlocal+1+4);
buf[0] = 0xFF;
FCEU_en32lsb(&buf[numlocal], len);
buf[numlocal + 4] = cmd;
if(!FCEUD_SendData(buf,numlocal + 1 + 4))
{
NetError();
return(0);
}
return(1);
}
void FCEUI_NetplayText(uint8 *text)
{
uint32 len;
len = strlen((char*)text); //mbg merge 7/17/06 added cast
if(!FCEUNET_SendCommand(FCEUNPCMD_TEXT,len)) return;
if(!FCEUD_SendData(text,len))
NetError();
}
int FCEUNET_SendFile(uint8 cmd, char *fn)
{
uint32 len;
uLongf clen;
char *buf, *cbuf;
FILE *fp;
struct stat sb;
if(!(fp=FCEUD_UTF8fopen(fn,"rb"))) return(0);
fstat(fileno(fp),&sb);
len = sb.st_size;
buf = (char*)FCEU_dmalloc(len); //mbg merge 7/17/06 added cast
fread(buf, 1, len, fp);
fclose(fp);
cbuf = (char*)FCEU_dmalloc(4 + len + len / 1000 + 12); //mbg merge 7/17/06 added cast
FCEU_en32lsb((uint8*)cbuf, len); //mbg merge 7/17/06 added cast
compress2((uint8*)cbuf + 4, &clen, (uint8*)buf, len, 7); //mbg merge 7/17/06 added casts
free(buf);
//printf("Sending file: %s, %d, %d\n",fn,len,clen);
len = clen + 4;
if(!FCEUNET_SendCommand(cmd,len))
{
free(cbuf);
return(0);
}
if(!FCEUD_SendData(cbuf, len))
{
NetError();
free(cbuf);
return(0);
}
free(cbuf);
return(1);
}
static FILE *FetchFile(uint32 remlen)
{
uint32 clen = remlen;
char *cbuf;
uLongf len;
char *buf;
FILE *fp;
if(clen > 500000) // Sanity check
{
NetError();
return(0);
}
//printf("Receiving file: %d...\n",clen);
if((fp = tmpfile()))
{
cbuf = (char *)FCEU_dmalloc(clen); //mbg merge 7/17/06 added cast
if(!FCEUD_RecvData(cbuf, clen))
{
NetError();
fclose(fp);
free(cbuf);
return(0);
}
len = FCEU_de32lsb((uint8*)cbuf); //mbg merge 7/17/06 added cast
if(len > 500000) // Another sanity check
{
NetError();
fclose(fp);
free(cbuf);
return(0);
}
buf = (char *)FCEU_dmalloc(len); //mbg merge 7/17/06 added cast
uncompress((uint8*)buf, &len, (uint8*)cbuf + 4, clen - 4); //mbg merge 7/17/06 added casts
fwrite(buf, 1, len, fp);
free(buf);
fseek(fp, 0, SEEK_SET);
return(fp);
}
return(0);
}
void NetplayUpdate(uint8 *joyp)
{
static uint8 buf[5]; /* 4 play states, + command/extra byte */
static uint8 joypb[4];
memcpy(joypb,joyp,4);
/* This shouldn't happen, but just in case. 0xFF is used as a command escape elsewhere. */
if(joypb[0] == 0xFF)
joypb[0] = 0xF;
if(!netdcount)
if(!FCEUD_SendData(joypb,numlocal))
{
NetError();
return;
}
if(!netdcount)
{
do
{
if(!FCEUD_RecvData(buf,5))
{
NetError();
return;
}
switch(buf[4])
{
default: FCEU_DoSimpleCommand(buf[4]);break;
case FCEUNPCMD_TEXT:
{
uint8 *tbuf;
uint32 len = FCEU_de32lsb(buf);
if(len > 100000) // Insanity check!
{
NetError();
return;
}
tbuf = (uint8*)malloc(len + 1); //mbg merge 7/17/06 added cast
tbuf[len] = 0;
if(!FCEUD_RecvData(tbuf, len))
{
NetError();
free(tbuf);
return;
}
FCEUD_NetplayText(tbuf);
free(tbuf);
}
break;
case FCEUNPCMD_SAVESTATE:
{
//mbg todo netplay
//char *fn;
//FILE *fp;
////Send the cheats first, then the save state, since
////there might be a frame or two in between the two sendfile
////commands on the server side.
//fn = strdup(FCEU_MakeFName(FCEUMKF_CHEAT,0,0).c_str());
////why??????
////if(!
// FCEUNET_SendFile(FCEUNPCMD_LOADCHEATS,fn);
//// {
//// free(fn);
//// return;
//// }
//free(fn);
//if(!FCEUnetplay) return;
//fn = strdup(FCEU_MakeFName(FCEUMKF_NPTEMP,0,0).c_str());
//fp = fopen(fn, "wb");
//if(FCEUSS_SaveFP(fp,Z_BEST_COMPRESSION))
//{
// fclose(fp);
// if(!FCEUNET_SendFile(FCEUNPCMD_LOADSTATE, fn))
// {
// unlink(fn);
// free(fn);
// return;
// }
// unlink(fn);
// free(fn);
//}
//else
//{
// fclose(fp);
// FCEUD_PrintError("File error. (K)ill, (M)aim, (D)estroy? Now!");
// unlink(fn);
// free(fn);
// return;
//}
}
break;
case FCEUNPCMD_LOADCHEATS:
{
FILE *fp = FetchFile(FCEU_de32lsb(buf));
if(!fp) return;
FCEU_FlushGameCheats(0,1);
FCEU_LoadGameCheats(fp);
}
break;
//mbg 6/16/08 - netplay doesnt work right now anyway
/*case FCEUNPCMD_LOADSTATE:
{
FILE *fp = FetchFile(FCEU_de32lsb(buf));
if(!fp) return;
if(FCEUSS_LoadFP(fp,SSLOADPARAM_BACKUP))
{
fclose(fp);
FCEU_DispMessage("Remote state loaded.",0);
} else FCEUD_PrintError("File error. (K)ill, (M)aim, (D)estroy?");
}
break;*/
}
} while(buf[4]);
netdcount=(netdcount+1)%netdivisor;
memcpy(netjoy,buf,4);
*(uint32 *)joyp=*(uint32 *)netjoy;
}
}
| zear/fceu320-rzx50 | src/netplay.cpp | C++ | gpl-2.0 | 7,392 |
/*
* Copyright 2006-2015 The MZmine 2 Development Team
*
* This file is part of MZmine 2.
*
* MZmine 2 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.
*
* MZmine 2 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
* MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
package net.sf.mzmine.modules.peaklistmethods.peakpicking.deconvolution.savitzkygolay;
public final class SGDerivative {
/**
* This method returns the second smoothed derivative values of an array.
*
* @param double[] values
* @param boolean is first derivative
* @param int level of filter (1 - 12)
* @return double[] derivative of values
*/
public static double[] calculateDerivative(double[] values,
boolean firstDerivative, int levelOfFilter) {
double[] derivative = new double[values.length];
int M = 0;
for (int k = 0; k < derivative.length; k++) {
// Determine boundaries
if (k <= levelOfFilter)
M = k;
if (k + M > derivative.length - 1)
M = derivative.length - (k + 1);
// Perform derivative using Savitzky Golay coefficients
for (int i = -M; i <= M; i++) {
derivative[k] += values[k + i]
* getSGCoefficient(M, i, firstDerivative);
}
// if ((Math.abs(derivative[k])) > maxValueDerivative)
// maxValueDerivative = Math.abs(derivative[k]);
}
return derivative;
}
/**
* This method return the Savitzky-Golay 2nd smoothed derivative coefficient
* from an array
*
* @param M
* @param signedC
* @return
*/
private static Double getSGCoefficient(int M, int signedC,
boolean firstDerivate) {
int C = Math.abs(signedC), sign = 1;
if (firstDerivate) {
if (signedC < 0)
sign = -1;
return sign
* SGCoefficients.SGCoefficientsFirstDerivativeQuartic[M][C];
} else {
return SGCoefficients.SGCoefficientsSecondDerivative[M][C];
}
}
}
| DrewG/mzmine2 | src/main/java/net/sf/mzmine/modules/peaklistmethods/peakpicking/deconvolution/savitzkygolay/SGDerivative.java | Java | gpl-2.0 | 2,508 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Yuri A. Kropachev
* @version $Revision$
*/
package org.apache.harmony.security.provider.crypto;
/**
* This interface contains : <BR>
* - a set of constant values, H0-H4, defined in "SECURE HASH STANDARD", FIPS PUB 180-2 ;<BR>
* - implementation constant values to use in classes using SHA-1 algorithm. <BR>
*/
public interface SHA1_Data {
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H0 = 0x67452301;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H1 = 0xEFCDAB89;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H2 = 0x98BADCFE;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H3 = 0x10325476;
/**
* constant defined in "SECURE HASH STANDARD"
*/
static final int H4 = 0xC3D2E1F0;
/**
* offset in buffer to store number of bytes in 0-15 word frame
*/
static final int BYTES_OFFSET = 81;
/**
* offset in buffer to store current hash value
*/
static final int HASH_OFFSET = 82;
/**
* # of bytes in H0-H4 words; <BR>
* in this implementation # is set to 20 (in general # varies from 1 to 20)
*/
static final int DIGEST_LENGTH = 20;
}
| xdajog/samsung_sources_i927 | libcore/luni/src/main/java/org/apache/harmony/security/provider/crypto/SHA1_Data.java | Java | gpl-2.0 | 2,129 |
// license:BSD-3-Clause
// copyright-holders:Krzysztof Strzecha, Miodrag Milanovic
/***************************************************************************
Galaksija driver by Krzysztof Strzecha and Miodrag Milanovic
22/05/2008 Tape support added (Miodrag Milanovic)
21/05/2008 Galaksija plus initial support (Miodrag Milanovic)
20/05/2008 Added real video implementation (Miodrag Milanovic)
18/04/2005 Possibilty to disable ROM 2. 2k, 22k, 38k and 54k memory
configurations added.
13/03/2005 Memory mapping improved. Palette corrected. Supprort for newer
version of snapshots added. Lot of cleanups. Keyboard mapping
corrected.
19/09/2002 malloc() replaced by image_malloc().
15/09/2002 Snapshot loading fixed. Code cleanup.
31/01/2001 Snapshot loading corrected.
09/01/2001 Fast mode implemented (many thanks to Kevin Thacker).
07/01/2001 Keyboard corrected (still some keys unknown).
Horizontal screen positioning in video subsystem added.
05/01/2001 Keyboard implemented (some keys unknown).
03/01/2001 Snapshot loading added.
01/01/2001 Preliminary driver.
***************************************************************************/
#include "emu.h"
#include "cpu/z80/z80.h"
#include "sound/wave.h"
#include "includes/galaxy.h"
#include "imagedev/snapquik.h"
#include "imagedev/cassette.h"
#include "sound/ay8910.h"
#include "formats/gtp_cas.h"
#include "machine/ram.h"
#include "softlist.h"
static ADDRESS_MAP_START (galaxyp_io, AS_IO, 8, galaxy_state )
ADDRESS_MAP_GLOBAL_MASK(0x01)
ADDRESS_MAP_UNMAP_HIGH
AM_RANGE(0xbe, 0xbe) AM_DEVWRITE("ay8910", ay8910_device, address_w)
AM_RANGE(0xbf, 0xbf) AM_DEVWRITE("ay8910", ay8910_device, data_w)
ADDRESS_MAP_END
static ADDRESS_MAP_START (galaxy_mem, AS_PROGRAM, 8, galaxy_state )
AM_RANGE(0x0000, 0x0fff) AM_ROM
AM_RANGE(0x2000, 0x2037) AM_MIRROR(0x07c0) AM_READ(galaxy_keyboard_r )
AM_RANGE(0x2038, 0x203f) AM_MIRROR(0x07c0) AM_WRITE(galaxy_latch_w )
ADDRESS_MAP_END
static ADDRESS_MAP_START (galaxyp_mem, AS_PROGRAM, 8, galaxy_state )
AM_RANGE(0x0000, 0x0fff) AM_ROM // ROM A
AM_RANGE(0x1000, 0x1fff) AM_ROM // ROM B
AM_RANGE(0x2000, 0x2037) AM_MIRROR(0x07c0) AM_READ(galaxy_keyboard_r )
AM_RANGE(0x2038, 0x203f) AM_MIRROR(0x07c0) AM_WRITE(galaxy_latch_w )
AM_RANGE(0xe000, 0xefff) AM_ROM // ROM C
AM_RANGE(0xf000, 0xffff) AM_ROM // ROM D
ADDRESS_MAP_END
/* 2008-05 FP:
Small note about natural keyboard support. Currently:
- "List" is mapped to 'ESC'
- "Break" is mapped to 'F1'
- "Repeat" is mapped to 'F2' */
static INPUT_PORTS_START (galaxy_common)
PORT_START("LINE0")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_UNUSED)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_START("LINE1")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_START("LINE2")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_Q) PORT_CHAR('Q')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_R) PORT_CHAR('R')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_S) PORT_CHAR('S')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_T) PORT_CHAR('T')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_U) PORT_CHAR('U')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_V) PORT_CHAR('V')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_W) PORT_CHAR('W')
PORT_START("LINE3")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_Y) PORT_CHAR('Y')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_Z) PORT_CHAR('Z')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP))
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ')
PORT_START("LINE4")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_CHAR('_')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('"')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('&')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('\'')
PORT_START("LINE5")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('(')
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR(')')
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_COLON) PORT_CHAR(';') PORT_CHAR('+')
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_QUOTE) PORT_CHAR(':') PORT_CHAR('*')
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('<')
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('=') PORT_CHAR('-')
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR('>')
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('?')
PORT_START("LINE6")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13)
PORT_BIT(0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Break") PORT_CODE(KEYCODE_PAUSE) PORT_CHAR(UCHAR_MAMEKEY(F1))
PORT_BIT(0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Repeat") PORT_CODE(KEYCODE_LALT) PORT_CHAR(UCHAR_MAMEKEY(F2))
PORT_BIT(0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Delete") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
PORT_BIT(0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("List") PORT_CODE(KEYCODE_ESC) PORT_CHAR(UCHAR_MAMEKEY(ESC))
PORT_BIT(0x20, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(KEYCODE_LSHIFT) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1)
PORT_BIT(0x40, IP_ACTIVE_HIGH, IPT_UNUSED)
PORT_BIT(0x80, IP_ACTIVE_HIGH, IPT_UNUSED)
INPUT_PORTS_END
static INPUT_PORTS_START( galaxy )
PORT_INCLUDE( galaxy_common )
PORT_START("ROM2")
PORT_CONFNAME(0x01, 0x01, "ROM 2")
PORT_CONFSETTING(0x01, "Installed")
PORT_CONFSETTING(0x00, "Not installed")
INPUT_PORTS_END
static INPUT_PORTS_START( galaxyp )
PORT_INCLUDE( galaxy_common )
INPUT_PORTS_END
#define XTAL 6144000
/* F4 Character Displayer */
static const gfx_layout galaxy_charlayout =
{
8, 16, /* 8 x 16 characters */
128, /* 128 characters */
1, /* 1 bits per pixel */
{ 0 }, /* no bitplanes */
/* x offsets */
{ 7, 6, 5, 4, 3, 2, 1, 0 },
/* y offsets */
{ 0, 1*128*8, 2*128*8, 3*128*8, 4*128*8, 5*128*8, 6*128*8, 7*128*8, 8*128*8, 9*128*8, 10*128*8, 11*128*8, 12*128*8, 13*128*8, 14*128*8, 15*128*8 },
8 /* every char takes 1 x 16 bytes */
};
static GFXDECODE_START( galaxy )
GFXDECODE_ENTRY( "gfx1", 0x0000, galaxy_charlayout, 0, 1 )
GFXDECODE_END
static MACHINE_CONFIG_START( galaxy, galaxy_state )
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", Z80, XTAL / 2)
MCFG_CPU_PROGRAM_MAP(galaxy_mem)
MCFG_CPU_VBLANK_INT_DRIVER("screen", galaxy_state, galaxy_interrupt)
MCFG_CPU_IRQ_ACKNOWLEDGE_DRIVER(galaxy_state,galaxy_irq_callback)
MCFG_SCREEN_ADD("screen", RASTER)
MCFG_SCREEN_REFRESH_RATE(50)
MCFG_SCREEN_PALETTE("palette")
MCFG_MACHINE_RESET_OVERRIDE(galaxy_state, galaxy )
/* video hardware */
MCFG_SCREEN_SIZE(384, 212)
MCFG_SCREEN_VISIBLE_AREA(0, 384-1, 0, 208-1)
MCFG_SCREEN_UPDATE_DRIVER(galaxy_state, screen_update_galaxy)
MCFG_GFXDECODE_ADD("gfxdecode", "palette", galaxy)
MCFG_PALETTE_ADD_MONOCHROME("palette")
/* snapshot */
MCFG_SNAPSHOT_ADD("snapshot", galaxy_state, galaxy, "gal", 0)
MCFG_SPEAKER_STANDARD_MONO("mono")
MCFG_SOUND_WAVE_ADD(WAVE_TAG, "cassette")
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25)
MCFG_CASSETTE_ADD( "cassette" )
MCFG_CASSETTE_FORMATS(gtp_cassette_formats)
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_SPEAKER_ENABLED | CASSETTE_MOTOR_ENABLED)
MCFG_CASSETTE_INTERFACE("galaxy_cass")
MCFG_SOFTWARE_LIST_ADD("cass_list","galaxy")
/* internal ram */
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("6K")
MCFG_RAM_EXTRA_OPTIONS("2K,22K,38K,54K")
MACHINE_CONFIG_END
static MACHINE_CONFIG_START( galaxyp, galaxy_state )
/* basic machine hardware */
MCFG_CPU_ADD("maincpu", Z80, XTAL / 2)
MCFG_CPU_PROGRAM_MAP(galaxyp_mem)
MCFG_CPU_IO_MAP(galaxyp_io)
MCFG_CPU_VBLANK_INT_DRIVER("screen", galaxy_state, galaxy_interrupt)
MCFG_CPU_IRQ_ACKNOWLEDGE_DRIVER(galaxy_state,galaxy_irq_callback)
MCFG_SCREEN_ADD("screen", RASTER)
MCFG_SCREEN_REFRESH_RATE(50)
MCFG_SCREEN_PALETTE("palette")
MCFG_MACHINE_RESET_OVERRIDE(galaxy_state, galaxyp )
/* video hardware */
MCFG_SCREEN_SIZE(384, 208)
MCFG_SCREEN_VISIBLE_AREA(0, 384-1, 0, 208-1)
MCFG_SCREEN_UPDATE_DRIVER(galaxy_state, screen_update_galaxy)
MCFG_PALETTE_ADD_MONOCHROME("palette")
/* snapshot */
MCFG_SNAPSHOT_ADD("snapshot", galaxy_state, galaxy, "gal", 0)
/* sound hardware */
MCFG_SPEAKER_STANDARD_MONO("mono")
MCFG_SOUND_ADD("ay8910", AY8910, XTAL/4)
MCFG_SOUND_WAVE_ADD(WAVE_TAG, "cassette")
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25)
MCFG_CASSETTE_ADD( "cassette" )
MCFG_CASSETTE_FORMATS(gtp_cassette_formats)
MCFG_CASSETTE_DEFAULT_STATE(CASSETTE_STOPPED | CASSETTE_SPEAKER_ENABLED | CASSETTE_MOTOR_ENABLED)
MCFG_CASSETTE_INTERFACE("galaxy_cass")
MCFG_SOFTWARE_LIST_ADD("cass_list","galaxy")
/* internal ram */
MCFG_RAM_ADD(RAM_TAG)
MCFG_RAM_DEFAULT_SIZE("38K")
MACHINE_CONFIG_END
ROM_START (galaxy)
ROM_REGION (0x10000, "maincpu", ROMREGION_ERASEFF)
ROM_LOAD ("galrom1.bin", 0x0000, 0x1000, CRC(dc970a32) SHA1(dfc92163654a756b70f5a446daf49d7534f4c739))
ROM_LOAD_OPTIONAL ("galrom2.bin", 0x1000, 0x1000, CRC(5dc5a100) SHA1(5d5ab4313a2d0effe7572bb129193b64cab002c1))
ROM_REGION(0x0800, "gfx1",0)
ROM_LOAD ("galchr.bin", 0x0000, 0x0800, CRC(5c3b5bb5) SHA1(19429a61dc5e55ddec3242a8f695e06dd7961f88))
ROM_END
ROM_START (galaxyp)
ROM_REGION (0x10000, "maincpu", ROMREGION_ERASEFF)
ROM_LOAD ("galrom1.bin", 0x0000, 0x1000, CRC(dc970a32) SHA1(dfc92163654a756b70f5a446daf49d7534f4c739))
ROM_LOAD ("galrom2.bin", 0x1000, 0x1000, CRC(5dc5a100) SHA1(5d5ab4313a2d0effe7572bb129193b64cab002c1))
ROM_LOAD ("galplus.bin", 0xe000, 0x1000, CRC(d4cfab14) SHA1(b507b9026844eeb757547679907394aa42055eee))
ROM_REGION(0x0800, "gfx1",0)
ROM_LOAD ("galchr.bin", 0x0000, 0x0800, CRC(5c3b5bb5) SHA1(19429a61dc5e55ddec3242a8f695e06dd7961f88))
ROM_END
/* YEAR NAME PARENT COMPAT MACHINE INPUT INIT COMPANY FULLNAME */
COMP(1983, galaxy, 0, 0, galaxy, galaxy, galaxy_state, galaxy, "Voja Antonic / Elektronika inzenjering", "Galaksija", 0)
COMP(1985, galaxyp, galaxy, 0, galaxyp,galaxyp, galaxy_state,galaxyp,"Nenad Dunjic", "Galaksija plus", 0)
| RJRetro/mame | src/mame/drivers/galaxy.cpp | C++ | gpl-2.0 | 12,956 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "lastexpress/entities/pascale.h"
#include "lastexpress/game/entities.h"
#include "lastexpress/game/logic.h"
#include "lastexpress/game/object.h"
#include "lastexpress/game/savepoint.h"
#include "lastexpress/game/scenes.h"
#include "lastexpress/game/state.h"
#include "lastexpress/sound/queue.h"
#include "lastexpress/lastexpress.h"
namespace LastExpress {
Pascale::Pascale(LastExpressEngine *engine) : Entity(engine, kEntityPascale) {
ADD_CALLBACK_FUNCTION(Pascale, draw);
ADD_CALLBACK_FUNCTION(Pascale, callbackActionRestaurantOrSalon);
ADD_CALLBACK_FUNCTION(Pascale, callbackActionOnDirection);
ADD_CALLBACK_FUNCTION(Pascale, updateFromTime);
ADD_CALLBACK_FUNCTION(Pascale, updatePosition);
ADD_CALLBACK_FUNCTION(Pascale, playSound);
ADD_CALLBACK_FUNCTION(Pascale, draw2);
ADD_CALLBACK_FUNCTION(Pascale, welcomeSophieAndRebecca);
ADD_CALLBACK_FUNCTION(Pascale, sitSophieAndRebecca);
ADD_CALLBACK_FUNCTION(Pascale, welcomeCath);
ADD_CALLBACK_FUNCTION(Pascale, function11);
ADD_CALLBACK_FUNCTION(Pascale, chapter1);
ADD_CALLBACK_FUNCTION(Pascale, getMessageFromAugustToTyler);
ADD_CALLBACK_FUNCTION(Pascale, sitAnna);
ADD_CALLBACK_FUNCTION(Pascale, welcomeAnna);
ADD_CALLBACK_FUNCTION(Pascale, serveTatianaVassili);
ADD_CALLBACK_FUNCTION(Pascale, chapter1Handler);
ADD_CALLBACK_FUNCTION(Pascale, function18);
ADD_CALLBACK_FUNCTION(Pascale, function19);
ADD_CALLBACK_FUNCTION(Pascale, chapter2);
ADD_CALLBACK_FUNCTION(Pascale, chapter3);
ADD_CALLBACK_FUNCTION(Pascale, chapter3Handler);
ADD_CALLBACK_FUNCTION(Pascale, function23);
ADD_CALLBACK_FUNCTION(Pascale, welcomeAbbot);
ADD_CALLBACK_FUNCTION(Pascale, chapter4);
ADD_CALLBACK_FUNCTION(Pascale, chapter4Handler);
ADD_CALLBACK_FUNCTION(Pascale, function27);
ADD_CALLBACK_FUNCTION(Pascale, messageFromAnna);
ADD_CALLBACK_FUNCTION(Pascale, function29);
ADD_CALLBACK_FUNCTION(Pascale, function30);
ADD_CALLBACK_FUNCTION(Pascale, chapter5);
ADD_CALLBACK_FUNCTION(Pascale, chapter5Handler);
ADD_CALLBACK_FUNCTION(Pascale, function33);
ADD_NULL_FUNCTION();
}
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION_S(1, Pascale, draw)
Entity::draw(savepoint, true);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(2, Pascale, callbackActionRestaurantOrSalon)
Entity::callbackActionRestaurantOrSalon(savepoint);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(3, Pascale, callbackActionOnDirection)
if (savepoint.action == kActionExcuseMeCath) {
if (!params->param1) {
getSound()->excuseMe(kEntityPascale);
params->param1 = 1;
}
return;
}
Entity::callbackActionOnDirection(savepoint);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION_I(4, Pascale, updateFromTime, uint32)
Entity::updateFromTime(savepoint);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION_NOSETUP(5, Pascale, updatePosition)
Entity::updatePosition(savepoint, true);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION_S(6, Pascale, playSound)
Entity::playSound(savepoint);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION_NOSETUP(7, Pascale, draw2)
Entity::draw2(savepoint);
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(8, Pascale, welcomeSophieAndRebecca)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_850;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("901");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
switch (getProgress().chapter) {
default:
break;
case kChapter1:
getSound()->playSound(kEntityPascale, "REB1198", kFlagInvalid, 30);
break;
case kChapter3:
getSound()->playSound(kEntityPascale, "REB3001", kFlagInvalid, 30);
break;
case kChapter4:
getSound()->playSound(kEntityPascale, "REB4001", kFlagInvalid, 30);
break;
}
setCallback(2);
setup_sitSophieAndRebecca();
break;
case 2:
getSavePoints()->push(kEntityPascale, kEntityRebecca, kAction157370960);
setCallback(3);
setup_draw("905");
break;
case 3:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(0, 4) = 0;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(9, Pascale, sitSophieAndRebecca)
switch (savepoint.action) {
default:
break;
case kActionExitCompartment:
callbackAction();
break;
case kActionDefault:
getEntities()->drawSequenceLeft(kEntityPascale, "012C1");
getEntities()->drawSequenceLeft(kEntityRebecca, "012C2");
getEntities()->drawSequenceLeft(kEntityTables3, "012C3");
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(10, Pascale, welcomeCath)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (params->param1 && !getSoundQueue()->isBuffered(kEntityPascale))
getEntities()->updatePositionExit(kEntityPascale, kCarRestaurant, 64);
break;
case kActionExitCompartment:
if (!params->param2) {
params->param2 = 1;
getSound()->playSound(kEntityPascale, "HED1001A");
getSound()->playSound(kEntityPlayer, "LIB004");
getScenes()->loadSceneFromPosition(kCarRestaurant, 69);
}
callbackAction();
break;
case kAction4:
if (!params->param1) {
params->param1 = 1;
getSound()->playSound(kEntityPascale, "HED1001");
}
break;
case kActionDefault:
getEntities()->updatePositionEnter(kEntityPascale, kCarRestaurant, 64);
getEntities()->drawSequenceRight(kEntityPascale, "035A");
break;
case kActionDrawScene:
if (params->param1 && getEntities()->isPlayerPosition(kCarRestaurant, 64)) {
getSound()->playSound(kEntityPascale, "HED1001A");
getSound()->playSound(kEntityPlayer, "LIB004");
getScenes()->loadSceneFromPosition(kCarRestaurant, 69);
callbackAction();
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(11, Pascale, function11)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
getSavePoints()->push(kEntityPascale, kEntityAugust, kAction168046720);
getSavePoints()->push(kEntityPascale, kEntityAnna, kAction168046720);
getSavePoints()->push(kEntityPascale, kEntityAlexei, kAction168046720);
getEntities()->updatePositionEnter(kEntityPascale, kCarRestaurant, 55);
setCallback(1);
setup_welcomeCath();
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getSavePoints()->push(kEntityPascale, kEntityAugust, kAction168627977);
getSavePoints()->push(kEntityPascale, kEntityAnna, kAction168627977);
getSavePoints()->push(kEntityPascale, kEntityAlexei, kAction168627977);
getEntities()->updatePositionExit(kEntityPascale, kCarRestaurant, 55);
setCallback(2);
setup_draw("905");
break;
case 2:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(12, Pascale, chapter1)
switch (savepoint.action) {
default:
break;
case kActionNone:
setup_chapter1Handler();
break;
case kActionDefault:
getSavePoints()->addData(kEntityPascale, kAction239072064, 0);
getSavePoints()->addData(kEntityPascale, kAction257489762, 2);
getSavePoints()->addData(kEntityPascale, kAction207769280, 6);
getSavePoints()->addData(kEntityPascale, kAction101824388, 7);
getSavePoints()->addData(kEntityPascale, kAction136059947, 8);
getSavePoints()->addData(kEntityPascale, kAction223262556, 1);
getSavePoints()->addData(kEntityPascale, kAction269479296, 3);
getSavePoints()->addData(kEntityPascale, kAction352703104, 4);
getSavePoints()->addData(kEntityPascale, kAction352768896, 5);
getSavePoints()->addData(kEntityPascale, kAction191604416, 10);
getSavePoints()->addData(kEntityPascale, kAction190605184, 11);
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
getData()->car = kCarRestaurant;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(13, Pascale, getMessageFromAugustToTyler)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("902");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
if (!ENTITY_PARAM(1, 3)) {
getEntities()->drawSequenceLeft(kEntityPascale, "010E");
getEntities()->drawSequenceLeft(kEntityAugust, "BLANK");
setCallback(2);
setup_playSound("AUG1001");
break;
}
setCallback(3);
setup_draw("905");
break;
case 2:
getEntities()->drawSequenceLeft(kEntityPascale, "010B");
setCallback(3);
setup_draw("905");
break;
case 3:
getData()->entityPosition = kPosition_5900;
getEntities()->clearSequences(kEntityPascale);
getSavePoints()->push(kEntityPascale, kEntityVerges, kActionDeliverMessageToTyler);
ENTITY_PARAM(0, 1) = 0;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(14, Pascale, sitAnna)
switch (savepoint.action) {
default:
break;
case kActionExitCompartment:
getEntities()->updatePositionExit(kEntityPascale, kCarRestaurant, 62);
callbackAction();
break;
case kActionDefault:
getEntities()->drawSequenceRight(kEntityTables0, "001C3");
getEntities()->drawSequenceRight(kEntityAnna, "001C2");
getEntities()->drawSequenceRight(kEntityPascale, "001C1");
getEntities()->updatePositionEnter(kEntityPascale, kCarRestaurant, 62);
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(15, Pascale, welcomeAnna)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("901");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getSound()->playSound(kEntityPascale, "ANN1047");
setCallback(2);
setup_sitAnna();
break;
case 2:
getSavePoints()->push(kEntityPascale, kEntityAnna, kAction157370960);
setCallback(3);
setup_draw("904");
break;
case 3:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(0, 2) = 0;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(16, Pascale, serveTatianaVassili)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("903");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getSavePoints()->push(kEntityPascale, kEntityTatiana, kAction122358304);
getEntities()->drawSequenceLeft(kEntityPascale, "014B");
getEntities()->updatePositionEnter(kEntityPascale, kCarRestaurant, 67);
if (getSoundQueue()->isBuffered("TAT1069A"))
getSoundQueue()->processEntry("TAT1069A");
else if (getSoundQueue()->isBuffered("TAT1069B"))
getSoundQueue()->processEntry("TAT1069B");
setCallback(2);
setup_playSound("TAT1066");
break;
case 2:
getEntities()->updatePositionExit(kEntityPascale, kCarRestaurant, 67);
getSavePoints()->push(kEntityPascale, kEntityTatiana, kAction122288808);
setCallback(3);
setup_draw("906");
break;
case 3:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(0, 3) = 0;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(17, Pascale, chapter1Handler)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (!params->param2) {
if (getEntities()->isPlayerPosition(kCarRestaurant, 69)
|| getEntities()->isPlayerPosition(kCarRestaurant, 70)
|| getEntities()->isPlayerPosition(kCarRestaurant, 71))
params->param2 = 1;
if (!params->param2 && getEntities()->isPlayerPosition(kCarRestaurant, 61))
params->param1 = 1;
}
if (!getEntities()->isInKitchen(kEntityPascale))
break;
if (ENTITY_PARAM(0, 5) && ENTITY_PARAM(0, 6)) {
setup_function18();
break;
}
if (!getEntities()->isSomebodyInsideRestaurantOrSalon())
goto label_callback3;
if (params->param1 && !params->param2 && getEntities()->isPlayerPosition(kCarRestaurant, 61)) {
setCallback(1);
setup_function11();
break;
}
label_callback1:
if (ENTITY_PARAM(0, 1) && !ENTITY_PARAM(1, 3)) {
setCallback(2);
setup_getMessageFromAugustToTyler();
break;
}
label_callback2:
if (ENTITY_PARAM(0, 3)) {
setCallback(3);
setup_serveTatianaVassili();
break;
}
label_callback3:
if (ENTITY_PARAM(0, 2)) {
setCallback(4);
setup_welcomeAnna();
break;
}
label_callback4:
if (ENTITY_PARAM(0, 4)) {
setCallback(5);
setup_welcomeSophieAndRebecca();
}
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
params->param1 = 0;
params->param2 = 1;
goto label_callback1;
case 2:
goto label_callback2;
case 3:
goto label_callback3;
case 4:
goto label_callback4;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(18, Pascale, function18)
if (savepoint.action != kActionNone)
return;
if (getState()->time > kTime1242000 && !params->param1) {
params->param1 = 1;
getSavePoints()->push(kEntityPascale, kEntityServers0, kAction101632192);
getSavePoints()->push(kEntityPascale, kEntityServers1, kAction101632192);
getSavePoints()->push(kEntityPascale, kEntityCooks, kAction101632192);
getSavePoints()->push(kEntityPascale, kEntityVerges, kAction101632192);
setup_function19();
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(19, Pascale, function19)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (!params->param1 && getEntityData(kEntityPlayer)->entityPosition < kPosition_3650) {
getObjects()->update(kObject65, kEntityPlayer, kObjectLocation1, kCursorHandKnock, kCursorHand);
getSavePoints()->push(kEntityPascale, kEntityTables0, kActionDrawTablesWithChairs, "001P");
getSavePoints()->push(kEntityPascale, kEntityTables1, kActionDrawTablesWithChairs, "005J");
getSavePoints()->push(kEntityPascale, kEntityTables2, kActionDrawTablesWithChairs, "009G");
getSavePoints()->push(kEntityPascale, kEntityTables3, kActionDrawTablesWithChairs, "010M");
getSavePoints()->push(kEntityPascale, kEntityTables4, kActionDrawTablesWithChairs, "014F");
getSavePoints()->push(kEntityPascale, kEntityTables5, kActionDrawTablesWithChairs, "024D");
params->param1 = 1;
}
break;
case kActionDefault:
getData()->car = kCarRestaurant;
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
getEntities()->clearSequences(kEntityPascale);
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(20, Pascale, chapter2)
if (savepoint.action == kActionDefault) {
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
getData()->car = kCarRestaurant;
getData()->clothes = kClothes1;
getData()->inventoryItem = kItemNone;
getObjects()->update(kObject65, kEntityPlayer, kObjectLocationNone, kCursorNormal, kCursorForward);
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(21, Pascale, chapter3)
switch (savepoint.action) {
default:
break;
case kActionNone:
setup_chapter3Handler();
break;
case kActionDefault:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
getData()->car = kCarRestaurant;
getData()->inventoryItem = kItemNone;
ENTITY_PARAM(0, 4) = 0;
ENTITY_PARAM(0, 7) = 0;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(22, Pascale, chapter3Handler)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (!getEntities()->isInKitchen(kEntityPascale))
break;
if (ENTITY_PARAM(0, 7)) {
setCallback(1);
setup_function23();
break;
}
label_callback:
if (ENTITY_PARAM(0, 4)) {
setCallback(2);
setup_welcomeSophieAndRebecca();
}
break;
case kActionCallback:
if (getCallback() == 1)
goto label_callback;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(23, Pascale, function23)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
getEntities()->updatePositionEnter(kEntityPascale, kCarRestaurant, 67);
setCallback(1);
setup_welcomeAbbot();
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getEntities()->updatePositionExit(kEntityPascale, kCarRestaurant, 67);
getSavePoints()->push(kEntityPascale, kEntityAbbot, kAction122288808);
setCallback(2);
setup_draw("906");
break;
case 2:
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(0, 7) = 0;
getEntities()->clearSequences(kEntityPascale);
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(24, Pascale, welcomeAbbot)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (!params->param1) {
getSound()->playSound(kEntityPascale, "ABB3015A");
params->param1 = 1;
}
break;
case kActionExitCompartment:
callbackAction();
break;
case kAction10:
getSavePoints()->push(kEntityPascale, kEntityTables4, kAction136455232);
break;
case kActionDefault:
getSound()->playSound(kEntityPascale, "ABB3015", kFlagInvalid, 105);
getEntities()->drawSequenceRight(kEntityPascale, "029A1");
getEntities()->drawSequenceRight(kEntityAbbot, "029A2");
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(25, Pascale, chapter4)
switch (savepoint.action) {
default:
break;
case kActionNone:
setup_chapter4Handler();
break;
case kActionDefault:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
getData()->car = kCarRestaurant;
getData()->inventoryItem = kItemNone;
ENTITY_PARAM(0, 4) = 0;
ENTITY_PARAM(0, 8) = 0;
ENTITY_PARAM(1, 1) = 0;
ENTITY_PARAM(1, 2) = 0;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(26, Pascale, chapter4Handler)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (getState()->time > kTime2511000 && !params->param4) {
params->param2 = 1;
params->param4 = 1;
}
if (!getEntities()->isInKitchen(kEntityPascale))
break;
if (getEntities()->isSomebodyInsideRestaurantOrSalon()) {
if (ENTITY_PARAM(0, 8)) {
setCallback(1);
setup_function27();
break;
}
label_callback1:
if (ENTITY_PARAM(1, 2) && ENTITY_PARAM(1, 4)) {
if (!params->param3)
params->param3 = (uint)(getState()->time + 9000);
if (params->param5 != kTimeInvalid) {
if (params->param3 < getState()->time) {
params->param5 = kTimeInvalid;
setCallback(2);
setup_messageFromAnna();
break;
}
if (!getEntities()->isInRestaurant(kEntityPlayer) || !params->param5)
params->param5 = (uint)getState()->time;
if (params->param5 < getState()->time) {
params->param5 = kTimeInvalid;
setCallback(2);
setup_messageFromAnna();
break;
}
}
}
label_callback2:
if (params->param1 && !params->param2 && getEntities()->isPlayerPosition(kCarRestaurant, 61)) {
setCallback(3);
setup_function11();
break;
}
}
label_callback3:
if (ENTITY_PARAM(0, 4)) {
setCallback(4);
setup_welcomeSophieAndRebecca();
}
break;
case kActionDefault:
if (getEntities()->isPlayerPosition(kCarRestaurant, 69)
|| getEntities()->isPlayerPosition(kCarRestaurant, 70)
|| getEntities()->isPlayerPosition(kCarRestaurant, 71))
params->param2 = 1;
break;
case kActionDrawScene:
if (!params->param2) {
if (getEntities()->isPlayerPosition(kCarRestaurant, 69)
|| getEntities()->isPlayerPosition(kCarRestaurant, 70)
|| getEntities()->isPlayerPosition(kCarRestaurant, 71))
params->param2 = 1;
if (!params->param2 && getEntities()->isPlayerPosition(kCarRestaurant, 61))
params->param1 = 1;
}
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
goto label_callback1;
case 2:
goto label_callback2;
case 3:
params->param1 = 0;
params->param2 = 1;
goto label_callback3;
}
break;
case kAction201431954:
ENTITY_PARAM(0, 4) = 0;
ENTITY_PARAM(0, 8) = 0;
getSavePoints()->push(kEntityPascale, kEntityTables0, kActionDrawTablesWithChairs, "001P");
getSavePoints()->push(kEntityPascale, kEntityTables1, kActionDrawTablesWithChairs, "005J");
getSavePoints()->push(kEntityPascale, kEntityTables2, kActionDrawTablesWithChairs, "009G");
getSavePoints()->push(kEntityPascale, kEntityTables3, kActionDrawTablesWithChairs, "010M");
getSavePoints()->push(kEntityPascale, kEntityTables4, kActionDrawTablesWithChairs, "014F");
getSavePoints()->push(kEntityPascale, kEntityTables5, kActionDrawTablesWithChairs, "024D");
getData()->entityPosition = kPosition_5900;
getData()->location = kLocationOutsideCompartment;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(27, Pascale, function27)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (ENTITY_PARAM(1, 1)) {
setCallback(2);
setup_updateFromTime(450);
}
break;
case kActionDefault:
setCallback(1);
setup_function29();
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getEntities()->clearSequences(kEntityPascale);
break;
case 2:
getSavePoints()->push(kEntityPascale, kEntityCoudert, kAction123712592);
setCallback(3);
setup_callbackActionRestaurantOrSalon();
break;
case 3:
setCallback(4);
setup_function30();
break;
case 4:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(0, 8) = 0;
ENTITY_PARAM(1, 1) = 0;
ENTITY_PARAM(1, 2) = 1;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(28, Pascale, messageFromAnna)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_5800;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("902");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getSavePoints()->push(kEntityPascale, kEntityAugust, kAction122358304);
getEntities()->drawSequenceLeft(kEntityPascale, "010E2");
setCallback(2);
setup_playSound("Aug4001");
break;
case 2:
getSavePoints()->push(kEntityPascale, kEntityAugust, kAction123793792);
setCallback(3);
setup_draw("905");
break;
case 3:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_5900;
ENTITY_PARAM(1, 2) = 0;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(29, Pascale, function29)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_1540;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("817DD");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getEntities()->drawSequenceRight(kEntityPascale, "817DS");
if (getEntities()->isInRestaurant(kEntityPlayer))
getEntities()->updateFrame(kEntityPascale);
setCallback(2);
setup_callbackActionOnDirection();
break;
case 2:
getData()->entityPosition = kPosition_850;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(30, Pascale, function30)
switch (savepoint.action) {
default:
break;
case kActionDefault:
getData()->entityPosition = kPosition_9270;
getData()->location = kLocationOutsideCompartment;
setCallback(1);
setup_draw("817US");
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getEntities()->drawSequenceRight(kEntityPascale, "817UD");
if (getEntities()->isInSalon(kEntityPlayer))
getEntities()->updateFrame(kEntityPascale);
setCallback(2);
setup_callbackActionOnDirection();
break;
case 2:
getData()->entityPosition = kPosition_5900;
callbackAction();
break;
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(31, Pascale, chapter5)
switch (savepoint.action) {
default:
break;
case kActionNone:
setup_chapter5Handler();
break;
case kActionDefault:
getEntities()->clearSequences(kEntityPascale);
getData()->entityPosition = kPosition_3969;
getData()->location = kLocationInsideCompartment;
getData()->car = kCarRestaurant;
getData()->inventoryItem = kItemNone;
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(32, Pascale, chapter5Handler)
if (savepoint.action == kActionProceedChapter5)
setup_function33();
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_FUNCTION(33, Pascale, function33)
switch (savepoint.action) {
default:
break;
case kActionNone:
if (params->param4) {
if (Entity::updateParameter(params->param5, getState()->time, 4500)) {
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorNormal, kCursorNormal);
setCallback(1);
setup_playSound("Wat5010");
break;
}
}
label_callback1:
if (params->param1) {
if (!Entity::updateParameter(params->param6, getState()->timeTicks, 75))
break;
params->param1 = 0;
params->param2 = 2;
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorNormal, kCursorNormal);
}
params->param6 = 0;
break;
case kActionKnock:
case kActionOpenDoor:
if (params->param1) {
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorNormal, kCursorNormal);
params->param1 = 0;
setCallback(2);
setup_playSound(getSound()->justCheckingCath());
} else {
setCallback(savepoint.action == kActionKnock ? 3 : 4);
setup_playSound(savepoint.action == kActionKnock ? "LIB012" : "LIB013");
}
break;
case kActionDefault:
getData()->car = kCarRedSleeping;
getData()->entityPosition = kPosition_3050;
getData()->location = kLocationInsideCompartment;
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorHandKnock, kCursorHand);
break;
case kActionDrawScene:
if (params->param2 || params->param1) {
params->param1 = 0;
params->param2 = 0;
params->param3 = 0;
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorHandKnock, kCursorHand);
}
break;
case kActionCallback:
switch (getCallback()) {
default:
break;
case 1:
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorHandKnock, kCursorHand);
goto label_callback1;
case 2:
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorHandKnock, kCursorHand);
break;
case 3:
case 4:
params->param3++;
if (params->param3 == 1 || params->param3 == 2) {
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorNormal, kCursorNormal);
setCallback(params->param3 == 1 ? 5 : 6);
setup_playSound(params->param3 == 1 ? "Wat5001" : "Wat5002");
}
break;
case 5:
params->param1 = 1;
getObjects()->update(kObjectCompartmentG, kEntityPascale, kObjectLocation1, kCursorTalk, kCursorNormal);
break;
case 6:
params->param2 = 1;
break;
case 7:
params->param4 = 1;
break;
}
break;
case kAction135800432:
setup_nullfunction();
break;
case kAction169750080:
if (getSoundQueue()->isBuffered(kEntityPascale)) {
params->param4 = 1;
} else {
setCallback(7);
setup_playSound("Wat5002");
}
break;
}
IMPLEMENT_FUNCTION_END
//////////////////////////////////////////////////////////////////////////
IMPLEMENT_NULL_FUNCTION(34, Pascale)
} // End of namespace LastExpress
| MaddTheSane/scummvm | engines/lastexpress/entities/pascale.cpp | C++ | gpl-2.0 | 31,531 |
/*
* Copyright (C) 2002-2015 The DOSBox Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "dosbox.h"
#if C_DEBUG
#include "control.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <curses.h>
#include <string.h>
#include "support.h"
#include "regs.h"
#include "debug.h"
#include "debug_inc.h"
struct _LogGroup {
char const* front;
bool enabled;
};
#include <list>
#include <string>
using namespace std;
#define MAX_LOG_BUFFER 500
static list<string> logBuff;
static list<string>::iterator logBuffPos = logBuff.end();
static _LogGroup loggrp[LOG_MAX]={{"",true},{0,false}};
static FILE* debuglog;
extern int old_cursor_state;
void DEBUG_ShowMsg(char const* format,...) {
char buf[512];
va_list msg;
va_start(msg,format);
vsprintf(buf,format,msg);
va_end(msg);
/* Add newline if not present */
Bitu len=strlen(buf);
if(buf[len-1]!='\n') strcat(buf,"\n");
if(debuglog) fprintf(debuglog,"%s",buf);
if (logBuffPos!=logBuff.end()) {
logBuffPos=logBuff.end();
DEBUG_RefreshPage(0);
// mvwprintw(dbg.win_out,dbg.win_out->_maxy-1, 0, "");
}
logBuff.push_back(buf);
if (logBuff.size() > MAX_LOG_BUFFER)
logBuff.pop_front();
logBuffPos = logBuff.end();
wprintw(dbg.win_out,"%s",buf);
wrefresh(dbg.win_out);
}
void DEBUG_RefreshPage(char scroll) {
if (scroll==-1 && logBuffPos!=logBuff.begin()) logBuffPos--;
else if (scroll==1 && logBuffPos!=logBuff.end()) logBuffPos++;
list<string>::iterator i = logBuffPos;
int maxy, maxx; getmaxyx(dbg.win_out,maxy,maxx);
int rem_lines = maxy;
if(rem_lines == -1) return;
wclear(dbg.win_out);
while (rem_lines > 0 && i!=logBuff.begin()) {
--i;
for (string::size_type posf=0, posl; (posl=(*i).find('\n',posf)) != string::npos ;posf=posl+1)
rem_lines -= (int) ((posl-posf) / maxx) + 1; // len=(posl+1)-posf-1
/* Const cast is needed for pdcurses which has no const char in mvwprintw (bug maybe) */
mvwprintw(dbg.win_out,rem_lines-1, 0, const_cast<char*>((*i).c_str()));
}
mvwprintw(dbg.win_out,maxy-1, 0, "");
wrefresh(dbg.win_out);
}
void LOG::operator() (char const* format, ...){
char buf[512];
va_list msg;
va_start(msg,format);
vsprintf(buf,format,msg);
va_end(msg);
if (d_type>=LOG_MAX) return;
if ((d_severity!=LOG_ERROR) && (!loggrp[d_type].enabled)) return;
DEBUG_ShowMsg("%10u: %s:%s\n",static_cast<Bit32u>(cycle_count),loggrp[d_type].front,buf);
}
static void Draw_RegisterLayout(void) {
mvwaddstr(dbg.win_reg,0,0,"EAX=");
mvwaddstr(dbg.win_reg,1,0,"EBX=");
mvwaddstr(dbg.win_reg,2,0,"ECX=");
mvwaddstr(dbg.win_reg,3,0,"EDX=");
mvwaddstr(dbg.win_reg,0,14,"ESI=");
mvwaddstr(dbg.win_reg,1,14,"EDI=");
mvwaddstr(dbg.win_reg,2,14,"EBP=");
mvwaddstr(dbg.win_reg,3,14,"ESP=");
mvwaddstr(dbg.win_reg,0,28,"DS=");
mvwaddstr(dbg.win_reg,0,38,"ES=");
mvwaddstr(dbg.win_reg,0,48,"FS=");
mvwaddstr(dbg.win_reg,0,58,"GS=");
mvwaddstr(dbg.win_reg,0,68,"SS=");
mvwaddstr(dbg.win_reg,1,28,"CS=");
mvwaddstr(dbg.win_reg,1,38,"EIP=");
mvwaddstr(dbg.win_reg,2,75,"CPL");
mvwaddstr(dbg.win_reg,2,68,"IOPL");
mvwaddstr(dbg.win_reg,1,52,"C Z S O A P D I T ");
}
static void DrawBars(void) {
if (has_colors()) {
attrset(COLOR_PAIR(PAIR_BLACK_BLUE));
}
/* Show the Register bar */
mvaddstr(1-1,0, "---(Register Overview )---");
/* Show the Data Overview bar perhaps with more special stuff in the end */
mvaddstr(6-1,0,"---(Data Overview Scroll: page up/down)---");
/* Show the Code Overview perhaps with special stuff in bar too */
mvaddstr(17-1,0,"---(Code Overview Scroll: up/down )---");
/* Show the Variable Overview bar */
mvaddstr(29-1,0, "---(Variable Overview )---");
/* Show the Output OverView */
mvaddstr(34-1,0, "---(Output Scroll: home/end )---");
attrset(0);
//Match values with below. So we don't need to touch the internal window structures
}
static void MakeSubWindows(void) {
/* The Std output win should go at the bottom */
/* Make all the subwindows */
int win_main_maxy, win_main_maxx; getmaxyx(dbg.win_main,win_main_maxy,win_main_maxx);
int outy=1; //Match values with above
/* The Register window */
dbg.win_reg=subwin(dbg.win_main,4,win_main_maxx,outy,0);
outy+=5; // 6
/* The Data Window */
dbg.win_data=subwin(dbg.win_main,10,win_main_maxx,outy,0);
outy+=11; // 17
/* The Code Window */
dbg.win_code=subwin(dbg.win_main,11,win_main_maxx,outy,0);
outy+=12; // 29
/* The Variable Window */
dbg.win_var=subwin(dbg.win_main,4,win_main_maxx,outy,0);
outy+=5; // 34
/* The Output Window */
dbg.win_out=subwin(dbg.win_main,win_main_maxy-outy,win_main_maxx,outy,0);
if(!dbg.win_reg ||!dbg.win_data || !dbg.win_code || !dbg.win_var || !dbg.win_out) E_Exit("Setting up windows failed");
// dbg.input_y=win_main_maxy-1;
scrollok(dbg.win_out,TRUE);
DrawBars();
Draw_RegisterLayout();
refresh();
}
static void MakePairs(void) {
init_pair(PAIR_BLACK_BLUE, COLOR_BLACK, COLOR_CYAN);
init_pair(PAIR_BYELLOW_BLACK, COLOR_YELLOW /*| FOREGROUND_INTENSITY */, COLOR_BLACK);
init_pair(PAIR_GREEN_BLACK, COLOR_GREEN /*| FOREGROUND_INTENSITY */, COLOR_BLACK);
init_pair(PAIR_BLACK_GREY, COLOR_BLACK /*| FOREGROUND_INTENSITY */, COLOR_WHITE);
init_pair(PAIR_GREY_RED, COLOR_WHITE/*| FOREGROUND_INTENSITY */, COLOR_RED);
}
static void LOG_Destroy(Section*) {
if(debuglog) fclose(debuglog);
}
static void LOG_Init(Section * sec) {
Section_prop * sect=static_cast<Section_prop *>(sec);
const char * blah=sect->Get_string("logfile");
if(blah && blah[0] &&(debuglog = fopen(blah,"wt+"))){
}else{
debuglog=0;
}
sect->AddDestroyFunction(&LOG_Destroy);
char buf[1024];
for (Bitu i=1;i<LOG_MAX;i++) {
strcpy(buf,loggrp[i].front);
buf[strlen(buf)]=0;
lowcase(buf);
loggrp[i].enabled=sect->Get_bool(buf);
}
}
void LOG_StartUp(void) {
/* Setup logging groups */
loggrp[LOG_ALL].front="ALL";
loggrp[LOG_VGA].front="VGA";
loggrp[LOG_VGAGFX].front="VGAGFX";
loggrp[LOG_VGAMISC].front="VGAMISC";
loggrp[LOG_INT10].front="INT10";
loggrp[LOG_SB].front="SBLASTER";
loggrp[LOG_DMACONTROL].front="DMA_CONTROL";
loggrp[LOG_FPU].front="FPU";
loggrp[LOG_CPU].front="CPU";
loggrp[LOG_PAGING].front="PAGING";
loggrp[LOG_FCB].front="FCB";
loggrp[LOG_FILES].front="FILES";
loggrp[LOG_IOCTL].front="IOCTL";
loggrp[LOG_EXEC].front="EXEC";
loggrp[LOG_DOSMISC].front="DOSMISC";
loggrp[LOG_PIT].front="PIT";
loggrp[LOG_KEYBOARD].front="KEYBOARD";
loggrp[LOG_PIC].front="PIC";
loggrp[LOG_MOUSE].front="MOUSE";
loggrp[LOG_BIOS].front="BIOS";
loggrp[LOG_GUI].front="GUI";
loggrp[LOG_MISC].front="MISC";
loggrp[LOG_IO].front="IO";
loggrp[LOG_PCI].front="PCI";
/* Register the log section */
Section_prop * sect=control->AddSection_prop("log",LOG_Init);
Prop_string* Pstring = sect->Add_string("logfile",Property::Changeable::Always,"");
Pstring->Set_help("file where the log messages will be saved to");
char buf[1024];
for (Bitu i=1;i<LOG_MAX;i++) {
strcpy(buf,loggrp[i].front);
lowcase(buf);
Prop_bool* Pbool = sect->Add_bool(buf,Property::Changeable::Always,true);
Pbool->Set_help("Enable/Disable logging of this type.");
}
// MSG_Add("LOG_CONFIGFILE_HELP","Logging related options for the debugger.\n");
}
void DBGUI_StartUp(void) {
/* Start the main window */
dbg.win_main=initscr();
cbreak(); /* take input chars one at a time, no wait for \n */
noecho(); /* don't echo input */
nodelay(dbg.win_main,true);
keypad(dbg.win_main,true);
#ifndef WIN32
printf("\e[8;50;80t");
fflush(NULL);
resizeterm(50,80);
touchwin(dbg.win_main);
#endif
old_cursor_state = curs_set(0);
start_color();
cycle_count=0;
MakePairs();
MakeSubWindows();
}
#endif
| danielrh/dosbox3d | src/debug/debug_gui.cpp | C++ | gpl-2.0 | 8,366 |
/*
* Copyright © 2018 Google, Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Google Author(s): Garret Rieger
*/
#ifndef HB_SUBSET_GLYF_HH
#define HB_SUBSET_GLYF_HH
#include "hb.hh"
#include "hb-subset.hh"
HB_INTERNAL bool
hb_subset_glyf_and_loca (hb_subset_plan_t *plan,
bool *use_short_loca, /* OUT */
hb_blob_t **glyf_prime /* OUT */,
hb_blob_t **loca_prime /* OUT */);
#endif /* HB_SUBSET_GLYF_HH */
| md-5/jdk10 | src/java.desktop/share/native/libfontmanager/harfbuzz/hb-subset-glyf.hh | C++ | gpl-2.0 | 1,511 |
/***************************************************************************
qgsalgorithmlayouttopdf.cpp
---------------------
begin : June 2020
copyright : (C) 2020 by Nyall Dawson
email : nyall dot dawson at gmail dot 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. *
* *
***************************************************************************/
#include "qgsalgorithmlayouttopdf.h"
#include "qgslayout.h"
#include "qgslayoutitemmap.h"
#include "qgsprintlayout.h"
#include "qgsprocessingoutputs.h"
#include "qgslayoutexporter.h"
///@cond PRIVATE
QString QgsLayoutToPdfAlgorithm::name() const
{
return QStringLiteral( "printlayouttopdf" );
}
QString QgsLayoutToPdfAlgorithm::displayName() const
{
return QObject::tr( "Export print layout as PDF" );
}
QStringList QgsLayoutToPdfAlgorithm::tags() const
{
return QObject::tr( "layout,composer,composition,save" ).split( ',' );
}
QString QgsLayoutToPdfAlgorithm::group() const
{
return QObject::tr( "Cartography" );
}
QString QgsLayoutToPdfAlgorithm::groupId() const
{
return QStringLiteral( "cartography" );
}
QString QgsLayoutToPdfAlgorithm::shortDescription() const
{
return QObject::tr( "Exports a print layout as a PDF." );
}
QString QgsLayoutToPdfAlgorithm::shortHelpString() const
{
return QObject::tr( "This algorithm outputs a print layout as a PDF file." );
}
void QgsLayoutToPdfAlgorithm::initAlgorithm( const QVariantMap & )
{
addParameter( new QgsProcessingParameterLayout( QStringLiteral( "LAYOUT" ), QObject::tr( "Print layout" ) ) );
std::unique_ptr< QgsProcessingParameterMultipleLayers > layersParam = std::make_unique< QgsProcessingParameterMultipleLayers>( QStringLiteral( "LAYERS" ), QObject::tr( "Map layers to assign to unlocked map item(s)" ), QgsProcessing::TypeMapLayer, QVariant(), true );
layersParam->setFlags( layersParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( layersParam.release() );
std::unique_ptr< QgsProcessingParameterNumber > dpiParam = std::make_unique< QgsProcessingParameterNumber >( QStringLiteral( "DPI" ), QObject::tr( "DPI (leave blank for default layout DPI)" ), QgsProcessingParameterNumber::Double, QVariant(), true, 0 );
dpiParam->setFlags( dpiParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( dpiParam.release() );
std::unique_ptr< QgsProcessingParameterBoolean > forceVectorParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "FORCE_VECTOR" ), QObject::tr( "Always export as vectors" ), false );
forceVectorParam->setFlags( forceVectorParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( forceVectorParam.release() );
std::unique_ptr< QgsProcessingParameterBoolean > appendGeorefParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "GEOREFERENCE" ), QObject::tr( "Append georeference information" ), true );
appendGeorefParam->setFlags( appendGeorefParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( appendGeorefParam.release() );
std::unique_ptr< QgsProcessingParameterBoolean > exportRDFParam = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "INCLUDE_METADATA" ), QObject::tr( "Export RDF metadata (title, author, etc.)" ), true );
exportRDFParam->setFlags( exportRDFParam->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( exportRDFParam.release() );
std::unique_ptr< QgsProcessingParameterBoolean > disableTiled = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "DISABLE_TILED" ), QObject::tr( "Disable tiled raster layer exports" ), false );
disableTiled->setFlags( disableTiled->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( disableTiled.release() );
std::unique_ptr< QgsProcessingParameterBoolean > simplify = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "SIMPLIFY" ), QObject::tr( "Simplify geometries to reduce output file size" ), true );
simplify->setFlags( simplify->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( simplify.release() );
QStringList textExportOptions
{
QObject::tr( "Always Export Text as Paths (Recommended)" ),
QObject::tr( "Always Export Text as Text Objects" )
};
std::unique_ptr< QgsProcessingParameterEnum > textFormat = std::make_unique< QgsProcessingParameterEnum >( QStringLiteral( "TEXT_FORMAT" ), QObject::tr( "Text export" ), textExportOptions, false, 0 );
textFormat->setFlags( textFormat->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( textFormat.release() );
std::unique_ptr< QgsProcessingParameterBoolean > layeredExport = std::make_unique< QgsProcessingParameterBoolean >( QStringLiteral( "SEPARATE_LAYERS" ), QObject::tr( "Export layers as separate PDF files" ), false );
layeredExport->setFlags( layeredExport->flags() | QgsProcessingParameterDefinition::FlagAdvanced );
addParameter( layeredExport.release() );
addParameter( new QgsProcessingParameterFileDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "PDF file" ), QObject::tr( "PDF Format" ) + " (*.pdf *.PDF)" ) );
}
QgsProcessingAlgorithm::Flags QgsLayoutToPdfAlgorithm::flags() const
{
return QgsProcessingAlgorithm::flags() | FlagNoThreading;
}
QgsLayoutToPdfAlgorithm *QgsLayoutToPdfAlgorithm::createInstance() const
{
return new QgsLayoutToPdfAlgorithm();
}
QVariantMap QgsLayoutToPdfAlgorithm::processAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
// this needs to be done in main thread, layouts are not thread safe
QgsPrintLayout *l = parameterAsLayout( parameters, QStringLiteral( "LAYOUT" ), context );
if ( !l )
throw QgsProcessingException( QObject::tr( "Cannot find layout with name \"%1\"" ).arg( parameters.value( QStringLiteral( "LAYOUT" ) ).toString() ) );
std::unique_ptr< QgsPrintLayout > layout( l->clone() );
const QList< QgsMapLayer * > layers = parameterAsLayerList( parameters, QStringLiteral( "LAYERS" ), context );
if ( layers.size() > 0 )
{
const QList<QGraphicsItem *> items = layout->items();
for ( QGraphicsItem *graphicsItem : items )
{
QgsLayoutItem *item = dynamic_cast<QgsLayoutItem *>( graphicsItem );
QgsLayoutItemMap *map = dynamic_cast<QgsLayoutItemMap *>( item );
if ( map && !map->followVisibilityPreset() && !map->keepLayerSet() )
{
map->setKeepLayerSet( true );
map->setLayers( layers );
}
}
}
const QString dest = parameterAsFileOutput( parameters, QStringLiteral( "OUTPUT" ), context );
QgsLayoutExporter exporter( layout.get() );
QgsLayoutExporter::PdfExportSettings settings;
if ( parameters.value( QStringLiteral( "DPI" ) ).isValid() )
{
settings.dpi = parameterAsDouble( parameters, QStringLiteral( "DPI" ), context );
}
settings.forceVectorOutput = parameterAsBool( parameters, QStringLiteral( "FORCE_VECTOR" ), context );
settings.appendGeoreference = parameterAsBool( parameters, QStringLiteral( "GEOREFERENCE" ), context );
settings.exportMetadata = parameterAsBool( parameters, QStringLiteral( "INCLUDE_METADATA" ), context );
settings.exportMetadata = parameterAsBool( parameters, QStringLiteral( "INCLUDE_METADATA" ), context );
settings.simplifyGeometries = parameterAsBool( parameters, QStringLiteral( "SIMPLIFY" ), context );
settings.textRenderFormat = parameterAsEnum( parameters, QStringLiteral( "TEXT_FORMAT" ), context ) == 0 ? QgsRenderContext::TextFormatAlwaysOutlines : QgsRenderContext::TextFormatAlwaysText;
settings.exportLayersAsSeperateFiles = parameterAsBool( parameters, QStringLiteral( "SEPARATE_LAYERS" ), context ); //#spellok
if ( parameterAsBool( parameters, QStringLiteral( "DISABLE_TILED" ), context ) )
settings.flags = settings.flags | QgsLayoutRenderContext::FlagDisableTiledRasterLayerRenders;
else
settings.flags = settings.flags & ~QgsLayoutRenderContext::FlagDisableTiledRasterLayerRenders;
switch ( exporter.exportToPdf( dest, settings ) )
{
case QgsLayoutExporter::Success:
{
feedback->pushInfo( QObject::tr( "Successfully exported layout to %1" ).arg( QDir::toNativeSeparators( dest ) ) );
break;
}
case QgsLayoutExporter::FileError:
throw QgsProcessingException( QObject::tr( "Cannot write to %1.\n\nThis file may be open in another application." ).arg( QDir::toNativeSeparators( dest ) ) );
case QgsLayoutExporter::PrintError:
throw QgsProcessingException( QObject::tr( "Could not create print device." ) );
case QgsLayoutExporter::MemoryError:
throw QgsProcessingException( QObject::tr( "Exporting the PDF "
"resulted in a memory overflow.\n\n"
"Please try a lower resolution or a smaller paper size." ) );
case QgsLayoutExporter::SvgLayerError:
case QgsLayoutExporter::IteratorError:
case QgsLayoutExporter::Canceled:
// no meaning for PDF exports, will not be encountered
break;
}
feedback->setProgress( 100 );
QVariantMap outputs;
outputs.insert( QStringLiteral( "OUTPUT" ), dest );
return outputs;
}
///@endcond
| NaturalGIS/naturalgis_qgis | src/analysis/processing/qgsalgorithmlayouttopdf.cpp | C++ | gpl-2.0 | 9,906 |
<?php
/**
* @file
* Definition of Drupal\search\Tests\SearchBlockTest.
*/
namespace Drupal\search\Tests;
/**
* Tests the rendering of the search block.
*/
class SearchBlockTest extends SearchTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('block');
public static function getInfo() {
return array(
'name' => 'Block availability',
'description' => 'Check if the search form block is available.',
'group' => 'Search',
);
}
function setUp() {
parent::setUp();
// Create and login user.
$admin_user = $this->drupalCreateUser(array('administer blocks', 'search content'));
$this->drupalLogin($admin_user);
}
/**
* Test that the search form block can be placed and works.
*/
protected function testSearchFormBlock() {
// Test availability of the search block in the admin "Place blocks" list.
$this->drupalGet('admin/structure/block');
$this->assertLinkByHref('/admin/structure/block/add/search_form_block/stark', 0,
'Did not find the search block in block candidate list.');
$block = $this->drupalPlaceBlock('search_form_block');
$this->drupalGet('');
$this->assertText($block->label(), 'Block title was found.');
// Test a normal search via the block form, from the front page.
$terms = array('search_block_form' => 'test');
$this->drupalPostForm('', $terms, t('Search'));
$this->assertResponse(200);
$this->assertText('Your search yielded no results');
// Test a search from the block on a 404 page.
$this->drupalGet('foo');
$this->assertResponse(404);
$this->drupalPostForm(NULL, $terms, t('Search'));
$this->assertResponse(200);
$this->assertText('Your search yielded no results');
$visibility = $block->get('visibility');
$visibility['path']['pages'] = 'search';
$block->set('visibility', $visibility);
$this->drupalPostForm('', $terms, t('Search'));
$this->assertResponse(200);
$this->assertText('Your search yielded no results');
// Confirm that the user is redirected to the search page.
$this->assertEqual(
$this->getUrl(),
url('search/node/' . $terms['search_block_form'], array('absolute' => TRUE)),
'Redirected to correct url.'
);
// Test an empty search via the block form, from the front page.
$terms = array('search_block_form' => '');
$this->drupalPostForm('', $terms, t('Search'));
$this->assertResponse(200);
$this->assertText('Please enter some keywords');
// Confirm that the user is redirected to the search page, when form is
// submitted empty.
$this->assertEqual(
$this->getUrl(),
url('search/node/', array('absolute' => TRUE)),
'Redirected to correct url.'
);
}
}
| glibey/drupal8 | core/modules/search/lib/Drupal/search/Tests/SearchBlockTest.php | PHP | gpl-2.0 | 2,805 |
define(["../../buildControl"], function(bc){
if(bc.stripConsole){
var consoleMethods = "assert|count|debug|dir|dirxml|group|groupEnd|info|profile|profileEnd|time|timeEnd|trace|log";
if(bc.stripConsole === "warn"){
consoleMethods += "|warn";
}else if(bc.stripConsole === "all"){
consoleMethods += "|warn|error";
}
// Match on "window.console" and plain "console" but not things like "myconsole" or "my.console"
var stripConsoleRe = new RegExp("([^\\w\\.]|^)((window.)?console\\.(" + consoleMethods + ")\\s*\\()", "g");
return function(text){
return text.replace(stripConsoleRe, "$1 0 && $2");
};
}else{
return function(text){
return text;
};
}
}); | avz-cmf/zaboy-middleware | www/js/util/build/transforms/optimizer/stripConsole.js | JavaScript | gpl-3.0 | 681 |
/**
* This file contains JS functionality required by mforms and is included automatically
* when required.
*/
// Namespace for the form bits and bobs
M.form = M.form || {};
/**
* Initialises the show advanced functionality and events.
* This should only ever happen ONCE per page.
*
* @param {YUI} Y
* @param {object} config
*/
M.form.initShowAdvanced = function(Y, config) {
if (M.form.showAdvanced) {
return M.form.showAdvanced;
}
var showAdvanced = function(config) {
showAdvanced.superclass.constructor.apply(this, arguments);
};
showAdvanced.prototype = {
_advButtons : [],
_advAreas : [],
_stateInput : null,
initializer : function() {
this._advAreas = Y.all('form .advanced');
this._advButtons = Y.all('.showadvancedbtn');
if (this._advButtons.size() > 0) {
this._stateInput = new Y.NodeList(document.getElementsByName('mform_showadvanced_last'));
this._advButtons.on('click', this.switchState, this);
}
},
/**
* Toggles between showing advanced items and hiding them.
* Should be fired by an event.
*/
switchState : function(e) {
e.preventDefault();
if (this._stateInput.get('value')=='1') {
this._stateInput.set('value', '0');
this._advButtons.setAttribute('value', M.str.form.showadvanced);
this._advAreas.addClass('hide');
} else {
this._stateInput.set('value', '1');
this._advButtons.setAttribute('value', M.str.form.hideadvanced);
this._advAreas.removeClass('hide');
}
}
};
// Extend it with the YUI widget fw.
Y.extend(showAdvanced, Y.Base, showAdvanced.prototype, {
NAME : 'mform-showAdvanced'
});
M.form.showAdvanced = new showAdvanced(config);
return M.form.showAdvanced;
};
/**
* Initialises a manager for a forms dependencies.
* This should happen once per form.
*/
M.form.initFormDependencies = function(Y, formid, dependencies) {
// If the dependencies isn't an array or object we don't want to
// know about it
if (!Y.Lang.isArray(dependencies) && !Y.Lang.isObject(dependencies)) {
return false;
}
/**
* Fixes an issue with YUI's processing method of form.elements property
* in Internet Explorer.
* http://yuilibrary.com/projects/yui3/ticket/2528030
*/
Y.Node.ATTRS.elements = {
getter: function() {
return Y.all(new Y.Array(this._node.elements, 0, true));
}
};
// Define the dependency manager if it hasn't already been defined.
M.form.dependencyManager = M.form.dependencyManager || (function(){
var dependencyManager = function(config) {
dependencyManager.superclass.constructor.apply(this, arguments);
};
dependencyManager.prototype = {
_form : null,
_depElements : [],
_nameCollections : [],
initializer : function(config) {
var i = 0, nodeName;
this._form = Y.one('#'+formid);
for (i in dependencies) {
this._depElements[i] = this.elementsByName(i);
if (this._depElements[i].size() == 0) {
continue;
}
this._depElements[i].each(function(node){
nodeName = node.get('nodeName').toUpperCase();
if (nodeName == 'INPUT') {
if (node.getAttribute('type').match(/^(button|submit|radio|checkbox)$/)) {
node.on('click', this.checkDependencies, this);
} else {
node.on('blur', this.checkDependencies, this);
}
node.on('change', this.checkDependencies, this);
} else if (nodeName == 'SELECT') {
node.on('change', this.checkDependencies, this);
} else {
node.on('click', this.checkDependencies, this);
node.on('blur', this.checkDependencies, this);
node.on('change', this.checkDependencies, this);
}
}, this);
}
this._form.get('elements').each(function(input){
if (input.getAttribute('type')=='reset') {
input.on('click', function(){
this._form.reset();
this.checkDependencies();
}, this);
}
}, this);
return this.checkDependencies(null);
},
/**
* Gets all elements in the form by thier name and returns
* a YUI NodeList
* @return Y.NodeList
*/
elementsByName : function(name) {
if (!this._nameCollections[name]) {
var elements = [];
this._form.get('elements').each(function(){
if (this.getAttribute('name') == name) {
elements.push(this);
}
});
this._nameCollections[name] = new Y.NodeList(elements);
}
return this._nameCollections[name];
},
/**
* Checks the dependencies the form has an makes any changes to the
* form that are required.
*
* Changes are made by functions title _dependency_{dependencytype}
* and more can easily be introduced by defining further functions.
*/
checkDependencies : function(e) {
var tolock = [],
tohide = [],
dependon, condition, value,
lock, hide, checkfunction, result;
for (dependon in dependencies) {
if (this._depElements[dependon].size() == 0) {
continue;
}
for (condition in dependencies[dependon]) {
for (value in dependencies[dependon][condition]) {
lock = false;
hide = false;
checkfunction = '_dependency_'+condition;
if (Y.Lang.isFunction(this[checkfunction])) {
result = this[checkfunction].apply(this, [this._depElements[dependon], value, e]);
} else {
result = this._dependency_default(this._depElements[dependon], value, e);
}
lock = result.lock || false;
hide = result.hide || false;
for (var ei in dependencies[dependon][condition][value]) {
var eltolock = dependencies[dependon][condition][value][ei];
if (hide) {
tohide[eltolock] = true;
}
if (tolock[eltolock] != null) {
tolock[eltolock] = lock || tolock[eltolock];
} else {
tolock[eltolock] = lock;
}
}
}
}
}
for (var el in tolock) {
this._disableElement(el, tolock[el]);
if (tohide.propertyIsEnumerable(el)) {
this._hideElement(el, tohide[el]);
}
}
return true;
},
/**
* Disabled all form elements with the given name
*/
_disableElement : function(name, disabled) {
var els = this.elementsByName(name);
els.each(function(){
if (disabled) {
this.setAttribute('disabled', 'disabled');
} else {
this.removeAttribute('disabled');
}
})
},
/**
* Hides all elements with the given name.
*/
_hideElement : function(name, hidden) {
var els = this.elementsByName(name);
els.each(function(){
var e = els.ancestor('.fitem');
if (e) {
e.setStyles({
display : (hidden)?'none':''
})
}
});
},
_dependency_notchecked : function(elements, value) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && this.get('value') != value) {
return;
}
lock = lock || !Y.Node.getDOMNode(this).checked;
});
return {
lock : lock,
hide : false
}
},
_dependency_checked : function(elements, value) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && this.get('value') != value) {
return;
}
lock = lock || Y.Node.getDOMNode(this).checked;
});
return {
lock : lock,
hide : false
}
},
_dependency_noitemselected : function(elements, value) {
var lock = false;
elements.each(function(){
lock = lock || this.get('selectedIndex') == -1;
});
return {
lock : lock,
hide : false
}
},
_dependency_eq : function(elements, value) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && !Y.Node.getDOMNode(this).checked) {
return;
} else if (this.getAttribute('type').toLowerCase() == 'checkbox' && !Y.Node.getDOMNode(this).checked) {
return;
}
lock = lock || this.get('value') == value;
});
return {
lock : lock,
hide : false
}
},
_dependency_hide : function(elements, value) {
return {
lock : false,
hide : true
}
},
_dependency_default : function(elements, value, ev) {
var lock = false;
elements.each(function(){
if (this.getAttribute('type').toLowerCase()=='radio' && !Y.Node.getDOMNode(this).checked) {
return;
} else if (this.getAttribute('type').toLowerCase() == 'checkbox' && !Y.Node.getDOMNode(this).checked) {
return;
}
lock = lock || this.get('value') != value;
});
return {
lock : lock,
hide : false
}
}
};
Y.extend(dependencyManager, Y.Base, dependencyManager.prototype, {
NAME : 'mform-dependency-manager'
});
return dependencyManager;
})();
return new M.form.dependencyManager();
}; | dhamma-dev/SEA | web/lib/form/form.js | JavaScript | gpl-3.0 | 12,220 |
#ifndef __XRDCMSBLACKLIST_HH__
#define __XRDCMSBLACKLIST_HH__
/******************************************************************************/
/* */
/* X r d C m s B l a c k L i s t . h h */
/* */
/* (c) 2014 by the Board of Trustees of the Leland Stanford, Jr., University */
/* All Rights Reserved */
/* Produced by Andrew Hanushevsky for Stanford University under contract */
/* DE-AC02-76-SFO0515 with the Department of Energy */
/* */
/* This file is part of the XRootD software suite. */
/* */
/* XRootD is free software: you can redistribute it and/or modify it under */
/* the terms of the GNU Lesser General Public License as published by the */
/* Free Software Foundation, either version 3 of the License, or (at your */
/* option) any later version. */
/* */
/* XRootD is distributed in the hope that it will be useful, but WITHOUT */
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public */
/* License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public License */
/* along with XRootD in a file called COPYING.LESSER (LGPL license) and file */
/* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */
/* */
/* The copyright holder's institutional names and contributor's names may not */
/* be used to endorse or promote products derived from this software without */
/* specific prior written permission of the institution or contributor. */
/******************************************************************************/
#include "Xrd/XrdJob.hh"
class XrdCmsCluster;
class XrdOucTList;
class XrdScheduler;
class BL_Grip;
class XrdCmsBlackList : public XrdJob
{
public:
//------------------------------------------------------------------------------
//! Time driven method for checking black list file.
//------------------------------------------------------------------------------
void DoIt();
//------------------------------------------------------------------------------
//! Initialize the black list
//!
//! @param sP Pointer to the scheduler object.
//! @param cP Pointer to the cluster object.
//! @param blfn The path to the black list file or null.
//! @param chkt Seconds between checks for blacklist changes. If the value
//! is negative, the blacklist is treated as a whitelist.
//------------------------------------------------------------------------------
static void Init(XrdScheduler *sP, XrdCmsCluster *cP,
const char *blfn, int chkt=600);
//------------------------------------------------------------------------------
//! Check if host is in the black list and how it should be managed.
//!
//! @param hName Pointer to the host name or address.
//! @param bList Optional pointer to a private black list.
//! @param rbuff Pointer to the buffer to contain the redirect response. If
//! nil, the host is not redirected.
//! @param rblen The size of rbuff. If zero or insufficiently large the host
//! is not redirected.
//!
//! @return < -1 Host is in the black list and would be redirected;
//! but either rbuff was nil or the buffer was too small. The
//! abs(returned value) is the size the buffer should have been.
//! @return = -1 Host is in the black list and should not be redirected.
//! @return = 0 Host not in the black list.
//! @return > 0 Host is in the black list and should be redirected.
//! The return value is the size of the redirect response placed
//! in the supplied buffer.
//------------------------------------------------------------------------------
static int Present(const char *hName, XrdOucTList *bList=0,
char *rbuff=0, int rblen=0);
//------------------------------------------------------------------------------
//! Constructor and Destructor
//------------------------------------------------------------------------------
XrdCmsBlackList() : XrdJob("Black List Check") {}
~XrdCmsBlackList() {}
private:
static bool AddBL(BL_Grip &bAnchor, char *hSpec,
BL_Grip *rAnchor, char *rSpec);
static int AddRD(BL_Grip *rAnchor, char *rSpec, char *hSpec);
static bool AddRD(XrdOucTList **rList, char *rSpec, char *hSpec);
static
XrdOucTList *Flatten(XrdOucTList *tList, int tPort);
static bool GetBL(XrdOucTList *&bList, XrdOucTList **&rList, int &rcnt);
};
#endif
| alja/xrootd | src/XrdCms/XrdCmsBlackList.hh | C++ | gpl-3.0 | 5,380 |
/*
#########################################################################
#
# Copyright (C) 2019 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
*/
export default 'ALERT_SETTINGS';
| tomkralidis/geonode | geonode/monitoring/frontend/monitoring/src/pages/alerts-settings/constants.js | JavaScript | gpl-3.0 | 853 |
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay;
/**
* Invoice
*
* @package Bitpay
*/
interface InvoiceInterface
{
/**
* An invoice starts in this state. When in this state and only in this state, payments
* to the associated bitcoin address are credited to the invoice. If an invoice has
* received a partial payment, it will still reflect a status of new to the merchant
* (from a merchant system perspective, an invoice is either paid or not paid, partial
* payments and over payments are handled by bitpay.com by either refunding the
* customer or applying the funds to a new invoice.
*/
const STATUS_NEW = 'new';
/**
* As soon as full payment (or over payment) is received, an invoice goes into the
* paid status.
*/
const STATUS_PAID = 'paid';
/**
* The transaction speed preference of an invoice determines when an invoice is
* confirmed. For the high speed setting, it will be confirmed as soon as full
* payment is received on the bitcoin network (note, the invoice will go from a status
* of new to confirmed, bypassing the paid status). For the medium speed setting,
* the invoice is confirmed after the payment transaction(s) have been confirmed by
* 1 block on the bitcoin network. For the low speed setting, 6 blocks on the bitcoin
* network are required. Invoices are considered complete after 6 blocks on the
* bitcoin network, therefore an invoice will go from a paid status directly to a
* complete status if the transaction speed is set to low.
*/
const STATUS_CONFIRMED = 'confirmed';
/**
* When an invoice is complete, it means that BitPay.com has credited the
* merchant’s account for the invoice. Currently, 6 confirmation blocks on the
* bitcoin network are required for an invoice to be complete. Note, in the future (for
* qualified payers), invoices may move to a complete status immediately upon
* payment, in which case the invoice will move directly from a new status to a
* complete status.
*/
const STATUS_COMPLETE = 'complete';
/**
* An expired invoice is one where payment was not received and the 15 minute
* payment window has elapsed.
*/
const STATUS_EXPIRED = 'expired';
/**
* An invoice is considered invalid when it was paid, but payment was not confirmed
* within 1 hour after receipt. It is possible that some transactions on the bitcoin
* network can take longer than 1 hour to be included in a block. In such
* circumstances, once payment is confirmed, BitPay.com will make arrangements
* with the merchant regarding the funds (which can either be credited to the
* merchant account on another invoice, or returned to the buyer).
*/
const STATUS_INVALID = 'invalid';
/**
* Code comment for each transaction speed
*/
const TRANSACTION_SPEED_HIGH = 'high';
const TRANSACTION_SPEED_MEDIUM = 'medium';
const TRANSACTION_SPEED_LOW = 'low';
/**
* This is the amount that is required to be collected from the buyer. Note, if this is
* specified in a currency other than BTC, the price will be converted into BTC at
* market exchange rates to determine the amount collected from the buyer.
*
* @return string
*/
public function getPrice();
/**
* This is the currency code set for the price setting. The pricing currencies
* currently supported are USD, EUR, BTC, and all of the codes listed on this page:
* https://bitpay.com/bitcoinexchangerates
*
* @return CurrencyInterface
*/
public function getCurrency();
/**
* @return ItemInterface
*/
public function getItem();
/**
* @return BuyerInterface
*/
public function getBuyer();
/**
* default value: set in your https://bitpay.com/ordersettings, the default value set in
* your merchant dashboard is “medium”.
*
* ● “high”: An invoice is considered to be "confirmed" immediately upon
* receipt of payment.
* ● “medium”: An invoice is considered to be "confirmed" after 1 block
* confirmation (~10 minutes).
* ● “low”: An invoice is considered to be "confirmed" after 6 block
* confirmations (~1 hour).
*
* NOTE: Orders are posted to your Account Summary after 6 block confirmations
* regardless of this setting.
*
* @return string
*/
public function getTransactionSpeed();
/**
* Bitpay.com will send an email to this email address when the invoice status
* changes.
*
* @return string
*/
public function getNotificationEmail();
/**
* A URL to send status update messages to your server (this must be an https
* URL, unencrypted http URLs or any other type of URL is not supported).
* Bitpay.com will send a POST request with a JSON encoding of the invoice to
* this URL when the invoice status changes.
*
* @return string
*/
public function getNotificationUrl();
/**
* This is the URL for a return link that is displayed on the receipt, to return the
* shopper back to your website after a successful purchase. This could be a page
* specific to the order, or to their account.
*
* @return string
*/
public function getRedirectUrl();
/**
* A passthru variable provided by the merchant and designed to be used by the
* merchant to correlate the invoice with an order or other object in their system.
* Maximum string length is 100 characters.
*
* @return array|object
*/
public function getPosData();
/**
* The current invoice status. The possible states are described earlier in this
* document.
*
* @return string
*/
public function getStatus();
/**
* default value: true
* ● true: Notifications will be sent on every status change.
* ● false: Notifications are only sent when an invoice is confirmed (according
* to the “transactionSpeed” setting).
*
* @return boolean
*/
public function isFullNotifications();
/**
* default value: false
* ● true: Notifications will also be sent for expired invoices and refunds.
* ● false: Notifications will not be sent for expired invoices and refunds
*
* @return boolean
*/
public function isExtendedNotifications();
/**
* The unique id of the invoice assigned by bitpay.com
*
* @return string
*/
public function getId();
/**
* An https URL where the invoice can be viewed.
*
* @return string
*/
public function getUrl();
/**
* The amount of bitcoins being requested for payment of this invoice (same as the
* price if the merchant set the price in BTC).
*
* @return string
*/
public function getBtcPrice();
/**
* The time the invoice was created in milliseconds since midnight January 1,
* 1970. Time format is “20140101T19:01:01.123Z”.
*
* @return DateTime
*/
public function getInvoiceTime();
/**
* The time at which the invoice expires and no further payment will be accepted (in
* milliseconds since midnight January 1, 1970). Currently, all invoices are valid for
* 15 minutes. Time format is “20140101T19:01:01.123Z”.
*
* @return DateTime
*/
public function getExpirationTime();
/**
* The current time on the BitPay.com system (by subtracting the current time from
* the expiration time, the amount of time remaining for payment can be
* determined). Time format is “20140101T19:01:01.123Z”.
*
* @return DateTime
*/
public function getCurrentTime();
/**
* Used to display your public order number to the buyer on the BitPay invoice. In
* the merchant Account Summary page, this value is used to identify the ledger
* entry. Maximum string length is 100 characters.
*
* @return string
*/
public function getOrderId();
/**
* Used to display an item description to the buyer. Maximum string length is 100
* characters.
*
* @deprecated
* @return string
*/
public function getItemDesc();
/**
* Used to display an item SKU code or part number to the buyer. Maximum string
* length is 100 characters.
*
* @deprecated
* @return string
*/
public function getItemCode();
/**
* default value: false
* ● true: Indicates a physical item will be shipped (or picked up)
* ● false: Indicates that nothing is to be shipped for this order
*
* @deprecated
* @return boolean
*/
public function isPhysical();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerName();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerAddress1();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerAddress2();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerCity();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerState();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerZip();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerCountry();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerEmail();
/**
* These fields are used for display purposes only and will be shown on the invoice
* if provided. Maximum string length of each field is 100 characters.
*
* @deprecated
* @return string
*/
public function getBuyerPhone();
/**
*/
public function getExceptionStatus();
/**
*/
public function getBtcPaid();
/**
*/
public function getRate();
/**
*/
public function getToken();
/**
* An array containing all bitcoin addresses linked to the invoice.
* Only filled when doing a getInvoice using the Merchant facade.
* The array contains
* [refundAddress] => Array
* [type] => string (e.g. "PaymentProtocol")
* [date] => datetime string
*
* @return array|object
*/
public function getRefundAddresses();
}
| yclas/yclas | oc/vendor/bitpay/vendor/bitpay/php-client/src/Bitpay/InvoiceInterface.php | PHP | gpl-3.0 | 12,475 |
// ***************************************************************** -*- C++ -*-
/*
* Copyright (C) 2004-2015 Andreas Huggel <ahuggel@gmx.net>
*
* This program is part of the Exiv2 distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
*/
/*!
@file asfvideo.hpp
@brief An Image subclass to support ASF video files
@version $Rev$
@author Abhinav Badola for GSoC 2012
<a href="mailto:mail.abu.to@gmail.com">mail.abu.to@gmail.com</a>
@date 08-Aug-12, AB: created
*/
#ifndef ASFVIDEO_HPP
#define ASFVIDEO_HPP
// *****************************************************************************
// included header files
#include "exif.hpp"
#include "image.hpp"
#include "tags_int.hpp"
// *****************************************************************************
// namespace extensions
using namespace Exiv2::Internal;
namespace Exiv2 {
// *****************************************************************************
// class definitions
// Add ASF to the supported image formats
namespace ImageType {
const int asf = 24; //!< Treating asf as an image type>
}
/*!
@brief Class to access ASF video files.
*/
class EXIV2API AsfVideo:public Image
{
public:
//! @name Creators
//@{
/*!
@brief Constructor for a ASF video. Since the constructor
can not return a result, callers should check the good() method
after object construction to determine success or failure.
@param io An auto-pointer that owns a BasicIo instance used for
reading and writing image metadata. \b Important: The constructor
takes ownership of the passed in BasicIo instance through the
auto-pointer. Callers should not continue to use the BasicIo
instance after it is passed to this method. Use the Image::io()
method to get a temporary reference.
*/
AsfVideo(BasicIo::AutoPtr io);
//@}
//! @name Manipulators
//@{
void readMetadata();
void writeMetadata();
//@}
//! @name Accessors
//@{
std::string mimeType() const;
//@}
protected:
/*!
@brief Check for a valid tag and decode the block at the current IO
position. Calls tagDecoder() or skips to next tag, if required.
*/
void decodeBlock();
/*!
@brief Interpret tag information, and call the respective function
to save it in the respective XMP container. Decodes a Tag
Information and saves it in the respective XMP container, if
the block size is small.
@param tv Pointer to current tag,
@param size Size of the data block used to store Tag Information.
*/
void tagDecoder(const TagVocabulary* tv, uint64_t size);
/*!
@brief Interpret File_Properties tag information, and save it in
the respective XMP container.
*/
void fileProperties();
/*!
@brief Interpret Stream_Properties tag information, and save it
in the respective XMP container.
*/
void streamProperties();
/*!
@brief Interpret Codec_List tag information, and save it in
the respective XMP container.
*/
void codecList();
/*!
@brief Interpret Content_Description tag information, and save it
in the respective XMP container.
@param size Size of the data block used to store Tag Data.
*/
void contentDescription(uint64_t size);
/*!
@brief Interpret Extended_Stream_Properties tag information, and
save it in the respective XMP container.
@param size Size of the data block used to store Tag Data.
*/
void extendedStreamProperties(uint64_t size);
/*!
@brief Interpret Header_Extension tag information, and save it in
the respective XMP container.
@param size Size of the data block used to store Tag Data.
*/
void headerExtension(uint64_t size);
/*!
@brief Interpret Metadata, Extended_Content_Description,
Metadata_Library tag information, and save it in the respective
XMP container.
@param meta A default integer which helps to overload the function
for various Tags that have a similar method of decoding.
*/
void metadataHandler(int meta = 1);
/*!
@brief Calculates Aspect Ratio of a video, and stores it in the
respective XMP container.
*/
void aspectRatio();
private:
//! @name NOT Implemented
//@{
//! Copy constructor
AsfVideo(const AsfVideo& rhs);
//! Assignment operator
AsfVideo& operator=(const AsfVideo& rhs);
//@}
private:
//! Variable to check the end of metadata traversing.
bool continueTraversing_;
//! Variable which stores current position of the read pointer.
uint64_t localPosition_;
//! Variable which stores current stream being processsed.
int streamNumber_;
//! Variable to store height and width of a video frame.
uint64_t height_, width_;
}; //Class AsfVideo
// *****************************************************************************
// template, inline and free functions
// These could be static private functions on Image subclasses but then
// ImageFactory needs to be made a friend.
/*!
@brief Create a new AsfVideo instance and return an auto-pointer to it.
Caller owns the returned object and the auto-pointer ensures that
it will be deleted.
*/
EXIV2API Image::AutoPtr newAsfInstance(BasicIo::AutoPtr io, bool create);
//! Check if the file iIo is a Windows Asf Video.
EXIV2API bool isAsfType(BasicIo& iIo, bool advance);
} // namespace Exiv2
#endif // #ifndef ASFVIDEO_HPP_
| gnidorah/xpiks | vendors/exiv2-0.25/include/exiv2/asfvideo.hpp | C++ | gpl-3.0 | 6,875 |
import bpy
camera = bpy.context.edit_movieclip.tracking.camera
camera.sensor_width = 23.6
camera.units = 'MILLIMETERS'
camera.pixel_aspect = 1
camera.k1 = 0.0
camera.k2 = 0.0
camera.k3 = 0.0
| Microvellum/Fluid-Designer | win64-vc/2.78/scripts/presets/tracking_camera/Nikon_DX.py | Python | gpl-3.0 | 192 |
"""
Tools and data structures for working with genomic intervals (or sets of
regions on a line in general) efficiently.
"""
# For compatiblity with existing stuff
from bx.intervals.intersection import * | dnanexus/rseqc | rseqc/lib/bx/intervals/__init__.py | Python | gpl-3.0 | 204 |
# -*- coding: utf-8 -*-
from ..internal.DeadCrypter import DeadCrypter
class Movie2KTo(DeadCrypter):
__name__ = "Movie2KTo"
__type__ = "crypter"
__version__ = "0.56"
__status__ = "stable"
__pattern__ = r'http://(?:www\.)?movie2k\.to/(.+)\.html'
__config__ = [("activated", "bool", "Activated", True)]
__description__ = """Movie2k.to decrypter plugin"""
__license__ = "GPLv3"
__authors__ = [("4Christopher", "4Christopher@gmx.de")]
| TheBraveWarrior/pyload | module/plugins/crypter/Movie2KTo.py | Python | gpl-3.0 | 472 |
/**
* Model that represents our form template.
*
* @package Ninja Forms client
* @copyright (c) 2017 WP Ninjas
* @since 3.0
*/
define( [], function() {
var model = Backbone.Model.extend( {
defaults: {
objectType: 'template',
id: 'none',
title: 'unknown'
},
initialize: function() {
this.set( 'desc', this.get( 'template-desc' ) );
}
} );
return model;
} ); | dexxtr/osbb-web-manager | www/wp-content/plugins/ninja-forms/client/dashboard/models/formTemplateModel.js | JavaScript | gpl-3.0 | 441 |
package org.thoughtcrime.securesms.video;
import android.media.MediaDataSource;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import org.thoughtcrime.securesms.crypto.AttachmentSecret;
import org.thoughtcrime.securesms.crypto.ClassicDecryptingPartInputStream;
import org.thoughtcrime.securesms.util.Util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@RequiresApi(23)
final class ClassicEncryptedMediaDataSource extends MediaDataSource {
private final AttachmentSecret attachmentSecret;
private final File mediaFile;
private final long length;
ClassicEncryptedMediaDataSource(@NonNull AttachmentSecret attachmentSecret, @NonNull File mediaFile, long length) {
this.attachmentSecret = attachmentSecret;
this.mediaFile = mediaFile;
this.length = length;
}
@Override
public int readAt(long position, byte[] bytes, int offset, int length) throws IOException {
try (InputStream inputStream = ClassicDecryptingPartInputStream.createFor(attachmentSecret, mediaFile)) {
byte[] buffer = new byte[4096];
long headerRemaining = position;
while (headerRemaining > 0) {
int read = inputStream.read(buffer, 0, Util.toIntExact(Math.min((long)buffer.length, headerRemaining)));
if (read == -1) return -1;
headerRemaining -= read;
}
return inputStream.read(bytes, offset, length);
}
}
@Override
public long getSize() {
return length;
}
@Override
public void close() {}
}
| jtracey/Signal-Android | src/org/thoughtcrime/securesms/video/ClassicEncryptedMediaDataSource.java | Java | gpl-3.0 | 1,585 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_ike_peer
short_description: Manage IPSec IKE Peer configuration on BIG-IP
description:
- Manage IPSec IKE Peer configuration on BIG-IP.
version_added: 2.8
options:
name:
description:
- Specifies the name of the IKE peer.
required: True
description:
description:
- Description of the IKE peer.
version:
description:
- Specifies which version of IKE is used.
- If the system you are configuring is the IPsec initiator, and you select
both versions, the system tries using IKEv2 for negotiation. If the remote
peer does not support IKEv2, the IPsec tunnel fails. To use IKEv1 in this
case, you must deselect Version 2 and try again.
- If the system you are configuring is the IPsec responder, and you select
both versions, the IPsec initiator system determines which IKE version to use.
- When creating a new IKE peer, this value is required.
choices:
- v1
- v2
presented_id_type:
description:
- Specifies the identifier type that the local system uses to identify
itself to the peer during IKE Phase 1 negotiations.
choices:
- address
- asn1dn
- fqdn
- keyid-tag
- user-fqdn
- override
presented_id_value:
description:
- This is a required value when C(version) includes (Cv2).
- Specifies a value for the identity when using a C(presented_id_type) of
C(override).
verified_id_type:
description:
- Specifies the identifier type that the local system uses to identify
the peer during IKE Phase 1 negotiation.
- This is a required value when C(version) includes (Cv2).
- When C(user-fqdn), value of C(verified_id_value) must be in the form of
User @ DNS domain string.
choices:
- address
- asn1dn
- fqdn
- keyid-tag
- user-fqdn
- override
verified_id_value:
description:
- This is a required value when C(version) includes (Cv2).
- Specifies a value for the identity when using a C(verified_id_type) of
C(override).
phase1_auth_method:
description:
- Specifies the authentication method for phase 1 negotiation.
- When creating a new IKE peer, if this value is not specified, the default is
C(rsa-signature).
choices:
- pre-shared-key
- rsa-signature
phase1_cert:
description:
- Specifies the digital certificate to use for the RSA signature.
- When creating a new IKE peer, if this value is not specified, and
C(phase1_auth_method) is C(rsa-signature), the default is C(default.crt).
- This parameter is invalid when C(phase1_auth_method) is C(pre-shared-key).
phase1_key:
description:
- Specifies the public key that the digital certificate contains.
- When creating a new IKE peer, if this value is not specified, and
C(phase1_auth_method) is C(rsa-signature), the default is C(default.key).
- This parameter is invalid when C(phase1_auth_method) is C(pre-shared-key).
phase1_verify_peer_cert:
description:
- In IKEv2, specifies whether the certificate sent by the IKE peer is verified
using the Trusted Certificate Authorities, a CRL, and/or a peer certificate.
- In IKEv1, specifies whether the identifier sent by the peer is verified with
the credentials in the certificate, in the following manner - ASN1DN; specifies
that the entire certificate subject name is compared with the identifier.
Address, FQDN, or User FQDN; specifies that the certificate's subjectAltName is
compared with the identifier. If the two do not match, the negotiation fails.
- When creating a new IKE peer, if this value is not specified, and
C(phase1_auth_method) is C(rsa-signature), the default is C(no).
- This parameter is invalid when C(phase1_auth_method) is C(pre-shared-key).
type: bool
preshared_key:
description:
- Specifies a string that the IKE peers share for authenticating each other.
- This parameter is only relevant when C(phase1_auth_method) is C(pre-shared-key).
- This parameter is invalid when C(phase1_auth_method) is C(rsa-signature).
remote_address:
description:
- Displays the IP address of the BIG-IP system that is remote to the system
you are configuring.
phase1_encryption_algorithm:
description:
- Specifies the algorithm to use for IKE encryption.
- IKE C(version) C(v2) does not support C(blowfish), C(camellia), or C(cast128).
choices:
- 3des
- des
- blowfish
- cast128
- aes128
- aes192
- aes256
- camellia
phase1_hash_algorithm:
description:
- Specifies the algorithm to use for IKE authentication.
choices:
- sha1
- md5
- sha256
- sha384
- sha512
phase1_perfect_forward_secrecy:
description:
- Specifies the Diffie-Hellman group to use for IKE Phase 1 and Phase 2 negotiations.
choices:
- ecp256
- ecp384
- ecp521
- modp768
- modp1024
- modp1536
- modp2048
- modp3072
- modp4096
- modp6144
- modp8192
update_password:
description:
- C(always) will allow to update passwords if the user chooses to do so.
C(on_create) will only set the password for newly created IKE peers.
default: always
choices:
- always
- on_create
partition:
description:
- Device partition to manage resources on.
default: Common
state:
description:
- When C(present), ensures that the resource exists.
- When C(absent), ensures the resource is removed.
default: present
choices:
- present
- absent
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
- Wojciech Wypior (@wojtek0806)
'''
EXAMPLES = r'''
- name: Create a ...
bigip_ike_peer:
name: foo
provider:
password: secret
server: lb.mydomain.com
user: admin
delegate_to: localhost
'''
RETURN = r'''
presented_id_type:
description: The new Presented ID Type value of the resource.
returned: changed
type: string
sample: address
verified_id_type:
description: The new Verified ID Type value of the resource.
returned: changed
type: string
sample: address
phase1_auth_method:
description: The new IKE Phase 1 Credentials Authentication Method value of the resource.
returned: changed
type: string
sample: rsa-signature
remote_address:
description: The new Remote Address value of the resource.
returned: changed
type: string
sample: 1.2.2.1
version:
description: The new list of IKE versions.
returned: changed
type: list
sample: ['v1', 'v2']
phase1_encryption_algorithm:
description: The new IKE Phase 1 Encryption Algorithm.
returned: changed
type: string
sample: 3des
phase1_hash_algorithm:
description: The new IKE Phase 1 Authentication Algorithm.
returned: changed
type: string
sample: sha256
phase1_perfect_forward_secrecy:
description: The new IKE Phase 1 Perfect Forward Secrecy.
returned: changed
type: string
sample: modp1024
phase1_cert:
description: The new IKE Phase 1 Certificate Credentials.
returned: changed
type: string
sample: /Common/cert1.crt
phase1_key:
description: The new IKE Phase 1 Key Credentials.
returned: changed
type: string
sample: /Common/cert1.key
phase1_verify_peer_cert:
description: The new IKE Phase 1 Key Verify Peer Certificate setting.
returned: changed
type: bool
sample: yes
verified_id_value:
description: The new Verified ID Value setting for the Verified ID Type.
returned: changed
type: string
sample: 1.2.3.1
presented_id_value:
description: The new Presented ID Value setting for the Presented ID Type.
returned: changed
type: string
sample: 1.2.3.1
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
try:
from library.module_utils.network.f5.bigip import F5RestClient
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import fq_name
from library.module_utils.network.f5.common import f5_argument_spec
from library.module_utils.network.f5.common import exit_json
from library.module_utils.network.f5.common import fail_json
from library.module_utils.network.f5.common import transform_name
from library.module_utils.network.f5.common import flatten_boolean
from library.module_utils.network.f5.compare import cmp_str_with_none
except ImportError:
from ansible.module_utils.network.f5.bigip import F5RestClient
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import fq_name
from ansible.module_utils.network.f5.common import f5_argument_spec
from ansible.module_utils.network.f5.common import exit_json
from ansible.module_utils.network.f5.common import fail_json
from ansible.module_utils.network.f5.common import transform_name
from ansible.module_utils.network.f5.common import flatten_boolean
from ansible.module_utils.network.f5.compare import cmp_str_with_none
class Parameters(AnsibleF5Parameters):
api_map = {
'myIdType': 'presented_id_type',
'peersIdType': 'verified_id_type',
'phase1AuthMethod': 'phase1_auth_method',
'presharedKeyEncrypted': 'preshared_key',
'remoteAddress': 'remote_address',
'version': 'version',
'phase1EncryptAlgorithm': 'phase1_encryption_algorithm',
'phase1HashAlgorithm': 'phase1_hash_algorithm',
'phase1PerfectForwardSecrecy': 'phase1_perfect_forward_secrecy',
'myCertFile': 'phase1_cert',
'myCertKeyFile': 'phase1_key',
'verifyCert': 'phase1_verify_peer_cert',
'peersIdValue': 'verified_id_value',
'myIdValue': 'presented_id_value',
}
api_attributes = [
'myIdType',
'peersIdType',
'phase1AuthMethod',
'presharedKeyEncrypted',
'remoteAddress',
'version',
'phase1EncryptAlgorithm',
'phase1HashAlgorithm',
'phase1PerfectForwardSecrecy',
'myCertFile',
'myCertKeyFile',
'verifyCert',
'peersIdValue',
'myIdValue',
'description',
]
returnables = [
'presented_id_type',
'verified_id_type',
'phase1_auth_method',
'preshared_key',
'remote_address',
'version',
'phase1_encryption_algorithm',
'phase1_hash_algorithm',
'phase1_perfect_forward_secrecy',
'phase1_cert',
'phase1_key',
'phase1_verify_peer_cert',
'verified_id_value',
'presented_id_value',
'description',
]
updatables = [
'presented_id_type',
'verified_id_type',
'phase1_auth_method',
'preshared_key',
'remote_address',
'version',
'phase1_encryption_algorithm',
'phase1_hash_algorithm',
'phase1_perfect_forward_secrecy',
'phase1_cert',
'phase1_key',
'phase1_verify_peer_cert',
'verified_id_value',
'presented_id_value',
'description',
]
@property
def phase1_verify_peer_cert(self):
return flatten_boolean(self._values['phase1_verify_peer_cert'])
class ApiParameters(Parameters):
@property
def description(self):
if self._values['description'] in [None, 'none']:
return None
return self._values['description']
class ModuleParameters(Parameters):
@property
def phase1_cert(self):
if self._values['phase1_cert'] is None:
return None
if self._values['phase1_cert'] in ['', 'none']:
return ''
return fq_name(self.partition, self._values['phase1_cert'])
@property
def phase1_key(self):
if self._values['phase1_key'] is None:
return None
if self._values['phase1_key'] in ['', 'none']:
return ''
return fq_name(self.partition, self._values['phase1_key'])
@property
def description(self):
if self._values['description'] is None:
return None
elif self._values['description'] in ['none', '']:
return ''
return self._values['description']
class Changes(Parameters):
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
pass
return result
class UsableChanges(Changes):
@property
def phase1_verify_peer_cert(self):
if self._values['phase1_verify_peer_cert'] is None:
return None
elif self._values['phase1_verify_peer_cert'] == 'yes':
return 'true'
else:
return 'false'
class ReportableChanges(Changes):
@property
def phase1_verify_peer_cert(self):
return flatten_boolean(self._values['phase1_verify_peer_cert'])
@property
def preshared_key(self):
return None
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
@property
def description(self):
return cmp_str_with_none(self.want.description, self.have.description)
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.want = ModuleParameters(params=self.module.params)
self.have = ApiParameters()
self.changes = UsableChanges()
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = UsableChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def exec_module(self):
changed = False
result = dict()
state = self.want.state
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
return result
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def exists(self):
uri = "https://{0}:{1}/mgmt/tm/net/ipsec/ike-peer/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError:
return False
if resp.status == 404 or 'code' in response and response['code'] == 404:
return False
return True
def update(self):
self.have = self.read_current_from_device()
if self.changes.version is not None and len(self.changes.version) == 0:
raise F5ModuleError(
"At least one version value must be specified."
)
if self.changes.phase1_auth_method == 'pre-shared-key':
if self.changes.preshared_key is None and self.have.preshared_key is None:
raise F5ModuleError(
"A 'preshared_key' must be specified when changing 'phase1_auth_method' "
"to 'pre-shared-key'."
)
if self.want.update_password == 'always':
self.want.update({'preshared_key': self.want.preshared_key})
else:
if self.want.preshared_key:
del self.want._values['preshared_key']
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def remove(self):
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the resource.")
return True
def create(self):
self._set_changed_options()
if self.changes.version is None:
raise F5ModuleError(
"The 'version' parameter is required when creating a new IKE peer."
)
if self.changes.phase1_auth_method is None:
self.changes.update({'phase1_auth_method': 'rsa-signature'})
if self.changes.phase1_cert is None:
self.changes.update({'phase1_cert': 'default.crt'})
if self.changes.phase1_key is None:
self.changes.update({'phase1_key': 'default.key'})
if self.module.check_mode:
return True
self.create_on_device()
return True
def create_on_device(self):
params = self.changes.api_params()
params['name'] = self.want.name
params['partition'] = self.want.partition
uri = "https://{0}:{1}/mgmt/tm/net/ipsec/ike-peer/".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def update_on_device(self):
params = self.changes.api_params()
uri = "https://{0}:{1}/mgmt/tm/net/ipsec/ike-peer/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.patch(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def absent(self):
if self.exists():
return self.remove()
return False
def remove_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/net/ipsec/ike-peer/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.delete(uri)
if resp.status == 200:
return True
def read_current_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/net/ipsec/ike-peer/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return ApiParameters(params=response)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
name=dict(required=True),
presented_id_type=dict(
choices=['address', 'asn1dn', 'fqdn', 'keyid-tag', 'user-fqdn', 'override']
),
presented_id_value=dict(),
verified_id_type=dict(
choices=['address', 'asn1dn', 'fqdn', 'keyid-tag', 'user-fqdn', 'override']
),
verified_id_value=dict(),
phase1_auth_method=dict(
choices=[
'pre-shared-key', 'rsa-signature'
]
),
preshared_key=dict(no_log=True),
remote_address=dict(),
version=dict(
type='list',
choices=['v1', 'v2']
),
phase1_encryption_algorithm=dict(
choices=[
'3des', 'des', 'blowfish', 'cast128', 'aes128', 'aes192',
'aes256', 'camellia'
]
),
phase1_hash_algorithm=dict(
choices=[
'sha1', 'md5', 'sha256', 'sha384', 'sha512'
]
),
phase1_perfect_forward_secrecy=dict(
choices=[
'ecp256', 'ecp384', 'ecp521', 'modp768', 'modp1024', 'modp1536',
'modp2048', 'modp3072', 'modp4096', 'modp6144', 'modp8192'
]
),
phase1_cert=dict(),
phase1_key=dict(),
phase1_verify_peer_cert=dict(type='bool'),
update_password=dict(
default='always',
choices=['always', 'on_create']
),
description=dict(),
state=dict(default='present', choices=['absent', 'present']),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
self.required_if = [
['presented_id_type', 'fqdn', ['presented_id_value']],
['presented_id_type', 'keyid-tag', ['presented_id_value']],
['presented_id_type', 'user-fqdn', ['presented_id_value']],
['presented_id_type', 'override', ['presented_id_value']],
['verified_id_type', 'fqdn', ['verified_id_value']],
['verified_id_type', 'keyid-tag', ['verified_id_value']],
['verified_id_type', 'user-fqdn', ['verified_id_value']],
['verified_id_type', 'override', ['verified_id_value']],
]
self.required_together = [
['phase1_cert', 'phase1_key']
]
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
required_if=spec.required_if,
required_together=spec.required_together,
)
client = F5RestClient(**module.params)
try:
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
exit_json(module, results, client)
except F5ModuleError as ex:
cleanup_tokens(client)
fail_json(module, ex, client)
if __name__ == '__main__':
main()
| yfried/ansible | lib/ansible/modules/network/f5/bigip_ike_peer.py | Python | gpl-3.0 | 25,483 |
/*
* The JTS Topology Suite is a collection of Java classes that
* implement the fundamental operations required to validate a given
* geo-spatial data set to a known topological specification.
*
* Copyright (C) 2001 Vivid Solutions
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* For more information, contact:
*
* Vivid Solutions
* Suite #1A
* 2328 Government Street
* Victoria BC V8T 5G5
* Canada
*
* (250)385-6040
* www.vividsolutions.com
*/
package com.vividsolutions.jts.index.chain;
import java.util.*;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geomgraph.Quadrant;
/**
* Constructs {@link MonotoneChain}s
* for sequences of {@link Coordinate}s.
*
* @version 1.7
*/
public class MonotoneChainBuilder {
public static int[] toIntArray(List list)
{
int[] array = new int[list.size()];
for (int i = 0; i < array.length; i++) {
array[i] = ((Integer) list.get(i)).intValue();
}
return array;
}
public static List getChains(Coordinate[] pts)
{
return getChains(pts, null);
}
/**
* Return a list of the {@link MonotoneChain}s
* for the given list of coordinates.
*/
public static List getChains(Coordinate[] pts, Object context)
{
List mcList = new ArrayList();
int[] startIndex = getChainStartIndices(pts);
for (int i = 0; i < startIndex.length - 1; i++) {
MonotoneChain mc = new MonotoneChain(pts, startIndex[i], startIndex[i + 1], context);
mcList.add(mc);
}
return mcList;
}
/**
* Return an array containing lists of start/end indexes of the monotone chains
* for the given list of coordinates.
* The last entry in the array points to the end point of the point array,
* for use as a sentinel.
*/
public static int[] getChainStartIndices(Coordinate[] pts)
{
// find the startpoint (and endpoints) of all monotone chains in this edge
int start = 0;
List startIndexList = new ArrayList();
startIndexList.add(new Integer(start));
do {
int last = findChainEnd(pts, start);
startIndexList.add(new Integer(last));
start = last;
} while (start < pts.length - 1);
// copy list to an array of ints, for efficiency
int[] startIndex = toIntArray(startIndexList);
return startIndex;
}
/**
* Finds the index of the last point in a monotone chain
* starting at a given point.
* Any repeated points (0-length segments) will be included
* in the monotone chain returned.
*
* @return the index of the last point in the monotone chain
* starting at <code>start</code>.
*/
private static int findChainEnd(Coordinate[] pts, int start)
{
int safeStart = start;
// skip any zero-length segments at the start of the sequence
// (since they cannot be used to establish a quadrant)
while (safeStart < pts.length - 1 && pts[safeStart].equals2D(pts[safeStart + 1])) {
safeStart++;
}
// check if there are NO non-zero-length segments
if (safeStart >= pts.length - 1) {
return pts.length - 1;
}
// determine overall quadrant for chain (which is the starting quadrant)
int chainQuad = Quadrant.quadrant(pts[safeStart], pts[safeStart + 1]);
int last = start + 1;
while (last < pts.length) {
// skip zero-length segments, but include them in the chain
if (! pts[last - 1].equals2D(pts[last])) {
// compute quadrant for next possible segment in chain
int quad = Quadrant.quadrant(pts[last - 1], pts[last]);
if (quad != chainQuad) break;
}
last++;
}
return last - 1;
}
public MonotoneChainBuilder() {
}
}
| Jules-/terraingis | src/TerrainGIS/src/com/vividsolutions/jts/index/chain/MonotoneChainBuilder.java | Java | gpl-3.0 | 4,504 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | foam-extend: Open Source CFD
\\ / O peration |
\\ / A nd | For copyright notice see file Copyright
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of foam-extend.
foam-extend is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
foam-extend is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with foam-extend. If not, see <http://www.gnu.org/licenses/>.
Description
\*---------------------------------------------------------------------------*/
#include "writeFuns.H"
#include "interpolatePointToCell.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Store List in dest
template<class Type>
void Foam::writeFuns::insert
(
const List<Type>& source,
DynamicList<floatScalar>& dest
)
{
forAll(source, i)
{
insert(source[i], dest);
}
}
//// Store List (indexed through map) in dest
//template<class Type>
//void Foam::writeFuns::insert
//(
// const labelList& map,
// const List<Type>& source,
// DynamicList<floatScalar>& dest
//)
//{
// forAll(map, i)
// {
// insert(source[map[i]], dest);
// }
//}
template<class Type>
void Foam::writeFuns::write
(
std::ostream& os,
const bool binary,
const GeometricField<Type, fvPatchField, volMesh>& vvf,
const vtkMesh& vMesh
)
{
const fvMesh& mesh = vMesh.mesh();
const labelList& superCells = vMesh.topo().superCells();
label nValues = mesh.nCells() + superCells.size();
os << vvf.name() << ' ' << pTraits<Type>::nComponents << ' '
<< nValues << " float" << std::endl;
DynamicList<floatScalar> fField(pTraits<Type>::nComponents*nValues);
insert(vvf.internalField(), fField);
forAll(superCells, superCellI)
{
label origCellI = superCells[superCellI];
insert(vvf[origCellI], fField);
}
write(os, binary, fField);
}
template<class Type>
void Foam::writeFuns::write
(
std::ostream& os,
const bool binary,
const GeometricField<Type, pointPatchField, pointMesh>& pvf,
const vtkMesh& vMesh
)
{
const fvMesh& mesh = vMesh.mesh();
const vtkTopo& topo = vMesh.topo();
const labelList& addPointCellLabels = topo.addPointCellLabels();
const label nTotPoints = mesh.nPoints() + addPointCellLabels.size();
os << pvf.name() << ' ' << pTraits<Type>::nComponents << ' '
<< nTotPoints << " float" << std::endl;
DynamicList<floatScalar> fField(pTraits<Type>::nComponents*nTotPoints);
insert(pvf, fField);
forAll(addPointCellLabels, api)
{
label origCellI = addPointCellLabels[api];
insert(interpolatePointToCell(pvf, origCellI), fField);
}
write(os, binary, fField);
}
template<class Type>
void Foam::writeFuns::write
(
std::ostream& os,
const bool binary,
const GeometricField<Type, fvPatchField, volMesh>& vvf,
const GeometricField<Type, pointPatchField, pointMesh>& pvf,
const vtkMesh& vMesh
)
{
const fvMesh& mesh = vMesh.mesh();
const vtkTopo& topo = vMesh.topo();
const labelList& addPointCellLabels = topo.addPointCellLabels();
const label nTotPoints = mesh.nPoints() + addPointCellLabels.size();
os << vvf.name() << ' ' << pTraits<Type>::nComponents << ' '
<< nTotPoints << " float" << std::endl;
DynamicList<floatScalar> fField(pTraits<Type>::nComponents*nTotPoints);
insert(pvf, fField);
forAll(addPointCellLabels, api)
{
label origCellI = addPointCellLabels[api];
insert(vvf[origCellI], fField);
}
write(os, binary, fField);
}
template<class Type, template<class> class PatchField, class GeoMesh>
void Foam::writeFuns::write
(
std::ostream& os,
const bool binary,
const PtrList<GeometricField<Type, PatchField, GeoMesh> >& flds,
const vtkMesh& vMesh
)
{
forAll(flds, i)
{
write(os, binary, flds[i], vMesh);
}
}
template<class Type>
void Foam::writeFuns::write
(
std::ostream& os,
const bool binary,
const volPointInterpolation& pInterp,
const PtrList<GeometricField<Type, fvPatchField, volMesh> >& flds,
const vtkMesh& vMesh
)
{
forAll(flds, i)
{
write(os, binary, flds[i], pInterp.interpolate(flds[i])(), vMesh);
}
}
// ************************************************************************* //
| WensiWu/openfoam-extend-foam-extend-3.1 | applications/utilities/postProcessing/dataConversion/foamToVTK/writeFunsTemplates.C | C++ | gpl-3.0 | 5,008 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('sites', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('object_pk', models.TextField(verbose_name='object ID')),
('user_name', models.CharField(max_length=50, verbose_name="user's name", blank=True)),
('user_email', models.EmailField(max_length=254, verbose_name="user's email address", blank=True)),
('user_url', models.URLField(verbose_name="user's URL", blank=True)),
('comment', models.TextField(max_length=3000, verbose_name='comment')),
('submit_date', models.DateTimeField(default=None, verbose_name='date/time submitted', db_index=True)),
('ip_address', models.GenericIPAddressField(unpack_ipv4=True, null=True, verbose_name='IP address', blank=True)),
('is_public', models.BooleanField(default=True, help_text='Uncheck this box to make the comment effectively disappear from the site.', verbose_name='is public')),
('is_removed', models.BooleanField(default=False, help_text='Check this box if the comment is inappropriate. A "This comment has been removed" message will be displayed instead.', verbose_name='is removed')),
('content_type', models.ForeignKey(related_name='content_type_set_for_comment', verbose_name='content type', to='contenttypes.ContentType', on_delete=models.CASCADE)),
('site', models.ForeignKey(to='sites.Site', on_delete=models.CASCADE)),
('user', models.ForeignKey(related_name='comment_comments', verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)),
],
options={
'ordering': ('submit_date',),
'abstract': False,
'verbose_name': 'comment',
'verbose_name_plural': 'comments',
'permissions': [('can_moderate', 'Can moderate comments')],
},
),
]
| claudep/pootle | pootle/apps/pootle_comment/migrations/0001_initial.py | Python | gpl-3.0 | 2,477 |
class AddImmutableToUserfiles < ActiveRecord::Migration
def change
add_column :userfiles, :immutable, :boolean, :default => false
end
end
| crocodoyle/cbrain | BrainPortal/db/migrate/20130805152115_add_immutable_to_userfiles.rb | Ruby | gpl-3.0 | 146 |
########################################################################
# $HeadURL$
# File: ReqProxyHandler.py
# Author: Krzysztof.Ciba@NOSPAMgmail.com
# Date: 2013/06/04 13:18:41
########################################################################
"""
:mod: RequestProxyHandler
.. module: ReqtProxyHandler
:synopsis: ReqProxy service
.. moduleauthor:: Krzysztof.Ciba@NOSPAMgmail.com
Careful with that axe, Eugene! Some 'transfer' requests are using local fs
and they never should be forwarded to the central RequestManager.
"""
__RCSID__ = "$Id$"
# #
# @file RequestProxyHandler.py
# @author Krzysztof.Ciba@NOSPAMgmail.com
# @date 2012/07/20 13:18:58
# @brief Definition of RequestProxyHandler class.
# # imports
import os
from types import DictType
try:
from hashlib import md5
except ImportError:
from md5 import md5
# # from DIRAC
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.DISET.RequestHandler import RequestHandler
from DIRAC.Core.DISET.RPCClient import RPCClient
from DIRAC.RequestManagementSystem.Client.Request import Request
from DIRAC.Core.Utilities.ThreadScheduler import gThreadScheduler
def initializeReqProxyHandler( serviceInfo ):
""" init RequestProxy handler
:param serviceInfo: whatever
"""
gLogger.info( "Initalizing ReqProxyHandler" )
gThreadScheduler.addPeriodicTask( 120, ReqProxyHandler.sweeper )
return S_OK()
########################################################################
class ReqProxyHandler( RequestHandler ):
"""
.. class:: ReqProxyHandler
:param RPCCLient requestManager: a RPCClient to RequestManager
:param str cacheDir: os.path.join( workDir, "requestCache" )
"""
__requestManager = None
__cacheDir = None
def initialize( self ):
""" service initialization
:param self: self reference
"""
gLogger.notice( "CacheDirectory: %s" % self.cacheDir() )
return S_OK()
@classmethod
def requestManager( cls ):
""" get request manager """
if not cls.__requestManager:
cls.__requestManager = RPCClient( "RequestManagement/ReqManager" )
return cls.__requestManager
@classmethod
def cacheDir( cls ):
""" get cache dir """
if not cls.__cacheDir:
cls.__cacheDir = os.path.abspath( "requestCache" )
if not os.path.exists( cls.__cacheDir ):
os.mkdir( cls.__cacheDir )
return cls.__cacheDir
@classmethod
def sweeper( cls ):
""" move cached request to the central request manager
:param self: self reference
"""
cacheDir = cls.cacheDir()
# # cache dir empty?
if not os.listdir( cacheDir ):
gLogger.always( "sweeper: CacheDir %s is empty, nothing to do" % cacheDir )
return S_OK()
else:
# # read 10 cache dir files, the oldest first
cachedRequests = [ os.path.abspath( requestFile ) for requestFile in
sorted( filter( os.path.isfile,
[ os.path.join( cacheDir, requestName )
for requestName in os.listdir( cacheDir ) ] ),
key = os.path.getctime ) ][:10]
# # set cached requests to the central RequestManager
for cachedFile in cachedRequests:
# # break if something went wrong last time
try:
requestString = "".join( open( cachedFile, "r" ).readlines() )
cachedRequest = eval( requestString )
cachedName = cachedRequest.get( "RequestName", "***UNKNOWN***" )
setRequest = cls.requestManager().putRequest( cachedRequest )
if not setRequest["OK"]:
gLogger.error( "sweeper: unable to set request %s @ ReqManager: %s" % ( cachedName,
setRequest["Message"] ) )
continue
gLogger.info( "sweeper: successfully set request '%s' @ ReqManager" % cachedName )
os.unlink( cachedFile )
except Exception, error:
gLogger.exception( "sweeper: hit by exception %s" % str( error ) )
return S_ERROR( "sweeper: hit by exception: %s" % str( error ) )
return S_OK()
def __saveRequest( self, requestName, requestJSON ):
""" save request string to the working dir cache
:param self: self reference
:param str requestName: request name
:param str requestJSON: request serialized to JSON format
"""
try:
requestFile = os.path.join( self.cacheDir(), md5( str( requestJSON ) ).hexdigest() )
request = open( requestFile, "w+" )
request.write( str( requestJSON ) )
request.close()
return S_OK( requestFile )
except OSError, error:
err = "unable to dump %s to cache file: %s" % ( requestName, str( error ) )
gLogger.exception( err )
return S_ERROR( err )
types_getStatus = []
def export_getStatus( self ):
""" get number of requests in cache """
try:
cachedRequests = len( os.listdir( self.cacheDir() ) )
except OSError, error:
err = "getStatus: unable to list cache dir contents: %s" % str( error )
gLogger.exception( err )
return S_ERROR( err )
return S_OK( cachedRequests )
types_putRequest = [ DictType ]
def export_putRequest( self, requestJSON ):
""" forward request from local RequestDB to central RequestManager
:param self: self reference
:param str requestType: request type
"""
requestName = requestJSON.get( "RequestName", "***UNKNOWN***" )
gLogger.info( "setRequest: got request '%s'" % requestName )
forwardable = self.__forwardable( requestJSON )
if not forwardable["OK"]:
gLogger.warn( "setRequest: %s" % forwardable["Message"] )
setRequest = self.requestManager().putRequest( requestJSON )
if not setRequest["OK"]:
gLogger.error( "setReqeuest: unable to set request '%s' @ RequestManager: %s" % ( requestName,
setRequest["Message"] ) )
# # put request to the request file cache
save = self.__saveRequest( requestName, requestJSON )
if not save["OK"]:
gLogger.error( "setRequest: unable to save request to the cache: %s" % save["Message"] )
return save
gLogger.info( "setRequest: %s is saved to %s file" % ( requestName, save["Value"] ) )
return S_OK( { "set" : False, "saved" : True } )
gLogger.info( "setRequest: request '%s' has been set to the ReqManager" % ( requestName ) )
return S_OK( { "set" : True, "saved" : False } )
@staticmethod
def __forwardable( requestJSON ):
""" check if request if forwardable
The sub-request of type transfer:putAndRegister, removal:physicalRemoval and removal:reTransfer are
definitely not, they should be executed locally, as they are using local fs.
:param str requestJSON: serialized request
"""
operations = requestJSON.get( "Operations", [] )
for operationDict in operations:
if operationDict.get( "Type", "" ) in ( "PutAndRegister", "PhysicalRemoval", "ReTransfer" ):
return S_ERROR( "found operation '%s' that cannot be forwarded" % operationDict.get( "Type", "" ) )
return S_OK()
| Sbalbp/DIRAC | RequestManagementSystem/Service/ReqProxyHandler.py | Python | gpl-3.0 | 7,200 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('trans', '0045_auto_20150916_1007'),
]
operations = [
migrations.CreateModel(
name='Billing',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
],
),
migrations.CreateModel(
name='Plan',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(unique=True, max_length=100)),
('price', models.IntegerField()),
('limit_strings', models.IntegerField()),
('limit_languages', models.IntegerField()),
('limit_repositories', models.IntegerField()),
('limit_projects', models.IntegerField()),
],
options={
'ordering': ['name'],
},
),
migrations.AddField(
model_name='billing',
name='plan',
field=models.ForeignKey(to='billing.Plan'),
),
migrations.AddField(
model_name='billing',
name='projects',
field=models.ManyToManyField(to='trans.Project', blank=True),
),
migrations.AddField(
model_name='billing',
name='user',
field=models.OneToOneField(to=settings.AUTH_USER_MODEL),
),
]
| miumok98/weblate | weblate/billing/migrations/0001_initial.py | Python | gpl-3.0 | 1,726 |
/**
* Aptana Studio
* Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
* Please see the license.html included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.ide.ui.io.navigator;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.viewers.Viewer;
import com.aptana.core.util.ArrayUtil;
import com.aptana.ide.core.io.CoreIOPlugin;
import com.aptana.ui.util.UIUtils;
public class ProjectExplorerContentProvider extends FileTreeContentProvider
{
private static final String LOCAL_SHORTCUTS_ID = "com.aptana.ide.core.io.localShortcuts"; //$NON-NLS-1$
private Viewer treeViewer;
private IResourceChangeListener resourceListener = new IResourceChangeListener()
{
public void resourceChanged(IResourceChangeEvent event)
{
// to fix https://jira.appcelerator.org/browse/TISTUD-1695, we need to force a selection update when a
// project is closed or opened
if (shouldUpdateActions(event.getDelta()))
{
UIUtils.getDisplay().asyncExec(new Runnable()
{
public void run()
{
treeViewer.setSelection(treeViewer.getSelection());
}
});
}
}
};
public ProjectExplorerContentProvider()
{
ResourcesPlugin.getWorkspace().addResourceChangeListener(resourceListener, IResourceChangeEvent.POST_CHANGE);
}
@Override
public void dispose()
{
ResourcesPlugin.getWorkspace().removeResourceChangeListener(resourceListener);
super.dispose();
}
@Override
public Object[] getChildren(Object parentElement)
{
if (parentElement instanceof IResource)
{
return ArrayUtil.NO_OBJECTS;
}
return super.getChildren(parentElement);
}
@Override
public Object[] getElements(Object inputElement)
{
if (inputElement instanceof IWorkspaceRoot)
{
List<Object> children = new ArrayList<Object>();
children.add(LocalFileSystems.getInstance());
children.add(CoreIOPlugin.getConnectionPointManager().getConnectionPointCategory(LOCAL_SHORTCUTS_ID));
return children.toArray(new Object[children.size()]);
}
return super.getElements(inputElement);
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
treeViewer = viewer;
super.inputChanged(viewer, oldInput, newInput);
}
private boolean shouldUpdateActions(IResourceDelta delta)
{
if (delta.getFlags() == IResourceDelta.OPEN)
{
return true;
}
IResourceDelta[] children = delta.getAffectedChildren();
for (IResourceDelta child : children)
{
if (shouldUpdateActions(child))
{
return true;
}
}
return false;
}
}
| HossainKhademian/Studio3 | plugins/com.aptana.ui.io/src/com/aptana/ide/ui/io/navigator/ProjectExplorerContentProvider.java | Java | gpl-3.0 | 3,028 |
require_relative "../client"
require_relative "../request"
require_relative "../response"
module Vault
class Client
# A proxy to the {Sys} methods.
# @return [Sys]
def sys
@sys ||= Sys.new(self)
end
end
class Sys < Request; end
end
require_relative "sys/audit"
require_relative "sys/auth"
require_relative "sys/init"
require_relative "sys/leader"
require_relative "sys/lease"
require_relative "sys/mount"
require_relative "sys/policy"
require_relative "sys/seal"
| NicheProject/vault-ruby | lib/vault/api/sys.rb | Ruby | mpl-2.0 | 494 |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/language/v1beta2/language_service.proto
namespace Google\Cloud\Language\V1beta2;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* The entity analysis request message.
*
* Generated from protobuf message <code>google.cloud.language.v1beta2.AnalyzeEntitiesRequest</code>
*/
class AnalyzeEntitiesRequest extends \Google\Protobuf\Internal\Message
{
/**
* Input document.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.Document document = 1;</code>
*/
private $document = null;
/**
* The encoding type used by the API to calculate offsets.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.EncodingType encoding_type = 2;</code>
*/
private $encoding_type = 0;
public function __construct() {
\GPBMetadata\Google\Cloud\Language\V1Beta2\LanguageService::initOnce();
parent::__construct();
}
/**
* Input document.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.Document document = 1;</code>
* @return \Google\Cloud\Language\V1beta2\Document
*/
public function getDocument()
{
return $this->document;
}
/**
* Input document.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.Document document = 1;</code>
* @param \Google\Cloud\Language\V1beta2\Document $var
* @return $this
*/
public function setDocument($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Language\V1beta2\Document::class);
$this->document = $var;
return $this;
}
/**
* The encoding type used by the API to calculate offsets.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.EncodingType encoding_type = 2;</code>
* @return int
*/
public function getEncodingType()
{
return $this->encoding_type;
}
/**
* The encoding type used by the API to calculate offsets.
*
* Generated from protobuf field <code>.google.cloud.language.v1beta2.EncodingType encoding_type = 2;</code>
* @param int $var
* @return $this
*/
public function setEncodingType($var)
{
GPBUtil::checkEnum($var, \Google\Cloud\Language\V1beta2\EncodingType::class);
$this->encoding_type = $var;
return $this;
}
}
| wlwwt/shopware | vendor/google/proto-client/src/Google/Cloud/Language/V1beta2/AnalyzeEntitiesRequest.php | PHP | agpl-3.0 | 2,541 |
/* This file is part of VoltDB.
* Copyright (C) 2008-2015 VoltDB 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.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.groovy;
import static java.lang.Character.toLowerCase;
import static java.lang.Character.toUpperCase;
import groovy.lang.Closure;
import groovy.lang.GString;
import groovy.lang.GroovyObjectSupport;
import java.util.NavigableMap;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import com.google_voltpatches.common.collect.ImmutableSortedMap;
/**
* Groovy table access expediter. It allows you to easily navigate a VoltTable,
* and access its column values.
* <p>
* Example usage on a query that returns results for the :
* <code><pre>
* cr = client.callProcedure('@AdHoc','select INTEGER_COL, STRING_COL from FOO')
* tuplerator(cr.results[0]).eachRow {
*
* integerColValueByIndex = it[0]
* stringColValueByIndex = it[1]
*
* integerColValueByName = it['integerCol']
* stringColValyeByName = it['stringCol']
*
* integerColValueByField = it.integerCol
* stringColValyeByField = it.stringCol
* }
*
* </code></pre>
*
*/
public class Tuplerator extends GroovyObjectSupport {
private final VoltTable table;
private final VoltType [] byIndex;
private final NavigableMap<String, Integer> byName;
public static Tuplerator newInstance(VoltTable table) {
return new Tuplerator(table);
}
public Tuplerator(final VoltTable table) {
this.table = table;
this.byIndex = new VoltType[table.getColumnCount()];
ImmutableSortedMap.Builder<String, Integer> byNameBuilder =
ImmutableSortedMap.naturalOrder();
for (int c = 0; c < byIndex.length; ++c) {
VoltType cType = table.getColumnType(c);
StringBuilder cName = new StringBuilder(table.getColumnName(c));
byIndex[c] = cType;
boolean upperCaseIt = false;
for (int i = 0; i < cName.length();) {
char chr = cName.charAt(i);
if (chr == '_' || chr == '.' || chr == '$') {
cName.deleteCharAt(i);
upperCaseIt = true;
} else {
chr = upperCaseIt ? toUpperCase(chr) : toLowerCase(chr);
cName.setCharAt(i, chr);
upperCaseIt = false;
++i;
}
}
byNameBuilder.put(cName.toString(),c);
}
byName = byNameBuilder.build();
}
/**
* It calls the given closure on each row of the underlying table by passing itself
* as the only closure parameter
*
* @param c the self instance of Tuplerator
*/
public void eachRow(Closure<Void> c) {
while (table.advanceRow()) {
c.call(this);
}
table.resetRowPosition();
}
/**
* It calls the given closure on each row of the underlying table for up to the specified limit,
* by passing itself as the only closure parameter
*
* @param maxRows maximum rows to call the closure on
* @param c closure
*/
public void eachRow(int maxRows, Closure<Void> c) {
while (--maxRows >= 0 && table.advanceRow()) {
c.call(this);
}
}
public Object getAt(int cidx) {
Object cval = table.get(cidx, byIndex[cidx]);
if (table.wasNull()) cval = null;
return cval;
}
public Object getAt(String cname) {
Integer cidx = byName.get(cname);
if (cidx == null) {
throw new IllegalArgumentException("No Column named '" + cname + "'");
}
return getAt(cidx);
}
public Object getAt(GString cname) {
return getAt(cname.toString());
}
@Override
public Object getProperty(String name) {
return getAt(name);
}
/**
* Sets the table row cursor to the given position
* @param num row number to set the row cursor to
* @return an instance of self
*/
public Tuplerator atRow(int num) {
table.advanceToRow(num);
return this;
}
/**
* Resets the table row cursor
* @return an instance of self
*/
public Tuplerator reset() {
table.resetRowPosition();
return this;
}
/**
* Returns the underlying table
* @return the underlying table
*/
public VoltTable getTable() {
return table;
}
}
| wolffcm/voltdb | src/frontend/org/voltdb/groovy/Tuplerator.java | Java | agpl-3.0 | 5,058 |
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
function additionalDetailsCampaign($fields) {
static $mod_strings;
if(empty($mod_strings)) {
global $current_language;
$mod_strings = return_module_language($current_language, 'Campaigns');
}
$overlib_string = '';
if(!empty($fields['START_DATE']))
$overlib_string .= '<b>'. $mod_strings['LBL_CAMPAIGN_START_DATE'] . '</b> ' . $fields['START_DATE'] . '<br>';
if(!empty($fields['TRACKER_TEXT']))
$overlib_string .= '<b>'. $mod_strings['LBL_TRACKER_TEXT'] . '</b> ' . $fields['TRACKER_TEXT'] . '<br>';
if(!empty($fields['REFER_URL']))
$overlib_string .= '<a target=_blank href='. $fields['REFER_URL'] . '>' . $fields['REFER_URL'] . '</a><br>';
if(!empty($fields['OBJECTIVE'])) {
$overlib_string .= '<b>'. $mod_strings['LBL_CAMPAIGN_OBJECTIVE'] . '</b> ' . substr($fields['OBJECTIVE'], 0, 300);
if(strlen($fields['OBJECTIVE']) > 300) $overlib_string .= '...';
$overlib_string .= '<br>';
}
if(!empty($fields['CONTENT'])) {
$overlib_string .= '<b>'. $mod_strings['LBL_CAMPAIGN_CONTENT'] . '</b> ' . substr($fields['CONTENT'], 0, 300);
if(strlen($fields['CONTENT']) > 300) $overlib_string .= '...';
}
return array('fieldToAddTo' => 'NAME',
'string' => $overlib_string,
'editLink' => "index.php?action=EditView&module=Campaigns&return_module=Campaigns&record={$fields['ID']}",
'viewLink' => "index.php?action=DetailView&module=Campaigns&return_module=Campaigns&record={$fields['ID']}");
}
?>
| shahrooz33ce/sugarcrm | modules/Campaigns/metadata/additionalDetails.php | PHP | agpl-3.0 | 3,552 |
/**
* Copyright 2007-2015, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.k3po.driver.internal.behavior.handler.codec.http;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.US_ASCII;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.kaazing.k3po.driver.internal.behavior.handler.codec.ConfigEncoder;
import org.kaazing.k3po.driver.internal.behavior.handler.codec.MessageEncoder;
import org.kaazing.k3po.driver.internal.netty.bootstrap.http.HttpChannelConfig;
public class HttpStatusEncoder implements ConfigEncoder {
private final MessageEncoder codeEncoder;
private final MessageEncoder reasonEncoder;
public HttpStatusEncoder(MessageEncoder codeEncoder, MessageEncoder reasonEncoder) {
this.codeEncoder = codeEncoder;
this.reasonEncoder = reasonEncoder;
}
@Override
public void encode(Channel channel) throws Exception {
HttpChannelConfig httpConfig = (HttpChannelConfig) channel.getConfig();
int code = Integer.parseInt(codeEncoder.encode().toString(US_ASCII));
String reason = reasonEncoder.encode().toString(US_ASCII);
HttpResponseStatus status = new HttpResponseStatus(code, reason);
httpConfig.setStatus(status);
}
@Override
public String toString() {
return format("http:status %s %s", codeEncoder, reasonEncoder);
}
}
| mgherghe/k3po | driver/src/main/java/org/kaazing/k3po/driver/internal/behavior/handler/codec/http/HttpStatusEncoder.java | Java | agpl-3.0 | 2,014 |
/*
* Slimey - SLIdeshow Microformat Editor - http://slimey.sourceforge.net
* Copyright (C) 2007 - 2008 Ignacio de Soto
*
* Base Action definitions.
*/
/**
* abstract class SlimeyAction - Actions on the editor
* name: name of the action
*/
var SlimeyAction = function(name, slimey) {
this.name = name;
this.slimey = slimey;
}
/**
* returns the action's name.
*/
SlimeyAction.prototype.getName = function() {
return this.name;
}
/**
* base perform() implementation
*/
SlimeyAction.prototype.perform = function() {
}
/**
* base undo() implementation
*/
SlimeyAction.prototype.undo = function() {
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyInsertAction - Handles insertion of new elements
* tagname: HTML tagname of the element to be inserted
*/
var SlimeyInsertAction = function(slimey, tagname) {
SlimeyAction.call(this, 'insert', slimey);
var elem = this.slimey.editor.getContainer().ownerDocument.createElement(tagname);
/* set element attributes */
elem.slimey = this.slimey;
elem.className = 'slimeyElement';
elem.style.position = 'absolute';
elem.style.left = '40%';
elem.style.top = '30%';
elem.style.lineHeight = '1.';
elem.style.cursor = 'move';
elem.style.fontFamily = 'sans-serif';
elem.style.fontSize = '160%';
elem.style.margin = '0px';
elem.style.padding = '0px';
elem.style.border = '0px';
elem.style.zIndex = 10000;
if (elem.tagName == 'DIV') {
elem.style.left = '5%';
elem.style.top = '15%';
elem.style.width = '90%';
elem.style.height = '10%';
elem.innerHTML = lang("some text");
elem.style.textAlign = 'center';
elem.resizable = true;
elem.editable = true;
} else if (elem.tagName == 'IMG') {
elem.style.width = '20%';
elem.style.height = '20%';
elem.resizable = true;
elem.title = lang("drag the bottom right corner to resize");
} else {
if (elem.tagName == 'UL') {
elem.innerHTML = '<li>' + lang("some text") + '</li>';
} else if (elem.tagName == 'OL') {
elem.innerHTML = '<li>' + lang("some text") + '</li>';
} else {
elem.innerHTML = lang("some text");
}
elem.editable = true;
elem.title = lang("double click to edit content");
}
/* event handlers */
setEventHandler(elem, "mousedown", slimeyDrag);
setEventHandler(elem, "click", slimeyClick);
setEventHandler(elem, "dblclick", slimeyEdit);
setEventHandler(elem, "mouseover", slimeyHighlight);
setEventHandler(elem, "mouseout", slimeyLowshadow);
this.element = elem;
}
/**
* SlimeyInsertAction extends SlimeyAction
*/
SlimeyInsertAction.prototype = new SlimeyAction();
/**
* returns the element created by this action
*/
SlimeyInsertAction.prototype.getElement = function() {
return this.element;
}
/**
* adds the created element to the editor
*/
SlimeyInsertAction.prototype.perform = function() {
this.slimey.editor.getContainer().appendChild(this.element);
}
/**
* removes the created element from the editor
*/
SlimeyInsertAction.prototype.undo = function() {
this.slimey.editor.getContainer().removeChild(this.element);
var selected = this.slimey.editor.getSelected();
if (selected == this.element) {
this.slimey.editor.deselect();
}
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyEditContentAction - edits the contents of the selected element in the editor
* content: HTML content to set to the element
*/
var SlimeyEditContentAction = function(slimey, content, element) {
SlimeyAction.call(this, 'editContent', slimey);
if (element) {
this.element = element;
} else {
this.element = this.slimey.editor.getSelected();
}
this.content = content;
}
/**
* SlimeyInsertAction extends SlimeyAction
*/
SlimeyEditContentAction.prototype = new SlimeyAction();
/**
* edits the contents of the selected item in the editor
*/
SlimeyEditContentAction.prototype.perform = function() {
this.previousContent = this.element.innerHTML;
this.element.innerHTML = this.content;
}
/**
* restores the elements original content
*/
SlimeyEditContentAction.prototype.undo = function() {
this.element.innerHTML = this.previousContent;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyEditStyleAction - edits a style property of the selected element in the editor
* property: CSS property to be modified (i.e. fontFamily)
* value: Value to set to the property (i.e. sans-serif)
*/
var SlimeyEditStyleAction = function(slimey, property, value) {
SlimeyAction.call(this, 'editStyle', slimey);
this.element = this.slimey.editor.getSelected();
this.property = property;
this.value = value;
}
/**
* SlimeyInsertAction extends SlimeyAction
*/
SlimeyEditStyleAction.prototype = new SlimeyAction();
/**
* edits the contents of the selected item in the editor
*/
SlimeyEditStyleAction.prototype.perform = function() {
this.previousValue = this.element.style[this.property];
this.element.style[this.property] = this.value;
}
/**
* restores the elements original content
*/
SlimeyEditStyleAction.prototype.undo = function() {
this.element.style[this.property] = this.previousValue;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyDeleteAction - Deletes the selected element
*/
var SlimeyDeleteAction = function(slimey) {
SlimeyAction.call(this, 'delete', slimey);
var selected = this.slimey.editor.getSelected();
this.element = selected;
}
/**
* SlimeyDeleteAction extends SlimeyAction
*/
SlimeyDeleteAction.prototype = new SlimeyAction();
/**
* removes the selected element from the editor
*/
SlimeyDeleteAction.prototype.perform = function() {
this.slimey.editor.getContainer().removeChild(this.element);
this.slimey.editor.deselect();
}
/**
* adds the previously deleted element to the editor
*/
SlimeyDeleteAction.prototype.undo = function() {
this.slimey.editor.getContainer().appendChild(this.element);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyMoveAction - Moves the selected element
* newx: new horizontal position
* newy: new vertical position
* oldx: (optional) previous horizontal position if different than current
* oldy: (optional) previous vertical position if different than current
*/
var SlimeyMoveAction = function(slimey, newx, newy, oldx, oldy) {
SlimeyAction.call(this, 'move', slimey);
var selected = this.slimey.editor.getSelected();
this.newx = newx;
this.newy = newy;
if (oldx) {
this.oldx = oldx;
} else {
this.oldx = selected.style.left;
}
if (oldy) {
this.oldy = oldy;
} else {
this.oldy = selected.style.top;
}
this.element = selected;
}
/**
* SlimeyMoveAction extends SlimeyAction
*/
SlimeyMoveAction.prototype = new SlimeyAction();
/**
* moves the selected element to the new position
*/
SlimeyMoveAction.prototype.perform = function() {
this.element.style.left = this.newx;
this.element.style.top = this.newy;
}
/**
* returns the moved element to its original position
*/
SlimeyMoveAction.prototype.undo = function() {
this.element.style.left = this.oldx;
this.element.style.top = this.oldy;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyResizeAction - Resizes the selected element
* neww: new width
* newh: new height
* oldw: (optional) previous width if different than current
* oldh: (optional) previous height if different than current
*/
var SlimeyResizeAction = function(slimey, neww, newh, oldw, oldh) {
SlimeyAction.call(this, 'resize', slimey);
var selected = this.slimey.editor.getSelected();
this.neww = neww;
this.newh = newh;
if (oldw) {
this.oldw = oldw;
} else {
this.oldw = selected.style.width;
}
if (oldh) {
this.oldh = oldh;
} else {
this.oldh = selected.style.height;
}
this.element = selected;
}
/**
* SlimeyResizeAction extends SlimeyAction
*/
SlimeyResizeAction.prototype = new SlimeyAction();
/**
* resizes the selected element
*/
SlimeyResizeAction.prototype.perform = function() {
this.element.style.width = this.neww;
this.element.style.height = this.newh;
}
/**
* returns the element to its original size
*/
SlimeyResizeAction.prototype.undo = function() {
this.element.style.width = this.oldw;
this.element.style.height = this.oldh;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeySendToBackAction - Sends the selected element to the back
*/
var SlimeySendToBackAction = function(slimey) {
SlimeyAction.call(this, 'sendToBack', slimey);
var selected = this.slimey.editor.getSelected();
this.element = selected;
}
/**
* SlimeySendToBackAction extends SlimeyAction
*/
SlimeySendToBackAction.prototype = new SlimeyAction();
/**
* sends the selected element to the back
*/
SlimeySendToBackAction.prototype.perform = function() {
var minZ = 100000000;
for (var elem = this.slimey.editor.getContainer().firstChild; elem; elem = elem.nextSibling) {
if (elem.nodeType == 1) {
thisZ = parseInt(elem.style.zIndex);
if (thisZ < minZ) {
minZ = thisZ;
}
}
}
this.oldZ = this.element.style.zIndex;
this.element.style.zIndex = minZ - 1;
}
/**
* sends the selected element back ot the previous z-index
*/
SlimeySendToBackAction.prototype.undo = function() {
this.element.style.zIndex = this.oldZ;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyBringToFrontAction - Brings the selected element to the front
*/
var SlimeyBringToFrontAction = function(slimey) {
SlimeyAction.call(this, 'bringToFront', slimey);
var selected = this.slimey.editor.getSelected();
this.element = selected;
}
/**
* SlimeyBringToFrontAction extends SlimeyAction
*/
SlimeyBringToFrontAction.prototype = new SlimeyAction();
/**
* brings the selected element to the front
*/
SlimeyBringToFrontAction.prototype.perform = function() {
var maxZ = 0;
for (var elem = this.slimey.editor.getContainer().firstChild; elem; elem = elem.nextSibling) {
if (elem.nodeType == 1) {
thisZ = parseInt(elem.style.zIndex);
if (thisZ > maxZ) {
maxZ = thisZ;
}
}
}
this.oldZ = this.element.style.zIndex;
this.element.style.zIndex = maxZ + 1;
}
/**
* returns the element to its original z-index
*/
SlimeyBringToFrontAction.prototype.undo = function() {
this.element.style.zIndex = this.oldZ;
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyChangeSlideAction - Changes the current slide
* num: Slide number to change to
*/
var SlimeyChangeSlideAction = function(slimey, num) {
SlimeyAction.call(this, 'changeSlide', slimey);
this.num = num;
}
/**
* SlimeyChangeSlideAction extends SlimeyAction
*/
SlimeyChangeSlideAction.prototype = new SlimeyAction();
/**
* changes the current slide
*/
SlimeyChangeSlideAction.prototype.perform = function() {
this.previousSlide = this.slimey.navigation.currentSlide;
this.slimey.navigation.getSlide(this.num);
}
/**
* returns to the previous slide
*/
SlimeyChangeSlideAction.prototype.undo = function() {
this.slimey.navigation.getSlide(this.previousSlide);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyInsertSlideAction - Inserts a new slide
* num: Position where to insert the new slide
*/
var SlimeyInsertSlideAction = function(slimey, num) {
SlimeyAction.call(this, 'insertSlide', slimey);
this.num = num;
}
/**
* SlimeyInsertSlideAction extends SlimeyAction
*/
SlimeyInsertSlideAction.prototype = new SlimeyAction();
/**
* insert the new slide
*/
SlimeyInsertSlideAction.prototype.perform = function() {
this.slimey.navigation.insertNewSlide(this.num);
}
/**
* remove the inserted slide
*/
SlimeyInsertSlideAction.prototype.undo = function() {
this.slimey.navigation.deleteSlide(this.num);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyDeleteSlideAction - Deletes the current slide
* num: Number of the slide to be deleted
*/
var SlimeyDeleteSlideAction = function(slimey, num) {
SlimeyAction.call(this, 'deleteSlide', slimey);
this.num = num;
}
/**
* SlimeyDeleteSlideAction extends SlimeyAction
*/
SlimeyDeleteSlideAction.prototype = new SlimeyAction();
/**
* delete the current slide
*/
SlimeyDeleteSlideAction.prototype.perform = function() {
this.html = this.slimey.editor.getHTML();
this.dom = document.createElement('div');
this.slimey.editor.getDOM(this.dom);
this.slimey.navigation.deleteSlide(this.num);
}
/**
* reinsert the deleted slide
*/
SlimeyDeleteSlideAction.prototype.undo = function() {
this.slimey.navigation.insertNewSlide(this.num, this.html, this.dom);
}
/*---------------------------------------------------------------------------*/
/**
* class SlimeyMoveSlideAction - Moves the current slide to a new position
* from: Number of the slide to be moved
* to: The new position of the slide
*/
var SlimeyMoveSlideAction = function(slimey, from, to) {
SlimeyAction.call(this, 'moveSlide', slimey);
this.from = from;
this.to = to;
}
/**
* SlimeyMoveSlideAction extends SlimeyAction
*/
SlimeyMoveSlideAction.prototype = new SlimeyAction();
/**
* move the slide to the new position
*/
SlimeyMoveSlideAction.prototype.perform = function() {
this.slimey.navigation.moveSlide(this.from, this.to);
}
/**
* move the slide back to its original position
*/
SlimeyMoveSlideAction.prototype.undo = function() {
this.slimey.navigation.moveSlide(this.to, this.from);
}
/*---------------------------------------------------------------------------*/ | maestrano/fengoffice | public/assets/javascript/slimey/actions.js | JavaScript | agpl-3.0 | 14,292 |
#include "bench_framework.hpp"
#include <mapnik/image_util.hpp>
class test : public benchmark::test_case
{
mapnik::image_rgba8 im_;
public:
test(mapnik::parameters const& params)
: test_case(params),
im_(256,256) {}
bool validate() const
{
return true;
}
bool operator()() const
{
std::string out;
for (std::size_t i=0;i<iterations_;++i) {
out.clear();
out = mapnik::save_to_string(im_,"png8:m=h:z=1");
}
return true;
}
};
BENCHMARK(test,"encoding blank png")
| mapycz/mapnik | benchmark/test_png_encoding1.cpp | C++ | lgpl-2.1 | 570 |
package dr.app.beauti.types;
/**
* @author Marc A. Suchard
*/
public enum HierarchicalModelType {
NORMAL_HPM,
LOGNORMAL_HPM;
public String toString() {
switch (this) {
case NORMAL_HPM:
return "Normal";
case LOGNORMAL_HPM:
return "Lognormal";
default:
return "";
}
}
}
| evolvedmicrobe/beast-mcmc | src/dr/app/beauti/types/HierarchicalModelType.java | Java | lgpl-2.1 | 406 |
using System;
namespace AutoTest.VM
{
class LaunchArguments
{
public Guid CorrelationId { get; private set; }
public int Port { get; private set; }
public string WatchPath { get; private set; }
public bool Debug { get; private set; }
public int OwnerPort { get; private set; }
public bool IsGlobal { get; private set; }
public int MasterProcessId { get; private set; }
public string ConfigPath { get; private set; }
public LaunchArguments(Guid correlationId, int port, string watchPath, string debug, int ownerPort, string runProfile, int masterProcessId, string configPath)
{
CorrelationId = correlationId;
Port = port;
WatchPath = watchPath;
Debug = (debug == "debug");
OwnerPort = ownerPort;
IsGlobal = (runProfile == "global");
MasterProcessId = masterProcessId;
ConfigPath = configPath;
}
}
}
| nahojd/ContinuousTests | src/AutoTest.VM/LaunchArguments.cs | C# | lgpl-2.1 | 999 |
/*
* Copyright (C) 2004, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "KURL.h"
#include <wtf/RetainPtr.h>
#include <CoreFoundation/CFURL.h>
using namespace std;
namespace WebCore {
typedef Vector<char, 512> CharBuffer;
CFURLRef createCFURLFromBuffer(const CharBuffer&);
KURL::KURL(CFURLRef url)
{
if (!url) {
invalidate();
return;
}
CFIndex bytesLength = CFURLGetBytes(url, 0, 0);
Vector<char, 512> buffer(bytesLength + 1);
char* bytes = &buffer[0];
CFURLGetBytes(url, reinterpret_cast<UInt8*>(bytes), bytesLength);
bytes[bytesLength] = '\0';
#if !USE(WTFURL)
parse(bytes);
#else
// FIXME: Add WTFURL Implementation.
UNUSED_PARAM(url);
invalidate();
#endif // USE(WTFURL)
}
CFURLRef createCFURLFromBuffer(const CharBuffer& buffer)
{
// NOTE: We use UTF-8 here since this encoding is used when computing strings when returning URL components
// (e.g calls to NSURL -path). However, this function is not tolerant of illegal UTF-8 sequences, which
// could either be a malformed string or bytes in a different encoding, like Shift-JIS, so we fall back
// onto using ISO Latin-1 in those cases.
CFURLRef result = CFURLCreateAbsoluteURLWithBytes(0, reinterpret_cast<const UInt8*>(buffer.data()), buffer.size(), kCFStringEncodingUTF8, 0, true);
if (!result)
result = CFURLCreateAbsoluteURLWithBytes(0, reinterpret_cast<const UInt8*>(buffer.data()), buffer.size(), kCFStringEncodingISOLatin1, 0, true);
return result;
}
#if !PLATFORM(MAC) && !(PLATFORM(QT) && USE(QTKIT))
CFURLRef KURL::createCFURL() const
{
#if !USE(WTFURL)
// FIXME: What should this return for invalid URLs?
// Currently it throws away the high bytes of the characters in the string in that case,
// which is clearly wrong.
CharBuffer buffer;
copyToBuffer(buffer);
return createCFURLFromBuffer(buffer);
#else // USE(WTFURL)
// FIXME: Add WTFURL Implementation.
return 0;
#endif
}
#endif
#if !USE(WTFURL) && !(PLATFORM(QT) && USE(QTKIT))
String KURL::fileSystemPath() const
{
RetainPtr<CFURLRef> cfURL(AdoptCF, createCFURL());
if (!cfURL)
return String();
#if PLATFORM(WIN)
CFURLPathStyle pathStyle = kCFURLWindowsPathStyle;
#else
CFURLPathStyle pathStyle = kCFURLPOSIXPathStyle;
#endif
return RetainPtr<CFStringRef>(AdoptCF, CFURLCopyFileSystemPath(cfURL.get(), pathStyle)).get();
}
#endif
}
| nawawi/wkhtmltopdf | webkit/Source/WebCore/platform/cf/KURLCFNet.cpp | C++ | lgpl-3.0 | 3,741 |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
HEADRequest,
sanitized_Request,
urlencode_postdata,
)
class GDCVaultIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gdcvault\.com/play/(?P<id>\d+)/(?P<name>(\w|-)+)?'
_NETRC_MACHINE = 'gdcvault'
_TESTS = [
{
'url': 'http://www.gdcvault.com/play/1019721/Doki-Doki-Universe-Sweet-Simple',
'md5': '7ce8388f544c88b7ac11c7ab1b593704',
'info_dict': {
'id': '1019721',
'display_id': 'Doki-Doki-Universe-Sweet-Simple',
'ext': 'mp4',
'title': 'Doki-Doki Universe: Sweet, Simple and Genuine (GDC Next 10)'
}
},
{
'url': 'http://www.gdcvault.com/play/1015683/Embracing-the-Dark-Art-of',
'info_dict': {
'id': '1015683',
'display_id': 'Embracing-the-Dark-Art-of',
'ext': 'flv',
'title': 'Embracing the Dark Art of Mathematical Modeling in AI'
},
'params': {
'skip_download': True, # Requires rtmpdump
}
},
{
'url': 'http://www.gdcvault.com/play/1015301/Thexder-Meets-Windows-95-or',
'md5': 'a5eb77996ef82118afbbe8e48731b98e',
'info_dict': {
'id': '1015301',
'display_id': 'Thexder-Meets-Windows-95-or',
'ext': 'flv',
'title': 'Thexder Meets Windows 95, or Writing Great Games in the Windows 95 Environment',
},
'skip': 'Requires login',
},
{
'url': 'http://gdcvault.com/play/1020791/',
'only_matching': True,
},
{
# Hard-coded hostname
'url': 'http://gdcvault.com/play/1023460/Tenacious-Design-and-The-Interface',
'md5': 'a8efb6c31ed06ca8739294960b2dbabd',
'info_dict': {
'id': '1023460',
'ext': 'mp4',
'display_id': 'Tenacious-Design-and-The-Interface',
'title': 'Tenacious Design and The Interface of \'Destiny\'',
},
},
{
# Multiple audios
'url': 'http://www.gdcvault.com/play/1014631/Classic-Game-Postmortem-PAC',
'info_dict': {
'id': '1014631',
'ext': 'flv',
'title': 'How to Create a Good Game - From My Experience of Designing Pac-Man',
},
'params': {
'skip_download': True, # Requires rtmpdump
'format': 'jp', # The japanese audio
}
},
{
# gdc-player.html
'url': 'http://www.gdcvault.com/play/1435/An-American-engine-in-Tokyo',
'info_dict': {
'id': '1435',
'display_id': 'An-American-engine-in-Tokyo',
'ext': 'flv',
'title': 'An American Engine in Tokyo:/nThe collaboration of Epic Games and Square Enix/nFor THE LAST REMINANT',
},
'params': {
'skip_download': True, # Requires rtmpdump
},
},
]
def _login(self, webpage_url, display_id):
username, password = self._get_login_info()
if username is None or password is None:
self.report_warning('It looks like ' + webpage_url + ' requires a login. Try specifying a username and password and try again.')
return None
mobj = re.match(r'(?P<root_url>https?://.*?/).*', webpage_url)
login_url = mobj.group('root_url') + 'api/login.php'
logout_url = mobj.group('root_url') + 'logout'
login_form = {
'email': username,
'password': password,
}
request = sanitized_Request(login_url, urlencode_postdata(login_form))
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
self._download_webpage(request, display_id, 'Logging in')
start_page = self._download_webpage(webpage_url, display_id, 'Getting authenticated video page')
self._download_webpage(logout_url, display_id, 'Logging out')
return start_page
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
display_id = mobj.group('name') or video_id
webpage_url = 'http://www.gdcvault.com/play/' + video_id
start_page = self._download_webpage(webpage_url, display_id)
direct_url = self._search_regex(
r's1\.addVariable\("file",\s*encodeURIComponent\("(/[^"]+)"\)\);',
start_page, 'url', default=None)
if direct_url:
title = self._html_search_regex(
r'<td><strong>Session Name</strong></td>\s*<td>(.*?)</td>',
start_page, 'title')
video_url = 'http://www.gdcvault.com' + direct_url
# resolve the url so that we can detect the correct extension
head = self._request_webpage(HEADRequest(video_url), video_id)
video_url = head.geturl()
return {
'id': video_id,
'display_id': display_id,
'url': video_url,
'title': title,
}
PLAYER_REGEX = r'<iframe src="(?P<xml_root>.+?)/(?:gdc-)?player.*?\.html.*?".*?</iframe>'
xml_root = self._html_search_regex(
PLAYER_REGEX, start_page, 'xml root', default=None)
if xml_root is None:
# Probably need to authenticate
login_res = self._login(webpage_url, display_id)
if login_res is None:
self.report_warning('Could not login.')
else:
start_page = login_res
# Grab the url from the authenticated page
xml_root = self._html_search_regex(
PLAYER_REGEX, start_page, 'xml root')
xml_name = self._html_search_regex(
r'<iframe src=".*?\?xml=(.+?\.xml).*?".*?</iframe>',
start_page, 'xml filename', default=None)
if xml_name is None:
# Fallback to the older format
xml_name = self._html_search_regex(
r'<iframe src=".*?\?xmlURL=xml/(?P<xml_file>.+?\.xml).*?".*?</iframe>',
start_page, 'xml filename')
return {
'_type': 'url_transparent',
'id': video_id,
'display_id': display_id,
'url': '%s/xml/%s' % (xml_root, xml_name),
'ie_key': 'DigitallySpeaking',
}
| stannynuytkens/youtube-dl | youtube_dl/extractor/gdcvault.py | Python | unlicense | 6,690 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eagle.jobrunning.crawler;
public class JobContext {
public String jobId;
public String user;
public Long fetchedTime;
public JobContext() {
}
public JobContext(JobContext context) {
this.jobId = new String(context.jobId);
this.user = new String(context.user);
this.fetchedTime = new Long(context.fetchedTime);
}
public JobContext(String jobId, String user, Long fetchedTime) {
this.jobId = jobId;
this.user = user;
this.fetchedTime = fetchedTime;
}
@Override
public int hashCode() {
return jobId.hashCode() ;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof JobContext) {
JobContext context = (JobContext)obj;
if (this.jobId.equals(context.jobId)) {
return true;
}
}
return false;
}
}
| eBay/Eagle | eagle-core/eagle-data-process/eagle-storm-jobrunning-spout/src/main/java/org/apache/eagle/jobrunning/crawler/JobContext.java | Java | apache-2.0 | 1,589 |
// Code generated by protoc-gen-gogo.
// source: uuid.proto
// DO NOT EDIT!
package events
import proto "github.com/gogo/protobuf/proto"
import math "math"
// discarding unused import gogoproto "github.com/gogo/protobuf/gogoproto/gogo.pb"
import io "io"
import fmt "fmt"
import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf
// / Type representing a 128-bit UUID.
//
// The bytes of the UUID should be packed in little-endian **byte** (not bit) order. For example, the UUID `f47ac10b-58cc-4372-a567-0e02b2c3d479` should be encoded as `UUID{ low: 0x7243cc580bc17af4, high: 0x79d4c3b2020e67a5 }`
type UUID struct {
Low *uint64 `protobuf:"varint,1,req,name=low" json:"low,omitempty"`
High *uint64 `protobuf:"varint,2,req,name=high" json:"high,omitempty"`
XXX_unrecognized []byte `json:"-"`
}
func (m *UUID) Reset() { *m = UUID{} }
func (m *UUID) String() string { return proto.CompactTextString(m) }
func (*UUID) ProtoMessage() {}
func (m *UUID) GetLow() uint64 {
if m != nil && m.Low != nil {
return *m.Low
}
return 0
}
func (m *UUID) GetHigh() uint64 {
if m != nil && m.High != nil {
return *m.High
}
return 0
}
func init() {
}
func (m *UUID) Unmarshal(data []byte) error {
var hasFields [1]uint64
l := len(data)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Low", wireType)
}
var v uint64
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
v |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.Low = &v
hasFields[0] |= uint64(0x00000001)
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field High", wireType)
}
var v uint64
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
v |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
m.High = &v
hasFields[0] |= uint64(0x00000002)
default:
var sizeOfWire int
for {
sizeOfWire++
wire >>= 7
if wire == 0 {
break
}
}
iNdEx -= sizeOfWire
skippy, err := skipUuid(data[iNdEx:])
if err != nil {
return err
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, data[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if hasFields[0]&uint64(0x00000001) == 0 {
return github_com_gogo_protobuf_proto.NewRequiredNotSetError("low")
}
if hasFields[0]&uint64(0x00000002) == 0 {
return github_com_gogo_protobuf_proto.NewRequiredNotSetError("high")
}
return nil
}
func skipUuid(data []byte) (n int, err error) {
l := len(data)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for {
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if data[iNdEx-1] < 0x80 {
break
}
}
return iNdEx, nil
case 1:
iNdEx += 8
return iNdEx, nil
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
iNdEx += length
return iNdEx, nil
case 3:
for {
var wire uint64
var start int = iNdEx
for shift := uint(0); ; shift += 7 {
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := data[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
if wireType == 4 {
break
}
next, err := skipUuid(data[start:])
if err != nil {
return 0, err
}
iNdEx = start + next
}
return iNdEx, nil
case 4:
return iNdEx, nil
case 5:
iNdEx += 4
return iNdEx, nil
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
}
panic("unreachable")
}
func (m *UUID) Size() (n int) {
var l int
_ = l
if m.Low != nil {
n += 1 + sovUuid(uint64(*m.Low))
}
if m.High != nil {
n += 1 + sovUuid(uint64(*m.High))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func sovUuid(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozUuid(x uint64) (n int) {
return sovUuid(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *UUID) Marshal() (data []byte, err error) {
size := m.Size()
data = make([]byte, size)
n, err := m.MarshalTo(data)
if err != nil {
return nil, err
}
return data[:n], nil
}
func (m *UUID) MarshalTo(data []byte) (n int, err error) {
var i int
_ = i
var l int
_ = l
if m.Low == nil {
return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("low")
} else {
data[i] = 0x8
i++
i = encodeVarintUuid(data, i, uint64(*m.Low))
}
if m.High == nil {
return 0, github_com_gogo_protobuf_proto.NewRequiredNotSetError("high")
} else {
data[i] = 0x10
i++
i = encodeVarintUuid(data, i, uint64(*m.High))
}
if m.XXX_unrecognized != nil {
i += copy(data[i:], m.XXX_unrecognized)
}
return i, nil
}
func encodeFixed64Uuid(data []byte, offset int, v uint64) int {
data[offset] = uint8(v)
data[offset+1] = uint8(v >> 8)
data[offset+2] = uint8(v >> 16)
data[offset+3] = uint8(v >> 24)
data[offset+4] = uint8(v >> 32)
data[offset+5] = uint8(v >> 40)
data[offset+6] = uint8(v >> 48)
data[offset+7] = uint8(v >> 56)
return offset + 8
}
func encodeFixed32Uuid(data []byte, offset int, v uint32) int {
data[offset] = uint8(v)
data[offset+1] = uint8(v >> 8)
data[offset+2] = uint8(v >> 16)
data[offset+3] = uint8(v >> 24)
return offset + 4
}
func encodeVarintUuid(data []byte, offset int, v uint64) int {
for v >= 1<<7 {
data[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
data[offset] = uint8(v)
return offset + 1
}
| freeformz/sonde-go | events/uuid.pb.go | GO | apache-2.0 | 6,590 |
// Copyright 2016 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package types
import (
"github.com/coreos/ignition/config/shared/errors"
"github.com/coreos/ignition/config/validate/report"
)
type Filesystem struct {
Name string `json:"name,omitempty"`
Mount *FilesystemMount `json:"mount,omitempty"`
Path *Path `json:"path,omitempty"`
}
type FilesystemMount struct {
Device Path `json:"device,omitempty"`
Format FilesystemFormat `json:"format,omitempty"`
Create *FilesystemCreate `json:"create,omitempty"`
}
type FilesystemCreate struct {
Force bool `json:"force,omitempty"`
Options MkfsOptions `json:"options,omitempty"`
}
func (f Filesystem) Validate() report.Report {
if f.Mount == nil && f.Path == nil {
return report.ReportFromError(errors.ErrFilesystemNoMountPath, report.EntryError)
}
if f.Mount != nil && f.Path != nil {
return report.ReportFromError(errors.ErrFilesystemMountAndPath, report.EntryError)
}
return report.Report{}
}
type FilesystemFormat string
func (f FilesystemFormat) Validate() report.Report {
switch f {
case "ext4", "btrfs", "xfs":
return report.Report{}
default:
return report.ReportFromError(errors.ErrFilesystemInvalidFormat, report.EntryError)
}
}
type MkfsOptions []string
| dm0-/mantle | vendor/github.com/coreos/ignition/config/v2_0/types/filesystem.go | GO | apache-2.0 | 1,814 |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(249)
var __weex_template__ = __webpack_require__(250)
var __weex_style__ = __webpack_require__(251)
var __weex_script__ = __webpack_require__(252)
__weex_define__('@weex-component/81fdd9b8b8bce1b304791aba10e15462', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
__weex_module__.exports.style = __weex_style__
})
__weex_bootstrap__('@weex-component/81fdd9b8b8bce1b304791aba10e15462',undefined,undefined)
/***/ },
/***/ 244:
/***/ function(module, exports) {
module.exports = {
"type": "image",
"style": {
"width": function () {return this.width},
"height": function () {return this.height}
},
"attr": {
"src": function () {return this.src},
"imageQuality": function () {return this.quality}
},
"events": {
"click": "_clickHandler"
}
}
/***/ },
/***/ 245:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
quality: 'normal',
width: 0,
height: 0,
src: '',
href: '',
spmc: 0,
spmd: 0
}},
methods: {
ready: function ready() {},
_clickHandler: function _clickHandler() {
this.$call('modal', 'toast', {
message: 'click',
duration: 1
});
}
}
};}
/* generated by weex-loader */
/***/ },
/***/ 246:
/***/ function(module, exports, __webpack_require__) {
var __weex_template__ = __webpack_require__(244)
var __weex_script__ = __webpack_require__(245)
__weex_define__('@weex-component/banner', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
})
/***/ },
/***/ 247:
/***/ function(module, exports) {
module.exports = {
"type": "container",
"children": [
{
"type": "container",
"shown": function () {return this.direction==='row'},
"style": {
"flexDirection": "row"
},
"children": [
{
"type": "container",
"repeat": function () {return this.ds},
"style": {
"width": function () {return this.width},
"height": function () {return this.height},
"marginLeft": function () {return this.space}
},
"children": [
{
"type": "banner",
"attr": {
"width": function () {return this.width},
"height": function () {return this.height},
"src": function () {return this.img},
"href": function () {return this.url}
}
}
]
}
]
},
{
"type": "container",
"shown": function () {return this.direction==='column'},
"children": [
{
"type": "container",
"repeat": function () {return this.ds},
"style": {
"width": function () {return this.width},
"height": function () {return this.height},
"marginTop": function () {return this.space}
},
"children": [
{
"type": "banner",
"attr": {
"width": function () {return this.width},
"height": function () {return this.height},
"src": function () {return this.img},
"href": function () {return this.url}
}
}
]
}
]
}
]
}
/***/ },
/***/ 248:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){'use strict';
module.exports = {
data: function () {return {
space: 0,
width: 0,
height: 0,
spmc: 0,
spmdprefix: '',
ds: []
}},
methods: {
ready: function ready() {
var self = this;
var ds = self.ds;
var length = ds.length;
for (var i = 0; i < length; i++) {
var item = ds[i];
item.index = i;
item.space = i % length === 0 ? 0 : self.space;
}
}
}
};}
/* generated by weex-loader */
/***/ },
/***/ 249:
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(246)
var __weex_template__ = __webpack_require__(247)
var __weex_script__ = __webpack_require__(248)
__weex_define__('@weex-component/banners', [], function(__weex_require__, __weex_exports__, __weex_module__) {
__weex_script__(__weex_module__, __weex_exports__, __weex_require__)
if (__weex_exports__.__esModule && __weex_exports__.default) {
__weex_module__.exports = __weex_exports__.default
}
__weex_module__.exports.template = __weex_template__
})
/***/ },
/***/ 250:
/***/ function(module, exports) {
module.exports = {
"type": "container",
"classList": [
"container"
],
"children": [
{
"type": "image",
"shown": function () {return this.ds.floorTitle},
"classList": [
"title"
],
"attr": {
"src": function () {return this.ds.floorTitle}
}
},
{
"type": "container",
"style": {
"marginLeft": 4,
"marginRight": 4
},
"children": [
{
"type": "banners",
"attr": {
"ds": function () {return this.bannerItems},
"direction": "column",
"width": function () {return this.NUMBER_742},
"height": function () {return this.NUMBER_230},
"space": function () {return this.NUMBER_4}
}
}
]
}
]
}
/***/ },
/***/ 251:
/***/ function(module, exports) {
module.exports = {
"title": {
"width": 750,
"height": 100
},
"container": {
"marginBottom": 4,
"backgroundColor": "#C0BABC"
}
}
/***/ },
/***/ 252:
/***/ function(module, exports) {
module.exports = function(module, exports, __weex_require__){"use strict";
module.exports = {
data: function () {return {
NUMBER_742: 742,
NUMBER_230: 230,
NUMBER_4: 4
}},
methods: {
ready: function ready() {
var self = this;
self._randomBrand();
},
_randomBrand: function _randomBrand() {
var self = this;
var bannerItems = self.ds.bannerItems;
bannerItems = bannerItems.sort(function () {
return Math.random() - 0.5;
});
self.bannerItems = bannerItems.slice(0, 8);
for (var i = 0; i < bannerItems.length; i++) {
var item = bannerItems[i];
if (i % 2 === 0) {
item.img = item.leftImg;
item.url = item.rightUrl;
} else {
item.img = item.rightImg;
item.url = item.rightUrl;
}
}
}
}
};}
/* generated by weex-loader */
/***/ }
/******/ }); | MrRaindrop/incubator-weex | android/playground/app/src/main/assets/showcase/new-fashion/brand.js | JavaScript | apache-2.0 | 8,757 |
/*
* Copyright 2012-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.jvm.java;
import static com.facebook.buck.rules.BuildableProperties.Kind.PACKAGING;
import com.facebook.buck.io.DirectoryTraverser;
import com.facebook.buck.model.BuildTargets;
import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BinaryBuildRule;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRules;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.BuildableProperties;
import com.facebook.buck.rules.CommandTool;
import com.facebook.buck.rules.RuleKeyAppendable;
import com.facebook.buck.rules.RuleKeyBuilder;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.SourcePaths;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.step.fs.MkdirAndSymlinkFileStep;
import com.facebook.buck.step.fs.MkdirStep;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.ImmutableSortedSet;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.annotation.Nullable;
@BuildsAnnotationProcessor
public class JavaBinary extends AbstractBuildRule
implements BinaryBuildRule, HasClasspathEntries, RuleKeyAppendable {
private static final BuildableProperties OUTPUT_TYPE = new BuildableProperties(PACKAGING);
@AddToRuleKey
@Nullable
private final String mainClass;
@AddToRuleKey
@Nullable
private final SourcePath manifestFile;
private final boolean mergeManifests;
@Nullable
private final Path metaInfDirectory;
@AddToRuleKey
private final ImmutableSet<String> blacklist;
private final DirectoryTraverser directoryTraverser;
private final ImmutableSetMultimap<JavaLibrary, Path> transitiveClasspathEntries;
public JavaBinary(
BuildRuleParams params,
SourcePathResolver resolver,
@Nullable String mainClass,
@Nullable SourcePath manifestFile,
boolean mergeManifests,
@Nullable Path metaInfDirectory,
ImmutableSet<String> blacklist,
DirectoryTraverser directoryTraverser,
ImmutableSetMultimap<JavaLibrary, Path> transitiveClasspathEntries) {
super(params, resolver);
this.mainClass = mainClass;
this.manifestFile = manifestFile;
this.mergeManifests = mergeManifests;
this.metaInfDirectory = metaInfDirectory;
this.blacklist = blacklist;
this.directoryTraverser = directoryTraverser;
this.transitiveClasspathEntries = transitiveClasspathEntries;
}
@Override
public BuildableProperties getProperties() {
return OUTPUT_TYPE;
}
@Override
public RuleKeyBuilder appendToRuleKey(RuleKeyBuilder builder) {
// Build a sorted set so that metaInfDirectory contents are listed in a canonical order.
ImmutableSortedSet.Builder<Path> paths = ImmutableSortedSet.naturalOrder();
BuildRules.addInputsToSortedSet(metaInfDirectory, paths, directoryTraverser);
return builder.setReflectively(
"metaInfDirectory",
FluentIterable.from(paths.build())
.transform(SourcePaths.toSourcePath(getProjectFilesystem())));
}
@Override
public ImmutableList<Step> getBuildSteps(
BuildContext context,
BuildableContext buildableContext) {
ImmutableList.Builder<Step> commands = ImmutableList.builder();
Path outputDirectory = getOutputDirectory();
Step mkdir = new MkdirStep(getProjectFilesystem(), outputDirectory);
commands.add(mkdir);
ImmutableSortedSet<Path> includePaths;
if (metaInfDirectory != null) {
Path stagingRoot = outputDirectory.resolve("meta_inf_staging");
Path stagingTarget = stagingRoot.resolve("META-INF");
MakeCleanDirectoryStep createStagingRoot = new MakeCleanDirectoryStep(
getProjectFilesystem(),
stagingRoot);
commands.add(createStagingRoot);
MkdirAndSymlinkFileStep link = new MkdirAndSymlinkFileStep(
getProjectFilesystem(),
metaInfDirectory,
stagingTarget);
commands.add(link);
includePaths = ImmutableSortedSet.<Path>naturalOrder()
.add(stagingRoot)
.addAll(getTransitiveClasspathEntries().values())
.build();
} else {
includePaths = ImmutableSortedSet.copyOf(getTransitiveClasspathEntries().values());
}
Path outputFile = getPathToOutput();
Path manifestPath = manifestFile == null ? null : getResolver().getAbsolutePath(manifestFile);
Step jar = new JarDirectoryStep(
getProjectFilesystem(),
outputFile,
includePaths,
mainClass,
manifestPath,
mergeManifests,
blacklist);
commands.add(jar);
buildableContext.recordArtifact(outputFile);
return commands.build();
}
@Override
public ImmutableSetMultimap<JavaLibrary, Path> getTransitiveClasspathEntries() {
return transitiveClasspathEntries;
}
@Override
public ImmutableSet<JavaLibrary> getTransitiveClasspathDeps() {
return transitiveClasspathEntries.keySet();
}
private Path getOutputDirectory() {
return BuildTargets.getGenPath(getBuildTarget(), "%s").getParent();
}
@Override
public Path getPathToOutput() {
return Paths.get(
String.format(
"%s/%s.jar",
getOutputDirectory(),
getBuildTarget().getShortNameAndFlavorPostfix()));
}
@Override
public Tool getExecutableCommand() {
Preconditions.checkState(
mainClass != null,
"Must specify a main class for %s in order to to run it.",
getBuildTarget());
return new CommandTool.Builder()
.addArg("java")
.addArg("-jar")
.addArg(new BuildTargetSourcePath(getBuildTarget()))
.build();
}
}
| mikekap/buck | src/com/facebook/buck/jvm/java/JavaBinary.java | Java | apache-2.0 | 6,767 |
#!/usr/bin/python2
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
# To run this script please copy "out/<build_name>//pyproto/webrtc/modules/
# audio_coding/audio_network_adaptor/debug_dump_pb2.py" to this folder.
# The you can run this script with:
# "python parse_ana_dump.py -m uplink_bandwidth_bps -f dump_file.dat"
# You can add as may metrics or decisions to the plot as you like.
# form more information call:
# "python parse_ana_dump.py --help"
import struct
from optparse import OptionParser
import matplotlib.pyplot as plt
import debug_dump_pb2
def GetNextMessageSize(file_to_parse):
data = file_to_parse.read(4)
if data == '':
return 0
return struct.unpack('<I', data)[0]
def GetNextMessageFromFile(file_to_parse):
message_size = GetNextMessageSize(file_to_parse)
if message_size == 0:
return None
try:
event = debug_dump_pb2.Event()
event.ParseFromString(file_to_parse.read(message_size))
except IOError:
print 'Invalid message in file'
return None
return event
def InitMetrics():
metrics = {}
event = debug_dump_pb2.Event()
for metric in event.network_metrics.DESCRIPTOR.fields:
metrics[metric.name] = {'time': [], 'value': []}
return metrics
def InitDecisions():
decisions = {}
event = debug_dump_pb2.Event()
for decision in event.encoder_runtime_config.DESCRIPTOR.fields:
decisions[decision.name] = {'time': [], 'value': []}
return decisions
def ParseAnaDump(dump_file_to_parse):
with open(dump_file_to_parse, 'rb') as file_to_parse:
metrics = InitMetrics()
decisions = InitDecisions()
first_time_stamp = None
while True:
event = GetNextMessageFromFile(file_to_parse)
if event == None:
break
if first_time_stamp == None:
first_time_stamp = event.timestamp
if event.type == debug_dump_pb2.Event.ENCODER_RUNTIME_CONFIG:
for decision in event.encoder_runtime_config.DESCRIPTOR.fields:
if event.encoder_runtime_config.HasField(decision.name):
decisions[decision.name]['time'].append(event.timestamp -
first_time_stamp)
decisions[decision.name]['value'].append(
getattr(event.encoder_runtime_config, decision.name))
if event.type == debug_dump_pb2.Event.NETWORK_METRICS:
for metric in event.network_metrics.DESCRIPTOR.fields:
if event.network_metrics.HasField(metric.name):
metrics[metric.name]['time'].append(event.timestamp -
first_time_stamp)
metrics[metric.name]['value'].append(
getattr(event.network_metrics, metric.name))
return (metrics, decisions)
def main():
parser = OptionParser()
parser.add_option(
"-f", "--dump_file", dest="dump_file_to_parse", help="dump file to parse")
parser.add_option(
'-m',
'--metric_plot',
default=[],
type=str,
help='metric key (name of the metric) to plot',
dest='metric_keys',
action='append')
parser.add_option(
'-d',
'--decision_plot',
default=[],
type=str,
help='decision key (name of the decision) to plot',
dest='decision_keys',
action='append')
options = parser.parse_args()[0]
if options.dump_file_to_parse == None:
print "No dump file to parse is set.\n"
parser.print_help()
exit()
(metrics, decisions) = ParseAnaDump(options.dump_file_to_parse)
metric_keys = options.metric_keys
decision_keys = options.decision_keys
plot_count = len(metric_keys) + len(decision_keys)
if plot_count == 0:
print "You have to set at least one metric or decision to plot.\n"
parser.print_help()
exit()
plots = []
if plot_count == 1:
f, mp_plot = plt.subplots()
plots.append(mp_plot)
else:
f, mp_plots = plt.subplots(plot_count, sharex=True)
plots.extend(mp_plots.tolist())
for key in metric_keys:
plot = plots.pop()
plot.grid(True)
plot.set_title(key + " (metric)")
plot.plot(metrics[key]['time'], metrics[key]['value'])
for key in decision_keys:
plot = plots.pop()
plot.grid(True)
plot.set_title(key + " (decision)")
plot.plot(decisions[key]['time'], decisions[key]['value'])
f.subplots_adjust(hspace=0.3)
plt.show()
if __name__ == "__main__":
main()
| wangcy6/storm_app | frame/c++/webrtc-master/modules/audio_coding/audio_network_adaptor/parse_ana_dump.py | Python | apache-2.0 | 4,718 |
"""Support for Verisure Smartplugs."""
import logging
from time import monotonic
from homeassistant.components.switch import SwitchEntity
from . import CONF_SMARTPLUGS, HUB as hub
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Verisure switch platform."""
if not int(hub.config.get(CONF_SMARTPLUGS, 1)):
return False
hub.update_overview()
switches = []
switches.extend(
[
VerisureSmartplug(device_label)
for device_label in hub.get("$.smartPlugs[*].deviceLabel")
]
)
add_entities(switches)
class VerisureSmartplug(SwitchEntity):
"""Representation of a Verisure smartplug."""
def __init__(self, device_id):
"""Initialize the Verisure device."""
self._device_label = device_id
self._change_timestamp = 0
self._state = False
@property
def name(self):
"""Return the name or location of the smartplug."""
return hub.get_first(
"$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label
)
@property
def is_on(self):
"""Return true if on."""
if monotonic() - self._change_timestamp < 10:
return self._state
self._state = (
hub.get_first(
"$.smartPlugs[?(@.deviceLabel == '%s')].currentState",
self._device_label,
)
== "ON"
)
return self._state
@property
def available(self):
"""Return True if entity is available."""
return (
hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label)
is not None
)
def turn_on(self, **kwargs):
"""Set smartplug status on."""
hub.session.set_smartplug_state(self._device_label, True)
self._state = True
self._change_timestamp = monotonic()
def turn_off(self, **kwargs):
"""Set smartplug status off."""
hub.session.set_smartplug_state(self._device_label, False)
self._state = False
self._change_timestamp = monotonic()
# pylint: disable=no-self-use
def update(self):
"""Get the latest date of the smartplug."""
hub.update_overview()
| nkgilley/home-assistant | homeassistant/components/verisure/switch.py | Python | apache-2.0 | 2,311 |
/*
* Copyright 2015 JBoss, by Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.ext.wires.bayesian.network.client.factory;
import com.ait.lienzo.client.core.shape.Rectangle;
import com.ait.lienzo.client.core.shape.Shape;
import com.ait.lienzo.client.core.shape.Text;
import com.ait.lienzo.shared.core.types.Color;
import org.uberfire.ext.wires.core.client.util.ShapesUtils;
public class BaseFactory {
private static final String defaultFillColor = ShapesUtils.RGB_FILL_SHAPE;
private static final String defaultBorderColor = ShapesUtils.RGB_STROKE_SHAPE;
protected void setAttributes( final Shape<?> shape,
final String fillColor,
final double x,
final double y,
final String borderColor ) {
String fill = ( fillColor == null ) ? defaultFillColor : fillColor;
String border = ( borderColor == null ) ? defaultBorderColor : borderColor;
shape.setX( x ).setY( y ).setStrokeColor( border ).setStrokeWidth( ShapesUtils.RGB_STROKE_WIDTH_SHAPE ).setFillColor( fill ).setDraggable( false );
}
protected Rectangle drawComponent( final String color,
final int positionX,
final int positionY,
final int width,
final int height,
String borderColor,
double radius ) {
if ( borderColor == null ) {
borderColor = Color.rgbToBrowserHexColor( 0, 0, 0 );
}
Rectangle component = new Rectangle( width,
height );
setAttributes( component,
color,
positionX,
positionY,
borderColor );
component.setCornerRadius( radius );
return component;
}
protected Text drawText( final String description,
final int fontSize,
final int positionX,
final int positionY ) {
return new Text( description,
"Times",
fontSize ).setX( positionX ).setY( positionY );
}
}
| dgutierr/uberfire-extensions | uberfire-wires/uberfire-wires-bayesian-network/uberfire-wires-bayesian-network-client/src/main/java/org/uberfire/ext/wires/bayesian/network/client/factory/BaseFactory.java | Java | apache-2.0 | 2,954 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.template.impl;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupActionProvider;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementAction;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.util.Consumer;
import com.intellij.util.PlatformIcons;
/**
* @author peter
*/
public class LiveTemplateLookupActionProvider implements LookupActionProvider {
@Override
public void fillActions(LookupElement element, final Lookup lookup, Consumer<LookupElementAction> consumer) {
if (element instanceof LiveTemplateLookupElementImpl) {
final TemplateImpl template = ((LiveTemplateLookupElementImpl)element).getTemplate();
final TemplateImpl templateFromSettings = TemplateSettings.getInstance().getTemplate(template.getKey(), template.getGroupName());
if (templateFromSettings != null) {
consumer.consume(new LookupElementAction(PlatformIcons.EDIT, CodeInsightBundle.message("action.text.edit.live.template.settings")) {
@Override
public Result performLookupAction() {
final Project project = lookup.getProject();
ApplicationManager.getApplication().invokeLater(() -> {
if (project.isDisposed()) return;
final LiveTemplatesConfigurable configurable = new LiveTemplatesConfigurable();
ShowSettingsUtil.getInstance().editConfigurable(project, configurable, () -> configurable.getTemplateListPanel().editTemplate(template));
});
return Result.HIDE_LOOKUP;
}
});
consumer.consume(new LookupElementAction(AllIcons.Actions.Cancel, CodeInsightBundle.message("action.text.disable.live.template", template.getKey())) {
@Override
public Result performLookupAction() {
ApplicationManager.getApplication().invokeLater(() -> templateFromSettings.setDeactivated(true));
return Result.HIDE_LOOKUP;
}
});
}
}
}
}
| siosio/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java | Java | apache-2.0 | 2,424 |
// +build dfssh
package dockerfile2llb
import (
"github.com/moby/buildkit/client/llb"
"github.com/moby/buildkit/frontend/dockerfile/instructions"
"github.com/pkg/errors"
)
func dispatchSSH(m *instructions.Mount) (llb.RunOption, error) {
if m.Source != "" {
return nil, errors.Errorf("ssh does not support source")
}
opts := []llb.SSHOption{llb.SSHID(m.CacheID)}
if m.Target != "" {
// TODO(AkihiroSuda): support specifying permission bits
opts = append(opts, llb.SSHSocketTarget(m.Target))
}
if !m.Required {
opts = append(opts, llb.SSHOptional)
}
return llb.AddSSHSocket(opts...), nil
}
| laijs/moby | vendor/github.com/moby/buildkit/frontend/dockerfile/dockerfile2llb/convert_ssh.go | GO | apache-2.0 | 613 |
/*****************************************************************************
* *
* OpenNI 1.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* This file is part of OpenNI. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace OpenNI
{
public static class Log
{
public static readonly string MASK_ALL = "ALL";
public static void Init()
{
int status = SafeNativeMethods.xnLogInitSystem();
WrapperUtils.ThrowOnError(status);
}
public static void InitFromXmlFile(string xmlFile)
{
int status = SafeNativeMethods.xnLogInitFromXmlFile(xmlFile);
WrapperUtils.ThrowOnError(status);
}
public static void Close()
{
int status = SafeNativeMethods.xnLogClose();
WrapperUtils.ThrowOnError(status);
}
public static void SetMaskState(string maskName, bool on)
{
int status = SafeNativeMethods.xnLogSetMaskState(maskName, on);
WrapperUtils.ThrowOnError(status);
}
public static void SetSeverityFilter(LogSeverity severity)
{
int status = SafeNativeMethods.xnLogSetSeverityFilter(severity);
WrapperUtils.ThrowOnError(status);
}
public static void SetConsoleOutput(bool on)
{
int status = SafeNativeMethods.xnLogSetConsoleOutput(on);
WrapperUtils.ThrowOnError(status);
}
public static void SetFileOutput(bool on)
{
int status = SafeNativeMethods.xnLogSetFileOutput(on);
WrapperUtils.ThrowOnError(status);
}
public static void SetOutputFolder(string folder)
{
int status = SafeNativeMethods.xnLogSetOutputFolder(folder);
WrapperUtils.ThrowOnError(status);
}
}
} | rxl194/OpenNI | Wrappers/OpenNI.net/Log.cs | C# | apache-2.0 | 3,080 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.impl.engine;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.DataType;
import org.apache.camel.spi.Validator;
import org.apache.camel.spi.ValidatorRegistry;
import org.apache.camel.support.CamelContextHelper;
import org.apache.camel.support.service.ServiceHelper;
import org.apache.camel.util.ObjectHelper;
/**
* Default implementation of {@link org.apache.camel.spi.ValidatorRegistry}.
*/
public class DefaultValidatorRegistry extends AbstractDynamicRegistry<ValidatorKey, Validator>
implements ValidatorRegistry<ValidatorKey> {
public DefaultValidatorRegistry(CamelContext context) {
super(context, CamelContextHelper.getMaximumValidatorCacheSize(context));
}
@Override
public Validator resolveValidator(ValidatorKey key) {
Validator answer = get(key);
if (answer == null && ObjectHelper.isNotEmpty(key.getType().getName())) {
answer = get(new ValidatorKey(new DataType(key.getType().getModel())));
}
return answer;
}
@Override
public boolean isStatic(DataType type) {
return isStatic(new ValidatorKey(type));
}
@Override
public boolean isDynamic(DataType type) {
return isDynamic(new ValidatorKey(type));
}
@Override
public String toString() {
return "ValidatorRegistry for " + context.getName() + " [capacity: " + maxCacheSize + "]";
}
@Override
public Validator put(ValidatorKey key, Validator obj) {
// ensure validator is started before its being used
ServiceHelper.startService(obj);
return super.put(key, obj);
}
}
| nikhilvibhav/camel | core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/DefaultValidatorRegistry.java | Java | apache-2.0 | 2,457 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nutch.protocol.ftp;
import java.net.URL;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.ProtocolOutput;
import org.apache.nutch.protocol.ProtocolStatus;
import org.apache.nutch.protocol.RobotRulesParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import crawlercommons.robots.BaseRobotRules;
import crawlercommons.robots.SimpleRobotRules;
/**
* This class is used for parsing robots for urls belonging to FTP protocol.
* It extends the generic {@link RobotRulesParser} class and contains
* Ftp protocol specific implementation for obtaining the robots file.
*/
public class FtpRobotRulesParser extends RobotRulesParser {
private static final String CONTENT_TYPE = "text/plain";
public static final Logger LOG = LoggerFactory.getLogger(FtpRobotRulesParser.class);
FtpRobotRulesParser() { }
public FtpRobotRulesParser(Configuration conf) {
super(conf);
}
/**
* The hosts for which the caching of robots rules is yet to be done,
* it sends a Ftp request to the host corresponding to the {@link URL}
* passed, gets robots file, parses the rules and caches the rules object
* to avoid re-work in future.
*
* @param ftp The {@link Protocol} object
* @param url URL
*
* @return robotRules A {@link BaseRobotRules} object for the rules
*/
public BaseRobotRules getRobotRulesSet(Protocol ftp, URL url) {
String protocol = url.getProtocol().toLowerCase(); // normalize to lower case
String host = url.getHost().toLowerCase(); // normalize to lower case
BaseRobotRules robotRules = (SimpleRobotRules) CACHE.get(protocol + ":" + host);
boolean cacheRule = true;
if (robotRules == null) { // cache miss
if (LOG.isTraceEnabled())
LOG.trace("cache miss " + url);
try {
Text robotsUrl = new Text(new URL(url, "/robots.txt").toString());
ProtocolOutput output = ((Ftp)ftp).getProtocolOutput(robotsUrl, new CrawlDatum());
ProtocolStatus status = output.getStatus();
if (status.getCode() == ProtocolStatus.SUCCESS) {
robotRules = parseRules(url.toString(), output.getContent().getContent(),
CONTENT_TYPE, agentNames);
} else {
robotRules = EMPTY_RULES; // use default rules
}
} catch (Throwable t) {
if (LOG.isInfoEnabled()) {
LOG.info("Couldn't get robots.txt for " + url + ": " + t.toString());
}
cacheRule = false;
robotRules = EMPTY_RULES;
}
if (cacheRule)
CACHE.put(protocol + ":" + host, robotRules); // cache rules for host
}
return robotRules;
}
}
| fogbeam/Heceta_nutch | src/plugin/protocol-ftp/src/java/org/apache/nutch/protocol/ftp/FtpRobotRulesParser.java | Java | apache-2.0 | 3,708 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.spi.systemview.view;
import org.apache.ignite.internal.managers.systemview.walker.Order;
import org.apache.ignite.internal.processors.query.QueryUtils;
import org.apache.ignite.internal.processors.query.h2.sys.view.SqlSystemView;
/**
* Sql view representation for a {@link SystemView}.
*/
public class SqlViewView {
/** Sql system view. */
private final SqlSystemView view;
/** @param view Sql system view. */
public SqlViewView(SqlSystemView view) {
this.view = view;
}
/** View name. */
@Order
public String name() {
return view.getTableName();
}
/** View description. */
@Order(2)
public String description() {
return view.getDescription();
}
/** View schema. */
@Order(1)
public String schema() {
return QueryUtils.SCHEMA_SYS;
}
}
| samaitra/ignite | modules/indexing/src/main/java/org/apache/ignite/spi/systemview/view/SqlViewView.java | Java | apache-2.0 | 1,673 |