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 |
|---|---|---|---|---|---|
package org.zstack.header.volume;
import org.zstack.header.search.APISearchReply;
public class APISearchVolumeReply extends APISearchReply {
public static APISearchVolumeReply __example__() {
APISearchVolumeReply reply = new APISearchVolumeReply();
return reply;
}
}
| winger007/zstack | header/src/main/java/org/zstack/header/volume/APISearchVolumeReply.java | Java | apache-2.0 | 299 |
class ZshLovers < Formula
desc "Tips, tricks, and examples for zsh"
homepage "https://grml.org/zsh/#zshlovers"
url "https://deb.grml.org/pool/main/z/zsh-lovers/zsh-lovers_0.9.1_all.deb"
sha256 "011b7931a555c77e98aa9cdd16b3c4670c0e0e3b5355e5fd60188885a6678de8"
livecheck do
url "https://deb.grml.org/pool/main/z/zsh-lovers/"
regex(/href=.*?zsh-lovers[._-]v?(\d+(?:\.\d+)+)[._-]all/i)
end
bottle do
sha256 cellar: :any_skip_relocation, all: "a9a640ed5452e086874d853453e15cbd2e347a5a86d867db12a5245980f6aa54"
end
def install
system "tar", "xf", "zsh-lovers_#{version}_all.deb"
system "tar", "xf", "data.tar.xz"
system "gunzip", *Dir["usr/**/*.gz"]
prefix.install_metafiles "usr/share/doc/zsh-lovers"
prefix.install "usr/share"
end
test do
system "man", "zsh-lovers"
end
end
| sjackman/homebrew-core | Formula/zsh-lovers.rb | Ruby | bsd-2-clause | 835 |
#ifndef STD_HASH_HPP
#define STD_HASH_HPP
#include <functional>
// this is largely inspired by boost's hash combine as can be found in
// "The C++ Standard Library" 2nd Edition. Nicolai M. Josuttis. 2012.
template <typename T> void hash_combine(std::size_t &seed, const T &val)
{
seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template <typename T> void hash_val(std::size_t &seed, const T &val) { hash_combine(seed, val); }
template <typename T, typename... Types>
void hash_val(std::size_t &seed, const T &val, const Types &... args)
{
hash_combine(seed, val);
hash_val(seed, args...);
}
template <typename... Types> std::size_t hash_val(const Types &... args)
{
std::size_t seed = 0;
hash_val(seed, args...);
return seed;
}
namespace std
{
template <typename T1, typename T2> struct hash<std::pair<T1, T2>>
{
size_t operator()(const std::pair<T1, T2> &pair) const
{
return hash_val(pair.first, pair.second);
}
};
}
#endif // STD_HASH_HPP
| KnockSoftware/osrm-backend | include/util/std_hash.hpp | C++ | bsd-2-clause | 1,018 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/file_system_provider/operations/execute_action.h"
#include <algorithm>
#include <string>
#include "chrome/common/extensions/api/file_system_provider.h"
#include "chrome/common/extensions/api/file_system_provider_internal.h"
namespace chromeos {
namespace file_system_provider {
namespace operations {
ExecuteAction::ExecuteAction(
extensions::EventRouter* event_router,
const ProvidedFileSystemInfo& file_system_info,
const base::FilePath& entry_path,
const std::string& action_id,
const storage::AsyncFileUtil::StatusCallback& callback)
: Operation(event_router, file_system_info),
entry_path_(entry_path),
action_id_(action_id),
callback_(callback) {
}
ExecuteAction::~ExecuteAction() {
}
bool ExecuteAction::Execute(int request_id) {
using extensions::api::file_system_provider::ExecuteActionRequestedOptions;
ExecuteActionRequestedOptions options;
options.file_system_id = file_system_info_.file_system_id();
options.request_id = request_id;
options.entry_path = entry_path_.AsUTF8Unsafe();
options.action_id = action_id_;
return SendEvent(
request_id,
extensions::events::FILE_SYSTEM_PROVIDER_ON_EXECUTE_ACTION_REQUESTED,
extensions::api::file_system_provider::OnExecuteActionRequested::
kEventName,
extensions::api::file_system_provider::OnExecuteActionRequested::Create(
options));
}
void ExecuteAction::OnSuccess(int /* request_id */,
scoped_ptr<RequestValue> result,
bool has_more) {
callback_.Run(base::File::FILE_OK);
}
void ExecuteAction::OnError(int /* request_id */,
scoped_ptr<RequestValue> /* result */,
base::File::Error error) {
callback_.Run(error);
}
} // namespace operations
} // namespace file_system_provider
} // namespace chromeos
| Chilledheart/chromium | chrome/browser/chromeos/file_system_provider/operations/execute_action.cc | C++ | bsd-3-clause | 2,091 |
// Copyright 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.
package org.chromium.content.browser;
import android.content.Context;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Surface;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.chromium.base.CalledByNative;
import org.chromium.base.JNINamespace;
import org.chromium.base.SysUtils;
import org.chromium.base.ThreadUtils;
import org.chromium.content.app.ChildProcessService;
import org.chromium.content.app.Linker;
import org.chromium.content.app.LinkerParams;
import org.chromium.content.app.PrivilegedProcessService;
import org.chromium.content.app.SandboxedProcessService;
import org.chromium.content.common.IChildProcessCallback;
import org.chromium.content.common.IChildProcessService;
/**
* This class provides the method to start/stop ChildProcess called by native.
*/
@JNINamespace("content")
public class ChildProcessLauncher {
private static String TAG = "ChildProcessLauncher";
private static final int CALLBACK_FOR_UNKNOWN_PROCESS = 0;
private static final int CALLBACK_FOR_GPU_PROCESS = 1;
private static final int CALLBACK_FOR_RENDERER_PROCESS = 2;
private static final String SWITCH_PROCESS_TYPE = "type";
private static final String SWITCH_PPAPI_BROKER_PROCESS = "ppapi-broker";
private static final String SWITCH_RENDERER_PROCESS = "renderer";
private static final String SWITCH_GPU_PROCESS = "gpu-process";
// The upper limit on the number of simultaneous sandboxed and privileged child service process
// instances supported. Each limit must not exceed total number of SandboxedProcessServiceX
// classes and PrivilegedProcessServiceX classes declared in this package and defined as
// services in the embedding application's manifest file.
// (See {@link ChildProcessService} for more details on defining the services.)
/* package */ static final int MAX_REGISTERED_SANDBOXED_SERVICES = 13;
/* package */ static final int MAX_REGISTERED_PRIVILEGED_SERVICES = 3;
private static class ChildConnectionAllocator {
// Connections to services. Indices of the array correspond to the service numbers.
private ChildProcessConnection[] mChildProcessConnections;
// The list of free (not bound) service indices. When looking for a free service, the first
// index in that list should be used. When a service is unbound, its index is added to the
// end of the list. This is so that we avoid immediately reusing the freed service (see
// http://crbug.com/164069): the framework might keep a service process alive when it's been
// unbound for a short time. If a new connection to the same service is bound at that point,
// the process is reused and bad things happen (mostly static variables are set when we
// don't expect them to).
// SHOULD BE ACCESSED WITH mConnectionLock.
private ArrayList<Integer> mFreeConnectionIndices;
private final Object mConnectionLock = new Object();
private Class<? extends ChildProcessService> mChildClass;
private final boolean mInSandbox;
public ChildConnectionAllocator(boolean inSandbox) {
int numChildServices = inSandbox ?
MAX_REGISTERED_SANDBOXED_SERVICES : MAX_REGISTERED_PRIVILEGED_SERVICES;
mChildProcessConnections = new ChildProcessConnection[numChildServices];
mFreeConnectionIndices = new ArrayList<Integer>(numChildServices);
for (int i = 0; i < numChildServices; i++) {
mFreeConnectionIndices.add(i);
}
setServiceClass(inSandbox ?
SandboxedProcessService.class : PrivilegedProcessService.class);
mInSandbox = inSandbox;
}
public void setServiceClass(Class<? extends ChildProcessService> childClass) {
mChildClass = childClass;
}
public ChildProcessConnection allocate(
Context context, ChildProcessConnection.DeathCallback deathCallback,
LinkerParams linkerParams) {
synchronized(mConnectionLock) {
if (mFreeConnectionIndices.isEmpty()) {
Log.w(TAG, "Ran out of service." );
return null;
}
int slot = mFreeConnectionIndices.remove(0);
assert mChildProcessConnections[slot] == null;
mChildProcessConnections[slot] = new ChildProcessConnection(context, slot,
mInSandbox, deathCallback, mChildClass, linkerParams);
return mChildProcessConnections[slot];
}
}
public void free(ChildProcessConnection connection) {
synchronized(mConnectionLock) {
int slot = connection.getServiceNumber();
if (mChildProcessConnections[slot] != connection) {
int occupier = mChildProcessConnections[slot] == null ?
-1 : mChildProcessConnections[slot].getServiceNumber();
Log.e(TAG, "Unable to find connection to free in slot: " + slot +
" already occupied by service: " + occupier);
assert false;
} else {
mChildProcessConnections[slot] = null;
assert !mFreeConnectionIndices.contains(slot);
mFreeConnectionIndices.add(slot);
}
}
}
}
// Service class for child process. As the default value it uses SandboxedProcessService0 and
// PrivilegedProcessService0.
private static final ChildConnectionAllocator sSandboxedChildConnectionAllocator =
new ChildConnectionAllocator(true);
private static final ChildConnectionAllocator sPrivilegedChildConnectionAllocator =
new ChildConnectionAllocator(false);
private static boolean sConnectionAllocated = false;
// Sets service class for sandboxed service and privileged service.
public static void setChildProcessClass(
Class<? extends SandboxedProcessService> sandboxedServiceClass,
Class<? extends PrivilegedProcessService> privilegedServiceClass) {
// We should guarantee this is called before allocating connection.
assert !sConnectionAllocated;
sSandboxedChildConnectionAllocator.setServiceClass(sandboxedServiceClass);
sPrivilegedChildConnectionAllocator.setServiceClass(privilegedServiceClass);
}
private static ChildConnectionAllocator getConnectionAllocator(boolean inSandbox) {
return inSandbox ?
sSandboxedChildConnectionAllocator : sPrivilegedChildConnectionAllocator;
}
private static ChildProcessConnection allocateConnection(Context context,
boolean inSandbox, LinkerParams linkerParams) {
ChildProcessConnection.DeathCallback deathCallback =
new ChildProcessConnection.DeathCallback() {
@Override
public void onChildProcessDied(int pid) {
stop(pid);
}
};
sConnectionAllocated = true;
return getConnectionAllocator(inSandbox).allocate(context, deathCallback, linkerParams);
}
private static boolean sLinkerInitialized = false;
private static long sLinkerLoadAddress = 0;
private static LinkerParams getLinkerParamsForNewConnection() {
if (!sLinkerInitialized) {
if (Linker.isUsed()) {
sLinkerLoadAddress = Linker.getBaseLoadAddress();
if (sLinkerLoadAddress == 0) {
Log.i(TAG, "Shared RELRO support disabled!");
}
}
sLinkerInitialized = true;
}
if (sLinkerLoadAddress == 0)
return null;
// Always wait for the shared RELROs in service processes.
final boolean waitForSharedRelros = true;
return new LinkerParams(sLinkerLoadAddress,
waitForSharedRelros,
Linker.getTestRunnerClassName());
}
private static ChildProcessConnection allocateBoundConnection(Context context,
String[] commandLine, boolean inSandbox) {
LinkerParams linkerParams = getLinkerParamsForNewConnection();
ChildProcessConnection connection = allocateConnection(context, inSandbox, linkerParams);
if (connection != null) {
connection.start(commandLine);
}
return connection;
}
private static void freeConnection(ChildProcessConnection connection) {
if (connection == null) {
return;
}
getConnectionAllocator(connection.isInSandbox()).free(connection);
return;
}
// Represents an invalid process handle; same as base/process/process.h kNullProcessHandle.
private static final int NULL_PROCESS_HANDLE = 0;
// Map from pid to ChildService connection.
private static Map<Integer, ChildProcessConnection> sServiceMap =
new ConcurrentHashMap<Integer, ChildProcessConnection>();
// A pre-allocated and pre-bound connection ready for connection setup, or null.
private static ChildProcessConnection sSpareSandboxedConnection = null;
/**
* Manages oom bindings used to bound child services. "Oom binding" is a binding that raises the
* process oom priority so that it shouldn't be killed by the OS out-of-memory killer under
* normal conditions (it can still be killed under drastic memory pressure).
*
* This class serves a proxy between external calls that manipulate the bindings and the
* connections, allowing to enforce policies such as delayed removal of the bindings.
*/
static class BindingManager {
// Delay of 1 second used when removing the initial oom binding of a process.
private static final long REMOVE_INITIAL_BINDING_DELAY_MILLIS = 1 * 1000;
// Delay of 5 second used when removing temporary strong binding of a process (only on
// non-low-memory devices).
private static final long DETACH_AS_ACTIVE_HIGH_END_DELAY_MILLIS = 5 * 1000;
// Map from pid to the count of oom bindings bound for the service. Should be accessed with
// mCountLock.
private final SparseIntArray mOomBindingCount = new SparseIntArray();
// Pid of the renderer that was most recently oom bound. This is used on low-memory devices
// to drop oom bindings of a process when another one acquires them, making sure that only
// one renderer process at a time is oom bound. Should be accessed with mCountLock.
private int mLastOomPid = -1;
// Should be acquired before binding or unbinding the connections and modifying state
// variables: mOomBindingCount and mLastOomPid.
private final Object mCountLock = new Object();
/**
* Registers an oom binding bound for a child process. Should be called with mCountLock.
* @param pid handle of the process.
*/
private void incrementOomCount(int pid) {
mOomBindingCount.put(pid, mOomBindingCount.get(pid) + 1);
mLastOomPid = pid;
}
/**
* Registers an oom binding unbound for a child process. Should be called with mCountLock.
* @param pid handle of the process.
*/
private void decrementOomCount(int pid) {
int count = mOomBindingCount.get(pid, -1);
assert count > 0;
count--;
if (count > 0) {
mOomBindingCount.put(pid, count);
} else {
mOomBindingCount.delete(pid);
}
}
/**
* Drops all oom bindings for the given renderer.
* @param pid handle of the process.
*/
private void dropOomBindings(int pid) {
ChildProcessConnection connection = sServiceMap.get(pid);
if (connection == null) {
LogPidWarning(pid, "Tried to drop oom bindings for a non-existent connection");
return;
}
synchronized (mCountLock) {
connection.dropOomBindings();
mOomBindingCount.delete(pid);
}
}
/**
* Registers a freshly started child process. On low-memory devices this will also drop the
* oom bindings of the last process that was oom-bound. We can do that, because every time a
* connection is created on the low-end, it is used in foreground (no prerendering, no
* loading of tabs opened in background).
* @param pid handle of the process.
*/
void addNewConnection(int pid) {
synchronized (mCountLock) {
if (SysUtils.isLowEndDevice() && mLastOomPid >= 0) {
dropOomBindings(mLastOomPid);
}
// This will reset the previous entry for the pid in the unlikely event of the OS
// reusing renderer pids.
mOomBindingCount.put(pid, 0);
// Every new connection is bound with initial oom binding.
incrementOomCount(pid);
}
}
/**
* Remove the initial binding of the child process. Child processes are bound with initial
* binding to protect them from getting killed before they are put to use. This method
* allows to remove the binding once it is no longer needed. The binding is removed after a
* fixed delay period so that the renderer will not be killed immediately after the call.
*/
void removeInitialBinding(final int pid) {
final ChildProcessConnection connection = sServiceMap.get(pid);
if (connection == null) {
LogPidWarning(pid, "Tried to remove a binding for a non-existent connection");
return;
}
if (!connection.isInitialBindingBound()) return;
ThreadUtils.postOnUiThreadDelayed(new Runnable() {
@Override
public void run() {
synchronized (mCountLock) {
if (connection.isInitialBindingBound()) {
decrementOomCount(pid);
connection.removeInitialBinding();
}
}
}
}, REMOVE_INITIAL_BINDING_DELAY_MILLIS);
}
/**
* Bind a child process as a high priority process so that it has the same priority as the
* main process. This can be used for the foreground renderer process to distinguish it from
* the background renderer process.
* @param pid The process handle of the service connection.
*/
void bindAsHighPriority(final int pid) {
ChildProcessConnection connection = sServiceMap.get(pid);
if (connection == null) {
LogPidWarning(pid, "Tried to bind a non-existent connection");
return;
}
synchronized (mCountLock) {
connection.attachAsActive();
incrementOomCount(pid);
}
}
/**
* Unbind a high priority process which was previous bound with bindAsHighPriority.
* @param pid The process handle of the service.
*/
void unbindAsHighPriority(final int pid) {
final ChildProcessConnection connection = sServiceMap.get(pid);
if (connection == null) {
LogPidWarning(pid, "Tried to unbind non-existent connection");
return;
}
if (!connection.isStrongBindingBound()) return;
// This runnable performs the actual unbinding. It will be executed synchronously when
// on low-end devices and posted with a delay otherwise.
Runnable doUnbind = new Runnable() {
@Override
public void run() {
synchronized (mCountLock) {
if (connection.isStrongBindingBound()) {
decrementOomCount(pid);
connection.detachAsActive();
}
}
}
};
if (SysUtils.isLowEndDevice()) {
doUnbind.run();
} else {
ThreadUtils.postOnUiThreadDelayed(doUnbind, DETACH_AS_ACTIVE_HIGH_END_DELAY_MILLIS);
}
}
/**
* @return True iff the given service process is protected from the out-of-memory killing,
* or it was protected when it died (either crashed or was closed). This can be used to
* decide if a disconnection of a renderer was a crash or a probable out-of-memory kill. In
* the unlikely event of the OS reusing renderer pid, the call will refer to the most recent
* renderer of the given pid. The binding count is being reset in addNewConnection().
*/
boolean isOomProtected(int pid) {
synchronized (mCountLock) {
return mOomBindingCount.get(pid) > 0;
}
}
}
private static BindingManager sBindingManager = new BindingManager();
static BindingManager getBindingManager() {
return sBindingManager;
}
@CalledByNative
private static boolean isOomProtected(int pid) {
return sBindingManager.isOomProtected(pid);
}
/**
* Returns the child process service interface for the given pid. This may be called on
* any thread, but the caller must assume that the service can disconnect at any time. All
* service calls should catch and handle android.os.RemoteException.
*
* @param pid The pid (process handle) of the service obtained from {@link #start}.
* @return The IChildProcessService or null if the service no longer exists.
*/
public static IChildProcessService getChildService(int pid) {
ChildProcessConnection connection = sServiceMap.get(pid);
if (connection != null) {
return connection.getService();
}
return null;
}
/**
* Should be called early in startup so the work needed to spawn the child process can be done
* in parallel to other startup work. Must not be called on the UI thread. Spare connection is
* created in sandboxed child process.
* @param context the application context used for the connection.
*/
public static void warmUp(Context context) {
synchronized (ChildProcessLauncher.class) {
assert !ThreadUtils.runningOnUiThread();
if (sSpareSandboxedConnection == null) {
sSpareSandboxedConnection = allocateBoundConnection(context, null, true);
}
}
}
private static String getSwitchValue(final String[] commandLine, String switchKey) {
if (commandLine == null || switchKey == null) {
return null;
}
// This format should be matched with the one defined in command_line.h.
final String switchKeyPrefix = "--" + switchKey + "=";
for (String command : commandLine) {
if (command != null && command.startsWith(switchKeyPrefix)) {
return command.substring(switchKeyPrefix.length());
}
}
return null;
}
/**
* Spawns and connects to a child process. May be called on any thread. It will not block, but
* will instead callback to {@link #nativeOnChildProcessStarted} when the connection is
* established. Note this callback will not necessarily be from the same thread (currently it
* always comes from the main thread).
*
* @param context Context used to obtain the application context.
* @param commandLine The child process command line argv.
* @param file_ids The ID that should be used when mapping files in the created process.
* @param file_fds The file descriptors that should be mapped in the created process.
* @param file_auto_close Whether the file descriptors should be closed once they were passed to
* the created process.
* @param clientContext Arbitrary parameter used by the client to distinguish this connection.
*/
@CalledByNative
static void start(
Context context,
final String[] commandLine,
int[] fileIds,
int[] fileFds,
boolean[] fileAutoClose,
final int clientContext) {
assert fileIds.length == fileFds.length && fileFds.length == fileAutoClose.length;
FileDescriptorInfo[] filesToBeMapped = new FileDescriptorInfo[fileFds.length];
for (int i = 0; i < fileFds.length; i++) {
filesToBeMapped[i] =
new FileDescriptorInfo(fileIds[i], fileFds[i], fileAutoClose[i]);
}
assert clientContext != 0;
int callbackType = CALLBACK_FOR_UNKNOWN_PROCESS;
boolean inSandbox = true;
String processType = getSwitchValue(commandLine, SWITCH_PROCESS_TYPE);
if (SWITCH_RENDERER_PROCESS.equals(processType)) {
callbackType = CALLBACK_FOR_RENDERER_PROCESS;
} else if (SWITCH_GPU_PROCESS.equals(processType)) {
callbackType = CALLBACK_FOR_GPU_PROCESS;
} else if (SWITCH_PPAPI_BROKER_PROCESS.equals(processType)) {
inSandbox = false;
}
ChildProcessConnection allocatedConnection = null;
synchronized (ChildProcessLauncher.class) {
if (inSandbox) {
allocatedConnection = sSpareSandboxedConnection;
sSpareSandboxedConnection = null;
}
}
if (allocatedConnection == null) {
allocatedConnection = allocateBoundConnection(context, commandLine, inSandbox);
if (allocatedConnection == null) {
// Notify the native code so it can free the heap allocated callback.
nativeOnChildProcessStarted(clientContext, 0);
return;
}
}
final ChildProcessConnection connection = allocatedConnection;
Log.d(TAG, "Setting up connection to process: slot=" + connection.getServiceNumber());
ChildProcessConnection.ConnectionCallback connectionCallback =
new ChildProcessConnection.ConnectionCallback() {
public void onConnected(int pid) {
Log.d(TAG, "on connect callback, pid=" + pid + " context=" + clientContext);
if (pid != NULL_PROCESS_HANDLE) {
sBindingManager.addNewConnection(pid);
sServiceMap.put(pid, connection);
} else {
freeConnection(connection);
}
nativeOnChildProcessStarted(clientContext, pid);
}
};
// TODO(sievers): Revisit this as it doesn't correctly handle the utility process
// assert callbackType != CALLBACK_FOR_UNKNOWN_PROCESS;
connection.setupConnection(commandLine,
filesToBeMapped,
createCallback(callbackType),
connectionCallback,
Linker.getSharedRelros());
}
/**
* Terminates a child process. This may be called from any thread.
*
* @param pid The pid (process handle) of the service connection obtained from {@link #start}.
*/
@CalledByNative
static void stop(int pid) {
Log.d(TAG, "stopping child connection: pid=" + pid);
ChildProcessConnection connection = sServiceMap.remove(pid);
if (connection == null) {
LogPidWarning(pid, "Tried to stop non-existent connection");
return;
}
connection.stop();
freeConnection(connection);
}
/**
* This implementation is used to receive callbacks from the remote service.
*/
private static IChildProcessCallback createCallback(final int callbackType) {
return new IChildProcessCallback.Stub() {
/**
* This is called by the remote service regularly to tell us about new values. Note that
* IPC calls are dispatched through a thread pool running in each process, so the code
* executing here will NOT be running in our main thread -- so, to update the UI, we
* need to use a Handler.
*/
@Override
public void establishSurfacePeer(
int pid, Surface surface, int primaryID, int secondaryID) {
// Do not allow a malicious renderer to connect to a producer. This is only used
// from stream textures managed by the GPU process.
if (callbackType != CALLBACK_FOR_GPU_PROCESS) {
Log.e(TAG, "Illegal callback for non-GPU process.");
return;
}
nativeEstablishSurfacePeer(pid, surface, primaryID, secondaryID);
}
@Override
public Surface getViewSurface(int surfaceId) {
// Do not allow a malicious renderer to get to our view surface.
if (callbackType != CALLBACK_FOR_GPU_PROCESS) {
Log.e(TAG, "Illegal callback for non-GPU process.");
return null;
}
return nativeGetViewSurface(surfaceId);
}
};
};
private static void LogPidWarning(int pid, String message) {
// This class is effectively a no-op in single process mode, so don't log warnings there.
if (pid > 0 && !nativeIsSingleProcess()) {
Log.w(TAG, message + ", pid=" + pid);
}
}
private static native void nativeOnChildProcessStarted(int clientContext, int pid);
private static native Surface nativeGetViewSurface(int surfaceId);
private static native void nativeEstablishSurfacePeer(
int pid, Surface surface, int primaryID, int secondaryID);
private static native boolean nativeIsSingleProcess();
}
| cvsuser-chromium/chromium | content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java | Java | bsd-3-clause | 26,544 |
class Module:
def __init__(self, mainMenu, params=[]):
# metadata info about the module, not modified during runtime
self.info = {
# name for the module that will appear in module menus
'Name': 'Get FileServers',
# list of one or more authors for the module
'Author': ['@424f424f'],
# more verbose multi-line description of the module
'Description': 'This module will list file servers',
# True if the module needs to run in the background
'Background' : False,
# File extension to save the file as
'OutputExtension' : "",
# if the module needs administrative privileges
'NeedsAdmin' : False,
# True if the method doesn't touch disk/is reasonably opsec safe
'OpsecSafe' : True,
# the module language
'Language' : 'python',
# the minimum language version needed
'MinLanguageVersion' : '2.6',
# list of any references/other comments
'Comments': ['']
}
# any options needed by the module, settable during runtime
self.options = {
# format:
# value_name : {description, required, default_value}
'Agent' : {
# The 'Agent' option is the only one that MUST be in a module
'Description' : 'Agent to run on.',
'Required' : True,
'Value' : ''
},
'LDAPAddress' : {
# The 'Agent' option is the only one that MUST be in a module
'Description' : 'LDAP IP/Hostname',
'Required' : True,
'Value' : ''
},
'BindDN' : {
# The 'Agent' option is the only one that MUST be in a module
'Description' : 'user@penlab.local',
'Required' : True,
'Value' : ''
},
'Password' : {
# The 'Agent' option is the only one that MUST be in a module
'Description' : 'Password to connect to LDAP',
'Required' : False,
'Value' : ''
}
}
# save off a copy of the mainMenu object to access external functionality
# like listeners/agent handlers/etc.
self.mainMenu = mainMenu
# During instantiation, any settable option parameters
# are passed as an object set to the module and the
# options dictionary is automatically set. This is mostly
# in case options are passed on the command line
if params:
for param in params:
# parameter format is [Name, Value]
option, value = param
if option in self.options:
self.options[option]['Value'] = value
def generate(self, obfuscate=False, obfuscationCommand=""):
LDAPAddress = self.options['LDAPAddress']['Value']
BindDN = self.options['BindDN']['Value']
password = self.options['Password']['Value']
# the Python script itself, with the command to invoke
# for execution appended to the end. Scripts should output
# everything to the pipeline for proper parsing.
#
# the script should be stripped of comments, with a link to any
# original reference script included in the comments.
script = """
import sys, os, subprocess, re
BindDN = "%s"
LDAPAddress = "%s"
password = "%s"
regex = re.compile('.+@([^.]+)\..+')
global tld
match = re.match(regex, BindDN)
tld = match.group(1)
global ext
ext = BindDN.split('.')[1]
cmd = \"""ldapsearch -x -h {} -b "dc={},dc={}" -D {} -w {} "(&(samAccountType=805306368))" ""\".format(LDAPAddress, tld, ext, BindDN, password)
output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=1)
with output.stdout:
print ""
for line in iter(output.stdout.readline, b''):
if ("homeDirectory" or "scriptPath" or "profilePath") in line:
print "Results:"
print ""
m = re.search(r'([^\]*)', line)
if m:
print m.group(1)
output.wait()
print ""
""" % (BindDN, LDAPAddress, password)
return script
| EmpireProject/Empire | lib/modules/python/situational_awareness/network/active_directory/get_fileservers.py | Python | bsd-3-clause | 4,433 |
// ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2015, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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 <iostream>
#include <sstream>
#include <seqan/index.h>
#include <seqan/stream.h>
SEQAN_DEFINE_TEST(test_index_drawing_esa_dot)
{
seqan::CharString myString = "banana";
seqan::Index<seqan::CharString> stree(myString);
std::stringstream sstream;
writeRecords(sstream, stree, seqan::DotDrawing());
std::stringstream expected;
expected << "digraph G {\n"
<< "\n"
<< "/* Graph Attributes */\n"
<< "graph [rankdir = LR];\n"
<< "\n"
<< "/* Node Attributes */\n"
<< "node [shape = ellipse, fillcolor = lightgrey, style = filled, fontname = \"Times-Italic\"];\n"
<< "\n"
<< "/* Edge Attributes */\n"
<< "edge [fontname = \"Times-Italic\", arrowsize = 0.75, fontsize = 16];\n"
<< "\n"
<< "/* Edges */\n"
<< "\"[0:6)\" [style = dashed];\n"
<< "\"[0:3)\";\n"
<< "\"[0:6)\" -> \"[0:3)\" [label = \"a\"];\n"
<< "\"[1:3)\";\n"
<< "\"[0:3)\" -> \"[1:3)\" [label = \"na\"];\n"
<< "\"[2:3)\";\n"
<< "\"[1:3)\" -> \"[2:3)\" [label = \"na\"];\n"
<< "\"[3:4)\";\n"
<< "\"[0:6)\" -> \"[3:4)\" [label = \"banana\"];\n"
<< "\"[4:6)\";\n"
<< "\"[0:6)\" -> \"[4:6)\" [label = \"na\"];\n"
<< "\"[5:6)\";\n"
<< "\"[4:6)\" -> \"[5:6)\" [label = \"na\"];\n"
<< "\n"
<< "}\n";
SEQAN_ASSERT_EQ(expected.str(), sstream.str());
}
SEQAN_BEGIN_TESTSUITE(test_index_drawing)
{
SEQAN_CALL_TEST(test_index_drawing_esa_dot);
}
SEQAN_END_TESTSUITE
| catkira/seqan | tests/index/test_index_drawing.cpp | C++ | bsd-3-clause | 3,608 |
using System;
using System.Configuration;
using System.DirectoryServices.AccountManagement;
using System.Threading.Tasks;
using Umbraco.Core.Models.Identity;
namespace Umbraco.Core.Security
{
public class ActiveDirectoryBackOfficeUserPasswordChecker : IBackOfficeUserPasswordChecker
{
public virtual string ActiveDirectoryDomain
{
get
{
return ConfigurationManager.AppSettings["ActiveDirectoryDomain"];
}
}
public Task<BackOfficeUserPasswordCheckerResult> CheckPasswordAsync(BackOfficeIdentityUser user, string password)
{
bool isValid;
using (var pc = new PrincipalContext(ContextType.Domain, ActiveDirectoryDomain))
{
isValid = pc.ValidateCredentials(user.UserName, password);
}
if (isValid && user.HasIdentity == false)
{
//TODO: the user will need to be created locally (i.e. auto-linked)
throw new NotImplementedException("The user " + user.UserName + " does not exist locally and currently the " + typeof(ActiveDirectoryBackOfficeUserPasswordChecker) + " doesn't support auto-linking, see http://issues.umbraco.org/issue/U4-10181");
}
var result = isValid
? BackOfficeUserPasswordCheckerResult.ValidCredentials
: BackOfficeUserPasswordCheckerResult.InvalidCredentials;
return Task.FromResult(result);
}
}
}
| abryukhov/Umbraco-CMS | src/Umbraco.Core/Security/ActiveDirectoryBackOfficeUserPasswordChecker.cs | C# | mit | 1,537 |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Validation;
using Umbraco.Web.WebApi;
namespace Umbraco.Web.Models.ContentEditing
{
/// <summary>
/// A model representing a basic content item
/// </summary>
[DataContract(Name = "content", Namespace = "")]
public class ContentItemBasic : EntityBasic
{
[DataMember(Name = "updateDate")]
public DateTime UpdateDate { get; set; }
[DataMember(Name = "createDate")]
public DateTime CreateDate { get; set; }
[DataMember(Name = "published")]
public bool Published { get; set; }
[DataMember(Name = "hasPublishedVersion")]
public bool HasPublishedVersion { get; set; }
[DataMember(Name = "owner")]
public UserProfile Owner { get; set; }
[DataMember(Name = "updater")]
public UserProfile Updater { get; set; }
[DataMember(Name = "contentTypeAlias", IsRequired = true)]
[Required(AllowEmptyStrings = false)]
public string ContentTypeAlias { get; set; }
[DataMember(Name = "sortOrder")]
public int SortOrder { get; set; }
protected bool Equals(ContentItemBasic other)
{
return Id == other.Id;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
var other = obj as ContentItemBasic;
return other != null && Equals(other);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
/// <summary>
/// A model representing a basic content item with properties
/// </summary>
[DataContract(Name = "content", Namespace = "")]
public class ContentItemBasic<T, TPersisted> : ContentItemBasic
where T : ContentPropertyBasic
where TPersisted : IContentBase
{
public ContentItemBasic()
{
//ensure its not null
_properties = new List<T>();
}
private IEnumerable<T> _properties;
[DataMember(Name = "properties")]
public virtual IEnumerable<T> Properties
{
get { return _properties; }
set { _properties = value; }
}
/// <summary>
/// The real persisted content object - used during inbound model binding
/// </summary>
/// <remarks>
/// This is not used for outgoing model information.
/// </remarks>
[IgnoreDataMember]
internal TPersisted PersistedContent { get; set; }
/// <summary>
/// The DTO object used to gather all required content data including data type information etc... for use with validation - used during inbound model binding
/// </summary>
/// <remarks>
/// We basically use this object to hydrate all required data from the database into one object so we can validate everything we need
/// instead of having to look up all the data individually.
/// This is not used for outgoing model information.
/// </remarks>
[IgnoreDataMember]
internal ContentItemDto<TPersisted> ContentDto { get; set; }
}
} | aaronpowell/Umbraco-CMS | src/Umbraco.Web/Models/ContentEditing/ContentItemBasic.cs | C# | mit | 3,538 |
package levigo
// #cgo LDFLAGS: -lleveldb
// #include "leveldb/c.h"
import "C"
// CompressionOpt is a value for Options.SetCompression.
type CompressionOpt int
// Known compression arguments for Options.SetCompression.
const (
NoCompression = CompressionOpt(0)
SnappyCompression = CompressionOpt(1)
)
// Options represent all of the available options when opening a database with
// Open. Options should be created with NewOptions.
//
// It is usually with to call SetCache with a cache object. Otherwise, all
// data will be read off disk.
//
// To prevent memory leaks, Close must be called on an Options when the
// program no longer needs it.
type Options struct {
Opt *C.leveldb_options_t
}
// ReadOptions represent all of the available options when reading from a
// database.
//
// To prevent memory leaks, Close must called on a ReadOptions when the
// program no longer needs it.
type ReadOptions struct {
Opt *C.leveldb_readoptions_t
}
// WriteOptions represent all of the available options when writeing from a
// database.
//
// To prevent memory leaks, Close must called on a WriteOptions when the
// program no longer needs it.
type WriteOptions struct {
Opt *C.leveldb_writeoptions_t
}
// NewOptions allocates a new Options object.
func NewOptions() *Options {
opt := C.leveldb_options_create()
return &Options{opt}
}
// NewReadOptions allocates a new ReadOptions object.
func NewReadOptions() *ReadOptions {
opt := C.leveldb_readoptions_create()
return &ReadOptions{opt}
}
// NewWriteOptions allocates a new WriteOptions object.
func NewWriteOptions() *WriteOptions {
opt := C.leveldb_writeoptions_create()
return &WriteOptions{opt}
}
// Close deallocates the Options, freeing its underlying C struct.
func (o *Options) Close() {
C.leveldb_options_destroy(o.Opt)
}
// SetComparator sets the comparator to be used for all read and write
// operations.
//
// The comparator that created a database must be the same one (technically,
// one with the same name string) that is used to perform read and write
// operations.
//
// The default comparator is usually sufficient.
func (o *Options) SetComparator(cmp *C.leveldb_comparator_t) {
C.leveldb_options_set_comparator(o.Opt, cmp)
}
// SetErrorIfExists, if passed true, will cause the opening of a database that
// already exists to throw an error.
func (o *Options) SetErrorIfExists(error_if_exists bool) {
eie := boolToUchar(error_if_exists)
C.leveldb_options_set_error_if_exists(o.Opt, eie)
}
// SetCache places a cache object in the database when a database is opened.
//
// This is usually wise to use. See also ReadOptions.SetFillCache.
func (o *Options) SetCache(cache *Cache) {
C.leveldb_options_set_cache(o.Opt, cache.Cache)
}
// SetEnv sets the Env object for the new database handle.
func (o *Options) SetEnv(env *Env) {
C.leveldb_options_set_env(o.Opt, env.Env)
}
// SetInfoLog sets a *C.leveldb_logger_t object as the informational logger
// for the database.
func (o *Options) SetInfoLog(log *C.leveldb_logger_t) {
C.leveldb_options_set_info_log(o.Opt, log)
}
// SetWriteBufferSize sets the number of bytes the database will build up in
// memory (backed by an unsorted log on disk) before converting to a sorted
// on-disk file.
func (o *Options) SetWriteBufferSize(s int) {
C.leveldb_options_set_write_buffer_size(o.Opt, C.size_t(s))
}
// SetParanoidChecks, when called with true, will cause the database to do
// aggressive checking of the data it is processing and will stop early if it
// detects errors.
//
// See the LevelDB documentation docs for details.
func (o *Options) SetParanoidChecks(pc bool) {
C.leveldb_options_set_paranoid_checks(o.Opt, boolToUchar(pc))
}
// SetMaxOpenFiles sets the number of files than can be used at once by the
// database.
//
// See the LevelDB documentation for details.
func (o *Options) SetMaxOpenFiles(n int) {
C.leveldb_options_set_max_open_files(o.Opt, C.int(n))
}
// SetBlockSize sets the approximate size of user data packed per block.
//
// The default is roughly 4096 uncompressed bytes. A better setting depends on
// your use case. See the LevelDB documentation for details.
func (o *Options) SetBlockSize(s int) {
C.leveldb_options_set_block_size(o.Opt, C.size_t(s))
}
// SetBlockRestartInterval is the number of keys between restarts points for
// delta encoding keys.
//
// Most clients should leave this parameter alone. See the LevelDB
// documentation for details.
func (o *Options) SetBlockRestartInterval(n int) {
C.leveldb_options_set_block_restart_interval(o.Opt, C.int(n))
}
// SetCompression sets whether to compress blocks using the specified
// compresssion algorithm.
//
// The default value is SnappyCompression and it is fast enough that it is
// unlikely you want to turn it off. The other option is NoCompression.
//
// If the LevelDB library was built without Snappy compression enabled, the
// SnappyCompression setting will be ignored.
func (o *Options) SetCompression(t CompressionOpt) {
C.leveldb_options_set_compression(o.Opt, C.int(t))
}
// SetCreateIfMissing causes Open to create a new database on disk if it does
// not already exist.
func (o *Options) SetCreateIfMissing(b bool) {
C.leveldb_options_set_create_if_missing(o.Opt, boolToUchar(b))
}
// SetFilterPolicy causes Open to create a new database that will uses filter
// created from the filter policy passed in.
func (o *Options) SetFilterPolicy(fp *FilterPolicy) {
var policy *C.leveldb_filterpolicy_t
if fp != nil {
policy = fp.Policy
}
C.leveldb_options_set_filter_policy(o.Opt, policy)
}
// Close deallocates the ReadOptions, freeing its underlying C struct.
func (ro *ReadOptions) Close() {
C.leveldb_readoptions_destroy(ro.Opt)
}
// SetVerifyChecksums controls whether all data read with this ReadOptions
// will be verified against corresponding checksums.
//
// It defaults to false. See the LevelDB documentation for details.
func (ro *ReadOptions) SetVerifyChecksums(b bool) {
C.leveldb_readoptions_set_verify_checksums(ro.Opt, boolToUchar(b))
}
// SetFillCache controls whether reads performed with this ReadOptions will
// fill the Cache of the server. It defaults to true.
//
// It is useful to turn this off on ReadOptions for DB.Iterator (and DB.Get)
// calls used in offline threads to prevent bulk scans from flushing out live
// user data in the cache.
//
// See also Options.SetCache
func (ro *ReadOptions) SetFillCache(b bool) {
C.leveldb_readoptions_set_fill_cache(ro.Opt, boolToUchar(b))
}
// SetSnapshot causes reads to provided as they were when the passed in
// Snapshot was created by DB.NewSnapshot. This is useful for getting
// consistent reads during a bulk operation.
//
// See the LevelDB documentation for details.
func (ro *ReadOptions) SetSnapshot(snap *Snapshot) {
var s *C.leveldb_snapshot_t
if snap != nil {
s = snap.snap
}
C.leveldb_readoptions_set_snapshot(ro.Opt, s)
}
// Close deallocates the WriteOptions, freeing its underlying C struct.
func (wo *WriteOptions) Close() {
C.leveldb_writeoptions_destroy(wo.Opt)
}
// SetSync controls whether each write performed with this WriteOptions will
// be flushed from the operating system buffer cache before the write is
// considered complete.
//
// If called with true, this will signficantly slow down writes. If called
// with false, and the host machine crashes, some recent writes may be
// lost. The default is false.
//
// See the LevelDB documentation for details.
func (wo *WriteOptions) SetSync(b bool) {
C.leveldb_writeoptions_set_sync(wo.Opt, boolToUchar(b))
}
| influxdb/levigo | options.go | GO | mit | 7,553 |
version https://git-lfs.github.com/spec/v1
oid sha256:ac03974d85317d75edc2dc62eb1c40e9514aae0dcfe5e69e3a62c6d419484632
size 887
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.9.7/cldr/monetary.js | JavaScript | mit | 128 |
version https://git-lfs.github.com/spec/v1
oid sha256:98117aa63db915fed8f72d5c0c414049013e63982817c75864b5e01bb3997090
size 17927
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.9.1/dd-drop/dd-drop-debug.js | JavaScript | mit | 130 |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network.Models
{
using Azure;
using Management;
using Network;
using Rest;
using Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Public IP address resource.
/// </summary>
[JsonTransformation]
public partial class PublicIPAddress : Resource
{
/// <summary>
/// Initializes a new instance of the PublicIPAddress class.
/// </summary>
public PublicIPAddress() { }
/// <summary>
/// Initializes a new instance of the PublicIPAddress class.
/// </summary>
/// <param name="id">Resource ID.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type.</param>
/// <param name="location">Resource location.</param>
/// <param name="tags">Resource tags.</param>
/// <param name="publicIPAllocationMethod">The public IP allocation
/// method. Possible values are: 'Static' and 'Dynamic'. Possible
/// values include: 'Static', 'Dynamic'</param>
/// <param name="publicIPAddressVersion">The public IP address version.
/// Possible values are: 'IPv4' and 'IPv6'. Possible values include:
/// 'IPv4', 'IPv6'</param>
/// <param name="dnsSettings">The FQDN of the DNS record associated
/// with the public IP address.</param>
/// <param name="idleTimeoutInMinutes">The idle timeout of the public
/// IP address.</param>
/// <param name="resourceGuid">The resource GUID property of the public
/// IP resource.</param>
/// <param name="provisioningState">The provisioning state of the
/// PublicIP resource. Possible values are: 'Updating', 'Deleting', and
/// 'Failed'.</param>
/// <param name="etag">A unique read-only string that changes whenever
/// the resource is updated.</param>
public PublicIPAddress(string id = default(string), string name = default(string), string type = default(string), string location = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string publicIPAllocationMethod = default(string), string publicIPAddressVersion = default(string), IPConfiguration ipConfiguration = default(IPConfiguration), PublicIPAddressDnsSettings dnsSettings = default(PublicIPAddressDnsSettings), string ipAddress = default(string), int? idleTimeoutInMinutes = default(int?), string resourceGuid = default(string), string provisioningState = default(string), string etag = default(string))
: base(id, name, type, location, tags)
{
PublicIPAllocationMethod = publicIPAllocationMethod;
PublicIPAddressVersion = publicIPAddressVersion;
IpConfiguration = ipConfiguration;
DnsSettings = dnsSettings;
IpAddress = ipAddress;
IdleTimeoutInMinutes = idleTimeoutInMinutes;
ResourceGuid = resourceGuid;
ProvisioningState = provisioningState;
Etag = etag;
}
/// <summary>
/// Gets or sets the public IP allocation method. Possible values are:
/// 'Static' and 'Dynamic'. Possible values include: 'Static',
/// 'Dynamic'
/// </summary>
[JsonProperty(PropertyName = "properties.publicIPAllocationMethod")]
public string PublicIPAllocationMethod { get; set; }
/// <summary>
/// Gets or sets the public IP address version. Possible values are:
/// 'IPv4' and 'IPv6'. Possible values include: 'IPv4', 'IPv6'
/// </summary>
[JsonProperty(PropertyName = "properties.publicIPAddressVersion")]
public string PublicIPAddressVersion { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "properties.ipConfiguration")]
public IPConfiguration IpConfiguration { get; protected set; }
/// <summary>
/// Gets or sets the FQDN of the DNS record associated with the public
/// IP address.
/// </summary>
[JsonProperty(PropertyName = "properties.dnsSettings")]
public PublicIPAddressDnsSettings DnsSettings { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "properties.ipAddress")]
public string IpAddress { get; set; }
/// <summary>
/// Gets or sets the idle timeout of the public IP address.
/// </summary>
[JsonProperty(PropertyName = "properties.idleTimeoutInMinutes")]
public int? IdleTimeoutInMinutes { get; set; }
/// <summary>
/// Gets or sets the resource GUID property of the public IP resource.
/// </summary>
[JsonProperty(PropertyName = "properties.resourceGuid")]
public string ResourceGuid { get; set; }
/// <summary>
/// Gets or sets the provisioning state of the PublicIP resource.
/// Possible values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; set; }
/// <summary>
/// Gets or sets a unique read-only string that changes whenever the
/// resource is updated.
/// </summary>
[JsonProperty(PropertyName = "etag")]
public string Etag { get; set; }
}
}
| AzCiS/azure-sdk-for-net | src/SDKs/Network/Management.Network/Generated/Models/PublicIpAddress.cs | C# | mit | 5,851 |
/*
* Copyright (c) 2002-2008 LWJGL Project
* 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 'LWJGL' 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 org.lwjgl.opengl;
public interface ATI_texture_float {
/**
* Accepted by the <internalFormat> parameter of TexImage1D,
* TexImage2D, and TexImage3D:
*/
int GL_RGBA_FLOAT32_ATI = 0x8814;
int GL_RGB_FLOAT32_ATI = 0x8815;
int GL_ALPHA_FLOAT32_ATI = 0x8816;
int GL_INTENSITY_FLOAT32_ATI = 0x8817;
int GL_LUMINANCE_FLOAT32_ATI = 0x8818;
int GL_LUMINANCE_ALPHA_FLOAT32_ATI = 0x8819;
int GL_RGBA_FLOAT16_ATI = 0x881A;
int GL_RGB_FLOAT16_ATI = 0x881B;
int GL_ALPHA_FLOAT16_ATI = 0x881C;
int GL_INTENSITY_FLOAT16_ATI = 0x881D;
int GL_LUMINANCE_FLOAT16_ATI = 0x881E;
int GL_LUMINANCE_ALPHA_FLOAT16_ATI = 0x881F;
}
| andrewmcvearry/mille-bean | lwjgl/src/templates/org/lwjgl/opengl/ATI_texture_float.java | Java | mit | 2,261 |
<?php
namespace Kunstmaan\AdminListBundle\AdminList\FilterType\DBAL;
use DateTime;
use Symfony\Component\HttpFoundation\Request;
/**
* DateTimeFilterType
*/
class DateTimeFilterType extends AbstractDBALFilterType
{
/**
* @param Request $request The request
* @param array &$data The data
* @param string $uniqueId The unique identifier
*/
public function bindRequest(Request $request, array &$data, $uniqueId)
{
$data['comparator'] = $request->query->get('filter_comparator_' . $uniqueId);
$data['value'] = $request->query->get('filter_value_' . $uniqueId);
}
/**
* @param array $data The data
* @param string $uniqueId The unique identifier
*/
public function apply(array $data, $uniqueId)
{
if (isset($data['value']) && isset($data['comparator'])) {
/** @var DateTime $datetime */
$date = empty($data['value']['date']) ? date('d/m/Y') : $data['value']['date'];
$time = empty($data['value']['time']) ? date('H:i') : $data['value']['time'];
$dateTime = DateTime::createFromFormat('d/m/Y H:i', $date . ' ' . $time);
if (false === $dateTime) {
// Failed to create DateTime object.
return;
}
switch ($data['comparator']) {
case 'before':
$this->queryBuilder->andWhere($this->queryBuilder->expr()->lte($this->getAlias() . $this->columnName, ':var_' . $uniqueId));
break;
case 'after':
$this->queryBuilder->andWhere($this->queryBuilder->expr()->gt($this->getAlias() . $this->columnName, ':var_' . $uniqueId));
break;
}
$this->queryBuilder->setParameter('var_' . $uniqueId, $dateTime->format('Y-m-d H:i'));
}
}
/**
* @return string
*/
public function getTemplate()
{
return 'KunstmaanAdminListBundle:FilterType:dateTimeFilter.html.twig';
}
}
| iBenito/KunstmaanBundlesCMS | src/Kunstmaan/AdminListBundle/AdminList/FilterType/DBAL/DateTimeFilterType.php | PHP | mit | 2,049 |
module Fog
module Radosgw
VERSION = "0.0.4"
end
end
| sho-wtag/catarse-2.0 | vendor/bundle/ruby/2.2.0/gems/fog-radosgw-0.0.4/lib/fog/radosgw/version.rb | Ruby | mit | 60 |
// Type definitions for bufferstream v0.6.2
// Project: https://github.com/dodo/node-bufferstream
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module 'bufferstream' {
import stream = require('stream');
export = BufferStream;
class BufferStream extends stream.Duplex {
constructor(options?: BufferStream.Opts);
/*
different buffer behaviors can be triggered by size:
none when output drains, bufferstream drains too
flexible buffers everthing that it gets and not piping out
<number> TODO buffer has given size. buffers everthing until buffer is full. when buffer is full then the stream will drain
*/
setSize(size: string): void; // can be one of ['none', 'flexible', <number>]
setSize(size: number): void; // can be one of ['none', 'flexible', <number>]
/*
enables stream buffering default
*/
enable(): void;
/*
flushes buffer and disables stream buffering. BufferStream now pipes all data as long as the output accepting data. when the output is draining BufferStream will buffer all input temporary.
token[s] buffer splitters (should be String or Buffer)
disables given tokens. wont flush until no splitter tokens are left.
*/
disable(): void;
disable(token: string, ...tokens: string[]): void;
disable(tokens: string[]): void; // Array
disable(token: Buffer, ...tokens: Buffer[]): void;
disable(tokens: Buffer[]): void; // Array
/*
each time BufferStream finds a splitter token in the input data it will emit a split event. this also works for binary data.
token[s] buffer splitters (should be String or Buffer)
*/
split(token: string, ...tokens: string[]): void;
split(tokens: string[]): void; // Array
split(token: Buffer, ...tokens: Buffer[]): void;
split(tokens: Buffer[]): void; // Array
/*
returns Buffer.
*/
getBuffer(): Buffer;
/*
returns Buffer.
*/
buffer: Buffer;
/*
shortcut for buffer.toString()
*/
toString(): string;
/*
shortcut for buffer.length
*/
length: number;
}
namespace BufferStream {
export interface Opts {
/*
default encoding for writing strings
*/
encoding?: string;
/*
if true and the source is a child_process the stream will block the entire process (timeouts wont work anymore, but splitting and listening on data still works, because they work sync)
*/
blocking?: boolean;
/*
defines buffer level or sets buffer to given size (see ↓setSize for more)
*/
size?: any;
/*
immediately call disable
*/
disabled?: boolean;
/*
short form for:
split(token, function (chunk) {emit('data', chunk)})
*/
// String or Buffer
split?: any;
}
export var fn: {warn: boolean};
}
}
declare module 'bufferstream/postbuffer' {
import http = require('http');
import BufferStream = require('bufferstream');
class PostBuffer extends BufferStream {
/*
for if you want to get all the post data from a http server request and do some db reqeust before.
http client buffer
*/
constructor(req: http.IncomingMessage);
/*
set a callback to get all post data from a http server request
*/
onEnd(callback: (data: any) => void): void;
/*
pumps data into another stream to allow incoming streams given options will be passed to Stream.pipe
*/
pipe(stream: NodeJS.WritableStream, options?: BufferStream.Opts): NodeJS.ReadableStream;
}
export = PostBuffer;
}
| yuit/DefinitelyTyped | bufferstream/bufferstream.d.ts | TypeScript | mit | 3,540 |
"use strict";import"../../Stock/Indicators/SlowStochastic/SlowStochasticIndicator.js"; | cdnjs/cdnjs | ajax/libs/highcharts/9.3.3/es-modules/masters/indicators/slow-stochastic.src.min.js | JavaScript | mit | 86 |
/**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* 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
*/
package org.openhab.binding.ihc.ws;
import java.util.List;
import org.openhab.binding.ihc.ws.datatypes.WSBaseDataType;
import org.openhab.binding.ihc.ws.datatypes.WSControllerState;
import org.openhab.binding.ihc.ws.datatypes.WSFile;
import org.openhab.binding.ihc.ws.datatypes.WSProjectInfo;
/**
* Class to handle IHC / ELKO LS Controller's controller service.
*
* Controller service is used to fetch information from the controller.
* E.g. Project file or controller status.
*
* @author Pauli Anttila
* @since 1.5.0
*/
public class IhcControllerService extends IhcHttpsClient {
private static String emptyQuery = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<soapenv:Body>"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
private String url;
List<String> cookies;
IhcControllerService(String host) {
url = "https://" + host + "/ws/ControllerService";
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
/**
* Query project information from the controller.
*
* @return project information.
* @throws IhcExecption
*/
public synchronized WSProjectInfo getProjectInfo() throws IhcExecption {
openConnection(url);
super.setCookies(cookies);
setRequestProperty("SOAPAction", "getProjectInfo");
String response = sendQuery(emptyQuery);
closeConnection();
WSProjectInfo projectInfo = new WSProjectInfo();
projectInfo.encodeData(response);
return projectInfo;
}
/**
* Query number of segments project contains.
*
* @return number of segments.
*/
public synchronized int getProjectNumberOfSegments() throws IhcExecption {
openConnection(url);
super.setCookies(cookies);
setRequestProperty("SOAPAction", "getIHCProjectNumberOfSegments");
String response = sendQuery(emptyQuery);
String numberOfSegments = WSBaseDataType.parseValue(response,
"/SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:getIHCProjectNumberOfSegments1");
closeConnection();
return Integer.parseInt(numberOfSegments);
}
/**
* Query segmentation size.
*
* @return segmentation size in bytes.
*/
public synchronized int getProjectSegmentationSize() throws IhcExecption {
openConnection(url);
super.setCookies(cookies);
setRequestProperty("SOAPAction", "getIHCProjectSegmentationSize");
String response = sendQuery(emptyQuery);
String segmentationSize = WSBaseDataType.parseValue(response,
"/SOAP-ENV:Envelope/SOAP-ENV:Body/ns1:getIHCProjectSegmentationSize1");
closeConnection();
return Integer.parseInt(segmentationSize);
}
/**
* Query project segment data.
*
* @param index
* segments index.
* @param major
* project major revision number.
* @param minor
* project minor revision number.
* @return segments data.
*/
public synchronized WSFile getProjectSegment(int index, int major, int minor)
throws IhcExecption {
final String soapQuery = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<soap:Body>"
+ " <ns1:getIHCProjectSegment1 xmlns:ns1=\"utcs\" xsi:type=\"xsd:int\">%s</ns1:getIHCProjectSegment1>"
+ " <ns2:getIHCProjectSegment2 xmlns:ns2=\"utcs\" xsi:type=\"xsd:int\">%s</ns2:getIHCProjectSegment2>"
+ " <ns3:getIHCProjectSegment3 xmlns:ns3=\"utcs\" xsi:type=\"xsd:int\">%s</ns3:getIHCProjectSegment3>"
+ "</soap:Body>"
+ "</soap:Envelope>";
String query = String.format(soapQuery, index, major, minor);
openConnection(url);
super.setCookies(cookies);
setRequestProperty("SOAPAction", "getIHCProjectSegment");
String response = sendQuery(query);
closeConnection();
WSFile file = new WSFile();
file.encodeData(response);
return file;
}
/**
* Query controller current state.
*
* @return controller's current state.
*/
public synchronized WSControllerState getControllerState()
throws IhcExecption {
openConnection(url);
super.setCookies(cookies);
setRequestProperty("SOAPAction", "getState");
String response = sendQuery(emptyQuery);
WSControllerState controllerState = new WSControllerState();
controllerState.encodeData(response);
return controllerState;
}
/**
* Wait controller state change notification.
*
* @param previousState
* Previous controller state.
* @param timeoutInSeconds
* How many seconds to wait notifications.
* @return current controller state.
*/
public synchronized WSControllerState waitStateChangeNotifications(
WSControllerState previousState, int timeoutInSeconds)
throws IhcExecption {
final String soapQuery = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<soapenv:Header/>"
+ "<soapenv:Body>"
+ " <ns1:waitForControllerStateChange1 xmlns:ns1=\"utcs\" xsi:type=\"ns1:WSControllerState\">"
+ " <ns1:state xsi:type=\"xsd:string\">%s</ns1:state>"
+ " </ns1:waitForControllerStateChange1>"
+ " <ns2:waitForControllerStateChange2 xmlns:ns2=\"utcs\" xsi:type=\"xsd:int\">%s</ns2:waitForControllerStateChange2>"
+ "</soapenv:Body>"
+ "</soapenv:Envelope>";
String query = String.format(soapQuery, previousState.getState(), timeoutInSeconds);
openConnection(url);
super.setCookies(cookies);
setRequestProperty("SOAPAction", "waitForControllerStateChange");
setTimeout(getTimeout() + timeoutInSeconds * 1000);
String response = sendQuery(query);
closeConnection();
WSControllerState controllerState = new WSControllerState();
controllerState.encodeData(response);
return controllerState;
}
}
| rahulopengts/myhome | bundles/binding/org.openhab.binding.ihc/src/main/java/org/openhab/binding/ihc/ws/IhcControllerService.java | Java | epl-1.0 | 6,258 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
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 "Protocol.hpp"
#include "Util/CRC.hpp"
#include "Device/Port/Port.hpp"
#include "Operation/Operation.hpp"
#include "Time/TimeoutClock.hpp"
#include <string.h>
bool
Volkslogger::Reset(Port &port, OperationEnvironment &env, unsigned n)
{
static constexpr unsigned delay = 2;
while (n-- > 0) {
if (!port.Write(CAN))
return false;
env.Sleep(delay);
}
return true;
}
bool
Volkslogger::Handshake(Port &port, OperationEnvironment &env,
unsigned timeout_ms)
{
TimeoutClock timeout(timeout_ms);
while (true) { // Solange R's aussenden, bis ein L zurückkommt
if (!port.Write('R'))
return false;
int remaining = timeout.GetRemainingSigned();
if (remaining < 0)
return false;
if (remaining > 500)
remaining = 500;
Port::WaitResult result =
port.WaitForChar('L', env, remaining);
if (result == Port::WaitResult::READY)
break;
if (result != Port::WaitResult::TIMEOUT)
return false;
/* timeout, try again */
}
unsigned count = 1;
while (true) { // Auf 4 hintereinanderfolgende L's warten
int remaining = timeout.GetRemainingSigned();
if (remaining < 0)
return false;
if (port.WaitForChar('L', env, remaining) != Port::WaitResult::READY)
return false;
count++;
if (count >= 4)
return true;
}
}
bool
Volkslogger::Connect(Port &port, OperationEnvironment &env,
unsigned timeout_ms)
{
return Reset(port, env, 10) && Handshake(port, env, timeout_ms);
}
bool
Volkslogger::ConnectAndFlush(Port &port, OperationEnvironment &env,
unsigned timeout_ms)
{
port.Flush();
return Connect(port, env, timeout_ms) && port.FullFlush(env, 50, 300);
}
static bool
SendWithCRC(Port &port, const void *data, size_t length,
OperationEnvironment &env)
{
if (!port.FullWrite(data, length, env, 2000))
return false;
uint16_t crc16 = UpdateCRC16CCITT(data, length, 0);
return port.Write(crc16 >> 8) && port.Write(crc16 & 0xff);
}
bool
Volkslogger::SendCommand(Port &port, OperationEnvironment &env,
Command cmd, uint8_t param1, uint8_t param2)
{
static constexpr unsigned delay = 2;
/* flush buffers */
if (!port.FullFlush(env, 20, 100))
return false;
/* reset command interpreter */
if (!Reset(port, env, 6))
return false;
/* send command packet */
const uint8_t cmdarray[8] = {
(uint8_t)cmd, param1, param2,
0, 0, 0, 0, 0,
};
if (!port.Write(ENQ))
return false;
env.Sleep(delay);
if (!SendWithCRC(port, cmdarray, sizeof(cmdarray), env))
return false;
/* wait for confirmation */
return port.WaitRead(env, 4000) == Port::WaitResult::READY &&
port.GetChar() == 0;
}
gcc_const
static int
GetBaudRateIndex(unsigned baud_rate)
{
switch(baud_rate) {
case 9600:
return 1;
case 19200:
return 2;
case 38400:
return 3;
case 57600:
return 4;
case 115200:
return 5;
default:
return -1;
}
}
bool
Volkslogger::SendCommandSwitchBaudRate(Port &port, OperationEnvironment &env,
Command cmd, uint8_t param1,
unsigned baud_rate)
{
int baud_rate_index = GetBaudRateIndex(baud_rate);
if (baud_rate_index < 0)
return false;
if (!SendCommand(port, env, cmd, param1, baud_rate_index))
return false;
return port.SetBaudrate(baud_rate);
}
bool
Volkslogger::WaitForACK(Port &port, OperationEnvironment &env)
{
return port.WaitForChar(ACK, env, 30000) == Port::WaitResult::READY;
}
int
Volkslogger::ReadBulk(Port &port, OperationEnvironment &env,
void *buffer, size_t max_length,
unsigned timeout_firstchar_ms)
{
unsigned nbytes = 0;
bool dle_r = false;
uint16_t crc16 = 0;
bool start = false, ende = false;
memset(buffer, 0xff, max_length);
uint8_t *p = (uint8_t *)buffer;
constexpr unsigned TIMEOUT_NORMAL_MS = 2000;
/**
* We need to wait longer for the first char to
* give the logger time to calculate security
* when downloading a log-file.
* Therefore timeout_firstchar is configurable.
* If the timeout parameter is not specified or 0,
* set standard timeout
*/
if (timeout_firstchar_ms == 0)
timeout_firstchar_ms = TIMEOUT_NORMAL_MS;
while (!ende) {
// Zeichen anfordern und darauf warten
if (!port.Write(ACK))
return -1;
// Set longer timeout on first char
unsigned timeout = start ? TIMEOUT_NORMAL_MS : timeout_firstchar_ms;
if (port.WaitRead(env, timeout) != Port::WaitResult::READY)
return -1;
int ch = port.GetChar();
if (ch < 0)
return -1;
// dabei ist Benutzerabbruch jederzeit möglich
if (env.IsCancelled()) {
env.Sleep(10);
port.Write(CAN);
port.Write(CAN);
port.Write(CAN);
return -1;
}
// oder aber das empfangene Zeichen wird ausgewertet
switch (ch) {
case DLE:
if (!dle_r) { //!DLE, DLE -> Achtung!
dle_r = true;
}
else { // DLE, DLE -> DLE-Zeichen
dle_r = false;
if (start) {
if(nbytes < max_length)
*p++ = ch;
nbytes++;
crc16 = UpdateCRC16CCITT(ch, crc16);
}
}
break;
case ETX:
if (!dle_r) { //!DLE, ETX -> Zeichen
if (start) {
if(nbytes < max_length) {
*p++ = ch;
}
nbytes++;
crc16 = UpdateCRC16CCITT(ch, crc16);
};
}
else {
if (start) {
ende = true; // DLE, ETX -> Blockende
dle_r = false;
}
}
break;
case STX:
if (!dle_r) { //!DLE, STX -> Zeichen
if (start) {
if(nbytes < max_length)
*p++ = ch;
nbytes++;
crc16 = UpdateCRC16CCITT(ch, crc16);
}
}
else {
start = true; // DLE, STX -> Blockstart
dle_r = false;
crc16 = 0;
}
break;
default:
if (start) {
if(nbytes < max_length)
*p++ = ch;
nbytes++;
crc16 = UpdateCRC16CCITT(ch, crc16);
}
break;
}
}
env.Sleep(100);
if (crc16 != 0)
return -1;
if (nbytes < 2)
return 0;
// CRC am Ende abschneiden
return nbytes - 2;
}
bool
Volkslogger::WriteBulk(Port &port, OperationEnvironment &env,
const void *buffer, unsigned length)
{
const unsigned delay = 1;
env.SetProgressRange(length);
uint16_t crc16 = 0;
const uint8_t *p = (const uint8_t *)buffer, *end = p + length;
while (p < end) {
unsigned n = end - p;
if (n > 400)
n = 400;
n = port.Write(p, n);
if (n == 0)
return false;
crc16 = UpdateCRC16CCITT(p, n, crc16);
p += n;
env.SetProgressPosition(p - (const uint8_t *)buffer);
/* throttle sending a bit, or the Volkslogger's receive buffer
will overrun */
env.Sleep(delay * 100);
}
return port.Write(crc16 >> 8) && port.Write(crc16 & 0xff);
}
int
Volkslogger::SendCommandReadBulk(Port &port, OperationEnvironment &env,
Command cmd,
void *buffer, size_t max_length,
const unsigned timeout_firstchar_ms)
{
return SendCommand(port, env, cmd)
? ReadBulk(port, env, buffer, max_length, timeout_firstchar_ms)
: -1;
}
int
Volkslogger::SendCommandReadBulk(Port &port, unsigned baud_rate,
OperationEnvironment &env,
Command cmd, uint8_t param1,
void *buffer, size_t max_length,
const unsigned timeout_firstchar_ms)
{
unsigned old_baud_rate = port.GetBaudrate();
if (old_baud_rate != 0) {
if (!SendCommandSwitchBaudRate(port, env, cmd, param1, baud_rate))
return -1;
/* after switching baud rates, this sleep time is necessary; it has
been verified experimentally */
env.Sleep(300);
} else {
/* port does not support baud rate switching, use plain
SendCommand() without new baud rate */
if (!SendCommand(port, env, cmd, param1))
return -1;
}
int nbytes = ReadBulk(port, env, buffer, max_length, timeout_firstchar_ms);
if (old_baud_rate != 0)
port.SetBaudrate(old_baud_rate);
return nbytes;
}
bool
Volkslogger::SendCommandWriteBulk(Port &port, OperationEnvironment &env,
Command cmd,
const void *data, size_t size)
{
if (!SendCommand(port, env, cmd, 0, 0) || !WaitForACK(port, env))
return false;
env.Sleep(100);
return WriteBulk(port, env, data, size) && WaitForACK(port, env);
}
size_t
Volkslogger::ReadFlight(Port &port, unsigned databaud,
OperationEnvironment &env,
unsigned flightnr, bool secmode,
void *buffer, size_t buffersize)
{
const Volkslogger::Command cmd = secmode
? Volkslogger::cmd_GFS
: Volkslogger::cmd_GFL;
/*
* It is necessary to wait long for the first reply from
* the Logger in ReadBulk.
* Since the VL needs time to calculate the Security of
* the log before it responds.
*/
const unsigned timeout_firstchar_ms = 600000;
// Download binary log data supports BulkBaudrate
int groesse = SendCommandReadBulk(port, databaud, env, cmd,
flightnr, buffer, buffersize,
timeout_firstchar_ms);
if (groesse <= 0)
return 0;
// read signature
env.Sleep(300);
/*
* Testing has shown that downloading the Signature does not support
* BulkRate. It has to be done with standard IO Rate (9600)
*/
int sgr = SendCommandReadBulk(port, env, Volkslogger::cmd_SIG,
(uint8_t *)buffer + groesse,
buffersize - groesse);
if (sgr <= 0)
return 0;
return groesse + sgr;
}
| Exadios/XCSoar-the-library | src/Device/Driver/Volkslogger/Protocol.cpp | C++ | gpl-2.0 | 11,015 |
/*
* @(#)UnsupportedPhysicalMemoryException.java 1.2 05/10/20
*
* Copyright 2005 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package com.sun.squawk.realtime;
/**
* Thrown when the underlying hardware does not support the type of
* physical memory requested from an instance of
* one of the physical memory or raw memory access classes.
*
* @see RawMemoryAccess
* @see RawMemoryFloatAccess
*
*
* @since 1.0.1 Becomes unchecked
*/
public class UnsupportedPhysicalMemoryException extends RuntimeException
{
/**
* A constructor for <code>UnsupportedPhysicalMemoryException</code>.
*/
public UnsupportedPhysicalMemoryException(){
super();
}
/**
* A descriptive constructor for
* <code>UnsupportedPhysicalMemoryException</code>.
*
* @param description The description of the exception.
*/
public UnsupportedPhysicalMemoryException(String description) {
super(description);
}
}
| sics-sse/moped | squawk/cldc/src/com/sun/squawk/realtime/UnsupportedPhysicalMemoryException.java | Java | gpl-2.0 | 1,022 |
var class_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_sales_1_1_setup_1_1_bonus_slabs =
[
[ "OnControlLoad", "class_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_sales_1_1_setup_1_1_bonus_slabs.html#ab16b782e4c9f10ebbbc47fd52dbc6ae1", null ],
[ "ScrudPlaceholder", "class_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_sales_1_1_setup_1_1_bonus_slabs.html#a3402588f607d9920f295a38336e9ca8d", null ]
]; | mixerp6/mixerp | docs/api/class_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_sales_1_1_setup_1_1_bonus_slabs.js | JavaScript | gpl-2.0 | 401 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2015 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
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 "Dialogs/ComboPicker.hpp"
bool
ComboPicker(const TCHAR *caption, DataField &df,
const TCHAR *help_text)
{
return false;
}
| ahsparrow/xcsoar_orig | test/src/FakeListPicker.cpp | C++ | gpl-2.0 | 1,046 |
var class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee =
[
[ "AccountId", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#aa5f13daf52f6212580695248d62ed83d", null ],
[ "AuditTs", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a95210c8ea60bb4107cb1a76b0617e58a", null ],
[ "AuditUserId", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#ad3b75c8f461c7ebc2756c1fddca8991d", null ],
[ "IsFlatAmount", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a7f09ea80a18909ebaeb1f2c561a63e77", null ],
[ "LateFeeCode", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#af38567944abc8be98c7ac91c30d4f1f5", null ],
[ "LateFeeId", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a95fd529069d0e5705260329f8d895e5c", null ],
[ "LateFeeName", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a770c2823bf447fb41c54062fef2334ba", null ],
[ "Rate", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#ab6a4512cbe1dcde39c2ec00be539acbf", null ]
]; | mixerp6/mixerp | docs/api/class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.js | JavaScript | gpl-2.0 | 1,094 |
# Volatility
# Copyright (c) 2008-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility 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.
#
# Volatility 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 Volatility. If not, see <http://www.gnu.org/licenses/>.
#
"""
@author: MHL
@license: GNU General Public License 2.0
@contact: michael.ligh@mnin.org
This file provides support for Vista SP1 and SP2 x64
"""
syscalls = [
[
'NtMapUserPhysicalPagesScatter', # 0x0
'NtWaitForSingleObject', # 0x1
'NtCallbackReturn', # 0x2
'NtReadFile', # 0x3
'NtDeviceIoControlFile', # 0x4
'NtWriteFile', # 0x5
'NtRemoveIoCompletion', # 0x6
'NtReleaseSemaphore', # 0x7
'NtReplyWaitReceivePort', # 0x8
'NtReplyPort', # 0x9
'NtSetInformationThread', # 0xa
'NtSetEvent', # 0xb
'NtClose', # 0xc
'NtQueryObject', # 0xd
'NtQueryInformationFile', # 0xe
'NtOpenKey', # 0xf
'NtEnumerateValueKey', # 0x10
'NtFindAtom', # 0x11
'NtQueryDefaultLocale', # 0x12
'NtQueryKey', # 0x13
'NtQueryValueKey', # 0x14
'NtAllocateVirtualMemory', # 0x15
'NtQueryInformationProcess', # 0x16
'NtWaitForMultipleObjects32', # 0x17
'NtWriteFileGather', # 0x18
'NtSetInformationProcess', # 0x19
'NtCreateKey', # 0x1a
'NtFreeVirtualMemory', # 0x1b
'NtImpersonateClientOfPort', # 0x1c
'NtReleaseMutant', # 0x1d
'NtQueryInformationToken', # 0x1e
'NtRequestWaitReplyPort', # 0x1f
'NtQueryVirtualMemory', # 0x20
'NtOpenThreadToken', # 0x21
'NtQueryInformationThread', # 0x22
'NtOpenProcess', # 0x23
'NtSetInformationFile', # 0x24
'NtMapViewOfSection', # 0x25
'NtAccessCheckAndAuditAlarm', # 0x26
'NtUnmapViewOfSection', # 0x27
'NtReplyWaitReceivePortEx', # 0x28
'NtTerminateProcess', # 0x29
'NtSetEventBoostPriority', # 0x2a
'NtReadFileScatter', # 0x2b
'NtOpenThreadTokenEx', # 0x2c
'NtOpenProcessTokenEx', # 0x2d
'NtQueryPerformanceCounter', # 0x2e
'NtEnumerateKey', # 0x2f
'NtOpenFile', # 0x30
'NtDelayExecution', # 0x31
'NtQueryDirectoryFile', # 0x32
'NtQuerySystemInformation', # 0x33
'NtOpenSection', # 0x34
'NtQueryTimer', # 0x35
'NtFsControlFile', # 0x36
'NtWriteVirtualMemory', # 0x37
'NtCloseObjectAuditAlarm', # 0x38
'NtDuplicateObject', # 0x39
'NtQueryAttributesFile', # 0x3a
'NtClearEvent', # 0x3b
'NtReadVirtualMemory', # 0x3c
'NtOpenEvent', # 0x3d
'NtAdjustPrivilegesToken', # 0x3e
'NtDuplicateToken', # 0x3f
'NtContinue', # 0x40
'NtQueryDefaultUILanguage', # 0x41
'NtQueueApcThread', # 0x42
'NtYieldExecution', # 0x43
'NtAddAtom', # 0x44
'NtCreateEvent', # 0x45
'NtQueryVolumeInformationFile', # 0x46
'NtCreateSection', # 0x47
'NtFlushBuffersFile', # 0x48
'NtApphelpCacheControl', # 0x49
'NtCreateProcessEx', # 0x4a
'NtCreateThread', # 0x4b
'NtIsProcessInJob', # 0x4c
'NtProtectVirtualMemory', # 0x4d
'NtQuerySection', # 0x4e
'NtResumeThread', # 0x4f
'NtTerminateThread', # 0x50
'NtReadRequestData', # 0x51
'NtCreateFile', # 0x52
'NtQueryEvent', # 0x53
'NtWriteRequestData', # 0x54
'NtOpenDirectoryObject', # 0x55
'NtAccessCheckByTypeAndAuditAlarm', # 0x56
'NtQuerySystemTime', # 0x57
'NtWaitForMultipleObjects', # 0x58
'NtSetInformationObject', # 0x59
'NtCancelIoFile', # 0x5a
'NtTraceEvent', # 0x5b
'NtPowerInformation', # 0x5c
'NtSetValueKey', # 0x5d
'NtCancelTimer', # 0x5e
'NtSetTimer', # 0x5f
'NtAcceptConnectPort', # 0x60
'NtAccessCheck', # 0x61
'NtAccessCheckByType', # 0x62
'NtAccessCheckByTypeResultList', # 0x63
'NtAccessCheckByTypeResultListAndAuditAlarm', # 0x64
'NtAccessCheckByTypeResultListAndAuditAlarmByHandle', # 0x65
'NtAcquireCMFViewOwnership', # 0x66
'NtAddBootEntry', # 0x67
'NtAddDriverEntry', # 0x68
'NtAdjustGroupsToken', # 0x69
'NtAlertResumeThread', # 0x6a
'NtAlertThread', # 0x6b
'NtAllocateLocallyUniqueId', # 0x6c
'NtAllocateUserPhysicalPages', # 0x6d
'NtAllocateUuids', # 0x6e
'NtAlpcAcceptConnectPort', # 0x6f
'NtAlpcCancelMessage', # 0x70
'NtAlpcConnectPort', # 0x71
'NtAlpcCreatePort', # 0x72
'NtAlpcCreatePortSection', # 0x73
'NtAlpcCreateResourceReserve', # 0x74
'NtAlpcCreateSectionView', # 0x75
'NtAlpcCreateSecurityContext', # 0x76
'NtAlpcDeletePortSection', # 0x77
'NtAlpcDeleteResourceReserve', # 0x78
'NtAlpcDeleteSectionView', # 0x79
'NtAlpcDeleteSecurityContext', # 0x7a
'NtAlpcDisconnectPort', # 0x7b
'NtAlpcImpersonateClientOfPort', # 0x7c
'NtAlpcOpenSenderProcess', # 0x7d
'NtAlpcOpenSenderThread', # 0x7e
'NtAlpcQueryInformation', # 0x7f
'NtAlpcQueryInformationMessage', # 0x80
'NtAlpcRevokeSecurityContext', # 0x81
'NtAlpcSendWaitReceivePort', # 0x82
'NtAlpcSetInformation', # 0x83
'NtAreMappedFilesTheSame', # 0x84
'NtAssignProcessToJobObject', # 0x85
'NtCancelDeviceWakeupRequest', # 0x86
'NtCancelIoFileEx', # 0x87
'NtCancelSynchronousIoFile', # 0x88
'NtCommitComplete', # 0x89
'NtCommitEnlistment', # 0x8a
'NtCommitTransaction', # 0x8b
'NtCompactKeys', # 0x8c
'NtCompareTokens', # 0x8d
'NtCompleteConnectPort', # 0x8e
'NtCompressKey', # 0x8f
'NtConnectPort', # 0x90
'NtCreateDebugObject', # 0x91
'NtCreateDirectoryObject', # 0x92
'NtCreateEnlistment', # 0x93
'NtCreateEventPair', # 0x94
'NtCreateIoCompletion', # 0x95
'NtCreateJobObject', # 0x96
'NtCreateJobSet', # 0x97
'NtCreateKeyTransacted', # 0x98
'NtCreateKeyedEvent', # 0x99
'NtCreateMailslotFile', # 0x9a
'NtCreateMutant', # 0x9b
'NtCreateNamedPipeFile', # 0x9c
'NtCreatePagingFile', # 0x9d
'NtCreatePort', # 0x9e
'NtCreatePrivateNamespace', # 0x9f
'NtCreateProcess', # 0xa0
'NtCreateProfile', # 0xa1
'NtCreateResourceManager', # 0xa2
'NtCreateSemaphore', # 0xa3
'NtCreateSymbolicLinkObject', # 0xa4
'NtCreateThreadEx', # 0xa5
'NtCreateTimer', # 0xa6
'NtCreateToken', # 0xa7
'NtCreateTransaction', # 0xa8
'NtCreateTransactionManager', # 0xa9
'NtCreateUserProcess', # 0xaa
'NtCreateWaitablePort', # 0xab
'NtCreateWorkerFactory', # 0xac
'NtDebugActiveProcess', # 0xad
'NtDebugContinue', # 0xae
'NtDeleteAtom', # 0xaf
'NtDeleteBootEntry', # 0xb0
'NtDeleteDriverEntry', # 0xb1
'NtDeleteFile', # 0xb2
'NtDeleteKey', # 0xb3
'NtDeleteObjectAuditAlarm', # 0xb4
'NtDeletePrivateNamespace', # 0xb5
'NtDeleteValueKey', # 0xb6
'NtDisplayString', # 0xb7
'NtEnumerateBootEntries', # 0xb8
'NtEnumerateDriverEntries', # 0xb9
'NtEnumerateSystemEnvironmentValuesEx', # 0xba
'NtEnumerateTransactionObject', # 0xbb
'NtExtendSection', # 0xbc
'NtFilterToken', # 0xbd
'NtFlushInstallUILanguage', # 0xbe
'NtFlushInstructionCache', # 0xbf
'NtFlushKey', # 0xc0
'NtFlushProcessWriteBuffers', # 0xc1
'NtFlushVirtualMemory', # 0xc2
'NtFlushWriteBuffer', # 0xc3
'NtFreeUserPhysicalPages', # 0xc4
'NtFreezeRegistry', # 0xc5
'NtFreezeTransactions', # 0xc6
'NtGetContextThread', # 0xc7
'NtGetCurrentProcessorNumber', # 0xc8
'NtGetDevicePowerState', # 0xc9
'NtGetMUIRegistryInfo', # 0xca
'NtGetNextProcess', # 0xcb
'NtGetNextThread', # 0xcc
'NtGetNlsSectionPtr', # 0xcd
'NtGetNotificationResourceManager', # 0xce
'NtGetPlugPlayEvent', # 0xcf
'NtGetWriteWatch', # 0xd0
'NtImpersonateAnonymousToken', # 0xd1
'NtImpersonateThread', # 0xd2
'NtInitializeNlsFiles', # 0xd3
'NtInitializeRegistry', # 0xd4
'NtInitiatePowerAction', # 0xd5
'NtIsSystemResumeAutomatic', # 0xd6
'NtIsUILanguageComitted', # 0xd7
'NtListenPort', # 0xd8
'NtLoadDriver', # 0xd9
'NtLoadKey', # 0xda
'NtLoadKey2', # 0xdb
'NtLoadKeyEx', # 0xdc
'NtLockFile', # 0xdd
'NtLockProductActivationKeys', # 0xde
'NtLockRegistryKey', # 0xdf
'NtLockVirtualMemory', # 0xe0
'NtMakePermanentObject', # 0xe1
'NtMakeTemporaryObject', # 0xe2
'NtMapCMFModule', # 0xe3
'NtMapUserPhysicalPages', # 0xe4
'NtModifyBootEntry', # 0xe5
'NtModifyDriverEntry', # 0xe6
'NtNotifyChangeDirectoryFile', # 0xe7
'NtNotifyChangeKey', # 0xe8
'NtNotifyChangeMultipleKeys', # 0xe9
'NtOpenEnlistment', # 0xea
'NtOpenEventPair', # 0xeb
'NtOpenIoCompletion', # 0xec
'NtOpenJobObject', # 0xed
'NtOpenKeyTransacted', # 0xee
'NtOpenKeyedEvent', # 0xef
'NtOpenMutant', # 0xf0
'NtOpenObjectAuditAlarm', # 0xf1
'NtOpenPrivateNamespace', # 0xf2
'NtOpenProcessToken', # 0xf3
'NtOpenResourceManager', # 0xf4
'NtOpenSemaphore', # 0xf5
'NtOpenSession', # 0xf6
'NtOpenSymbolicLinkObject', # 0xf7
'NtOpenThread', # 0xf8
'NtOpenTimer', # 0xf9
'NtOpenTransaction', # 0xfa
'NtOpenTransactionManager', # 0xfb
'NtPlugPlayControl', # 0xfc
'NtPrePrepareComplete', # 0xfd
'NtPrePrepareEnlistment', # 0xfe
'NtPrepareComplete', # 0xff
'NtPrepareEnlistment', # 0x100
'NtPrivilegeCheck', # 0x101
'NtPrivilegeObjectAuditAlarm', # 0x102
'NtPrivilegedServiceAuditAlarm', # 0x103
'NtPropagationComplete', # 0x104
'NtPropagationFailed', # 0x105
'NtPulseEvent', # 0x106
'NtQueryBootEntryOrder', # 0x107
'NtQueryBootOptions', # 0x108
'NtQueryDebugFilterState', # 0x109
'NtQueryDirectoryObject', # 0x10a
'NtQueryDriverEntryOrder', # 0x10b
'NtQueryEaFile', # 0x10c
'NtQueryFullAttributesFile', # 0x10d
'NtQueryInformationAtom', # 0x10e
'NtQueryInformationEnlistment', # 0x10f
'NtQueryInformationJobObject', # 0x110
'NtQueryInformationPort', # 0x111
'NtQueryInformationResourceManager', # 0x112
'NtQueryInformationTransaction', # 0x113
'NtQueryInformationTransactionManager', # 0x114
'NtQueryInformationWorkerFactory', # 0x115
'NtQueryInstallUILanguage', # 0x116
'NtQueryIntervalProfile', # 0x117
'NtQueryIoCompletion', # 0x118
'NtQueryLicenseValue', # 0x119
'NtQueryMultipleValueKey', # 0x11a
'NtQueryMutant', # 0x11b
'NtQueryOpenSubKeys', # 0x11c
'NtQueryOpenSubKeysEx', # 0x11d
'NtQueryPortInformationProcess', # 0x11e
'NtQueryQuotaInformationFile', # 0x11f
'NtQuerySecurityObject', # 0x120
'NtQuerySemaphore', # 0x121
'NtQuerySymbolicLinkObject', # 0x122
'NtQuerySystemEnvironmentValue', # 0x123
'NtQuerySystemEnvironmentValueEx', # 0x124
'NtQueryTimerResolution', # 0x125
'NtRaiseException', # 0x126
'NtRaiseHardError', # 0x127
'NtReadOnlyEnlistment', # 0x128
'NtRecoverEnlistment', # 0x129
'NtRecoverResourceManager', # 0x12a
'NtRecoverTransactionManager', # 0x12b
'NtRegisterProtocolAddressInformation', # 0x12c
'NtRegisterThreadTerminatePort', # 0x12d
'NtReleaseCMFViewOwnership', # 0x12e
'NtReleaseKeyedEvent', # 0x12f
'NtReleaseWorkerFactoryWorker', # 0x130
'NtRemoveIoCompletionEx', # 0x131
'NtRemoveProcessDebug', # 0x132
'NtRenameKey', # 0x133
'NtRenameTransactionManager', # 0x134
'NtReplaceKey', # 0x135
'NtReplacePartitionUnit', # 0x136
'NtReplyWaitReplyPort', # 0x137
'NtRequestDeviceWakeup', # 0x138
'NtRequestPort', # 0x139
'NtRequestWakeupLatency', # 0x13a
'NtResetEvent', # 0x13b
'NtResetWriteWatch', # 0x13c
'NtRestoreKey', # 0x13d
'NtResumeProcess', # 0x13e
'NtRollbackComplete', # 0x13f
'NtRollbackEnlistment', # 0x140
'NtRollbackTransaction', # 0x141
'NtRollforwardTransactionManager', # 0x142
'NtSaveKey', # 0x143
'NtSaveKeyEx', # 0x144
'NtSaveMergedKeys', # 0x145
'NtSecureConnectPort', # 0x146
'NtSetBootEntryOrder', # 0x147
'NtSetBootOptions', # 0x148
'NtSetContextThread', # 0x149
'NtSetDebugFilterState', # 0x14a
'NtSetDefaultHardErrorPort', # 0x14b
'NtSetDefaultLocale', # 0x14c
'NtSetDefaultUILanguage', # 0x14d
'NtSetDriverEntryOrder', # 0x14e
'NtSetEaFile', # 0x14f
'NtSetHighEventPair', # 0x150
'NtSetHighWaitLowEventPair', # 0x151
'NtSetInformationDebugObject', # 0x152
'NtSetInformationEnlistment', # 0x153
'NtSetInformationJobObject', # 0x154
'NtSetInformationKey', # 0x155
'NtSetInformationResourceManager', # 0x156
'NtSetInformationToken', # 0x157
'NtSetInformationTransaction', # 0x158
'NtSetInformationTransactionManager', # 0x159
'NtSetInformationWorkerFactory', # 0x15a
'NtSetIntervalProfile', # 0x15b
'NtSetIoCompletion', # 0x15c
'NtSetLdtEntries', # 0x15d
'NtSetLowEventPair', # 0x15e
'NtSetLowWaitHighEventPair', # 0x15f
'NtSetQuotaInformationFile', # 0x160
'NtSetSecurityObject', # 0x161
'NtSetSystemEnvironmentValue', # 0x162
'NtSetSystemEnvironmentValueEx', # 0x163
'NtSetSystemInformation', # 0x164
'NtSetSystemPowerState', # 0x165
'NtSetSystemTime', # 0x166
'NtSetThreadExecutionState', # 0x167
'NtSetTimerResolution', # 0x168
'NtSetUuidSeed', # 0x169
'NtSetVolumeInformationFile', # 0x16a
'NtShutdownSystem', # 0x16b
'NtShutdownWorkerFactory', # 0x16c
'NtSignalAndWaitForSingleObject', # 0x16d
'NtSinglePhaseReject', # 0x16e
'NtStartProfile', # 0x16f
'NtStopProfile', # 0x170
'NtSuspendProcess', # 0x171
'NtSuspendThread', # 0x172
'NtSystemDebugControl', # 0x173
'NtTerminateJobObject', # 0x174
'NtTestAlert', # 0x175
'NtThawRegistry', # 0x176
'NtThawTransactions', # 0x177
'NtTraceControl', # 0x178
'NtTranslateFilePath', # 0x179
'NtUnloadDriver', # 0x17a
'NtUnloadKey', # 0x17b
'NtUnloadKey2', # 0x17c
'NtUnloadKeyEx', # 0x17d
'NtUnlockFile', # 0x17e
'NtUnlockVirtualMemory', # 0x17f
'NtVdmControl', # 0x180
'NtWaitForDebugEvent', # 0x181
'NtWaitForKeyedEvent', # 0x182
'NtWaitForWorkViaWorkerFactory', # 0x183
'NtWaitHighEventPair', # 0x184
'NtWaitLowEventPair', # 0x185
'NtWorkerFactoryWorkerReady', # 0x186
],
[
'NtUserGetThreadState', # 0x0
'NtUserPeekMessage', # 0x1
'NtUserCallOneParam', # 0x2
'NtUserGetKeyState', # 0x3
'NtUserInvalidateRect', # 0x4
'NtUserCallNoParam', # 0x5
'NtUserGetMessage', # 0x6
'NtUserMessageCall', # 0x7
'NtGdiBitBlt', # 0x8
'NtGdiGetCharSet', # 0x9
'NtUserGetDC', # 0xa
'NtGdiSelectBitmap', # 0xb
'NtUserWaitMessage', # 0xc
'NtUserTranslateMessage', # 0xd
'NtUserGetProp', # 0xe
'NtUserPostMessage', # 0xf
'NtUserQueryWindow', # 0x10
'NtUserTranslateAccelerator', # 0x11
'NtGdiFlush', # 0x12
'NtUserRedrawWindow', # 0x13
'NtUserWindowFromPoint', # 0x14
'NtUserCallMsgFilter', # 0x15
'NtUserValidateTimerCallback', # 0x16
'NtUserBeginPaint', # 0x17
'NtUserSetTimer', # 0x18
'NtUserEndPaint', # 0x19
'NtUserSetCursor', # 0x1a
'NtUserKillTimer', # 0x1b
'NtUserBuildHwndList', # 0x1c
'NtUserSelectPalette', # 0x1d
'NtUserCallNextHookEx', # 0x1e
'NtUserHideCaret', # 0x1f
'NtGdiIntersectClipRect', # 0x20
'NtUserCallHwndLock', # 0x21
'NtUserGetProcessWindowStation', # 0x22
'NtGdiDeleteObjectApp', # 0x23
'NtUserSetWindowPos', # 0x24
'NtUserShowCaret', # 0x25
'NtUserEndDeferWindowPosEx', # 0x26
'NtUserCallHwndParamLock', # 0x27
'NtUserVkKeyScanEx', # 0x28
'NtGdiSetDIBitsToDeviceInternal', # 0x29
'NtUserCallTwoParam', # 0x2a
'NtGdiGetRandomRgn', # 0x2b
'NtUserCopyAcceleratorTable', # 0x2c
'NtUserNotifyWinEvent', # 0x2d
'NtGdiExtSelectClipRgn', # 0x2e
'NtUserIsClipboardFormatAvailable', # 0x2f
'NtUserSetScrollInfo', # 0x30
'NtGdiStretchBlt', # 0x31
'NtUserCreateCaret', # 0x32
'NtGdiRectVisible', # 0x33
'NtGdiCombineRgn', # 0x34
'NtGdiGetDCObject', # 0x35
'NtUserDispatchMessage', # 0x36
'NtUserRegisterWindowMessage', # 0x37
'NtGdiExtTextOutW', # 0x38
'NtGdiSelectFont', # 0x39
'NtGdiRestoreDC', # 0x3a
'NtGdiSaveDC', # 0x3b
'NtUserGetForegroundWindow', # 0x3c
'NtUserShowScrollBar', # 0x3d
'NtUserFindExistingCursorIcon', # 0x3e
'NtGdiGetDCDword', # 0x3f
'NtGdiGetRegionData', # 0x40
'NtGdiLineTo', # 0x41
'NtUserSystemParametersInfo', # 0x42
'NtGdiGetAppClipBox', # 0x43
'NtUserGetAsyncKeyState', # 0x44
'NtUserGetCPD', # 0x45
'NtUserRemoveProp', # 0x46
'NtGdiDoPalette', # 0x47
'NtGdiPolyPolyDraw', # 0x48
'NtUserSetCapture', # 0x49
'NtUserEnumDisplayMonitors', # 0x4a
'NtGdiCreateCompatibleBitmap', # 0x4b
'NtUserSetProp', # 0x4c
'NtGdiGetTextCharsetInfo', # 0x4d
'NtUserSBGetParms', # 0x4e
'NtUserGetIconInfo', # 0x4f
'NtUserExcludeUpdateRgn', # 0x50
'NtUserSetFocus', # 0x51
'NtGdiExtGetObjectW', # 0x52
'NtUserDeferWindowPos', # 0x53
'NtUserGetUpdateRect', # 0x54
'NtGdiCreateCompatibleDC', # 0x55
'NtUserGetClipboardSequenceNumber', # 0x56
'NtGdiCreatePen', # 0x57
'NtUserShowWindow', # 0x58
'NtUserGetKeyboardLayoutList', # 0x59
'NtGdiPatBlt', # 0x5a
'NtUserMapVirtualKeyEx', # 0x5b
'NtUserSetWindowLong', # 0x5c
'NtGdiHfontCreate', # 0x5d
'NtUserMoveWindow', # 0x5e
'NtUserPostThreadMessage', # 0x5f
'NtUserDrawIconEx', # 0x60
'NtUserGetSystemMenu', # 0x61
'NtGdiDrawStream', # 0x62
'NtUserInternalGetWindowText', # 0x63
'NtUserGetWindowDC', # 0x64
'NtGdiD3dDrawPrimitives2', # 0x65
'NtGdiInvertRgn', # 0x66
'NtGdiGetRgnBox', # 0x67
'NtGdiGetAndSetDCDword', # 0x68
'NtGdiMaskBlt', # 0x69
'NtGdiGetWidthTable', # 0x6a
'NtUserScrollDC', # 0x6b
'NtUserGetObjectInformation', # 0x6c
'NtGdiCreateBitmap', # 0x6d
'NtGdiConsoleTextOut', # 0x6e
'NtUserFindWindowEx', # 0x6f
'NtGdiPolyPatBlt', # 0x70
'NtUserUnhookWindowsHookEx', # 0x71
'NtGdiGetNearestColor', # 0x72
'NtGdiTransformPoints', # 0x73
'NtGdiGetDCPoint', # 0x74
'NtUserCheckImeHotKey', # 0x75
'NtGdiCreateDIBBrush', # 0x76
'NtGdiGetTextMetricsW', # 0x77
'NtUserCreateWindowEx', # 0x78
'NtUserSetParent', # 0x79
'NtUserGetKeyboardState', # 0x7a
'NtUserToUnicodeEx', # 0x7b
'NtUserGetControlBrush', # 0x7c
'NtUserGetClassName', # 0x7d
'NtGdiAlphaBlend', # 0x7e
'NtGdiDdBlt', # 0x7f
'NtGdiOffsetRgn', # 0x80
'NtUserDefSetText', # 0x81
'NtGdiGetTextFaceW', # 0x82
'NtGdiStretchDIBitsInternal', # 0x83
'NtUserSendInput', # 0x84
'NtUserGetThreadDesktop', # 0x85
'NtGdiCreateRectRgn', # 0x86
'NtGdiGetDIBitsInternal', # 0x87
'NtUserGetUpdateRgn', # 0x88
'NtGdiDeleteClientObj', # 0x89
'NtUserGetIconSize', # 0x8a
'NtUserFillWindow', # 0x8b
'NtGdiExtCreateRegion', # 0x8c
'NtGdiComputeXformCoefficients', # 0x8d
'NtUserSetWindowsHookEx', # 0x8e
'NtUserNotifyProcessCreate', # 0x8f
'NtGdiUnrealizeObject', # 0x90
'NtUserGetTitleBarInfo', # 0x91
'NtGdiRectangle', # 0x92
'NtUserSetThreadDesktop', # 0x93
'NtUserGetDCEx', # 0x94
'NtUserGetScrollBarInfo', # 0x95
'NtGdiGetTextExtent', # 0x96
'NtUserSetWindowFNID', # 0x97
'NtGdiSetLayout', # 0x98
'NtUserCalcMenuBar', # 0x99
'NtUserThunkedMenuItemInfo', # 0x9a
'NtGdiExcludeClipRect', # 0x9b
'NtGdiCreateDIBSection', # 0x9c
'NtGdiGetDCforBitmap', # 0x9d
'NtUserDestroyCursor', # 0x9e
'NtUserDestroyWindow', # 0x9f
'NtUserCallHwndParam', # 0xa0
'NtGdiCreateDIBitmapInternal', # 0xa1
'NtUserOpenWindowStation', # 0xa2
'NtGdiDdDeleteSurfaceObject', # 0xa3
'NtGdiEnumFontClose', # 0xa4
'NtGdiEnumFontOpen', # 0xa5
'NtGdiEnumFontChunk', # 0xa6
'NtGdiDdCanCreateSurface', # 0xa7
'NtGdiDdCreateSurface', # 0xa8
'NtUserSetCursorIconData', # 0xa9
'NtGdiDdDestroySurface', # 0xaa
'NtUserCloseDesktop', # 0xab
'NtUserOpenDesktop', # 0xac
'NtUserSetProcessWindowStation', # 0xad
'NtUserGetAtomName', # 0xae
'NtGdiDdResetVisrgn', # 0xaf
'NtGdiExtCreatePen', # 0xb0
'NtGdiCreatePaletteInternal', # 0xb1
'NtGdiSetBrushOrg', # 0xb2
'NtUserBuildNameList', # 0xb3
'NtGdiSetPixel', # 0xb4
'NtUserRegisterClassExWOW', # 0xb5
'NtGdiCreatePatternBrushInternal', # 0xb6
'NtUserGetAncestor', # 0xb7
'NtGdiGetOutlineTextMetricsInternalW', # 0xb8
'NtGdiSetBitmapBits', # 0xb9
'NtUserCloseWindowStation', # 0xba
'NtUserGetDoubleClickTime', # 0xbb
'NtUserEnableScrollBar', # 0xbc
'NtGdiCreateSolidBrush', # 0xbd
'NtUserGetClassInfoEx', # 0xbe
'NtGdiCreateClientObj', # 0xbf
'NtUserUnregisterClass', # 0xc0
'NtUserDeleteMenu', # 0xc1
'NtGdiRectInRegion', # 0xc2
'NtUserScrollWindowEx', # 0xc3
'NtGdiGetPixel', # 0xc4
'NtUserSetClassLong', # 0xc5
'NtUserGetMenuBarInfo', # 0xc6
'NtGdiDdCreateSurfaceEx', # 0xc7
'NtGdiDdCreateSurfaceObject', # 0xc8
'NtGdiGetNearestPaletteIndex', # 0xc9
'NtGdiDdLockD3D', # 0xca
'NtGdiDdUnlockD3D', # 0xcb
'NtGdiGetCharWidthW', # 0xcc
'NtUserInvalidateRgn', # 0xcd
'NtUserGetClipboardOwner', # 0xce
'NtUserSetWindowRgn', # 0xcf
'NtUserBitBltSysBmp', # 0xd0
'NtGdiGetCharWidthInfo', # 0xd1
'NtUserValidateRect', # 0xd2
'NtUserCloseClipboard', # 0xd3
'NtUserOpenClipboard', # 0xd4
'NtGdiGetStockObject', # 0xd5
'NtUserSetClipboardData', # 0xd6
'NtUserEnableMenuItem', # 0xd7
'NtUserAlterWindowStyle', # 0xd8
'NtGdiFillRgn', # 0xd9
'NtUserGetWindowPlacement', # 0xda
'NtGdiModifyWorldTransform', # 0xdb
'NtGdiGetFontData', # 0xdc
'NtUserGetOpenClipboardWindow', # 0xdd
'NtUserSetThreadState', # 0xde
'NtGdiOpenDCW', # 0xdf
'NtUserTrackMouseEvent', # 0xe0
'NtGdiGetTransform', # 0xe1
'NtUserDestroyMenu', # 0xe2
'NtGdiGetBitmapBits', # 0xe3
'NtUserConsoleControl', # 0xe4
'NtUserSetActiveWindow', # 0xe5
'NtUserSetInformationThread', # 0xe6
'NtUserSetWindowPlacement', # 0xe7
'NtUserGetControlColor', # 0xe8
'NtGdiSetMetaRgn', # 0xe9
'NtGdiSetMiterLimit', # 0xea
'NtGdiSetVirtualResolution', # 0xeb
'NtGdiGetRasterizerCaps', # 0xec
'NtUserSetWindowWord', # 0xed
'NtUserGetClipboardFormatName', # 0xee
'NtUserRealInternalGetMessage', # 0xef
'NtUserCreateLocalMemHandle', # 0xf0
'NtUserAttachThreadInput', # 0xf1
'NtGdiCreateHalftonePalette', # 0xf2
'NtUserPaintMenuBar', # 0xf3
'NtUserSetKeyboardState', # 0xf4
'NtGdiCombineTransform', # 0xf5
'NtUserCreateAcceleratorTable', # 0xf6
'NtUserGetCursorFrameInfo', # 0xf7
'NtUserGetAltTabInfo', # 0xf8
'NtUserGetCaretBlinkTime', # 0xf9
'NtGdiQueryFontAssocInfo', # 0xfa
'NtUserProcessConnect', # 0xfb
'NtUserEnumDisplayDevices', # 0xfc
'NtUserEmptyClipboard', # 0xfd
'NtUserGetClipboardData', # 0xfe
'NtUserRemoveMenu', # 0xff
'NtGdiSetBoundsRect', # 0x100
'NtUserSetInformationProcess', # 0x101
'NtGdiGetBitmapDimension', # 0x102
'NtUserConvertMemHandle', # 0x103
'NtUserDestroyAcceleratorTable', # 0x104
'NtUserGetGUIThreadInfo', # 0x105
'NtGdiCloseFigure', # 0x106
'NtUserSetWindowsHookAW', # 0x107
'NtUserSetMenuDefaultItem', # 0x108
'NtUserCheckMenuItem', # 0x109
'NtUserSetWinEventHook', # 0x10a
'NtUserUnhookWinEvent', # 0x10b
'NtGdiSetupPublicCFONT', # 0x10c
'NtUserLockWindowUpdate', # 0x10d
'NtUserSetSystemMenu', # 0x10e
'NtUserThunkedMenuInfo', # 0x10f
'NtGdiBeginPath', # 0x110
'NtGdiEndPath', # 0x111
'NtGdiFillPath', # 0x112
'NtUserCallHwnd', # 0x113
'NtUserDdeInitialize', # 0x114
'NtUserModifyUserStartupInfoFlags', # 0x115
'NtUserCountClipboardFormats', # 0x116
'NtGdiAddFontMemResourceEx', # 0x117
'NtGdiEqualRgn', # 0x118
'NtGdiGetSystemPaletteUse', # 0x119
'NtGdiRemoveFontMemResourceEx', # 0x11a
'NtUserEnumDisplaySettings', # 0x11b
'NtUserPaintDesktop', # 0x11c
'NtGdiExtEscape', # 0x11d
'NtGdiSetBitmapDimension', # 0x11e
'NtGdiSetFontEnumeration', # 0x11f
'NtUserChangeClipboardChain', # 0x120
'NtUserResolveDesktop', # 0x121
'NtUserSetClipboardViewer', # 0x122
'NtUserShowWindowAsync', # 0x123
'NtUserSetConsoleReserveKeys', # 0x124
'NtGdiCreateColorSpace', # 0x125
'NtGdiDeleteColorSpace', # 0x126
'NtUserActivateKeyboardLayout', # 0x127
'NtGdiAbortDoc', # 0x128
'NtGdiAbortPath', # 0x129
'NtGdiAddEmbFontToDC', # 0x12a
'NtGdiAddFontResourceW', # 0x12b
'NtGdiAddRemoteFontToDC', # 0x12c
'NtGdiAddRemoteMMInstanceToDC', # 0x12d
'NtGdiAngleArc', # 0x12e
'NtGdiAnyLinkedFonts', # 0x12f
'NtGdiArcInternal', # 0x130
'NtGdiBRUSHOBJ_DeleteRbrush', # 0x131
'NtGdiBRUSHOBJ_hGetColorTransform', # 0x132
'NtGdiBRUSHOBJ_pvAllocRbrush', # 0x133
'NtGdiBRUSHOBJ_pvGetRbrush', # 0x134
'NtGdiBRUSHOBJ_ulGetBrushColor', # 0x135
'NtGdiCLIPOBJ_bEnum', # 0x136
'NtGdiCLIPOBJ_cEnumStart', # 0x137
'NtGdiCLIPOBJ_ppoGetPath', # 0x138
'NtGdiCancelDC', # 0x139
'NtGdiChangeGhostFont', # 0x13a
'NtGdiCheckBitmapBits', # 0x13b
'NtGdiClearBitmapAttributes', # 0x13c
'NtGdiClearBrushAttributes', # 0x13d
'NtGdiColorCorrectPalette', # 0x13e
'NtGdiConfigureOPMProtectedOutput', # 0x13f
'NtGdiConvertMetafileRect', # 0x140
'NtGdiCreateColorTransform', # 0x141
'NtGdiCreateEllipticRgn', # 0x142
'NtGdiCreateHatchBrushInternal', # 0x143
'NtGdiCreateMetafileDC', # 0x144
'NtGdiCreateOPMProtectedOutputs', # 0x145
'NtGdiCreateRoundRectRgn', # 0x146
'NtGdiCreateServerMetaFile', # 0x147
'NtGdiD3dContextCreate', # 0x148
'NtGdiD3dContextDestroy', # 0x149
'NtGdiD3dContextDestroyAll', # 0x14a
'NtGdiD3dValidateTextureStageState', # 0x14b
'NtGdiDDCCIGetCapabilitiesString', # 0x14c
'NtGdiDDCCIGetCapabilitiesStringLength', # 0x14d
'NtGdiDDCCIGetTimingReport', # 0x14e
'NtGdiDDCCIGetVCPFeature', # 0x14f
'NtGdiDDCCISaveCurrentSettings', # 0x150
'NtGdiDDCCISetVCPFeature', # 0x151
'NtGdiDdAddAttachedSurface', # 0x152
'NtGdiDdAlphaBlt', # 0x153
'NtGdiDdAttachSurface', # 0x154
'NtGdiDdBeginMoCompFrame', # 0x155
'NtGdiDdCanCreateD3DBuffer', # 0x156
'NtGdiDdColorControl', # 0x157
'NtGdiDdCreateD3DBuffer', # 0x158
'NtGdiDdCreateDirectDrawObject', # 0x159
'NtGdiDdCreateMoComp', # 0x15a
'NtGdiDdDDICheckExclusiveOwnership', # 0x15b
'NtGdiDdDDICheckMonitorPowerState', # 0x15c
'NtGdiDdDDICheckOcclusion', # 0x15d
'NtGdiDdDDICloseAdapter', # 0x15e
'NtGdiDdDDICreateAllocation', # 0x15f
'NtGdiDdDDICreateContext', # 0x160
'NtGdiDdDDICreateDCFromMemory', # 0x161
'NtGdiDdDDICreateDevice', # 0x162
'NtGdiDdDDICreateOverlay', # 0x163
'NtGdiDdDDICreateSynchronizationObject', # 0x164
'NtGdiDdDDIDestroyAllocation', # 0x165
'NtGdiDdDDIDestroyContext', # 0x166
'NtGdiDdDDIDestroyDCFromMemory', # 0x167
'NtGdiDdDDIDestroyDevice', # 0x168
'NtGdiDdDDIDestroyOverlay', # 0x169
'NtGdiDdDDIDestroySynchronizationObject', # 0x16a
'NtGdiDdDDIEscape', # 0x16b
'NtGdiDdDDIFlipOverlay', # 0x16c
'NtGdiDdDDIGetContextSchedulingPriority', # 0x16d
'NtGdiDdDDIGetDeviceState', # 0x16e
'NtGdiDdDDIGetDisplayModeList', # 0x16f
'NtGdiDdDDIGetMultisampleMethodList', # 0x170
'NtGdiDdDDIGetPresentHistory', # 0x171
'NtGdiDdDDIGetProcessSchedulingPriorityClass', # 0x172
'NtGdiDdDDIGetRuntimeData', # 0x173
'NtGdiDdDDIGetScanLine', # 0x174
'NtGdiDdDDIGetSharedPrimaryHandle', # 0x175
'NtGdiDdDDIInvalidateActiveVidPn', # 0x176
'NtGdiDdDDILock', # 0x177
'NtGdiDdDDIOpenAdapterFromDeviceName', # 0x178
'NtGdiDdDDIOpenAdapterFromHdc', # 0x179
'NtGdiDdDDIOpenResource', # 0x17a
'NtGdiDdDDIPollDisplayChildren', # 0x17b
'NtGdiDdDDIPresent', # 0x17c
'NtGdiDdDDIQueryAdapterInfo', # 0x17d
'NtGdiDdDDIQueryAllocationResidency', # 0x17e
'NtGdiDdDDIQueryResourceInfo', # 0x17f
'NtGdiDdDDIQueryStatistics', # 0x180
'NtGdiDdDDIReleaseProcessVidPnSourceOwners', # 0x181
'NtGdiDdDDIRender', # 0x182
'NtGdiDdDDISetAllocationPriority', # 0x183
'NtGdiDdDDISetContextSchedulingPriority', # 0x184
'NtGdiDdDDISetDisplayMode', # 0x185
'NtGdiDdDDISetDisplayPrivateDriverFormat', # 0x186
'NtGdiDdDDISetGammaRamp', # 0x187
'NtGdiDdDDISetProcessSchedulingPriorityClass', # 0x188
'NtGdiDdDDISetQueuedLimit', # 0x189
'NtGdiDdDDISetVidPnSourceOwner', # 0x18a
'NtGdiDdDDISharedPrimaryLockNotification', # 0x18b
'NtGdiDdDDISharedPrimaryUnLockNotification', # 0x18c
'NtGdiDdDDISignalSynchronizationObject', # 0x18d
'NtGdiDdDDIUnlock', # 0x18e
'NtGdiDdDDIUpdateOverlay', # 0x18f
'NtGdiDdDDIWaitForIdle', # 0x190
'NtGdiDdDDIWaitForSynchronizationObject', # 0x191
'NtGdiDdDDIWaitForVerticalBlankEvent', # 0x192
'NtGdiDdDeleteDirectDrawObject', # 0x193
'NtGdiDdDestroyD3DBuffer', # 0x194
'NtGdiDdDestroyMoComp', # 0x195
'NtGdiDdEndMoCompFrame', # 0x196
'NtGdiDdFlip', # 0x197
'NtGdiDdFlipToGDISurface', # 0x198
'NtGdiDdGetAvailDriverMemory', # 0x199
'NtGdiDdGetBltStatus', # 0x19a
'NtGdiDdGetDC', # 0x19b
'NtGdiDdGetDriverInfo', # 0x19c
'NtGdiDdGetDriverState', # 0x19d
'NtGdiDdGetDxHandle', # 0x19e
'NtGdiDdGetFlipStatus', # 0x19f
'NtGdiDdGetInternalMoCompInfo', # 0x1a0
'NtGdiDdGetMoCompBuffInfo', # 0x1a1
'NtGdiDdGetMoCompFormats', # 0x1a2
'NtGdiDdGetMoCompGuids', # 0x1a3
'NtGdiDdGetScanLine', # 0x1a4
'NtGdiDdLock', # 0x1a5
'NtGdiDdQueryDirectDrawObject', # 0x1a6
'NtGdiDdQueryMoCompStatus', # 0x1a7
'NtGdiDdReenableDirectDrawObject', # 0x1a8
'NtGdiDdReleaseDC', # 0x1a9
'NtGdiDdRenderMoComp', # 0x1aa
'NtGdiDdSetColorKey', # 0x1ab
'NtGdiDdSetExclusiveMode', # 0x1ac
'NtGdiDdSetGammaRamp', # 0x1ad
'NtGdiDdSetOverlayPosition', # 0x1ae
'NtGdiDdUnattachSurface', # 0x1af
'NtGdiDdUnlock', # 0x1b0
'NtGdiDdUpdateOverlay', # 0x1b1
'NtGdiDdWaitForVerticalBlank', # 0x1b2
'NtGdiDeleteColorTransform', # 0x1b3
'NtGdiDescribePixelFormat', # 0x1b4
'NtGdiDestroyOPMProtectedOutput', # 0x1b5
'NtGdiDestroyPhysicalMonitor', # 0x1b6
'NtGdiDoBanding', # 0x1b7
'NtGdiDrawEscape', # 0x1b8
'NtGdiDvpAcquireNotification', # 0x1b9
'NtGdiDvpCanCreateVideoPort', # 0x1ba
'NtGdiDvpColorControl', # 0x1bb
'NtGdiDvpCreateVideoPort', # 0x1bc
'NtGdiDvpDestroyVideoPort', # 0x1bd
'NtGdiDvpFlipVideoPort', # 0x1be
'NtGdiDvpGetVideoPortBandwidth', # 0x1bf
'NtGdiDvpGetVideoPortConnectInfo', # 0x1c0
'NtGdiDvpGetVideoPortField', # 0x1c1
'NtGdiDvpGetVideoPortFlipStatus', # 0x1c2
'NtGdiDvpGetVideoPortInputFormats', # 0x1c3
'NtGdiDvpGetVideoPortLine', # 0x1c4
'NtGdiDvpGetVideoPortOutputFormats', # 0x1c5
'NtGdiDvpGetVideoSignalStatus', # 0x1c6
'NtGdiDvpReleaseNotification', # 0x1c7
'NtGdiDvpUpdateVideoPort', # 0x1c8
'NtGdiDvpWaitForVideoPortSync', # 0x1c9
'NtGdiDwmGetDirtyRgn', # 0x1ca
'NtGdiDwmGetSurfaceData', # 0x1cb
'NtGdiDxgGenericThunk', # 0x1cc
'NtGdiEllipse', # 0x1cd
'NtGdiEnableEudc', # 0x1ce
'NtGdiEndDoc', # 0x1cf
'NtGdiEndPage', # 0x1d0
'NtGdiEngAlphaBlend', # 0x1d1
'NtGdiEngAssociateSurface', # 0x1d2
'NtGdiEngBitBlt', # 0x1d3
'NtGdiEngCheckAbort', # 0x1d4
'NtGdiEngComputeGlyphSet', # 0x1d5
'NtGdiEngCopyBits', # 0x1d6
'NtGdiEngCreateBitmap', # 0x1d7
'NtGdiEngCreateClip', # 0x1d8
'NtGdiEngCreateDeviceBitmap', # 0x1d9
'NtGdiEngCreateDeviceSurface', # 0x1da
'NtGdiEngCreatePalette', # 0x1db
'NtGdiEngDeleteClip', # 0x1dc
'NtGdiEngDeletePalette', # 0x1dd
'NtGdiEngDeletePath', # 0x1de
'NtGdiEngDeleteSurface', # 0x1df
'NtGdiEngEraseSurface', # 0x1e0
'NtGdiEngFillPath', # 0x1e1
'NtGdiEngGradientFill', # 0x1e2
'NtGdiEngLineTo', # 0x1e3
'NtGdiEngLockSurface', # 0x1e4
'NtGdiEngMarkBandingSurface', # 0x1e5
'NtGdiEngPaint', # 0x1e6
'NtGdiEngPlgBlt', # 0x1e7
'NtGdiEngStretchBlt', # 0x1e8
'NtGdiEngStretchBltROP', # 0x1e9
'NtGdiEngStrokeAndFillPath', # 0x1ea
'NtGdiEngStrokePath', # 0x1eb
'NtGdiEngTextOut', # 0x1ec
'NtGdiEngTransparentBlt', # 0x1ed
'NtGdiEngUnlockSurface', # 0x1ee
'NtGdiEnumObjects', # 0x1ef
'NtGdiEudcLoadUnloadLink', # 0x1f0
'NtGdiExtFloodFill', # 0x1f1
'NtGdiFONTOBJ_cGetAllGlyphHandles', # 0x1f2
'NtGdiFONTOBJ_cGetGlyphs', # 0x1f3
'NtGdiFONTOBJ_pQueryGlyphAttrs', # 0x1f4
'NtGdiFONTOBJ_pfdg', # 0x1f5
'NtGdiFONTOBJ_pifi', # 0x1f6
'NtGdiFONTOBJ_pvTrueTypeFontFile', # 0x1f7
'NtGdiFONTOBJ_pxoGetXform', # 0x1f8
'NtGdiFONTOBJ_vGetInfo', # 0x1f9
'NtGdiFlattenPath', # 0x1fa
'NtGdiFontIsLinked', # 0x1fb
'NtGdiForceUFIMapping', # 0x1fc
'NtGdiFrameRgn', # 0x1fd
'NtGdiFullscreenControl', # 0x1fe
'NtGdiGetBoundsRect', # 0x1ff
'NtGdiGetCOPPCompatibleOPMInformation', # 0x200
'NtGdiGetCertificate', # 0x201
'NtGdiGetCertificateSize', # 0x202
'NtGdiGetCharABCWidthsW', # 0x203
'NtGdiGetCharacterPlacementW', # 0x204
'NtGdiGetColorAdjustment', # 0x205
'NtGdiGetColorSpaceforBitmap', # 0x206
'NtGdiGetDeviceCaps', # 0x207
'NtGdiGetDeviceCapsAll', # 0x208
'NtGdiGetDeviceGammaRamp', # 0x209
'NtGdiGetDeviceWidth', # 0x20a
'NtGdiGetDhpdev', # 0x20b
'NtGdiGetETM', # 0x20c
'NtGdiGetEmbUFI', # 0x20d
'NtGdiGetEmbedFonts', # 0x20e
'NtGdiGetEudcTimeStampEx', # 0x20f
'NtGdiGetFontResourceInfoInternalW', # 0x210
'NtGdiGetFontUnicodeRanges', # 0x211
'NtGdiGetGlyphIndicesW', # 0x212
'NtGdiGetGlyphIndicesWInternal', # 0x213
'NtGdiGetGlyphOutline', # 0x214
'NtGdiGetKerningPairs', # 0x215
'NtGdiGetLinkedUFIs', # 0x216
'NtGdiGetMiterLimit', # 0x217
'NtGdiGetMonitorID', # 0x218
'NtGdiGetNumberOfPhysicalMonitors', # 0x219
'NtGdiGetOPMInformation', # 0x21a
'NtGdiGetOPMRandomNumber', # 0x21b
'NtGdiGetObjectBitmapHandle', # 0x21c
'NtGdiGetPath', # 0x21d
'NtGdiGetPerBandInfo', # 0x21e
'NtGdiGetPhysicalMonitorDescription', # 0x21f
'NtGdiGetPhysicalMonitors', # 0x220
'NtGdiGetRealizationInfo', # 0x221
'NtGdiGetServerMetaFileBits', # 0x222
'NtGdiGetSpoolMessage', # 0x223
'NtGdiGetStats', # 0x224
'NtGdiGetStringBitmapW', # 0x225
'NtGdiGetSuggestedOPMProtectedOutputArraySize', # 0x226
'NtGdiGetTextExtentExW', # 0x227
'NtGdiGetUFI', # 0x228
'NtGdiGetUFIPathname', # 0x229
'NtGdiGradientFill', # 0x22a
'NtGdiHT_Get8BPPFormatPalette', # 0x22b
'NtGdiHT_Get8BPPMaskPalette', # 0x22c
'NtGdiIcmBrushInfo', # 0x22d
'NtGdiInit', # 0x22e
'NtGdiInitSpool', # 0x22f
'NtGdiMakeFontDir', # 0x230
'NtGdiMakeInfoDC', # 0x231
'NtGdiMakeObjectUnXferable', # 0x232
'NtGdiMakeObjectXferable', # 0x233
'NtGdiMirrorWindowOrg', # 0x234
'NtGdiMonoBitmap', # 0x235
'NtGdiMoveTo', # 0x236
'NtGdiOffsetClipRgn', # 0x237
'NtGdiPATHOBJ_bEnum', # 0x238
'NtGdiPATHOBJ_bEnumClipLines', # 0x239
'NtGdiPATHOBJ_vEnumStart', # 0x23a
'NtGdiPATHOBJ_vEnumStartClipLines', # 0x23b
'NtGdiPATHOBJ_vGetBounds', # 0x23c
'NtGdiPathToRegion', # 0x23d
'NtGdiPlgBlt', # 0x23e
'NtGdiPolyDraw', # 0x23f
'NtGdiPolyTextOutW', # 0x240
'NtGdiPtInRegion', # 0x241
'NtGdiPtVisible', # 0x242
'NtGdiQueryFonts', # 0x243
'NtGdiRemoveFontResourceW', # 0x244
'NtGdiRemoveMergeFont', # 0x245
'NtGdiResetDC', # 0x246
'NtGdiResizePalette', # 0x247
'NtGdiRoundRect', # 0x248
'NtGdiSTROBJ_bEnum', # 0x249
'NtGdiSTROBJ_bEnumPositionsOnly', # 0x24a
'NtGdiSTROBJ_bGetAdvanceWidths', # 0x24b
'NtGdiSTROBJ_dwGetCodePage', # 0x24c
'NtGdiSTROBJ_vEnumStart', # 0x24d
'NtGdiScaleViewportExtEx', # 0x24e
'NtGdiScaleWindowExtEx', # 0x24f
'NtGdiSelectBrush', # 0x250
'NtGdiSelectClipPath', # 0x251
'NtGdiSelectPen', # 0x252
'NtGdiSetBitmapAttributes', # 0x253
'NtGdiSetBrushAttributes', # 0x254
'NtGdiSetColorAdjustment', # 0x255
'NtGdiSetColorSpace', # 0x256
'NtGdiSetDeviceGammaRamp', # 0x257
'NtGdiSetFontXform', # 0x258
'NtGdiSetIcmMode', # 0x259
'NtGdiSetLinkedUFIs', # 0x25a
'NtGdiSetMagicColors', # 0x25b
'NtGdiSetOPMSigningKeyAndSequenceNumbers', # 0x25c
'NtGdiSetPUMPDOBJ', # 0x25d
'NtGdiSetPixelFormat', # 0x25e
'NtGdiSetRectRgn', # 0x25f
'NtGdiSetSizeDevice', # 0x260
'NtGdiSetSystemPaletteUse', # 0x261
'NtGdiSetTextJustification', # 0x262
'NtGdiStartDoc', # 0x263
'NtGdiStartPage', # 0x264
'NtGdiStrokeAndFillPath', # 0x265
'NtGdiStrokePath', # 0x266
'NtGdiSwapBuffers', # 0x267
'NtGdiTransparentBlt', # 0x268
'NtGdiUMPDEngFreeUserMem', # 0x269
'NtGdiUnloadPrinterDriver', # 0x26a
'NtGdiUnmapMemFont', # 0x26b
'NtGdiUpdateColors', # 0x26c
'NtGdiUpdateTransform', # 0x26d
'NtGdiWidenPath', # 0x26e
'NtGdiXFORMOBJ_bApplyXform', # 0x26f
'NtGdiXFORMOBJ_iGetXform', # 0x270
'NtGdiXLATEOBJ_cGetPalette', # 0x271
'NtGdiXLATEOBJ_hGetColorTransform', # 0x272
'NtGdiXLATEOBJ_iXlate', # 0x273
'NtUserAddClipboardFormatListener', # 0x274
'NtUserAssociateInputContext', # 0x275
'NtUserBlockInput', # 0x276
'NtUserBuildHimcList', # 0x277
'NtUserBuildPropList', # 0x278
'NtUserCallHwndOpt', # 0x279
'NtUserChangeDisplaySettings', # 0x27a
'NtUserCheckAccessForIntegrityLevel', # 0x27b
'NtUserCheckDesktopByThreadId', # 0x27c
'NtUserCheckWindowThreadDesktop', # 0x27d
'NtUserChildWindowFromPointEx', # 0x27e
'NtUserClipCursor', # 0x27f
'NtUserCreateDesktopEx', # 0x280
'NtUserCreateInputContext', # 0x281
'NtUserCreateWindowStation', # 0x282
'NtUserCtxDisplayIOCtl', # 0x283
'NtUserDestroyInputContext', # 0x284
'NtUserDisableThreadIme', # 0x285
'NtUserDoSoundConnect', # 0x286
'NtUserDoSoundDisconnect', # 0x287
'NtUserDragDetect', # 0x288
'NtUserDragObject', # 0x289
'NtUserDrawAnimatedRects', # 0x28a
'NtUserDrawCaption', # 0x28b
'NtUserDrawCaptionTemp', # 0x28c
'NtUserDrawMenuBarTemp', # 0x28d
'NtUserDwmGetDxRgn', # 0x28e
'NtUserDwmHintDxUpdate', # 0x28f
'NtUserDwmStartRedirection', # 0x290
'NtUserDwmStopRedirection', # 0x291
'NtUserEndMenu', # 0x292
'NtUserEvent', # 0x293
'NtUserFlashWindowEx', # 0x294
'NtUserFrostCrashedWindow', # 0x295
'NtUserGetAppImeLevel', # 0x296
'NtUserGetCaretPos', # 0x297
'NtUserGetClipCursor', # 0x298
'NtUserGetClipboardViewer', # 0x299
'NtUserGetComboBoxInfo', # 0x29a
'NtUserGetCursorInfo', # 0x29b
'NtUserGetGuiResources', # 0x29c
'NtUserGetImeHotKey', # 0x29d
'NtUserGetImeInfoEx', # 0x29e
'NtUserGetInternalWindowPos', # 0x29f
'NtUserGetKeyNameText', # 0x2a0
'NtUserGetKeyboardLayoutName', # 0x2a1
'NtUserGetLayeredWindowAttributes', # 0x2a2
'NtUserGetListBoxInfo', # 0x2a3
'NtUserGetMenuIndex', # 0x2a4
'NtUserGetMenuItemRect', # 0x2a5
'NtUserGetMouseMovePointsEx', # 0x2a6
'NtUserGetPriorityClipboardFormat', # 0x2a7
'NtUserGetRawInputBuffer', # 0x2a8
'NtUserGetRawInputData', # 0x2a9
'NtUserGetRawInputDeviceInfo', # 0x2aa
'NtUserGetRawInputDeviceList', # 0x2ab
'NtUserGetRegisteredRawInputDevices', # 0x2ac
'NtUserGetUpdatedClipboardFormats', # 0x2ad
'NtUserGetWOWClass', # 0x2ae
'NtUserGetWindowMinimizeRect', # 0x2af
'NtUserGetWindowRgnEx', # 0x2b0
'NtUserGhostWindowFromHungWindow', # 0x2b1
'NtUserHardErrorControl', # 0x2b2
'NtUserHiliteMenuItem', # 0x2b3
'NtUserHungWindowFromGhostWindow', # 0x2b4
'NtUserImpersonateDdeClientWindow', # 0x2b5
'NtUserInitTask', # 0x2b6
'NtUserInitialize', # 0x2b7
'NtUserInitializeClientPfnArrays', # 0x2b8
'NtUserInternalGetWindowIcon', # 0x2b9
'NtUserLoadKeyboardLayoutEx', # 0x2ba
'NtUserLockWindowStation', # 0x2bb
'NtUserLockWorkStation', # 0x2bc
'NtUserLogicalToPhysicalPoint', # 0x2bd
'NtUserMNDragLeave', # 0x2be
'NtUserMNDragOver', # 0x2bf
'NtUserMenuItemFromPoint', # 0x2c0
'NtUserMinMaximize', # 0x2c1
'NtUserNotifyIMEStatus', # 0x2c2
'NtUserOpenInputDesktop', # 0x2c3
'NtUserOpenThreadDesktop', # 0x2c4
'NtUserPaintMonitor', # 0x2c5
'NtUserPhysicalToLogicalPoint', # 0x2c6
'NtUserPrintWindow', # 0x2c7
'NtUserQueryInformationThread', # 0x2c8
'NtUserQueryInputContext', # 0x2c9
'NtUserQuerySendMessage', # 0x2ca
'NtUserRealChildWindowFromPoint', # 0x2cb
'NtUserRealWaitMessageEx', # 0x2cc
'NtUserRegisterErrorReportingDialog', # 0x2cd
'NtUserRegisterHotKey', # 0x2ce
'NtUserRegisterRawInputDevices', # 0x2cf
'NtUserRegisterSessionPort', # 0x2d0
'NtUserRegisterTasklist', # 0x2d1
'NtUserRegisterUserApiHook', # 0x2d2
'NtUserRemoteConnect', # 0x2d3
'NtUserRemoteRedrawRectangle', # 0x2d4
'NtUserRemoteRedrawScreen', # 0x2d5
'NtUserRemoteStopScreenUpdates', # 0x2d6
'NtUserRemoveClipboardFormatListener', # 0x2d7
'NtUserResolveDesktopForWOW', # 0x2d8
'NtUserSetAppImeLevel', # 0x2d9
'NtUserSetClassWord', # 0x2da
'NtUserSetCursorContents', # 0x2db
'NtUserSetImeHotKey', # 0x2dc
'NtUserSetImeInfoEx', # 0x2dd
'NtUserSetImeOwnerWindow', # 0x2de
'NtUserSetInternalWindowPos', # 0x2df
'NtUserSetLayeredWindowAttributes', # 0x2e0
'NtUserSetMenu', # 0x2e1
'NtUserSetMenuContextHelpId', # 0x2e2
'NtUserSetMenuFlagRtoL', # 0x2e3
'NtUserSetMirrorRendering', # 0x2e4
'NtUserSetObjectInformation', # 0x2e5
'NtUserSetProcessDPIAware', # 0x2e6
'NtUserSetShellWindowEx', # 0x2e7
'NtUserSetSysColors', # 0x2e8
'NtUserSetSystemCursor', # 0x2e9
'NtUserSetSystemTimer', # 0x2ea
'NtUserSetThreadLayoutHandles', # 0x2eb
'NtUserSetWindowRgnEx', # 0x2ec
'NtUserSetWindowStationUser', # 0x2ed
'NtUserShowSystemCursor', # 0x2ee
'NtUserSoundSentry', # 0x2ef
'NtUserSwitchDesktop', # 0x2f0
'NtUserTestForInteractiveUser', # 0x2f1
'NtUserTrackPopupMenuEx', # 0x2f2
'NtUserUnloadKeyboardLayout', # 0x2f3
'NtUserUnlockWindowStation', # 0x2f4
'NtUserUnregisterHotKey', # 0x2f5
'NtUserUnregisterSessionPort', # 0x2f6
'NtUserUnregisterUserApiHook', # 0x2f7
'NtUserUpdateInputContext', # 0x2f8
'NtUserUpdateInstance', # 0x2f9
'NtUserUpdateLayeredWindow', # 0x2fa
'NtUserUpdatePerUserSystemParameters', # 0x2fb
'NtUserUpdateWindowTransform', # 0x2fc
'NtUserUserHandleGrantAccess', # 0x2fd
'NtUserValidateHandleSecure', # 0x2fe
'NtUserWaitForInputIdle', # 0x2ff
'NtUserWaitForMsgAndEvent', # 0x300
'NtUserWin32PoolAllocationStats', # 0x301
'NtUserWindowFromPhysicalPoint', # 0x302
'NtUserYieldTask', # 0x303
'NtUserSetClassLongPtr', # 0x304
'NtUserSetWindowLongPtr', # 0x305
],
]
| Cisco-Talos/pyrebox | volatility/volatility/plugins/overlays/windows/vista_sp12_x64_syscalls.py | Python | gpl-2.0 | 43,395 |
// license:BSD-3-Clause
// copyright-holders:Aaron Giles
/***************************************************************************
RIOT 6532 emulation
The timer seems to follow these rules:
- When the timer flag changes from 0 to 1 the timer continues to count
down at a 1 cycle rate.
- When the timer is being read or written the timer flag is reset.
- When the timer flag is set and the timer contents are 0, the counting
stops.
***************************************************************************/
#include "emu.h"
#include "6532riot.h"
//**************************************************************************
// CONSTANTS
//**************************************************************************
// device type definition
DEFINE_DEVICE_TYPE(RIOT6532, riot6532_device, "riot6532", "6532 RIOT")
enum
{
TIMER_IDLE,
TIMER_COUNTING,
TIMER_FINISHING
};
#define TIMER_FLAG 0x80
#define PA7_FLAG 0x40
/***************************************************************************
INTERNAL FUNCTIONS
***************************************************************************/
/*-------------------------------------------------
update_irqstate - update the IRQ state
based on interrupt enables
-------------------------------------------------*/
void riot6532_device::update_irqstate()
{
int irq = (m_irqstate & m_irqenable) ? ASSERT_LINE : CLEAR_LINE;
if (m_irq != irq)
{
m_irq_cb(irq);
m_irq = irq;
}
}
/*-------------------------------------------------
apply_ddr - combine inputs and outputs
according to the DDR
-------------------------------------------------*/
uint8_t riot6532_device::apply_ddr(const riot6532_port *port)
{
return (port->m_out & port->m_ddr) | (port->m_in & ~port->m_ddr);
}
/*-------------------------------------------------
update_pa7_state - see if PA7 has changed
and signal appropriately
-------------------------------------------------*/
void riot6532_device::update_pa7_state()
{
uint8_t data = apply_ddr(&m_port[0]) & 0x80;
/* if the state changed in the correct direction, set the PA7 flag and update IRQs */
if ((m_pa7prev ^ data) && (m_pa7dir ^ data) == 0)
{
m_irqstate |= PA7_FLAG;
update_irqstate();
}
m_pa7prev = data;
}
/*-------------------------------------------------
get_timer - return the current timer value
-------------------------------------------------*/
uint8_t riot6532_device::get_timer()
{
/* if idle, return 0 */
if (m_timerstate == TIMER_IDLE)
{
return 0;
}
/* if counting, return the number of ticks remaining */
else if (m_timerstate == TIMER_COUNTING)
{
return m_timer->remaining().as_ticks(clock()) >> m_timershift;
}
/* if finishing, return the number of ticks without the shift */
else
{
return m_timer->remaining().as_ticks(clock());
}
}
void riot6532_device::timer_end()
{
assert(m_timerstate != TIMER_IDLE);
/* if we finished counting, switch to the finishing state */
if(m_timerstate == TIMER_COUNTING)
{
m_timerstate = TIMER_FINISHING;
m_timer->adjust(attotime::from_ticks(256, clock()));
/* signal timer IRQ as well */
m_irqstate |= TIMER_FLAG;
update_irqstate();
}
/* if we finished finishing, keep spinning */
else if (m_timerstate == TIMER_FINISHING)
{
m_timer->adjust(attotime::from_ticks(256, clock()));
}
}
/***************************************************************************
I/O ACCESS
***************************************************************************/
/*-------------------------------------------------
riot6532_w - master I/O write access
-------------------------------------------------*/
void riot6532_device::write(offs_t offset, uint8_t data)
{
reg_w(offset, data);
}
void riot6532_device::reg_w(uint8_t offset, uint8_t data)
{
/* if A4 == 1 and A2 == 1, we are writing to the timer */
if ((offset & 0x14) == 0x14)
{
static const uint8_t timershift[4] = { 0, 3, 6, 10 };
attotime curtime = machine().time();
int64_t target;
/* A0-A1 contain the timer divisor */
m_timershift = timershift[offset & 3];
/* A3 contains the timer IRQ enable */
if (offset & 8)
m_irqenable |= TIMER_FLAG;
else
m_irqenable &= ~TIMER_FLAG;
/* writes here clear the timer flag */
if (m_timerstate != TIMER_FINISHING || get_timer() != 0xff)
{
m_irqstate &= ~TIMER_FLAG;
}
update_irqstate();
/* update the timer */
m_timerstate = TIMER_COUNTING;
target = curtime.as_ticks(clock()) + 1 + (data << m_timershift);
m_timer->adjust(attotime::from_ticks(target, clock()) - curtime);
}
/* if A4 == 0 and A2 == 1, we are writing to the edge detect control */
else if ((offset & 0x14) == 0x04)
{
/* A1 contains the A7 IRQ enable */
if (offset & 2)
{
m_irqenable |= PA7_FLAG;
}
else
{
m_irqenable &= ~PA7_FLAG;
}
/* A0 specifies the edge detect direction: 0=negative, 1=positive */
m_pa7dir = (offset & 1) << 7;
}
/* if A4 == anything and A2 == 0, we are writing to the I/O section */
else
{
/* A1 selects the port */
riot6532_port *port = &m_port[BIT(offset, 1)];
/* if A0 == 1, we are writing to the port's DDR */
if (offset & 1)
{
port->m_ddr = data;
}
/* if A0 == 0, we are writing to the port's output */
else
{
port->m_out = data;
(*port->m_out_cb)((offs_t)0, data);
}
/* writes to port A need to update the PA7 state */
if (port == &m_port[0])
{
update_pa7_state();
}
}
}
/*-------------------------------------------------
riot6532_r - master I/O read access
-------------------------------------------------*/
uint8_t riot6532_device::read(offs_t offset)
{
return reg_r(offset, machine().side_effects_disabled());
}
uint8_t riot6532_device::reg_r(uint8_t offset, bool debugger_access)
{
uint8_t val;
/* if A2 == 1 and A0 == 1, we are reading interrupt flags */
if ((offset & 0x05) == 0x05)
{
val = m_irqstate;
if ( ! debugger_access )
{
/* implicitly clears the PA7 flag */
m_irqstate &= ~PA7_FLAG;
update_irqstate();
}
}
/* if A2 == 1 and A0 == 0, we are reading the timer */
else if ((offset & 0x05) == 0x04)
{
val = get_timer();
if ( ! debugger_access )
{
/* A3 contains the timer IRQ enable */
if (offset & 8)
{
m_irqenable |= TIMER_FLAG;
}
else
{
m_irqenable &= ~TIMER_FLAG;
}
/* implicitly clears the timer flag */
if (m_timerstate != TIMER_FINISHING || val != 0xff)
{
m_irqstate &= ~TIMER_FLAG;
}
update_irqstate();
}
}
/* if A2 == 0 and A0 == anything, we are reading from ports */
else
{
/* A1 selects the port */
riot6532_port *port = &m_port[BIT(offset, 1)];
/* if A0 == 1, we are reading the port's DDR */
if (offset & 1)
{
val = port->m_ddr;
}
/* if A0 == 0, we are reading the port as an input */
else
{
/* call the input callback if it exists */
if (!(*port->m_in_cb).isnull())
{
port->m_in = (*port->m_in_cb)(0);
/* changes to port A need to update the PA7 state */
if (port == &m_port[0])
{
if (!debugger_access)
{
update_pa7_state();
}
}
}
/* apply the DDR to the result */
val = apply_ddr(port);
}
}
return val;
}
/*-------------------------------------------------
porta_in_set - set port A input value
-------------------------------------------------*/
void riot6532_device::porta_in_set(uint8_t data, uint8_t mask)
{
m_port[0].m_in = (m_port[0].m_in & ~mask) | (data & mask);
update_pa7_state();
}
/*-------------------------------------------------
portb_in_set - set port B input value
-------------------------------------------------*/
void riot6532_device::portb_in_set(uint8_t data, uint8_t mask)
{
m_port[1].m_in = (m_port[1].m_in & ~mask) | (data & mask);
}
/*-------------------------------------------------
porta_in_get - return port A input value
-------------------------------------------------*/
uint8_t riot6532_device::porta_in_get()
{
return m_port[0].m_in;
}
/*-------------------------------------------------
portb_in_get - return port B input value
-------------------------------------------------*/
uint8_t riot6532_device::portb_in_get()
{
return m_port[1].m_in;
}
/*-------------------------------------------------
porta_in_get - return port A output value
-------------------------------------------------*/
uint8_t riot6532_device::porta_out_get()
{
return m_port[0].m_out;
}
/*-------------------------------------------------
portb_in_get - return port B output value
-------------------------------------------------*/
uint8_t riot6532_device::portb_out_get()
{
return m_port[1].m_out;
}
//-------------------------------------------------
// paN_w - write Port A lines individually
//-------------------------------------------------
WRITE_LINE_MEMBER(riot6532_device::pa0_w) { porta_in_set(state ? 0x01 : 0x00, 0x01); }
WRITE_LINE_MEMBER(riot6532_device::pa1_w) { porta_in_set(state ? 0x02 : 0x00, 0x02); }
WRITE_LINE_MEMBER(riot6532_device::pa2_w) { porta_in_set(state ? 0x04 : 0x00, 0x04); }
WRITE_LINE_MEMBER(riot6532_device::pa3_w) { porta_in_set(state ? 0x08 : 0x00, 0x08); }
WRITE_LINE_MEMBER(riot6532_device::pa4_w) { porta_in_set(state ? 0x10 : 0x00, 0x10); }
WRITE_LINE_MEMBER(riot6532_device::pa5_w) { porta_in_set(state ? 0x20 : 0x00, 0x20); }
WRITE_LINE_MEMBER(riot6532_device::pa6_w) { porta_in_set(state ? 0x40 : 0x00, 0x40); }
WRITE_LINE_MEMBER(riot6532_device::pa7_w) { porta_in_set(state ? 0x80 : 0x00, 0x80); }
//-------------------------------------------------
// pbN_w - write Port B lines individually
//-------------------------------------------------
WRITE_LINE_MEMBER(riot6532_device::pb0_w) { portb_in_set(state ? 0x01 : 0x00, 0x01); }
WRITE_LINE_MEMBER(riot6532_device::pb1_w) { portb_in_set(state ? 0x02 : 0x00, 0x02); }
WRITE_LINE_MEMBER(riot6532_device::pb2_w) { portb_in_set(state ? 0x04 : 0x00, 0x04); }
WRITE_LINE_MEMBER(riot6532_device::pb3_w) { portb_in_set(state ? 0x08 : 0x00, 0x08); }
WRITE_LINE_MEMBER(riot6532_device::pb4_w) { portb_in_set(state ? 0x10 : 0x00, 0x10); }
WRITE_LINE_MEMBER(riot6532_device::pb5_w) { portb_in_set(state ? 0x20 : 0x00, 0x20); }
WRITE_LINE_MEMBER(riot6532_device::pb6_w) { portb_in_set(state ? 0x40 : 0x00, 0x40); }
WRITE_LINE_MEMBER(riot6532_device::pb7_w) { portb_in_set(state ? 0x80 : 0x00, 0x80); }
//**************************************************************************
// LIVE DEVICE
//**************************************************************************
//-------------------------------------------------
// riot6532_device - constructor
//-------------------------------------------------
riot6532_device::riot6532_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, RIOT6532, tag, owner, clock),
m_in_pa_cb(*this),
m_out_pa_cb(*this),
m_in_pb_cb(*this),
m_out_pb_cb(*this),
m_irq_cb(*this),
m_irqstate(0),
m_irqenable(0),
m_irq(CLEAR_LINE),
m_pa7dir(0),
m_pa7prev(0),
m_timershift(0),
m_timerstate(0),
m_timer(nullptr)
{
memset(m_port, 0x00, sizeof(m_port));
}
/*-------------------------------------------------
device_start - device-specific startup
-------------------------------------------------*/
void riot6532_device::device_start()
{
/* resolve callbacks */
m_in_pa_cb.resolve();
m_port[0].m_in_cb = &m_in_pa_cb;
m_out_pa_cb.resolve_safe();
m_port[0].m_out_cb = &m_out_pa_cb;
m_in_pb_cb.resolve();
m_port[1].m_in_cb = &m_in_pb_cb;
m_out_pb_cb.resolve_safe();
m_port[1].m_out_cb = &m_out_pb_cb;
m_irq_cb.resolve_safe();
/* allocate timers */
m_timer = timer_alloc(TIMER_END_CB);
/* register for save states */
save_item(NAME(m_port[0].m_in));
save_item(NAME(m_port[0].m_out));
save_item(NAME(m_port[0].m_ddr));
save_item(NAME(m_port[1].m_in));
save_item(NAME(m_port[1].m_out));
save_item(NAME(m_port[1].m_ddr));
save_item(NAME(m_irqstate));
save_item(NAME(m_irqenable));
save_item(NAME(m_irq));
save_item(NAME(m_pa7dir));
save_item(NAME(m_pa7prev));
save_item(NAME(m_timershift));
save_item(NAME(m_timerstate));
}
/*-------------------------------------------------
device_reset - device-specific reset
-------------------------------------------------*/
void riot6532_device::device_reset()
{
/* reset I/O states */
m_port[0].m_in = 0;
m_port[0].m_out = 0;
m_port[0].m_ddr = 0;
m_port[1].m_in = 0;
m_port[1].m_out = 0;
m_port[1].m_ddr = 0;
/* reset IRQ states */
m_irqenable = 0;
m_irqstate = 0;
update_irqstate();
/* reset PA7 states */
m_pa7dir = 0;
m_pa7prev = 0;
/* reset timer states */
m_timershift = 10;
m_timerstate = TIMER_COUNTING;
m_timer->adjust(attotime::from_ticks(256 << m_timershift, clock()));
}
void riot6532_device::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
{
switch (id)
{
case TIMER_END_CB:
timer_end();
break;
default:
throw emu_fatalerror("Unknown id in riot6532_device::device_timer");
}
}
| johnparker007/mame | src/devices/machine/6532riot.cpp | C++ | gpl-2.0 | 12,996 |
package net.oschina.app.ui;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.bean.FriendList;
import net.oschina.app.bean.MyInformation;
import net.oschina.app.bean.Result;
import net.oschina.app.common.FileUtils;
import net.oschina.app.common.ImageUtils;
import net.oschina.app.common.StringUtils;
import net.oschina.app.common.UIHelper;
import net.oschina.app.widget.LoadingDialog;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* 用户资料
* @author liux (http://my.oschina.net/liux)
* @version 1.0
* @created 2012-3-21
*/
public class UserInfo extends BaseActivity{
private ImageView back;
private ImageView refresh;
private ImageView face;
private ImageView gender;
private Button editer;
private TextView name;
private TextView jointime;
private TextView from;
private TextView devplatform;
private TextView expertise;
private TextView followers;
private TextView fans;
private TextView favorites;
private LinearLayout favorites_ll;
private LinearLayout followers_ll;
private LinearLayout fans_ll;
private LoadingDialog loading;
private MyInformation user;
private Handler mHandler;
private final static int CROP = 200;
private final static String FILE_SAVEPATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/OSChina/Portrait/";
private Uri origUri;
private Uri cropUri;
private File protraitFile;
private Bitmap protraitBitmap;
private String protraitPath;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_info);
//初始化视图控件
this.initView();
//初始化视图数据
this.initData();
}
private void initView(){
back = (ImageView)findViewById(R.id.user_info_back);
refresh = (ImageView)findViewById(R.id.user_info_refresh);
editer = (Button)findViewById(R.id.user_info_editer);
back.setOnClickListener(UIHelper.finish(this));
refresh.setOnClickListener(refreshClickListener);
editer.setOnClickListener(editerClickListener);
face = (ImageView)findViewById(R.id.user_info_userface);
gender = (ImageView)findViewById(R.id.user_info_gender);
name = (TextView)findViewById(R.id.user_info_username);
jointime = (TextView)findViewById(R.id.user_info_jointime);
from = (TextView)findViewById(R.id.user_info_from);
devplatform = (TextView)findViewById(R.id.user_info_devplatform);
expertise = (TextView)findViewById(R.id.user_info_expertise);
followers = (TextView)findViewById(R.id.user_info_followers);
fans = (TextView)findViewById(R.id.user_info_fans);
favorites = (TextView)findViewById(R.id.user_info_favorites);
favorites_ll = (LinearLayout)findViewById(R.id.user_info_favorites_ll);
followers_ll = (LinearLayout)findViewById(R.id.user_info_followers_ll);
fans_ll = (LinearLayout)findViewById(R.id.user_info_fans_ll);
}
private void initData(){
mHandler = new Handler(){
public void handleMessage(Message msg) {
if(loading != null) loading.dismiss();
if(msg.what == 1 && msg.obj != null){
user = (MyInformation)msg.obj;
//加载用户头像
UIHelper.showUserFace(face, user.getFace());
//用户性别
if(user.getGender() == 1)
gender.setImageResource(R.drawable.widget_gender_man);
else
gender.setImageResource(R.drawable.widget_gender_woman);
//其他资料
name.setText(user.getName());
jointime.setText(StringUtils.friendly_time(user.getJointime()));
from.setText(user.getFrom());
devplatform.setText(user.getDevplatform());
expertise.setText(user.getExpertise());
followers.setText(user.getFollowerscount()+"");
fans.setText(user.getFanscount()+"");
favorites.setText(user.getFavoritecount()+"");
favorites_ll.setOnClickListener(favoritesClickListener);
fans_ll.setOnClickListener(fansClickListener);
followers_ll.setOnClickListener(followersClickListener);
}else if(msg.obj != null){
((AppException)msg.obj).makeToast(UserInfo.this);
}
}
};
this.loadUserInfoThread(false);
}
private void loadUserInfoThread(final boolean isRefresh){
loading = new LoadingDialog(this);
loading.show();
new Thread(){
public void run() {
Message msg = new Message();
try {
MyInformation user = ((AppContext)getApplication()).getMyInformation(isRefresh);
msg.what = 1;
msg.obj = user;
} catch (AppException e) {
e.printStackTrace();
msg.what = -1;
msg.obj = e;
}
mHandler.sendMessage(msg);
}
}.start();
}
private View.OnClickListener editerClickListener = new View.OnClickListener(){
public void onClick(View v) {
CharSequence[] items = {
getString(R.string.img_from_album),
getString(R.string.img_from_camera)
};
imageChooseItem(items);
}
};
private View.OnClickListener refreshClickListener = new View.OnClickListener(){
public void onClick(View v) {
loadUserInfoThread(true);
}
};
private View.OnClickListener favoritesClickListener = new View.OnClickListener(){
public void onClick(View v) {
UIHelper.showUserFavorite(v.getContext());
}
};
private View.OnClickListener fansClickListener = new View.OnClickListener(){
public void onClick(View v) {
int followers = user!=null ? user.getFollowerscount() : 0;
int fans = user!=null ? user.getFanscount() : 0;
UIHelper.showUserFriend(v.getContext(), FriendList.TYPE_FANS, followers, fans);
}
};
private View.OnClickListener followersClickListener = new View.OnClickListener(){
public void onClick(View v) {
int followers = user!=null ? user.getFollowerscount() : 0;
int fans = user!=null ? user.getFanscount() : 0;
UIHelper.showUserFriend(v.getContext(), FriendList.TYPE_FOLLOWER, followers, fans);
}
};
/**
* 操作选择
* @param items
*/
public void imageChooseItem(CharSequence[] items )
{
AlertDialog imageDialog = new AlertDialog.Builder(this).setTitle("上传头像").setIcon(android.R.drawable.btn_star).setItems(items,
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int item)
{
//判断是否挂载了SD卡
String storageState = Environment.getExternalStorageState();
if(storageState.equals(Environment.MEDIA_MOUNTED)){
File savedir = new File(FILE_SAVEPATH);
if (!savedir.exists()) {
savedir.mkdirs();
}
}
else{
UIHelper.ToastMessage(UserInfo.this, "无法保存上传的头像,请检查SD卡是否挂载");
return;
}
//输出裁剪的临时文件
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//照片命名
String origFileName = "osc_" + timeStamp + ".jpg";
String cropFileName = "osc_crop_" + timeStamp + ".jpg";
//裁剪头像的绝对路径
protraitPath = FILE_SAVEPATH + cropFileName;
protraitFile = new File(protraitPath);
origUri = Uri.fromFile(new File(FILE_SAVEPATH, origFileName));
cropUri = Uri.fromFile(protraitFile);
//相册选图
if(item == 0) {
startActionPickCrop(cropUri);
}
//手机拍照
else if(item == 1){
startActionCamera(origUri);
}
}}).create();
imageDialog.show();
}
/**
* 选择图片裁剪
* @param output
*/
private void startActionPickCrop(Uri output) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.putExtra("output", output);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);// 裁剪框比例
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", CROP);// 输出图片大小
intent.putExtra("outputY", CROP);
startActivityForResult(Intent.createChooser(intent, "选择图片"),ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
}
/**
* 相机拍照
* @param output
*/
private void startActionCamera(Uri output) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
}
/**
* 拍照后裁剪
* @param data 原始图片
* @param output 裁剪后图片
*/
private void startActionCrop(Uri data, Uri output) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(data, "image/*");
intent.putExtra("output", output);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);// 裁剪框比例
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", CROP);// 输出图片大小
intent.putExtra("outputY", CROP);
startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
}
/**
* 上传新照片
*/
private void uploadNewPhoto() {
final Handler handler = new Handler(){
public void handleMessage(Message msg) {
if(loading != null) loading.dismiss();
if(msg.what == 1 && msg.obj != null){
Result res = (Result)msg.obj;
//提示信息
UIHelper.ToastMessage(UserInfo.this, res.getErrorMessage());
if(res.OK()){
//显示新头像
face.setImageBitmap(protraitBitmap);
}
}else if(msg.what == -1 && msg.obj != null){
((AppException)msg.obj).makeToast(UserInfo.this);
}
}
};
if(loading != null){
loading.setLoadText("正在上传头像···");
loading.show();
}
new Thread(){
public void run()
{
//获取头像缩略图
if(!StringUtils.isEmpty(protraitPath) && protraitFile.exists())
{
protraitBitmap = ImageUtils.loadImgThumbnail(protraitPath, 200, 200);
}
if(protraitBitmap != null)
{
Message msg = new Message();
try {
Result res = ((AppContext)getApplication()).updatePortrait(protraitFile);
if(res!=null && res.OK()){
//保存新头像到缓存
String filename = FileUtils.getFileName(user.getFace());
ImageUtils.saveImage(UserInfo.this, filename, protraitBitmap);
}
msg.what = 1;
msg.obj = res;
} catch (AppException e) {
e.printStackTrace();
msg.what = -1;
msg.obj = e;
} catch(IOException e) {
e.printStackTrace();
}
handler.sendMessage(msg);
}
};
}.start();
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data)
{
if(resultCode != RESULT_OK) return;
switch(requestCode){
case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA:
startActionCrop(origUri, cropUri);//拍照后裁剪
break;
case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:
case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:
uploadNewPhoto();//上传新照片
break;
}
}
}
| ivaners/android-app | src/net/oschina/app/ui/UserInfo.java | Java | gpl-2.0 | 11,772 |
var class_peta_poco_1_1_factory =
[
[ "ProviderName", "class_peta_poco_1_1_factory.html#ab3fd0d733879b1a810f8d5e3731c721b", null ]
]; | mixerp/mixerp | docs/api/class_peta_poco_1_1_factory.js | JavaScript | gpl-3.0 | 137 |
package com.objogate.wl.swing.driver;
import javax.swing.JProgressBar;
import java.awt.Component;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import com.objogate.wl.Prober;
import com.objogate.wl.swing.ComponentSelector;
import com.objogate.wl.swing.gesture.GesturePerformer;
public class JProgressBarDriver extends JComponentDriver<JProgressBar> {
public JProgressBarDriver(GesturePerformer gesturePerformer, ComponentSelector<JProgressBar> jProgressBarComponentSelector, Prober prober) {
super(gesturePerformer, jProgressBarComponentSelector, prober);
}
public JProgressBarDriver(ComponentDriver<? extends Component> parentOrOwner, ComponentSelector<JProgressBar> jProgressBarComponentSelector) {
super(parentOrOwner, jProgressBarComponentSelector);
}
public JProgressBarDriver(ComponentDriver<? extends Component> parentOrOwner, Class<JProgressBar> componentType, Matcher<? super JProgressBar>... matchers) {
super(parentOrOwner, componentType, matchers);
}
public void hasMinimum(final Matcher<Integer> matcher) {
is(new TypeSafeMatcher<JProgressBar>() {
@Override
public boolean matchesSafely(JProgressBar jProgressBar) {
return matcher.matches(jProgressBar.getMinimum());
}
public void describeTo(Description description) {
description.appendText("minimumvalue matches");
description.appendDescriptionOf(matcher);
}
});
}
public void hasMaximum(final Matcher<Integer> matcher) {
is(new TypeSafeMatcher<JProgressBar>() {
@Override
public boolean matchesSafely(JProgressBar jProgressBar) {
return matcher.matches(jProgressBar.getMaximum());
}
public void describeTo(Description description) {
description.appendText("maximumvalue matches");
description.appendDescriptionOf(matcher);
}
});
}
public void hasValue(final Matcher<Integer> matcher) {
is(new TypeSafeMatcher<JProgressBar>() {
@Override
public boolean matchesSafely(JProgressBar jProgressBar) {
return matcher.matches(jProgressBar.getValue());
}
public void describeTo(Description description) {
description.appendText("value matches");
description.appendDescriptionOf(matcher);
}
});
}
public void hasString(final Matcher<String> matcher) {
is(new TypeSafeMatcher<JProgressBar>() {
@Override
public boolean matchesSafely(JProgressBar jProgressBar) {
return matcher.matches(jProgressBar.getString());
}
public void describeTo(Description description) {
description.appendText("string matches");
description.appendDescriptionOf(matcher);
}
});
}
public void hasPercentComplete(final Matcher<Double> matcher) {
is(new TypeSafeMatcher<JProgressBar>() {
@Override
public boolean matchesSafely(JProgressBar jProgressBar) {
return matcher.matches(jProgressBar.getPercentComplete());
}
public void describeTo(Description description) {
description.appendText("percentage matches");
description.appendDescriptionOf(matcher);
}
});
}
}
| alienisty/windowlicker | src/swing/main/com/objogate/wl/swing/driver/JProgressBarDriver.java | Java | gpl-3.0 | 3,570 |
# Bundler and rubygems maintain a set of directories from which to
# load gems. If Bundler is loaded, let it determine what can be
# loaded. If it's not loaded, then use rubygems. But do this before
# loading any puppet code, so that our gem loading system is sane.
if not defined? ::Bundler
begin
require 'rubygems'
rescue LoadError
end
end
require 'puppet'
require 'puppet/util'
require "puppet/util/plugins"
require "puppet/util/rubygems"
require "puppet/util/limits"
require 'puppet/util/colors'
module Puppet
module Util
# This is the main entry point for all puppet applications / faces; it
# is basically where the bootstrapping process / lifecycle of an app
# begins.
class CommandLine
include Puppet::Util::Limits
OPTION_OR_MANIFEST_FILE = /^-|\.pp$|\.rb$/
# @param zero [String] the name of the executable
# @param argv [Array<String>] the arguments passed on the command line
# @param stdin [IO] (unused)
def initialize(zero = $0, argv = ARGV, stdin = STDIN)
@command = File.basename(zero, '.rb')
@argv = argv
Puppet::Plugins.on_commandline_initialization(:command_line_object => self)
end
# @return [String] name of the subcommand is being executed
# @api public
def subcommand_name
return @command if @command != 'puppet'
if @argv.first =~ OPTION_OR_MANIFEST_FILE
nil
else
@argv.first
end
end
# @return [Array<String>] the command line arguments being passed to the subcommand
# @api public
def args
return @argv if @command != 'puppet'
if subcommand_name.nil?
@argv
else
@argv[1..-1]
end
end
# @api private
# @deprecated
def self.available_subcommands
Puppet.deprecation_warning('Puppet::Util::CommandLine.available_subcommands is deprecated; please use Puppet::Application.available_application_names instead.')
Puppet::Application.available_application_names
end
# available_subcommands was previously an instance method, not a class
# method, and we have an unknown number of user-implemented applications
# that depend on that behaviour. Forwarding allows us to preserve a
# backward compatible API. --daniel 2011-04-11
# @api private
# @deprecated
def available_subcommands
Puppet.deprecation_warning('Puppet::Util::CommandLine#available_subcommands is deprecated; please use Puppet::Application.available_application_names instead.')
Puppet::Application.available_application_names
end
# Run the puppet subcommand. If the subcommand is determined to be an
# external executable, this method will never return and the current
# process will be replaced via {Kernel#exec}.
#
# @return [void]
def execute
Puppet::Util.exit_on_fail("initialize global default settings") do
Puppet.initialize_settings(args)
end
setpriority(Puppet[:priority])
find_subcommand.run
end
# @api private
def external_subcommand
Puppet::Util.which("puppet-#{subcommand_name}")
end
private
def find_subcommand
if subcommand_name.nil?
NilSubcommand.new(self)
elsif Puppet::Application.available_application_names.include?(subcommand_name)
ApplicationSubcommand.new(subcommand_name, self)
elsif path_to_subcommand = external_subcommand
ExternalSubcommand.new(path_to_subcommand, self)
else
UnknownSubcommand.new(subcommand_name, self)
end
end
# @api private
class ApplicationSubcommand
def initialize(subcommand_name, command_line)
@subcommand_name = subcommand_name
@command_line = command_line
end
def run
# For most applications, we want to be able to load code from the modulepath,
# such as apply, describe, resource, and faces.
# For agent, we only want to load pluginsync'ed code from libdir.
# For master, we shouldn't ever be loading per-enviroment code into the master's
# ruby process, but that requires fixing (#17210, #12173, #8750). So for now
# we try to restrict to only code that can be autoloaded from the node's
# environment.
# PUP-2114 - at this point in the bootstrapping process we do not
# have an appropriate application-wide current_environment set.
# If we cannot find the configured environment, which may not exist,
# we do not attempt to add plugin directories to the load path.
#
if @subcommand_name != 'master' and @subcommand_name != 'agent'
if configured_environment = Puppet.lookup(:environments).get(Puppet[:environment])
configured_environment.each_plugin_directory do |dir|
$LOAD_PATH << dir unless $LOAD_PATH.include?(dir)
end
end
end
app = Puppet::Application.find(@subcommand_name).new(@command_line)
Puppet::Plugins.on_application_initialization(:application_object => @command_line)
app.run
end
end
# @api private
class ExternalSubcommand
def initialize(path_to_subcommand, command_line)
@path_to_subcommand = path_to_subcommand
@command_line = command_line
end
def run
Kernel.exec(@path_to_subcommand, *@command_line.args)
end
end
# @api private
class NilSubcommand
include Puppet::Util::Colors
def initialize(command_line)
@command_line = command_line
end
def run
args = @command_line.args
if args.include? "--version" or args.include? "-V"
puts Puppet.version
elsif @command_line.subcommand_name.nil? && args.count > 0
# If the subcommand is truly nil and there is an arg, it's an option; print out the invalid option message
puts colorize(:hred, "Error: Could not parse application options: invalid option: #{args[0]}")
exit 1
else
puts "See 'puppet help' for help on available puppet subcommands"
end
end
end
# @api private
class UnknownSubcommand < NilSubcommand
def initialize(subcommand_name, command_line)
@subcommand_name = subcommand_name
super(command_line)
end
def run
puts colorize(:hred, "Error: Unknown Puppet subcommand '#{@subcommand_name}'")
super
exit 1
end
end
end
end
end
| dylanratcliffe/puppet-retrospec | vendor/gems/puppet-3.7.3/lib/puppet/util/command_line.rb | Ruby | agpl-3.0 | 6,784 |
/*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library 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: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package org.ow2.proactive.scheduler.rest.ds;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
import org.ow2.proactive.scheduler.rest.ds.IDataSpaceClient.Dataspace;
import org.ow2.proactive.scheduler.rest.ds.IDataSpaceClient.IRemoteSource;
import org.ow2.proactive_grid_cloud_portal.common.FileType;
import com.google.common.collect.Lists;
public class RemoteSource implements IRemoteSource {
private Dataspace dataspace;
private String path;
private List<String> includes;
private List<String> excludes;
private FileType pathType = FileType.UNKNOWN;
public RemoteSource() {
}
public RemoteSource(Dataspace dataspace) {
this.dataspace = dataspace;
}
public RemoteSource(Dataspace dataspace, String pathname) {
this.dataspace = dataspace;
this.path = pathname;
}
@Override
public Dataspace getDataspace() {
return dataspace;
}
public void setPath(String path) {
this.path = path;
}
@Override
public String getPath() {
return path;
}
public void setIncludes(List<String> includes) {
checkNotNull(includes);
this.includes = Lists.newArrayList(includes);
}
public void setIncludes(String... includes) {
checkNotNull(includes);
this.includes = Lists.newArrayList(includes);
}
@Override
public List<String> getIncludes() {
return includes;
}
public void setExcludes(List<String> excludes) {
checkNotNull(excludes);
this.excludes = Lists.newArrayList(excludes);
}
public void setExcludes(String... excludes) {
checkNotNull(excludes);
this.excludes = Lists.newArrayList(excludes);
}
@Override
public List<String> getExcludes() {
return excludes;
}
public FileType getType() {
return pathType;
}
public void setType(FileType pathType) {
this.pathType = pathType;
}
@Override
public String toString() {
return "RemoteSource{" + "dataspace=" + dataspace + ", path='" + path + '\'' + ", includes=" + includes +
", excludes=" + excludes + ", pathType=" + pathType + '}';
}
}
| tobwiens/scheduling | rest/rest-client/src/main/java/org/ow2/proactive/scheduler/rest/ds/RemoteSource.java | Java | agpl-3.0 | 3,278 |
class Timezones < ActiveRecord::Migration
def self.up
add_column :users, :timezone, :string, :default => 'UTC'
end
def self.down
remove_column :users, :timezone
end
end
| mconftec/mconf-web-mytruecloud | db/migrate/20090608143621_timezones.rb | Ruby | agpl-3.0 | 186 |
/**
* 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.component.wordpress.api.service;
import org.apache.camel.component.wordpress.api.model.Tag;
import org.apache.camel.component.wordpress.api.model.TagSearchCriteria;
public interface WordpressServiceTags extends WordpressCrudService<Tag, TagSearchCriteria> {
}
| curso007/camel | components/camel-wordpress/src/main/java/org/apache/camel/component/wordpress/api/service/WordpressServiceTags.java | Java | apache-2.0 | 1,091 |
namespace Messages
{
public enum ErrorCodes
{
None,
Fail
}
}
| eclaus/docs.particular.net | samples/web/asp-web-application/Version_6/Shared/ErrorCodes.cs | C# | apache-2.0 | 89 |
// @allowJs: true
// @noEmit: true
// @checkJs: true
// @Filename: bug27341.js
if (false) {
/**
* @param {string} s
*/
const x = function (s) {
};
}
| weswigham/TypeScript | tests/cases/conformance/jsdoc/jsdocBindingInUnreachableCode.ts | TypeScript | apache-2.0 | 171 |
package org.bouncycastle.crypto.tls;
/**
* RFC 4492 5.1.1
* <p>
* The named curves defined here are those specified in SEC 2 [13]. Note that many of these curves
* are also recommended in ANSI X9.62 [7] and FIPS 186-2 [11]. Values 0xFE00 through 0xFEFF are
* reserved for private use. Values 0xFF01 and 0xFF02 indicate that the client supports arbitrary
* prime and characteristic-2 curves, respectively (the curve parameters must be encoded explicitly
* in ECParameters).
*/
public class NamedCurve
{
public static final int sect163k1 = 1;
public static final int sect163r1 = 2;
public static final int sect163r2 = 3;
public static final int sect193r1 = 4;
public static final int sect193r2 = 5;
public static final int sect233k1 = 6;
public static final int sect233r1 = 7;
public static final int sect239k1 = 8;
public static final int sect283k1 = 9;
public static final int sect283r1 = 10;
public static final int sect409k1 = 11;
public static final int sect409r1 = 12;
public static final int sect571k1 = 13;
public static final int sect571r1 = 14;
public static final int secp160k1 = 15;
public static final int secp160r1 = 16;
public static final int secp160r2 = 17;
public static final int secp192k1 = 18;
public static final int secp192r1 = 19;
public static final int secp224k1 = 20;
public static final int secp224r1 = 21;
public static final int secp256k1 = 22;
public static final int secp256r1 = 23;
public static final int secp384r1 = 24;
public static final int secp521r1 = 25;
/*
* RFC 7027
*/
public static final int brainpoolP256r1 = 26;
public static final int brainpoolP384r1 = 27;
public static final int brainpoolP512r1 = 28;
/*
* reserved (0xFE00..0xFEFF)
*/
public static final int arbitrary_explicit_prime_curves = 0xFF01;
public static final int arbitrary_explicit_char2_curves = 0xFF02;
public static boolean isValid(int namedCurve)
{
return (namedCurve >= sect163k1 && namedCurve <= brainpoolP512r1)
|| (namedCurve >= arbitrary_explicit_prime_curves && namedCurve <= arbitrary_explicit_char2_curves);
}
public static boolean refersToASpecificNamedCurve(int namedCurve)
{
switch (namedCurve)
{
case arbitrary_explicit_prime_curves:
case arbitrary_explicit_char2_curves:
return false;
default:
return true;
}
}
}
| thedrummeraki/Aki-SSL | src/org/bouncycastle/crypto/tls/NamedCurve.java | Java | apache-2.0 | 2,521 |
/*
* #%L
* ACS AEM Commons Twitter Support Bundle
* %%
* Copyright (C) 2013 - 2014 Adobe
* %%
* 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.
* #L%
*/
package com.adobe.acs.commons.twitter.impl;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.ConfigurationPolicy;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.adobe.acs.commons.util.RunnableOnMaster;
@Component(immediate = true, metatype = true,
label = "ACS AEM Commons - Twitter Feed Refresh Scheduler",
description = "Schedule job which refreshes Twitter Feed components on a recurring basis",
policy = ConfigurationPolicy.REQUIRE)
@Service
@Properties(value = {
@Property(name = "scheduler.expression", value = "0 0/15 * * * ?", label = "Refresh Interval",
description = "Twitter Feed Refresh interval (Quartz Cron Expression)"),
@Property(name = "scheduler.concurrent", boolValue = false, propertyPrivate = true) })
public final class TwitterFeedScheduler extends RunnableOnMaster {
private static final Logger log = LoggerFactory.getLogger(TwitterFeedScheduler.class);
@Reference
private ResourceResolverFactory resourceResolverFactory;
@Reference
private TwitterFeedUpdater twitterFeedService;
@Override
public void runOnMaster() {
ResourceResolver resourceResolver = null;
try {
log.debug("Master Instance, Running ACS AEM Commons Twitter Feed Scheduler");
resourceResolver = resourceResolverFactory
.getAdministrativeResourceResolver(null);
twitterFeedService.updateTwitterFeedComponents(resourceResolver);
} catch (Exception e) {
log.error(
"Exception while running TwitterFeedScheduler.", e);
} finally {
if (resourceResolver != null) {
resourceResolver.close();
resourceResolver = null;
}
}
}
}
| steffenrosi/acs-aem-commons | bundle-twitter/src/main/java/com/adobe/acs/commons/twitter/impl/TwitterFeedScheduler.java | Java | apache-2.0 | 2,833 |
/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.api.client.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use this annotation to specify that an enum constant is the "null" data value to use for
* {@link Data#nullOf(Class)}.
* <p>
* See {@link Value} for an example.
* </p>
*
* @since 1.4
* @author Yaniv Inbar
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NullValue {
}
| wgpshashank/google-http-java-client | google-http-client/src/main/java/com/google/api/client/util/NullValue.java | Java | apache-2.0 | 1,108 |
import { InputNode } from '../core/InputNode';
export class PropertyNode extends InputNode {
constructor( object: object, property: string, type: string );
object: object;
property: string;
nodeType: string;
value: any;
}
| sinorise/sinorise.github.io | three/jsm/nodes/inputs/PropertyNode.d.ts | TypeScript | apache-2.0 | 231 |
// Copyright (C) 2015 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using GoogleMobileAds.Api;
namespace GoogleMobileAds.Common
{
internal interface IRewardBasedVideoAdClient
{
// Ad event fired when the reward based video ad has been received.
event EventHandler<EventArgs> OnAdLoaded;
// Ad event fired when the reward based video ad has failed to load.
event EventHandler<AdFailedToLoadEventArgs> OnAdFailedToLoad;
// Ad event fired when the reward based video ad is opened.
event EventHandler<EventArgs> OnAdOpening;
// Ad event fired when the reward based video ad has started playing.
event EventHandler<EventArgs> OnAdStarted;
// Ad event fired when the reward based video ad has rewarded the user.
event EventHandler<Reward> OnAdRewarded;
// Ad event fired when the reward based video ad is closed.
event EventHandler<EventArgs> OnAdClosed;
// Ad event fired when the reward based video ad is leaving the application.
event EventHandler<EventArgs> OnAdLeavingApplication;
// Creates a reward based video ad and adds it to the view hierarchy.
void CreateRewardBasedVideoAd();
// Requests a new ad for the reward based video ad.
void LoadAd(AdRequest request, string adUnitId);
// Determines whether the reward based video has loaded.
bool IsLoaded();
// Shows the reward based video ad on the screen.
void ShowRewardBasedVideoAd();
}
}
| andrewlord1990/unity-advert-bridge | src/AdvertBridge/Assets/GoogleMobileAds/Common/IRewardBasedVideoAdClient.cs | C# | apache-2.0 | 2,078 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/reference_util.h"
#include <array>
#include <utility>
#include "absl/container/flat_hash_set.h"
#include "absl/memory/memory.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/hlo_evaluator.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/shape_inference.h"
#include "tensorflow/compiler/xla/window_util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/math/math_util.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
/* static */ std::unique_ptr<Array2D<double>> ReferenceUtil::Array2DF32ToF64(
const Array2D<float>& input) {
auto result =
absl::make_unique<Array2D<double>>(input.height(), input.width());
for (int64 rowno = 0; rowno < input.height(); ++rowno) {
for (int64 colno = 0; colno < input.height(); ++colno) {
(*result)(rowno, colno) = input(rowno, colno);
}
}
return result;
}
/* static */ std::unique_ptr<Array3D<float>> ReferenceUtil::ConvArray3D(
const Array3D<float>& lhs, const Array3D<float>& rhs, int64 kernel_stride,
Padding padding) {
return ConvArray3DGeneralDimensionsDilated(
lhs, rhs, kernel_stride, padding, 1, 1,
XlaBuilder::CreateDefaultConvDimensionNumbers(1));
}
/*static*/ std::unique_ptr<Array3D<float>>
ReferenceUtil::ConvArray3DGeneralDimensionsDilated(
const Array3D<float>& lhs, const Array3D<float>& rhs, int64 kernel_stride,
Padding padding, int64 lhs_dilation, int64 rhs_dilation,
const ConvolutionDimensionNumbers& dnums) {
CHECK_EQ(dnums.input_spatial_dimensions_size(), 1);
CHECK_EQ(dnums.kernel_spatial_dimensions_size(), 1);
CHECK_EQ(dnums.output_spatial_dimensions_size(), 1);
// Reuse the code for Array4D-convolution by extending the 3D input into a 4D
// array by adding a fourth dummy dimension of size 1 without stride, padding
// and dilation.
Array4D<float> a4dlhs(lhs.n1(), lhs.n2(), lhs.n3(), 1);
a4dlhs.Each([&](absl::Span<const int64> indices, float* value_ptr) {
CHECK_EQ(indices[3], 0);
*value_ptr = lhs.operator()(indices[0], indices[1], indices[2]);
});
Array4D<float> a4drhs(rhs.n1(), rhs.n2(), rhs.n3(), 1);
a4drhs.Each([&](absl::Span<const int64> indices, float* value_ptr) {
CHECK_EQ(indices[3], 0);
*value_ptr = rhs.operator()(indices[0], indices[1], indices[2]);
});
// Add a second dummy spatial dimensions.
ConvolutionDimensionNumbers dnums2d = dnums;
dnums2d.add_input_spatial_dimensions(3);
dnums2d.add_kernel_spatial_dimensions(3);
dnums2d.add_output_spatial_dimensions(3);
std::unique_ptr<Array4D<float>> convr4 = ConvArray4DGeneralDimensionsDilated(
a4dlhs, a4drhs, {kernel_stride, 1}, padding, {lhs_dilation, 1},
{rhs_dilation, 1}, dnums2d);
auto convr3 = absl::make_unique<Array3D<float>>(
convr4->planes(), convr4->depth(), convr4->height());
convr4->Each([&](absl::Span<const int64> indices, float* value_ptr) {
CHECK_EQ(indices[3], 0);
convr3->operator()(indices[0], indices[1], indices[2]) = *value_ptr;
});
return convr3;
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::ConvArray4D(
const Array4D<float>& lhs, const Array4D<float>& rhs,
std::pair<int64, int64> kernel_stride, Padding padding) {
return ConvArray4DGeneralDimensions(
lhs, rhs, kernel_stride, padding,
XlaBuilder::CreateDefaultConvDimensionNumbers());
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::SeparableConvArray4D(const Array4D<float>& input,
const Array4D<float>& depthwise_weights,
const Array4D<float>& pointwise_weights,
std::pair<int64, int64> kernel_stride,
Padding padding) {
const int64 depth_multiplier = depthwise_weights.planes();
CHECK_EQ(pointwise_weights.depth(), input.depth() * depth_multiplier);
// Combine the two weights by reducing the depth_multiplier, so that we can
// apply a single convolution on the combined weights.
Array4D<float> weights(pointwise_weights.planes(), input.depth(),
depthwise_weights.height(), depthwise_weights.width());
for (int64 kx = 0; kx < depthwise_weights.width(); ++kx) {
for (int64 ky = 0; ky < depthwise_weights.height(); ++ky) {
for (int64 kz = 0; kz < input.depth(); ++kz) {
for (int64 out = 0; out < pointwise_weights.planes(); ++out) {
float weight = 0.0;
for (int64 depth = 0; depth < depth_multiplier; ++depth) {
weight +=
depthwise_weights(depth, kz, ky, kx) *
pointwise_weights(out, depth + kz * depth_multiplier, 0, 0);
}
weights(out, kz, ky, kx) = weight;
}
}
}
}
return ConvArray4D(input, weights, kernel_stride, padding);
}
/* static */ int64 ReferenceUtil::WindowCount(int64 unpadded_width,
int64 window_len, int64 stride,
Padding padding) {
if (padding == Padding::kValid) {
return window_util::StridedBound(unpadded_width, window_len, stride);
}
return tensorflow::MathUtil::CeilOfRatio(unpadded_width, stride);
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceWindow1DGeneric(
absl::Span<const float> operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
absl::Span<const std::pair<int64, int64>> padding) {
CHECK_EQ(window.size(), 1);
CHECK_EQ(stride.size(), 1);
CHECK_EQ(padding.size(), 1);
int64 padded_width = padding[0].first + operand.size() + padding[0].second;
int64 stride_amount = stride[0];
int64 window_size = window[0];
int64 result_size =
window_util::StridedBound(padded_width, window_size, stride_amount);
int64 pad_low = padding[0].first;
auto result = absl::make_unique<std::vector<float>>(result_size);
// Do a full 1D reduce window.
for (int64 i0 = 0; i0 < result_size; ++i0) {
int64 i0_base = i0 * stride_amount - pad_low;
float val = init;
for (int64 i0_win = 0; i0_win < window_size; ++i0_win) {
if (i0_base + i0_win >= 0 && i0_base + i0_win < operand.size()) {
val = reduce_func(val, operand[i0_base + i0_win]);
}
}
(*result)[i0] = val;
}
return result;
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceWindow1DAdd(absl::Span<const float> operand, float init,
absl::Span<const int64> window,
absl::Span<const int64> stride,
Padding padding) {
const auto add_reduce = [](float arg1, float arg2) { return arg1 + arg2; };
std::vector<int64> dim_lengths{static_cast<int64>(operand.size())};
return ReduceWindow1DGeneric(
operand, init, add_reduce, window, stride,
xla::MakePadding(dim_lengths, window, stride, padding));
}
/* static */ std::unique_ptr<Array3D<float>> ReferenceUtil::ReduceWindow3DAdd(
const Array3D<float>& operand, float init, absl::Span<const int64> window,
absl::Span<const int64> stride, Padding padding) {
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3()};
auto padding_both = xla::MakePadding(dim_lengths, window, stride, padding);
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
window_counts[i] =
WindowCount(dim_lengths[i], window[i], stride[i], padding);
pad_low[i] = padding_both[i].first;
}
auto result = absl::make_unique<Array3D<float>>(
window_counts[0], window_counts[1], window_counts[2]);
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
for (int64 i2 = 0; i2 < window_counts[2]; ++i2) {
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
int64 i2_base = i2 * stride[2] - pad_low[2];
float val = init;
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
for (int64 i2_win = 0; i2_win < window[2]; ++i2_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i2_base + i2_win >= 0 && i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2() &&
i2_base + i2_win < operand.n3()) {
val += operand(i0_base + i0_win, i1_base + i1_win,
i2_base + i2_win);
}
}
}
}
(*result)(i0, i1, i2) = val;
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ReduceWindow4DGeneric(
const Array4D<float>& operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
Padding padding) {
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3(),
operand.n4()};
return ReduceWindow4DGeneric(
operand, init, reduce_func, window, stride,
xla::MakePadding(dim_lengths, window, stride, padding));
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ReduceWindow4DGeneric(
const Array4D<float>& operand, float init,
const std::function<float(float, float)>& reduce_func,
absl::Span<const int64> window, absl::Span<const int64> stride,
absl::Span<const std::pair<int64, int64>> padding) {
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3(),
operand.n4()};
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
int64 padded_width = padding[i].first + dim_lengths[i] + padding[i].second;
window_counts[i] =
window_util::StridedBound(padded_width, window[i], stride[i]);
pad_low[i] = padding[i].first;
}
auto result = absl::make_unique<Array4D<float>>(
window_counts[0], window_counts[1], window_counts[2], window_counts[3]);
// Do a full 4D reduce window.
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
for (int64 i2 = 0; i2 < window_counts[2]; ++i2) {
for (int64 i3 = 0; i3 < window_counts[3]; ++i3) {
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
int64 i2_base = i2 * stride[2] - pad_low[2];
int64 i3_base = i3 * stride[3] - pad_low[3];
float val = init;
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
for (int64 i2_win = 0; i2_win < window[2]; ++i2_win) {
for (int64 i3_win = 0; i3_win < window[3]; ++i3_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i2_base + i2_win >= 0 && i3_base + i3_win >= 0 &&
i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2() &&
i2_base + i2_win < operand.n3() &&
i3_base + i3_win < operand.n4()) {
val = reduce_func(
val, operand(i0_base + i0_win, i1_base + i1_win,
i2_base + i2_win, i3_base + i3_win));
}
}
}
}
}
(*result)(i0, i1, i2, i3) = val;
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::ReduceWindow4DAdd(
const Array4D<float>& operand, float init, absl::Span<const int64> window,
absl::Span<const int64> stride, Padding padding) {
const auto add_reduce = [](float arg1, float arg2) { return arg1 + arg2; };
return ReduceWindow4DGeneric(operand, init, add_reduce, window, stride,
padding);
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::BatchNorm4D(
const Array4D<float>& input, const Array4D<float>& mean,
const Array4D<float>& var, const Array4D<float>& scale,
const Array4D<float>& offset, float epsilon) {
auto normalized =
*MapArray4D(input, mean, [](float a, float b) { return a - b; });
normalized = *MapArray4D(normalized, var, [&](float a, float b) {
return a / std::sqrt(b + epsilon);
});
normalized =
*MapArray4D(normalized, scale, [](float a, float b) { return a * b; });
return MapArray4D(normalized, offset, [](float a, float b) { return a + b; });
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::SelectAndScatter4DGePlus(const Array4D<float>& operand,
const Array4D<float>& source,
float init,
absl::Span<const int64> window,
absl::Span<const int64> stride,
bool same_padding) {
Padding padding = same_padding ? Padding::kSame : Padding::kValid;
auto result = absl::make_unique<Array4D<float>>(operand.n1(), operand.n2(),
operand.n3(), operand.n4());
std::vector<int64> dim_lengths{operand.n1(), operand.n2(), operand.n3(),
operand.n4()};
auto padding_both = xla::MakePadding(dim_lengths, window, stride, padding);
// Fill the output, with the initial value.
result->Fill(init);
std::vector<int64> window_counts(window.size(), 0);
std::vector<int64> pad_low(window.size(), 0);
for (int64 i = 0; i < window.size(); ++i) {
window_counts[i] =
WindowCount(dim_lengths[i], window[i], stride[i], padding);
pad_low[i] = padding_both[i].first;
}
CHECK_EQ(window_counts[0], source.n1());
CHECK_EQ(window_counts[1], source.n2());
CHECK_EQ(window_counts[2], source.n3());
CHECK_EQ(window_counts[3], source.n4());
// Do a full 4D select and Scatter.
for (int64 i0 = 0; i0 < window_counts[0]; ++i0) {
for (int64 i1 = 0; i1 < window_counts[1]; ++i1) {
for (int64 i2 = 0; i2 < window_counts[2]; ++i2) {
for (int64 i3 = 0; i3 < window_counts[3]; ++i3) {
// Now we are inside a window and need to find the max and the argmax.
int64 i0_base = i0 * stride[0] - pad_low[0];
int64 i1_base = i1 * stride[1] - pad_low[1];
int64 i2_base = i2 * stride[2] - pad_low[2];
int64 i3_base = i3 * stride[3] - pad_low[3];
int64 scatter_0 = (i0_base >= 0) ? i0_base : 0;
int64 scatter_1 = (i1_base >= 0) ? i1_base : 0;
int64 scatter_2 = (i2_base >= 0) ? i2_base : 0;
int64 scatter_3 = (i3_base >= 0) ? i3_base : 0;
float val = operand(scatter_0, scatter_1, scatter_2, scatter_3);
for (int64 i0_win = 0; i0_win < window[0]; ++i0_win) {
for (int64 i1_win = 0; i1_win < window[1]; ++i1_win) {
for (int64 i2_win = 0; i2_win < window[2]; ++i2_win) {
for (int64 i3_win = 0; i3_win < window[3]; ++i3_win) {
if (i0_base + i0_win >= 0 && i1_base + i1_win >= 0 &&
i2_base + i2_win >= 0 && i3_base + i3_win >= 0 &&
i0_base + i0_win < operand.n1() &&
i1_base + i1_win < operand.n2() &&
i2_base + i2_win < operand.n3() &&
i3_base + i3_win < operand.n4()) {
float tmp = operand(i0_base + i0_win, i1_base + i1_win,
i2_base + i2_win, i3_base + i3_win);
if (tmp > val) {
val = tmp;
scatter_0 = i0_base + i0_win;
scatter_1 = i1_base + i1_win;
scatter_2 = i2_base + i2_win;
scatter_3 = i3_base + i3_win;
}
}
}
}
}
}
(*result)(scatter_0, scatter_1, scatter_2, scatter_3) +=
source(i0, i1, i2, i3);
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ConvArray4DGeneralDimensions(
const Array4D<float>& lhs, const Array4D<float>& rhs,
std::pair<int64, int64> kernel_stride, Padding padding,
ConvolutionDimensionNumbers dimension_numbers) {
return ConvArray4DGeneralDimensionsDilated(lhs, rhs, kernel_stride, padding,
{1, 1}, {1, 1},
std::move(dimension_numbers));
}
/* static */ std::unique_ptr<Array4D<float>>
ReferenceUtil::ConvArray4DGeneralDimensionsDilated(
const Array4D<float>& lhs, const Array4D<float>& rhs,
std::pair<int64, int64> kernel_stride, Padding padding,
std::pair<int64, int64> lhs_dilation, std::pair<int64, int64> rhs_dilation,
ConvolutionDimensionNumbers dnums) {
HloComputation::Builder b("ConvArray4DGeneralDimensionDilated");
auto lhs_literal = LiteralUtil::CreateR4FromArray4D<float>(lhs);
auto rhs_literal = LiteralUtil::CreateR4FromArray4D<float>(rhs);
std::array<int64, 2> ordered_kernel_strides;
std::array<int64, 2> ordered_input_dimensions;
std::array<int64, 2> ordered_kernel_dimensions;
if (dnums.kernel_spatial_dimensions(0) > dnums.kernel_spatial_dimensions(1)) {
ordered_kernel_strides[0] = kernel_stride.second;
ordered_kernel_strides[1] = kernel_stride.first;
} else {
ordered_kernel_strides[0] = kernel_stride.first;
ordered_kernel_strides[1] = kernel_stride.second;
}
ordered_input_dimensions[0] =
lhs_literal.shape().dimensions(dnums.input_spatial_dimensions(0));
ordered_input_dimensions[1] =
lhs_literal.shape().dimensions(dnums.input_spatial_dimensions(1));
ordered_kernel_dimensions[0] =
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(0));
ordered_kernel_dimensions[1] =
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(1));
std::vector<std::pair<int64, int64>> paddings =
MakePadding(ordered_input_dimensions, ordered_kernel_dimensions,
ordered_kernel_strides, padding);
CHECK_EQ(paddings.size(), 2);
Window window;
WindowDimension dim;
dim.set_size(
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(0)));
dim.set_stride(kernel_stride.first);
dim.set_padding_low(paddings[0].first);
dim.set_padding_high(paddings[0].second);
dim.set_window_dilation(rhs_dilation.first);
dim.set_base_dilation(lhs_dilation.first);
*window.add_dimensions() = dim;
WindowDimension dim2;
dim2.set_size(
rhs_literal.shape().dimensions(dnums.kernel_spatial_dimensions(1)));
dim2.set_stride(kernel_stride.second);
dim2.set_padding_low(paddings[1].first);
dim2.set_padding_high(paddings[1].second);
dim2.set_window_dilation(rhs_dilation.second);
dim2.set_base_dilation(lhs_dilation.second);
*window.add_dimensions() = dim2;
const Shape& shape =
ShapeInference::InferConvolveShape(
lhs_literal.shape(), rhs_literal.shape(),
/*feature_group_count=*/1, /*batch_group_count=*/1, window, dnums)
.ConsumeValueOrDie();
HloInstruction* lhs_instruction =
b.AddInstruction(HloInstruction::CreateConstant(std::move(lhs_literal)));
HloInstruction* rhs_instruction =
b.AddInstruction(HloInstruction::CreateConstant(std::move(rhs_literal)));
PrecisionConfig precision_config;
precision_config.mutable_operand_precision()->Resize(
/*new_size=*/2, PrecisionConfig::DEFAULT);
b.AddInstruction(HloInstruction::CreateConvolve(
shape, lhs_instruction, rhs_instruction, /*feature_group_count=*/1,
/*batch_group_count=*/1, window, dnums, precision_config));
HloModuleConfig config;
HloModule module("ReferenceUtil", config);
auto computation = module.AddEntryComputation(b.Build());
HloEvaluator evaluator;
Literal result_literal =
evaluator.Evaluate(*computation, {}).ConsumeValueOrDie();
CHECK_EQ(result_literal.shape().rank(), 4);
auto result =
absl::make_unique<Array4D<float>>(result_literal.shape().dimensions(0),
result_literal.shape().dimensions(1),
result_literal.shape().dimensions(2),
result_literal.shape().dimensions(3));
result->Each([&](absl::Span<const int64> indices, float* value) {
*value = result_literal.Get<float>(indices);
});
return result;
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceToColArray2D(
const Array2D<float>& matrix, float init,
const std::function<float(float, float)>& reduce_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<std::vector<float>>();
for (int64 i = 0; i < rows; ++i) {
float acc = init;
for (int64 j = 0; j < cols; ++j) {
acc = reduce_function(acc, matrix(i, j));
}
result->push_back(acc);
}
return result;
}
/* static */ std::unique_ptr<std::vector<float>>
ReferenceUtil::ReduceToRowArray2D(
const Array2D<float>& matrix, float init,
const std::function<float(float, float)>& reduce_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<std::vector<float>>();
for (int64 i = 0; i < cols; ++i) {
float acc = init;
for (int64 j = 0; j < rows; ++j) {
acc = reduce_function(acc, matrix(j, i));
}
result->push_back(acc);
}
return result;
}
/*static*/ std::vector<float> ReferenceUtil::Reduce4DTo1D(
const Array4D<float>& array, float init, absl::Span<const int64> dims,
const std::function<float(float, float)>& reduce_function) {
std::vector<float> result;
CHECK_EQ(dims.size(), 3);
const absl::flat_hash_set<int64> dim_set(dims.begin(), dims.end());
CHECK_EQ(dim_set.size(), 3);
for (int64 a0 = 0; a0 == 0 || (!dim_set.contains(0) && a0 < array.n1());
++a0) {
for (int64 a1 = 0; a1 == 0 || (!dim_set.contains(1) && a1 < array.n2());
++a1) {
for (int64 a2 = 0; a2 == 0 || (!dim_set.contains(2) && a2 < array.n3());
++a2) {
for (int64 a3 = 0; a3 == 0 || (!dim_set.contains(3) && a3 < array.n4());
++a3) {
float accumulator = init;
for (int64 i0 = 0;
i0 == 0 || (dim_set.contains(0) && i0 < array.n1()); ++i0) {
for (int64 i1 = 0;
i1 == 0 || (dim_set.contains(1) && i1 < array.n2()); ++i1) {
for (int64 i2 = 0;
i2 == 0 || (dim_set.contains(2) && i2 < array.n3()); ++i2) {
for (int64 i3 = 0;
i3 == 0 || (dim_set.contains(3) && i3 < array.n4());
++i3) {
// Handle zero-sized arrays.
if (array.n1() > 0 && array.n2() > 0 && array.n3() > 0 &&
array.n4() > 0) {
accumulator = reduce_function(
accumulator, array(a0 + i0, a1 + i1, a2 + i2, a3 + i3));
}
}
}
}
}
result.push_back(accumulator);
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array4D<float>> ReferenceUtil::Broadcast1DTo4D(
const std::vector<float>& array, const std::vector<int64>& bounds,
int64 broadcast_from_dim) {
auto result = absl::make_unique<Array4D<float>>(bounds[0], bounds[1],
bounds[2], bounds[3]);
for (int64 i = 0; i < result->n1(); ++i) {
for (int64 j = 0; j < result->n2(); ++j) {
for (int64 k = 0; k < result->n3(); ++k) {
for (int64 l = 0; l < result->n4(); ++l) {
switch (broadcast_from_dim) {
case 0:
(*result)(i, j, k, l) = array[i];
break;
case 1:
(*result)(i, j, k, l) = array[j];
break;
case 2:
(*result)(i, j, k, l) = array[k];
break;
case 3:
(*result)(i, j, k, l) = array[l];
break;
default:
break;
}
}
}
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::Reduce3DTo2D(
const Array3D<float>& array, float init, absl::Span<const int64> dims,
const std::function<float(float, float)>& reduce_function) {
CHECK_EQ(dims.size(), 1);
int64 rows = dims[0] == 0 ? array.n2() : array.n1();
int64 cols = dims[0] == 2 ? array.n2() : array.n3();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
result->Fill(init);
for (int i0 = 0; i0 < array.n1(); ++i0) {
for (int i1 = 0; i1 < array.n2(); ++i1) {
for (int i2 = 0; i2 < array.n3(); ++i2) {
int64 row = dims[0] == 0 ? i1 : i0;
int64 col = dims[0] == 2 ? i1 : i2;
(*result)(row, col) =
reduce_function((*result)(row, col), array(i0, i1, i2));
}
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MapArray2D(
const Array2D<float>& matrix,
const std::function<float(float)>& map_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
for (int64 i = 0; i < rows; ++i) {
for (int64 j = 0; j < cols; ++j) {
(*result)(i, j) = map_function(matrix(i, j));
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MapArray2D(
const Array2D<float>& lhs, const Array2D<float>& rhs,
const std::function<float(float, float)>& map_function) {
CHECK_EQ(lhs.height(), rhs.height());
CHECK_EQ(lhs.width(), rhs.width());
int64 rows = lhs.height();
int64 cols = rhs.width();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
for (int64 i = 0; i < rows; ++i) {
for (int64 j = 0; j < cols; ++j) {
(*result)(i, j) = map_function(lhs(i, j), rhs(i, j));
}
}
return result;
}
/* static */ std::unique_ptr<Array2D<float>> ReferenceUtil::MapWithIndexArray2D(
const Array2D<float>& matrix,
const std::function<float(float, int64, int64)>& map_function) {
int64 rows = matrix.height();
int64 cols = matrix.width();
auto result = absl::make_unique<Array2D<float>>(rows, cols);
for (int64 i = 0; i < rows; ++i) {
for (int64 j = 0; j < cols; ++j) {
(*result)(i, j) = map_function(matrix(i, j), i, j);
}
}
return result;
}
} // namespace xla
| karllessard/tensorflow | tensorflow/compiler/xla/reference_util.cc | C++ | apache-2.0 | 27,741 |
<?php
final class DiffusionSubversionCommandEngine
extends DiffusionCommandEngine {
protected function canBuildForRepository(
PhabricatorRepository $repository) {
return $repository->isSVN();
}
protected function newFormattedCommand($pattern, array $argv) {
$flags = array();
$args = array();
$flags[] = '--non-interactive';
if ($this->isAnyHTTPProtocol() || $this->isSVNProtocol()) {
$flags[] = '--no-auth-cache';
if ($this->isAnyHTTPProtocol()) {
$flags[] = '--trust-server-cert';
}
$credential_phid = $this->getCredentialPHID();
if ($credential_phid) {
$key = PassphrasePasswordKey::loadFromPHID(
$credential_phid,
PhabricatorUser::getOmnipotentUser());
$flags[] = '--username %P';
$args[] = $key->getUsernameEnvelope();
$flags[] = '--password %P';
$args[] = $key->getPasswordEnvelope();
}
}
$flags = implode(' ', $flags);
$pattern = "svn {$flags} {$pattern}";
return array($pattern, array_merge($args, $argv));
}
protected function newCustomEnvironment() {
$env = array();
$env['SVN_SSH'] = $this->getSSHWrapper();
return $env;
}
}
| freebsd/phabricator | src/applications/diffusion/protocol/DiffusionSubversionCommandEngine.php | PHP | apache-2.0 | 1,221 |
// Author: mszal@google.com (Michael Szal)
package com.google.libwebm.mkvmuxer;
import com.google.libwebm.Common;
public class Segment extends Common {
public enum Mode {
None,
kLive,
kFile
};
public static final long kDefaultMaxClusterDuration = 30000000000L;
public Segment() {
nativePointer = newSegment();
}
public long addAudioTrack(int sampleRate, int channels, int number) {
return AddAudioTrack(nativePointer, sampleRate, channels, number);
}
public Chapter addChapter() {
long pointer = AddChapter(nativePointer);
return new Chapter(pointer);
}
public boolean addCuePoint(long timestamp, long track) {
return AddCuePoint(nativePointer, timestamp, track);
}
public boolean addFrame(byte[] frame, long trackNumber, long timestampNs, boolean isKey) {
return AddFrame(nativePointer, frame, frame.length, trackNumber, timestampNs, isKey);
}
public boolean addMetadata(byte[] frame, long trackNumber, long timestampNs, long durationNs) {
return AddMetadata(nativePointer, frame, frame.length, trackNumber, timestampNs, durationNs);
}
public Track addTrack(int number) {
long pointer = AddTrack(nativePointer, number);
return Track.newTrack(pointer);
}
public long addVideoTrack(int width, int height, int number) {
return AddVideoTrack(nativePointer, width, height, number);
}
public boolean chunking() {
return chunking(nativePointer);
}
public long cuesTrack() {
return getCuesTrack(nativePointer);
}
public boolean cuesTrack(long trackNumber) {
return setCuesTrack(nativePointer, trackNumber);
}
public boolean finalizeSegment() {
return Finalize(nativePointer);
}
public void forceNewClusterOnNextFrame() {
ForceNewClusterOnNextFrame(nativePointer);
}
public Cues getCues() {
long pointer = GetCues(nativePointer);
return new Cues(pointer);
}
public SegmentInfo getSegmentInfo() {
long pointer = GetSegmentInfo(nativePointer);
return new SegmentInfo(pointer);
}
public Track getTrackByNumber(long trackNumber) {
long pointer = GetTrackByNumber(nativePointer, trackNumber);
return Track.newTrack(pointer);
}
public boolean init(IMkvWriter writer) {
return Init(nativePointer, writer.getNativePointer());
}
public long maxClusterDuration() {
return maxClusterDuration(nativePointer);
}
public long maxClusterSize() {
return maxClusterSize(nativePointer);
}
public Mode mode() {
int ordinal = mode(nativePointer);
return Mode.values()[ordinal];
}
public boolean outputCues() {
return outputCues(nativePointer);
}
public void outputCues(boolean outputCues) {
OutputCues(nativePointer, outputCues);
}
public SegmentInfo segmentInfo() {
long pointer = segmentInfo(nativePointer);
return new SegmentInfo(pointer);
}
public void setMaxClusterDuration(long maxClusterDuration) {
setMaxClusterDuration(nativePointer, maxClusterDuration);
}
public void setMaxClusterSize(long maxClusterSize) {
setMaxClusterSize(nativePointer, maxClusterSize);
}
public void setMode(Mode mode) {
setMode(nativePointer, mode.ordinal());
}
public boolean setChunking(boolean chunking, String filename) {
return SetChunking(nativePointer, chunking, filename);
}
protected Segment(long nativePointer) {
super(nativePointer);
}
@Override
protected void deleteObject() {
deleteSegment(nativePointer);
}
private static native long AddAudioTrack(long jSegment, int sample_rate, int channels,
int number);
private static native long AddChapter(long jSegment);
private static native boolean AddCuePoint(long jSegment, long timestamp, long track);
private static native boolean AddFrame(long jSegment, byte[] jFrame, long length,
long track_number, long timestamp_ns, boolean is_key);
private static native boolean AddMetadata(long jSegment, byte[] jFrame, long length,
long track_number, long timestamp_ns, long duration_ns);
private static native long AddTrack(long jSegment, int number);
private static native long AddVideoTrack(long jSegment, int width, int height, int number);
private static native boolean chunking(long jSegment);
private static native void deleteSegment(long jSegment);
private static native boolean Finalize(long jSegment);
private static native void ForceNewClusterOnNextFrame(long jSegment);
private static native long GetCues(long jSegment);
private static native long getCuesTrack(long jSegment);
private static native long GetSegmentInfo(long jSegment);
private static native long GetTrackByNumber(long jSegment, long track_number);
private static native boolean Init(long jSegment, long jWriter);
private static native long maxClusterDuration(long jSegment);
private static native long maxClusterSize(long jSegment);
private static native int mode(long jSegment);
private static native long newSegment();
private static native boolean outputCues(long jSegment);
private static native void OutputCues(long jSegment, boolean output_cues);
private static native long segmentInfo(long jSegment);
private static native boolean setCuesTrack(long jSegment, long track_number);
private static native void setMaxClusterDuration(long jSegment, long max_cluster_duration);
private static native void setMaxClusterSize(long jSegment, long max_cluster_size);
private static native void setMode(long jSegment, int mode);
private static native boolean SetChunking(long jSegment, boolean chunking, String jFilename);
}
| wudingli/openfire | src/plugins/jitsivideobridge/src/java/com/google/libwebm/mkvmuxer/Segment.java | Java | apache-2.0 | 5,592 |
class C {
String s = "\u00C1\u00EE";
} | jwren/intellij-community | plugins/java-i18n/testData/quickFix/convertToBasicLatin/StringLiteral_after.java | Java | apache-2.0 | 42 |
// This file is generated automatically by `scripts/build/typings.js`. Please, don't change it.
import { lastDayOfISOWeekYear } from 'date-fns'
export default lastDayOfISOWeekYear
| BigBoss424/portfolio | v8/development/node_modules/date-fns/lastDayOfISOWeekYear/index.d.ts | TypeScript | apache-2.0 | 181 |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for rmsprop optimizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import math
from absl.testing import parameterized
import numpy as np
from tensorflow.contrib.optimizer_v2 import rmsprop
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import embedding_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
_DATA_TYPES = [dtypes.half, dtypes.float32]
_TEST_PARAM_VALUES = [
# learning_rate, decay, momentum, epsilon, centered, use_resource
[0.5, 0.9, 0.0, 1.0, True, False],
[0.5, 0.9, 0.0, 1.0, False, False],
[0.5, 0.9, 0.0, 1.0, True, True],
[0.5, 0.9, 0.0, 1.0, False, True],
[0.1, 0.9, 0.0, 1.0, True, False],
[0.5, 0.95, 0.0, 1.0, False, False],
[0.5, 0.8, 0.0, 1e-3, True, False],
[0.5, 0.8, 0.9, 1e-3, True, False],
]
class RMSPropOptimizerTest(test.TestCase, parameterized.TestCase):
def _rmsprop_update_numpy(self, var, g, mg, rms, mom, lr, decay, momentum,
centered):
rms_t = rms * decay + (1 - decay) * g * g
if centered:
mg_t = mg * decay + (1 - decay) * g
denom_t = rms_t - mg_t * mg_t
else:
mg_t = mg
denom_t = rms_t
mom_t = momentum * mom + lr * g / np.sqrt(denom_t, dtype=denom_t.dtype)
var_t = var - mom_t
return var_t, mg_t, rms_t, mom_t
def _sparse_rmsprop_update_numpy(self, var, gindexs, gvalues, mg, rms, mom,
lr, decay, momentum, centered):
mg_t = copy.deepcopy(mg)
rms_t = copy.deepcopy(rms)
mom_t = copy.deepcopy(mom)
var_t = copy.deepcopy(var)
for i in range(len(gindexs)):
gindex = gindexs[i]
gvalue = gvalues[i]
rms_t[gindex] = rms[gindex] * decay + (1 - decay) * gvalue * gvalue
denom_t = rms_t[gindex]
if centered:
mg_t[gindex] = mg_t[gindex] * decay + (1 - decay) * gvalue
denom_t -= mg_t[gindex] * mg_t[gindex]
mom_t[gindex] = momentum * mom[gindex] + lr * gvalue / np.sqrt(denom_t)
var_t[gindex] = var[gindex] - mom_t[gindex]
return var_t, mg_t, rms_t, mom_t
@parameterized.named_parameters(
*test_util.generate_combinations_with_testcase_name(
dtype=_DATA_TYPES, param_value=_TEST_PARAM_VALUES))
def testDense(self, dtype, param_value):
(learning_rate, decay, momentum, epsilon, centered, use_resource) = tuple(
param_value)
with self.session(use_gpu=True):
# Initialize variables for numpy implementation.
var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)
grads0_np = np.array([0.1, 0.2], dtype=dtype.as_numpy_dtype)
var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)
grads1_np = np.array([0.01, 0.2], dtype=dtype.as_numpy_dtype)
if use_resource:
var0 = resource_variable_ops.ResourceVariable(var0_np)
var1 = resource_variable_ops.ResourceVariable(var1_np)
else:
var0 = variables.Variable(var0_np)
var1 = variables.Variable(var1_np)
grads0 = constant_op.constant(grads0_np)
grads1 = constant_op.constant(grads1_np)
opt = rmsprop.RMSPropOptimizer(
learning_rate=learning_rate,
decay=decay,
momentum=momentum,
epsilon=epsilon,
centered=centered)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
variables.global_variables_initializer().run()
mg0 = opt.get_slot(var0, "mg")
self.assertEqual(mg0 is not None, centered)
mg1 = opt.get_slot(var1, "mg")
self.assertEqual(mg1 is not None, centered)
rms0 = opt.get_slot(var0, "rms")
self.assertIsNotNone(rms0)
rms1 = opt.get_slot(var1, "rms")
self.assertIsNotNone(rms1)
mom0 = opt.get_slot(var0, "momentum")
self.assertIsNotNone(mom0)
mom1 = opt.get_slot(var1, "momentum")
self.assertIsNotNone(mom1)
mg0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mg1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
rms0_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
rms1_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
mom0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mom1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
# Fetch params to validate initial values
self.assertAllClose([1.0, 2.0], var0.eval())
self.assertAllClose([3.0, 4.0], var1.eval())
# Run 4 steps of RMSProp
for _ in range(4):
update.run()
var0_np, mg0_np, rms0_np, mom0_np = self._rmsprop_update_numpy(
var0_np, grads0_np, mg0_np, rms0_np, mom0_np, learning_rate,
decay, momentum, centered)
var1_np, mg1_np, rms1_np, mom1_np = self._rmsprop_update_numpy(
var1_np, grads1_np, mg1_np, rms1_np, mom1_np, learning_rate,
decay, momentum, centered)
# Validate updated params
if centered:
self.assertAllCloseAccordingToType(mg0_np, mg0.eval())
self.assertAllCloseAccordingToType(mg1_np, mg1.eval())
self.assertAllCloseAccordingToType(rms0_np, rms0.eval())
self.assertAllCloseAccordingToType(rms1_np, rms1.eval())
self.assertAllCloseAccordingToType(mom0_np, mom0.eval())
self.assertAllCloseAccordingToType(mom1_np, mom1.eval())
# TODO(b/117393988): Reduce tolerances for float16.
self.assertAllCloseAccordingToType(
var0_np, var0.eval(), half_rtol=3e-3, half_atol=3e-3)
self.assertAllCloseAccordingToType(
var1_np, var1.eval(), half_rtol=3e-3, half_atol=3e-3)
@parameterized.parameters([dtypes.float32, dtypes.float64])
def testMinimizeSparseResourceVariable(self, dtype):
with self.cached_session():
var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
x = constant_op.constant([[4.0], [5.0]], dtype=dtype)
pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x)
loss = pred * pred
sgd_op = rmsprop.RMSPropOptimizer(
learning_rate=1.0,
decay=0.0,
momentum=0.0,
epsilon=0.0,
centered=False).minimize(loss)
variables.global_variables_initializer().run()
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[1.0, 2.0]], var0.eval())
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType(
[[0., 1.]], var0.eval(), atol=0.01)
@parameterized.parameters([dtypes.float32, dtypes.float64])
def testMinimizeSparseResourceVariableCentered(self, dtype):
with self.cached_session():
var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
x = constant_op.constant([[4.0], [5.0]], dtype=dtype)
pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x)
loss = pred * pred
sgd_op = rmsprop.RMSPropOptimizer(
learning_rate=1.0,
decay=0.1,
momentum=0.0,
epsilon=1.0,
centered=True).minimize(loss)
variables.global_variables_initializer().run()
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[1.0, 2.0]], var0.eval())
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType(
[[-7/3.0, -4/3.0]], var0.eval(), atol=0.01)
@parameterized.named_parameters(
*test_util.generate_combinations_with_testcase_name(
dtype=_DATA_TYPES, param_value=_TEST_PARAM_VALUES))
def testSparse(self, dtype, param_value):
(learning_rate, decay, momentum, epsilon, centered, _) = tuple(
param_value)
with self.session(use_gpu=True):
# Initialize variables for numpy implementation.
var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)
grads0_np = np.array([0.1], dtype=dtype.as_numpy_dtype)
var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)
grads1_np = np.array([0.01], dtype=dtype.as_numpy_dtype)
var0 = variables.Variable(var0_np)
var1 = variables.Variable(var1_np)
grads0_np_indices = np.array([0], dtype=np.int32)
grads0 = ops.IndexedSlices(
constant_op.constant(grads0_np),
constant_op.constant(grads0_np_indices), constant_op.constant([1]))
grads1_np_indices = np.array([1], dtype=np.int32)
grads1 = ops.IndexedSlices(
constant_op.constant(grads1_np),
constant_op.constant(grads1_np_indices), constant_op.constant([1]))
opt = rmsprop.RMSPropOptimizer(
learning_rate=learning_rate,
decay=decay,
momentum=momentum,
epsilon=epsilon,
centered=centered)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
variables.global_variables_initializer().run()
mg0 = opt.get_slot(var0, "mg")
self.assertEqual(mg0 is not None, centered)
mg1 = opt.get_slot(var1, "mg")
self.assertEqual(mg1 is not None, centered)
rms0 = opt.get_slot(var0, "rms")
self.assertIsNotNone(rms0)
rms1 = opt.get_slot(var1, "rms")
self.assertIsNotNone(rms1)
mom0 = opt.get_slot(var0, "momentum")
self.assertIsNotNone(mom0)
mom1 = opt.get_slot(var1, "momentum")
self.assertIsNotNone(mom1)
mg0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mg1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
rms0_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
rms1_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
mom0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mom1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
# Fetch params to validate initial values
self.assertAllClose([1.0, 2.0], var0.eval())
self.assertAllClose([3.0, 4.0], var1.eval())
# Run 4 steps of RMSProp
for _ in range(4):
update.run()
var0_np, mg0_np, rms0_np, mom0_np = self._sparse_rmsprop_update_numpy(
var0_np, grads0_np_indices, grads0_np, mg0_np, rms0_np, mom0_np,
learning_rate, decay, momentum, centered)
var1_np, mg1_np, rms1_np, mom1_np = self._sparse_rmsprop_update_numpy(
var1_np, grads1_np_indices, grads1_np, mg1_np, rms1_np, mom1_np,
learning_rate, decay, momentum, centered)
# Validate updated params
if centered:
self.assertAllCloseAccordingToType(mg0_np, mg0.eval())
self.assertAllCloseAccordingToType(mg1_np, mg1.eval())
self.assertAllCloseAccordingToType(rms0_np, rms0.eval())
self.assertAllCloseAccordingToType(rms1_np, rms1.eval())
self.assertAllCloseAccordingToType(mom0_np, mom0.eval())
self.assertAllCloseAccordingToType(mom1_np, mom1.eval())
self.assertAllCloseAccordingToType(var0_np, var0.eval())
self.assertAllCloseAccordingToType(var1_np, var1.eval())
@parameterized.parameters(_DATA_TYPES)
def testWithoutMomentum(self, dtype):
with self.session(use_gpu=True):
var0 = variables.Variable([1.0, 2.0], dtype=dtype)
var1 = variables.Variable([3.0, 4.0], dtype=dtype)
grads0 = constant_op.constant([0.1, 0.1], dtype=dtype)
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
opt = rmsprop.RMSPropOptimizer(
learning_rate=2.0, decay=0.9, momentum=0.0, epsilon=1.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
variables.global_variables_initializer().run()
rms0 = opt.get_slot(var0, "rms")
self.assertIsNotNone(rms0)
rms1 = opt.get_slot(var1, "rms")
self.assertIsNotNone(rms1)
mom0 = opt.get_slot(var0, "momentum")
self.assertIsNotNone(mom0)
mom1 = opt.get_slot(var1, "momentum")
self.assertIsNotNone(mom1)
# Fetch params to validate initial values
self.assertAllClose([1.0, 2.0], var0.eval())
self.assertAllClose([3.0, 4.0], var1.eval())
# Step 1: the rms accumulators where 1. So we should see a normal
# update: v -= grad * learning_rate
update.run()
# Check the root mean square accumulators.
self.assertAllCloseAccordingToType(
np.array([0.901, 0.901]), rms0.eval())
self.assertAllCloseAccordingToType(
np.array([0.90001, 0.90001]), rms1.eval())
# Check the parameters.
self.assertAllCloseAccordingToType(
np.array([
1.0 - (0.1 * 2.0 / math.sqrt(0.901)),
2.0 - (0.1 * 2.0 / math.sqrt(0.901))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
3.0 - (0.01 * 2.0 / math.sqrt(0.90001)),
4.0 - (0.01 * 2.0 / math.sqrt(0.90001))
]), var1.eval())
# Step 2: the root mean square accumulators contain the previous update.
update.run()
# Check the rms accumulators.
self.assertAllCloseAccordingToType(
np.array([0.901 * 0.9 + 0.001, 0.901 * 0.9 + 0.001]), rms0.eval())
self.assertAllCloseAccordingToType(
np.array([0.90001 * 0.9 + 1e-5, 0.90001 * 0.9 + 1e-5]), rms1.eval())
# Check the parameters.
self.assertAllCloseAccordingToType(
np.array([
1.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001)),
2.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
3.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5)),
4.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5))
]), var1.eval())
@parameterized.parameters(_DATA_TYPES)
def testWithMomentum(self, dtype):
with self.session(use_gpu=True):
var0 = variables.Variable([1.0, 2.0], dtype=dtype)
var1 = variables.Variable([3.0, 4.0], dtype=dtype)
grads0 = constant_op.constant([0.1, 0.1], dtype=dtype)
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
opt = rmsprop.RMSPropOptimizer(
learning_rate=2.0, decay=0.9, momentum=0.5, epsilon=1.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
variables.global_variables_initializer().run()
rms0 = opt.get_slot(var0, "rms")
self.assertIsNotNone(rms0)
rms1 = opt.get_slot(var1, "rms")
self.assertIsNotNone(rms1)
mom0 = opt.get_slot(var0, "momentum")
self.assertIsNotNone(mom0)
mom1 = opt.get_slot(var1, "momentum")
self.assertIsNotNone(mom1)
# Fetch params to validate initial values
self.assertAllClose([1.0, 2.0], var0.eval())
self.assertAllClose([3.0, 4.0], var1.eval())
# Step 1: rms = 1, mom = 0. So we should see a normal
# update: v -= grad * learning_rate
update.run()
# Check the root mean square accumulators.
self.assertAllCloseAccordingToType(
np.array([0.901, 0.901]), rms0.eval())
self.assertAllCloseAccordingToType(
np.array([0.90001, 0.90001]), rms1.eval())
# Check the momentum accumulators
self.assertAllCloseAccordingToType(
np.array([(0.1 * 2.0 / math.sqrt(0.901)),
(0.1 * 2.0 / math.sqrt(0.901))]), mom0.eval())
self.assertAllCloseAccordingToType(
np.array([(0.01 * 2.0 / math.sqrt(0.90001)),
(0.01 * 2.0 / math.sqrt(0.90001))]), mom1.eval())
# Check that the parameters.
self.assertAllCloseAccordingToType(
np.array([
1.0 - (0.1 * 2.0 / math.sqrt(0.901)),
2.0 - (0.1 * 2.0 / math.sqrt(0.901))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
3.0 - (0.01 * 2.0 / math.sqrt(0.90001)),
4.0 - (0.01 * 2.0 / math.sqrt(0.90001))
]), var1.eval())
# Step 2: the root mean square accumulators contain the previous update.
update.run()
# Check the rms accumulators.
self.assertAllCloseAccordingToType(
np.array([0.901 * 0.9 + 0.001, 0.901 * 0.9 + 0.001]), rms0.eval())
self.assertAllCloseAccordingToType(
np.array([0.90001 * 0.9 + 1e-5, 0.90001 * 0.9 + 1e-5]), rms1.eval())
self.assertAllCloseAccordingToType(
np.array([
0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001)),
0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001))
]), mom0.eval())
self.assertAllCloseAccordingToType(
np.array([
0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5)),
0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5))
]), mom1.eval())
# Check the parameters.
self.assertAllCloseAccordingToType(
np.array([
1.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
(0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001))),
2.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
(0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001)))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
3.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
(0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5))),
4.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
(0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5)))
]), var1.eval())
if __name__ == "__main__":
test.main()
| hfp/tensorflow-xsmm | tensorflow/contrib/optimizer_v2/rmsprop_test.py | Python | apache-2.0 | 19,033 |
cask 'routebuddy' do
version '4.2.1'
sha256 '95d979d775ebfbd5c835150d50c809fdb8f5e29823b54a13deec73b6df21c643'
# objects-us-west-1.dream.io/routebuddy was verified as official when first introduced to the cask
url "https://objects-us-west-1.dream.io/routebuddy/download/apps2/RouteBuddy_#{version}.dmg"
name 'RouteBuddy'
homepage 'https://routebuddy.com/'
app 'RouteBuddy.app'
end
| mrmachine/homebrew-cask | Casks/routebuddy.rb | Ruby | bsd-2-clause | 397 |
##########################################################################
#
# Copyright (c) 2014, Image Engine Design 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 John Haddon nor the names of
# any other contributors to this software 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.
#
##########################################################################
import Gaffer
import GafferScene
##########################################################################
# Metadata
##########################################################################
Gaffer.Metadata.registerNode(
GafferScene.DeleteOptions,
"description",
"""
A node which removes options from the globals.
""",
plugs = {
"names" : [
"description",
"""
The names of options to be removed. Names should be
separated by spaces and can use Gaffer's standard wildcards.
""",
],
"invertNames" : [
"description",
"""
When on, matching names are kept, and non-matching names are removed.
""",
],
}
)
| lucienfostier/gaffer | python/GafferSceneUI/DeleteOptionsUI.py | Python | bsd-3-clause | 2,461 |
// Generated by delombok at Wed Oct 02 19:12:43 GMT 2019
import java.util.Set;
public class SingularSet<T> {
private Set rawTypes;
private Set<Integer> integers;
private Set<T> generics;
private Set<? extends Number> extendsGenerics;
@java.lang.SuppressWarnings("all")
SingularSet(final Set rawTypes, final Set<Integer> integers, final Set<T> generics, final Set<? extends Number> extendsGenerics) {
this.rawTypes = rawTypes;
this.integers = integers;
this.generics = generics;
this.extendsGenerics = extendsGenerics;
}
@java.lang.SuppressWarnings("all")
public static class SingularSetBuilder<T> {
@java.lang.SuppressWarnings("all")
private java.util.ArrayList<java.lang.Object> rawTypes;
@java.lang.SuppressWarnings("all")
private java.util.ArrayList<Integer> integers;
@java.lang.SuppressWarnings("all")
private java.util.ArrayList<T> generics;
@java.lang.SuppressWarnings("all")
private java.util.ArrayList<Number> extendsGenerics;
@java.lang.SuppressWarnings("all")
SingularSetBuilder() {
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> rawType(final java.lang.Object rawType) {
if (this.rawTypes == null) this.rawTypes = new java.util.ArrayList<java.lang.Object>();
this.rawTypes.add(rawType);
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> rawTypes(final java.util.Collection<?> rawTypes) {
if (this.rawTypes == null) this.rawTypes = new java.util.ArrayList<java.lang.Object>();
this.rawTypes.addAll(rawTypes);
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> clearRawTypes() {
if (this.rawTypes != null) this.rawTypes.clear();
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> integer(final Integer integer) {
if (this.integers == null) this.integers = new java.util.ArrayList<Integer>();
this.integers.add(integer);
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> integers(final java.util.Collection<? extends Integer> integers) {
if (this.integers == null) this.integers = new java.util.ArrayList<Integer>();
this.integers.addAll(integers);
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> clearIntegers() {
if (this.integers != null) this.integers.clear();
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> generic(final T generic) {
if (this.generics == null) this.generics = new java.util.ArrayList<T>();
this.generics.add(generic);
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> generics(final java.util.Collection<? extends T> generics) {
if (this.generics == null) this.generics = new java.util.ArrayList<T>();
this.generics.addAll(generics);
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> clearGenerics() {
if (this.generics != null) this.generics.clear();
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> extendsGeneric(final Number extendsGeneric) {
if (this.extendsGenerics == null) this.extendsGenerics = new java.util.ArrayList<Number>();
this.extendsGenerics.add(extendsGeneric);
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> extendsGenerics(final java.util.Collection<? extends Number> extendsGenerics) {
if (this.extendsGenerics == null) this.extendsGenerics = new java.util.ArrayList<Number>();
this.extendsGenerics.addAll(extendsGenerics);
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSetBuilder<T> clearExtendsGenerics() {
if (this.extendsGenerics != null) this.extendsGenerics.clear();
return this;
}
@java.lang.SuppressWarnings("all")
public SingularSet<T> build() {
java.util.Set<java.lang.Object> rawTypes;
switch (this.rawTypes == null ? 0 : this.rawTypes.size()) {
case 0:
rawTypes = java.util.Collections.emptySet();
break;
case 1:
rawTypes = java.util.Collections.singleton(this.rawTypes.get(0));
break;
default:
rawTypes = new java.util.LinkedHashSet<java.lang.Object>(this.rawTypes.size() < 1073741824 ? 1 + this.rawTypes.size() + (this.rawTypes.size() - 3) / 3 : java.lang.Integer.MAX_VALUE);
rawTypes.addAll(this.rawTypes);
rawTypes = java.util.Collections.unmodifiableSet(rawTypes);
}
java.util.Set<Integer> integers;
switch (this.integers == null ? 0 : this.integers.size()) {
case 0:
integers = java.util.Collections.emptySet();
break;
case 1:
integers = java.util.Collections.singleton(this.integers.get(0));
break;
default:
integers = new java.util.LinkedHashSet<Integer>(this.integers.size() < 1073741824 ? 1 + this.integers.size() + (this.integers.size() - 3) / 3 : java.lang.Integer.MAX_VALUE);
integers.addAll(this.integers);
integers = java.util.Collections.unmodifiableSet(integers);
}
java.util.Set<T> generics;
switch (this.generics == null ? 0 : this.generics.size()) {
case 0:
generics = java.util.Collections.emptySet();
break;
case 1:
generics = java.util.Collections.singleton(this.generics.get(0));
break;
default:
generics = new java.util.LinkedHashSet<T>(this.generics.size() < 1073741824 ? 1 + this.generics.size() + (this.generics.size() - 3) / 3 : java.lang.Integer.MAX_VALUE);
generics.addAll(this.generics);
generics = java.util.Collections.unmodifiableSet(generics);
}
java.util.Set<Number> extendsGenerics;
switch (this.extendsGenerics == null ? 0 : this.extendsGenerics.size()) {
case 0:
extendsGenerics = java.util.Collections.emptySet();
break;
case 1:
extendsGenerics = java.util.Collections.singleton(this.extendsGenerics.get(0));
break;
default:
extendsGenerics = new java.util.LinkedHashSet<Number>(this.extendsGenerics.size() < 1073741824 ? 1 + this.extendsGenerics.size() + (this.extendsGenerics.size() - 3) / 3 : java.lang.Integer.MAX_VALUE);
extendsGenerics.addAll(this.extendsGenerics);
extendsGenerics = java.util.Collections.unmodifiableSet(extendsGenerics);
}
return new SingularSet<T>(rawTypes, integers, generics, extendsGenerics);
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
public java.lang.String toString() {
return "SingularSet.SingularSetBuilder(rawTypes=" + this.rawTypes + ", integers=" + this.integers + ", generics=" + this.generics + ", extendsGenerics=" + this.extendsGenerics + ")";
}
}
@java.lang.SuppressWarnings("all")
public static <T> SingularSetBuilder<T> builder() {
return new SingularSetBuilder<T>();
}
}
| mplushnikov/lombok-intellij-plugin | testData/after/builder/Singular/Generic/Util/Collection/SingularSet.java | Java | bsd-3-clause | 6,721 |
/**
* Usage for accepting signatures:
* $('.sigPad').signaturePad()
*
* Usage for displaying previous signatures:
* $('.sigPad').signaturePad({displayOnly:true}).regenerate(sig)
* or
* var api = $('.sigPad').signaturePad({displayOnly:true})
* api.regenerate(sig)
*/
(function ($) {
function SignaturePad (selector, options) {
/**
* Reference to the object for use in public methods
*
* @private
*
* @type {Object}
*/
var self = this
/**
* Holds the merged default settings and user passed settings
*
* @private
*
* @type {Object}
*/
, settings = $.extend({}, $.fn.signaturePad.defaults, options)
/**
* The current context, as passed by jQuery, of selected items
*
* @private
*
* @type {Object}
*/
, context = $(selector)
/**
* jQuery reference to the canvas element inside the signature pad
*
* @private
*
* @type {Object}
*/
, canvas = $(settings.canvas, context)
/**
* Dom reference to the canvas element inside the signature pad
*
* @private
*
* @type {Object}
*/
, element = canvas.get(0)
/**
* The drawing context for the signature canvas
*
* @private
*
* @type {Object}
*/
, canvasContext = null
/**
* Holds the previous point of drawing
* Disallows drawing over the same location to make lines more delicate
*
* @private
*
* @type {Object}
*/
, previous = {'x': null, 'y': null}
/**
* An array holding all the points and lines to generate the signature
* Each item is an object like:
* {
* mx: moveTo x coordinate
* my: moveTo y coordinate
* lx: lineTo x coordinate
* lx: lineTo y coordinate
* }
*
* @private
*
* @type {Array}
*/
, output = []
/**
* Stores a timeout for when the mouse leaves the canvas
* If the mouse has left the canvas for a specific amount of time
* Stops drawing on the canvas
*
* @private
*
* @type {Object}
*/
, mouseLeaveTimeout = false
/**
* Whether the mouse button is currently pressed down or not
*
* @private
*
* @type {Boolean}
*/
, mouseButtonDown = false
/**
* Whether the browser is a touch event browser or not
*
* @private
*
* @type {Boolean}
*/
, touchable = false
/**
* Whether events have already been bound to the canvas or not
*
* @private
*
* @type {Boolean}
*/
, eventsBound = false
/**
* Remembers the default font-size when typing, and will allow it to be scaled for bigger/smaller names
*
* @private
*
* @type {Number}
*/
, typeItDefaultFontSize = 30
/**
* Remembers the current font-size when typing
*
* @private
*
* @type {Number}
*/
, typeItCurrentFontSize = typeItDefaultFontSize
/**
* Remembers how many characters are in the name field, to help with the scaling feature
*
* @private
*
* @type {Number}
*/
, typeItNumChars = 0
/**
* Clears the mouseLeaveTimeout
* Resets some other variables that may be active
*
* @private
*/
function clearMouseLeaveTimeout () {
clearTimeout(mouseLeaveTimeout)
mouseLeaveTimeout = false
mouseButtonDown = false
}
/**
* Draws a line on canvas using the mouse position
* Checks previous position to not draw over top of previous drawing
* (makes the line really thick and poorly anti-aliased)
*
* @private
*
* @param {Object} e The event object
* @param {Number} newYOffset A pixel value for drawing the newY, used for drawing a single dot on click
*/
function drawLine (e, newYOffset) {
var offset, newX, newY
e.preventDefault()
offset = $(e.target).offset()
clearTimeout(mouseLeaveTimeout)
mouseLeaveTimeout = false
if (typeof e.targetTouches !== 'undefined') {
newX = Math.floor(e.targetTouches[0].pageX - offset.left)
newY = Math.floor(e.targetTouches[0].pageY - offset.top)
} else {
newX = Math.floor(e.pageX - offset.left)
newY = Math.floor(e.pageY - offset.top)
}
if (previous.x === newX && previous.y === newY)
return true
if (previous.x === null)
previous.x = newX
if (previous.y === null)
previous.y = newY
if (newYOffset)
newY += newYOffset
canvasContext.beginPath()
canvasContext.moveTo(previous.x, previous.y)
canvasContext.lineTo(newX, newY)
canvasContext.lineCap = settings.penCap
canvasContext.stroke()
canvasContext.closePath()
output.push({
'lx' : newX
, 'ly' : newY
, 'mx' : previous.x
, 'my' : previous.y
})
previous.x = newX
previous.y = newY
if (settings.onDraw && typeof settings.onDraw === 'function')
settings.onDraw.apply(self)
}
/**
* Callback wrapper for executing stopDrawing without the event
* Put up here so that it can be removed at a later time
*
* @private
*/
function stopDrawingWrapper () {
stopDrawing()
}
/**
* Callback registered to mouse/touch events of the canvas
* Stops the drawing abilities
*
* @private
*
* @param {Object} e The event object
*/
function stopDrawing (e) {
if (!!e) {
drawLine(e, 1)
} else {
if (touchable) {
canvas.each(function () {
this.removeEventListener('touchmove', drawLine)
// this.removeEventListener('MSPointerMove', drawLine)
})
} else {
canvas.unbind('mousemove.signaturepad')
}
if (output.length > 0 && settings.onDrawEnd && typeof settings.onDrawEnd === 'function')
settings.onDrawEnd.apply(self)
}
previous.x = null
previous.y = null
if (settings.output && output.length > 0)
$(settings.output, context).val(JSON.stringify(output))
}
/**
* Draws the signature line
*
* @private
*/
function drawSigLine () {
if (!settings.lineWidth)
return false
canvasContext.beginPath()
canvasContext.lineWidth = settings.lineWidth
canvasContext.strokeStyle = settings.lineColour
canvasContext.moveTo(settings.lineMargin, settings.lineTop)
canvasContext.lineTo(element.width - settings.lineMargin, settings.lineTop)
canvasContext.stroke()
canvasContext.closePath()
}
/**
* Clears all drawings off the canvas and redraws the signature line
*
* @private
*/
function clearCanvas () {
canvasContext.clearRect(0, 0, element.width, element.height)
canvasContext.fillStyle = settings.bgColour
canvasContext.fillRect(0, 0, element.width, element.height)
if (!settings.displayOnly)
drawSigLine()
canvasContext.lineWidth = settings.penWidth
canvasContext.strokeStyle = settings.penColour
$(settings.output, context).val('')
output = []
stopDrawing()
}
/**
* Callback registered to mouse/touch events of the canvas
* Draws a line at the mouse cursor location, starting a new line if necessary
*
* @private
*
* @param {Object} e The event object
* @param {Object} o The object context registered to the event; canvas
*/
function onMouseMove(e, o) {
if (previous.x == null) {
drawLine(e, 1)
} else {
drawLine(e, o)
}
}
/**
* Callback registered to mouse/touch events of canvas
* Triggers the drawLine function
*
* @private
*
* @param {Object} e The event object
* @param {Object} touchObject The object context registered to the event; canvas
*/
function startDrawing (e, touchObject) {
if (touchable) {
touchObject.addEventListener('touchmove', onMouseMove, false)
// touchObject.addEventListener('MSPointerMove', onMouseMove, false)
} else {
canvas.bind('mousemove.signaturepad', onMouseMove)
}
// Draws a single point on initial mouse down, for people with periods in their name
drawLine(e, 1)
}
/**
* Removes all the mouse events from the canvas
*
* @private
*/
function disableCanvas () {
eventsBound = false
canvas.each(function () {
if (this.removeEventListener) {
this.removeEventListener('touchend', stopDrawingWrapper)
this.removeEventListener('touchcancel', stopDrawingWrapper)
this.removeEventListener('touchmove', drawLine)
// this.removeEventListener('MSPointerUp', stopDrawingWrapper)
// this.removeEventListener('MSPointerCancel', stopDrawingWrapper)
// this.removeEventListener('MSPointerMove', drawLine)
}
if (this.ontouchstart)
this.ontouchstart = null;
})
$(document).unbind('mouseup.signaturepad')
canvas.unbind('mousedown.signaturepad')
canvas.unbind('mousemove.signaturepad')
canvas.unbind('mouseleave.signaturepad')
$(settings.clear, context).unbind('click.signaturepad')
}
/**
* Lazy touch event detection
* Uses the first press on the canvas to detect either touch or mouse reliably
* Will then bind other events as needed
*
* @private
*
* @param {Object} e The event object
*/
function initDrawEvents (e) {
if (eventsBound)
return false
eventsBound = true
// Closes open keyboards to free up space
$('input').blur();
if (typeof e.targetTouches !== 'undefined')
touchable = true
if (touchable) {
canvas.each(function () {
this.addEventListener('touchend', stopDrawingWrapper, false)
this.addEventListener('touchcancel', stopDrawingWrapper, false)
// this.addEventListener('MSPointerUp', stopDrawingWrapper, false)
// this.addEventListener('MSPointerCancel', stopDrawingWrapper, false)
})
canvas.unbind('mousedown.signaturepad')
} else {
$(document).bind('mouseup.signaturepad', function () {
if (mouseButtonDown) {
stopDrawing()
clearMouseLeaveTimeout()
}
})
canvas.bind('mouseleave.signaturepad', function (e) {
if (mouseButtonDown) stopDrawing(e)
if (mouseButtonDown && !mouseLeaveTimeout) {
mouseLeaveTimeout = setTimeout(function () {
stopDrawing()
clearMouseLeaveTimeout()
}, 500)
}
})
canvas.each(function () {
this.ontouchstart = null
})
}
}
/**
* Triggers the abilities to draw on the canvas
* Sets up mouse/touch events, hides and shows descriptions and sets current classes
*
* @private
*/
function drawIt () {
$(settings.typed, context).hide()
clearCanvas()
canvas.each(function () {
this.ontouchstart = function (e) {
e.preventDefault()
mouseButtonDown = true
initDrawEvents(e)
startDrawing(e, this)
}
})
canvas.bind('mousedown.signaturepad', function (e) {
e.preventDefault()
// Only allow left mouse clicks to trigger signature drawing
if (e.which > 1) return false
mouseButtonDown = true
initDrawEvents(e)
startDrawing(e)
})
$(settings.clear, context).bind('click.signaturepad', function (e) { e.preventDefault(); clearCanvas() })
$(settings.typeIt, context).bind('click.signaturepad', function (e) { e.preventDefault(); typeIt() })
$(settings.drawIt, context).unbind('click.signaturepad')
$(settings.drawIt, context).bind('click.signaturepad', function (e) { e.preventDefault() })
$(settings.typeIt, context).removeClass(settings.currentClass)
$(settings.drawIt, context).addClass(settings.currentClass)
$(settings.sig, context).addClass(settings.currentClass)
$(settings.typeItDesc, context).hide()
$(settings.drawItDesc, context).show()
$(settings.clear, context).show()
}
/**
* Triggers the abilities to type in the input for generating a signature
* Sets up mouse events, hides and shows descriptions and sets current classes
*
* @private
*/
function typeIt () {
clearCanvas()
disableCanvas()
$(settings.typed, context).show()
$(settings.drawIt, context).bind('click.signaturepad', function (e) { e.preventDefault(); drawIt() })
$(settings.typeIt, context).unbind('click.signaturepad')
$(settings.typeIt, context).bind('click.signaturepad', function (e) { e.preventDefault() })
$(settings.output, context).val('')
$(settings.drawIt, context).removeClass(settings.currentClass)
$(settings.typeIt, context).addClass(settings.currentClass)
$(settings.sig, context).removeClass(settings.currentClass)
$(settings.drawItDesc, context).hide()
$(settings.clear, context).hide()
$(settings.typeItDesc, context).show()
typeItCurrentFontSize = typeItDefaultFontSize = $(settings.typed, context).css('font-size').replace(/px/, '')
}
/**
* Callback registered on key up and blur events for input field
* Writes the text fields value as Html into an element
*
* @private
*
* @param {String} val The value of the input field
*/
function type (val) {
var typed = $(settings.typed, context)
, cleanedVal = val.replace(/>/g, '>').replace(/</g, '<').trim()
, oldLength = typeItNumChars
, edgeOffset = typeItCurrentFontSize * 0.5
typeItNumChars = cleanedVal.length
typed.html(cleanedVal)
if (!cleanedVal) {
typed.css('font-size', typeItDefaultFontSize + 'px')
return
}
if (typeItNumChars > oldLength && typed.outerWidth() > element.width) {
while (typed.outerWidth() > element.width) {
typeItCurrentFontSize--
typed.css('font-size', typeItCurrentFontSize + 'px')
}
}
if (typeItNumChars < oldLength && typed.outerWidth() + edgeOffset < element.width && typeItCurrentFontSize < typeItDefaultFontSize) {
while (typed.outerWidth() + edgeOffset < element.width && typeItCurrentFontSize < typeItDefaultFontSize) {
typeItCurrentFontSize++
typed.css('font-size', typeItCurrentFontSize + 'px')
}
}
}
/**
* Default onBeforeValidate function to clear errors
*
* @private
*
* @param {Object} context current context object
* @param {Object} settings provided settings
*/
function onBeforeValidate (context, settings) {
$('p.' + settings.errorClass, context).remove()
context.removeClass(settings.errorClass)
$('input, label', context).removeClass(settings.errorClass)
}
/**
* Default onFormError function to show errors
*
* @private
*
* @param {Object} errors object contains validation errors (e.g. nameInvalid=true)
* @param {Object} context current context object
* @param {Object} settings provided settings
*/
function onFormError (errors, context, settings) {
if (errors.nameInvalid) {
context.prepend(['<p class="', settings.errorClass, '">', settings.errorMessage, '</p>'].join(''))
$(settings.name, context).focus()
$(settings.name, context).addClass(settings.errorClass)
$('label[for=' + $(settings.name).attr('id') + ']', context).addClass(settings.errorClass)
}
if (errors.drawInvalid)
context.prepend(['<p class="', settings.errorClass, '">', settings.errorMessageDraw, '</p>'].join(''))
}
/**
* Validates the form to confirm a name was typed in the field
* If drawOnly also confirms that the user drew a signature
*
* @private
*
* @return {Boolean}
*/
function validateForm () {
var valid = true
, errors = {drawInvalid: false, nameInvalid: false}
, onBeforeArguments = [context, settings]
, onErrorArguments = [errors, context, settings]
if (settings.onBeforeValidate && typeof settings.onBeforeValidate === 'function') {
settings.onBeforeValidate.apply(self,onBeforeArguments)
} else {
onBeforeValidate.apply(self, onBeforeArguments)
}
if (settings.drawOnly && output.length < 1) {
errors.drawInvalid = true
valid = false
}
if ($(settings.name, context).val() === '') {
errors.nameInvalid = true
valid = false
}
if (settings.onFormError && typeof settings.onFormError === 'function') {
settings.onFormError.apply(self,onErrorArguments)
} else {
onFormError.apply(self, onErrorArguments)
}
return valid
}
/**
* Redraws the signature on a specific canvas
*
* @private
*
* @param {Array} paths the signature JSON
* @param {Object} context the canvas context to draw on
* @param {Boolean} saveOutput whether to write the path to the output array or not
*/
function drawSignature (paths, context, saveOutput) {
for(var i in paths) {
if (typeof paths[i] === 'object') {
context.beginPath()
context.moveTo(paths[i].mx, paths[i].my)
context.lineTo(paths[i].lx, paths[i].ly)
context.lineCap = settings.penCap
context.stroke()
context.closePath()
if (saveOutput) {
output.push({
'lx' : paths[i].lx
, 'ly' : paths[i].ly
, 'mx' : paths[i].mx
, 'my' : paths[i].my
})
}
}
}
}
/**
* Initialisation function, called immediately after all declarations
* Technically public, but only should be used internally
*
* @private
*/
function init () {
// Fixes the jQuery.fn.offset() function for Mobile Safari Browsers i.e. iPod Touch, iPad and iPhone
// https://gist.github.com/661844
// http://bugs.jquery.com/ticket/6446
if (parseFloat(((/CPU.+OS ([0-9_]{3}).*AppleWebkit.*Mobile/i.exec(navigator.userAgent)) || [0,'4_2'])[1].replace('_','.')) < 4.1) {
$.fn.Oldoffset = $.fn.offset;
$.fn.offset = function () {
var result = $(this).Oldoffset()
result.top -= window.scrollY
result.left -= window.scrollX
return result
}
}
// Disable selection on the typed div and canvas
$(settings.typed, context).bind('selectstart.signaturepad', function (e) { return $(e.target).is(':input') })
canvas.bind('selectstart.signaturepad', function (e) { return $(e.target).is(':input') })
if (!element.getContext && FlashCanvas)
FlashCanvas.initElement(element)
if (element.getContext) {
canvasContext = element.getContext('2d')
$(settings.sig, context).show()
if (!settings.displayOnly) {
if (!settings.drawOnly) {
$(settings.name, context).bind('keyup.signaturepad', function () {
type($(this).val())
})
$(settings.name, context).bind('blur.signaturepad', function () {
type($(this).val())
})
$(settings.drawIt, context).bind('click.signaturepad', function (e) {
e.preventDefault()
drawIt()
})
}
if (settings.drawOnly || settings.defaultAction === 'drawIt') {
drawIt()
} else {
typeIt()
}
if (settings.validateFields) {
if ($(selector).is('form')) {
$(selector).bind('submit.signaturepad', function () { return validateForm() })
} else {
$(selector).parents('form').bind('submit.signaturepad', function () { return validateForm() })
}
}
$(settings.sigNav, context).show()
}
}
}
$.extend(self, {
/**
* A property to store the current version of Signature Pad
*/
signaturePad : '{{version}}'
/**
* Initializes SignaturePad
*/
, init : function () { init() }
/**
* Allows options to be updated after initialization
*
* @param {Object} options An object containing the options to be changed
*/
, updateOptions : function (options) {
$.extend(settings, options)
}
/**
* Regenerates a signature on the canvas using an array of objects
* Follows same format as object property
* @see var object
*
* @param {Array} paths An array of the lines and points
*/
, regenerate : function (paths) {
self.clearCanvas()
$(settings.typed, context).hide()
if (typeof paths === 'string')
paths = JSON.parse(paths)
drawSignature(paths, canvasContext, true)
if (settings.output && $(settings.output, context).length > 0)
$(settings.output, context).val(JSON.stringify(output))
}
/**
* Clears the canvas
* Redraws the background colour and the signature line
*/
, clearCanvas : function () { clearCanvas() }
/**
* Returns the signature as a Js array
*
* @return {Array}
*/
, getSignature : function () { return output }
/**
* Returns the signature as a Json string
*
* @return {String}
*/
, getSignatureString : function () { return JSON.stringify(output) }
/**
* Returns the signature as an image
* Re-draws the signature in a shadow canvas to create a clean version
*
* @return {String}
*/
, getSignatureImage : function () {
var tmpCanvas = document.createElement('canvas')
, tmpContext = null
, data = null
tmpCanvas.style.position = 'absolute'
tmpCanvas.style.top = '-999em'
tmpCanvas.width = element.width
tmpCanvas.height = element.height
document.body.appendChild(tmpCanvas)
if (!tmpCanvas.getContext && FlashCanvas)
FlashCanvas.initElement(tmpCanvas)
tmpContext = tmpCanvas.getContext('2d')
tmpContext.fillStyle = settings.bgColour
tmpContext.fillRect(0, 0, element.width, element.height)
tmpContext.lineWidth = settings.penWidth
tmpContext.strokeStyle = settings.penColour
drawSignature(output, tmpContext)
data = tmpCanvas.toDataURL.apply(tmpCanvas, arguments)
document.body.removeChild(tmpCanvas)
tmpCanvas = null
return data
}
/**
* The form validation function
* Validates that the signature has been filled in properly
* Allows it to be hooked into another validation function and called at a different time
*
* @return {Boolean}
*/
, validateForm : function () { return validateForm() }
})
}
/**
* Create the plugin
* Returns an Api which can be used to call specific methods
*
* @param {Object} options The options array
*
* @return {Object} The Api for controlling the instance
*/
$.fn.signaturePad = function (options) {
var api = null
this.each(function () {
if (!$.data(this, 'plugin-signaturePad')) {
api = new SignaturePad(this, options)
api.init()
$.data(this, 'plugin-signaturePad', api)
} else {
api = $.data(this, 'plugin-signaturePad')
api.updateOptions(options)
}
})
return api
}
/**
* Expose the defaults so they can be overwritten for multiple instances
*
* @type {Object}
*/
$.fn.signaturePad.defaults = {
defaultAction : 'typeIt' // What action should be highlighted first: typeIt or drawIt
, displayOnly : false // Initialize canvas for signature display only; ignore buttons and inputs
, drawOnly : false // Whether the to allow a typed signature or not
, canvas : 'canvas' // Selector for selecting the canvas element
, sig : '.sig' // Parts of the signature form that require Javascript (hidden by default)
, sigNav : '.sigNav' // The TypeIt/DrawIt navigation (hidden by default)
, bgColour : '#ffffff' // The colour fill for the background of the canvas; or transparent
, penColour : '#145394' // Colour of the drawing ink
, penWidth : 2 // Thickness of the pen
, penCap : 'round' // Determines how the end points of each line are drawn (values: 'butt', 'round', 'square')
, lineColour : '#ccc' // Colour of the signature line
, lineWidth : 2 // Thickness of the signature line
, lineMargin : 5 // Margin on right and left of signature line
, lineTop : 35 // Distance to draw the line from the top
, name : '.name' // The input field for typing a name
, typed : '.typed' // The Html element to accept the printed name
, clear : '.clearButton' // Button for clearing the canvas
, typeIt : '.typeIt a' // Button to trigger name typing actions (current by default)
, drawIt : '.drawIt a' // Button to trigger name drawing actions
, typeItDesc : '.typeItDesc' // The description for TypeIt actions
, drawItDesc : '.drawItDesc' // The description for DrawIt actions (hidden by default)
, output : '.output' // The hidden input field for remembering line coordinates
, currentClass : 'current' // The class used to mark items as being currently active
, validateFields : true // Whether the name, draw fields should be validated
, errorClass : 'error' // The class applied to the new error Html element
, errorMessage : 'Please enter your name' // The error message displayed on invalid submission
, errorMessageDraw : 'Please sign the document' // The error message displayed when drawOnly and no signature is drawn
, onBeforeValidate : null // Pass a callback to be used instead of the built-in function
, onFormError : null // Pass a callback to be used instead of the built-in function
, onDraw : null // Pass a callback to be used to capture the drawing process
, onDrawEnd : null // Pass a callback to be exectued after the drawing process
}
}(jQuery))
| cornernote/yii-dressing | yii-dressing/assets/signature-pad/jquery.signaturepad.js | JavaScript | bsd-3-clause | 25,256 |
# encoding: UTF-8
require 'pathname'
base = Pathname(__FILE__).dirname.expand_path
Dir.glob(base + '*.rb').each do |file|
require file
end
| fluke777/gooddata-ruby | lib/gooddata/models/metadata/metadata.rb | Ruby | bsd-3-clause | 143 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package runtime
import (
"runtime/internal/sys"
"unsafe"
)
type sigctxt struct {
info *siginfo
ctxt unsafe.Pointer
}
func (c *sigctxt) regs() *sigcontext { return &(*ucontext)(c.ctxt).uc_mcontext }
func (c *sigctxt) r0() uint32 { return c.regs().r0 }
func (c *sigctxt) r1() uint32 { return c.regs().r1 }
func (c *sigctxt) r2() uint32 { return c.regs().r2 }
func (c *sigctxt) r3() uint32 { return c.regs().r3 }
func (c *sigctxt) r4() uint32 { return c.regs().r4 }
func (c *sigctxt) r5() uint32 { return c.regs().r5 }
func (c *sigctxt) r6() uint32 { return c.regs().r6 }
func (c *sigctxt) r7() uint32 { return c.regs().r7 }
func (c *sigctxt) r8() uint32 { return c.regs().r8 }
func (c *sigctxt) r9() uint32 { return c.regs().r9 }
func (c *sigctxt) r10() uint32 { return c.regs().r10 }
func (c *sigctxt) fp() uint32 { return c.regs().fp }
func (c *sigctxt) ip() uint32 { return c.regs().ip }
func (c *sigctxt) sp() uint32 { return c.regs().sp }
func (c *sigctxt) lr() uint32 { return c.regs().lr }
func (c *sigctxt) pc() uint32 { return c.regs().pc }
func (c *sigctxt) cpsr() uint32 { return c.regs().cpsr }
func (c *sigctxt) fault() uint32 { return c.regs().fault_address }
func (c *sigctxt) trap() uint32 { return c.regs().trap_no }
func (c *sigctxt) error() uint32 { return c.regs().error_code }
func (c *sigctxt) oldmask() uint32 { return c.regs().oldmask }
func (c *sigctxt) sigcode() uint32 { return uint32(c.info.si_code) }
func (c *sigctxt) sigaddr() uint32 { return c.info.si_addr }
func (c *sigctxt) set_pc(x uint32) { c.regs().pc = x }
func (c *sigctxt) set_sp(x uint32) { c.regs().sp = x }
func (c *sigctxt) set_lr(x uint32) { c.regs().lr = x }
func (c *sigctxt) set_r10(x uint32) { c.regs().r10 = x }
func (c *sigctxt) set_sigcode(x uint32) { c.info.si_code = int32(x) }
func (c *sigctxt) set_sigaddr(x uint32) {
*(*uintptr)(add(unsafe.Pointer(c.info), 2*sys.PtrSize)) = uintptr(x)
}
| ganboing/go-esx | src/runtime/signal_linux_arm.go | GO | bsd-3-clause | 2,199 |
// 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.
// Copyright 2006 Google Inc. All Rights Reserved.
/**
* @fileoverview Anchored viewport positioning class with both adjust and
* resize options for the popup.
*
*/
goog.provide('goog.positioning.MenuAnchoredPosition');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('goog.positioning');
goog.require('goog.positioning.AnchoredViewportPosition');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.CornerBit');
goog.require('goog.positioning.Overflow');
goog.require('goog.positioning.OverflowStatus');
/**
* Encapsulates a popup position where the popup is anchored at a corner of
* an element. The positioning behavior changes based on the values of
* opt_adjust and opt_resize.
*
* When using this positioning object it's recommended that the movable element
* be absolutely positioned.
*
* @param {Element} anchorElement Element the movable element should be
* anchored against.
* @param {goog.positioning.Corner} corner Corner of anchored element the
* movable element should be positioned at.
* @param {boolean} opt_adjust Whether the positioning should be adjusted until
* the element fits inside the viewport even if that means that the anchored
* corners are ignored.
* @param {boolean} opt_resize Whether the positioning should be adjusted until
* the element fits inside the viewport on the X axis and it's heigh is
* resized so if fits in the viewport. This take precedence over
* opt_adjust.
* @constructor
* @extends {goog.positioning.AnchoredViewportPosition}
*/
goog.positioning.MenuAnchoredPosition = function(anchorElement,
corner,
opt_adjust,
opt_resize) {
goog.positioning.AnchoredViewportPosition.call(this, anchorElement, corner,
opt_adjust);
/**
* Whether the positioning should be adjusted until the element fits inside
* the viewport even if that means that the anchored corners are ignored.
* @type {boolean|undefined}
* @private
*/
this.resize_ = opt_resize;
};
goog.inherits(goog.positioning.MenuAnchoredPosition,
goog.positioning.AnchoredViewportPosition);
/**
* Repositions the movable element.
*
* @param {Element} movableElement Element to position.
* @param {goog.positioning.Corner} movableCorner Corner of the movable element
* that should be positioned adjacent to the anchored element.
* @param {goog.math.Box} opt_margin A margin specifin pixels.
* @param {goog.math.Size} opt_preferredSize Preferred size of the
* moveableElement.
*/
goog.positioning.MenuAnchoredPosition.prototype.reposition =
function(movableElement, movableCorner, opt_margin, opt_preferredSize) {
if (this.resize_) {
goog.positioning.positionAtAnchor(this.element, this.corner,
movableElement, movableCorner, null, opt_margin,
goog.positioning.Overflow.ADJUST_X |
goog.positioning.Overflow.RESIZE_HEIGHT, opt_preferredSize);
} else {
goog.positioning.MenuAnchoredPosition.superClass_.reposition.call(
this,
movableElement,
movableCorner,
opt_margin,
opt_preferredSize);
}
};
| yesudeep/puppy | tools/google-closure-library/closure/goog/positioning/menuanchoredposition.js | JavaScript | mit | 3,921 |
//
// PodcastEpisodePage.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// 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;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena.Widgets;
using Banshee.Gui.TrackEditor;
using Banshee.Podcasting.Data;
namespace Banshee.Podcasting.Gui
{
public class PodcastEpisodePage : Gtk.ScrolledWindow, ITrackEditorPage
{
private VBox box;
private WrapLabel podcast = new WrapLabel ();
private WrapLabel author = new WrapLabel ();
private WrapLabel published = new WrapLabel ();
private WrapLabel description = new WrapLabel ();
public PodcastEpisodePage ()
{
BorderWidth = 2;
ShadowType = ShadowType.None;
HscrollbarPolicy = PolicyType.Never;
VscrollbarPolicy = PolicyType.Automatic;
box = new VBox ();
box.BorderWidth = 6;
box.Spacing = 12;
box.PackStart (podcast, false, false, 0);
box.PackStart (author, false, false, 0);
box.PackStart (published, false, false, 0);
box.PackStart (description, true, true, 0);
AddWithViewport (box);
ShowAll ();
}
public void Initialize (TrackEditorDialog dialog)
{
}
public void LoadTrack (EditorTrackInfo track)
{
BorderWidth = 2;
PodcastTrackInfo info = PodcastTrackInfo.From (track.SourceTrack);
if (info == null) {
Hide ();
return;
}
podcast.Markup = SetInfo (Catalog.GetString ("Podcast"), track.SourceTrack.AlbumTitle);
author.Markup = SetInfo (Catalog.GetString ("Author"), track.SourceTrack.ArtistName);
published.Markup = SetInfo (Catalog.GetString ("Published"), info.PublishedDate.ToLongDateString ());
description.Markup = SetInfo (Catalog.GetString ("Description"), info.Description);
// IsDownloaded
// IsNew
Show ();
}
private static string info_str = "<b>{0}</b>\n{1}";
private static string SetInfo (string title, string info)
{
return String.Format (info_str,
GLib.Markup.EscapeText (title),
GLib.Markup.EscapeText (info)
);
}
public int Order {
get { return 40; }
}
public string Title {
get { return Catalog.GetString ("Episode Details"); }
}
public PageType PageType {
get { return PageType.View; }
}
public Gtk.Widget TabWidget {
get { return null; }
}
public Gtk.Widget Widget {
get { return this; }
}
}
}
| mono-soc-2011/banshee | src/Extensions/Banshee.Podcasting/Banshee.Podcasting.Gui/PodcastEpisodePage.cs | C# | mit | 3,948 |
<?php
return [
'Names' => [
'AE' => 'Dei sameinte arabiske emirata',
'AT' => 'Austerrike',
'BL' => 'Saint Barthélemy',
'BY' => 'Kviterussland',
'CC' => 'Kokosøyane',
'CD' => 'Kongo-Kinshasa',
'CF' => 'Den sentralafrikanske republikken',
'CI' => 'Elfenbeinskysten',
'CK' => 'Cookøyane',
'DO' => 'Den dominikanske republikken',
'FK' => 'Falklandsøyane',
'FO' => 'Færøyane',
'GS' => 'Sør-Georgia og Sør-Sandwichøyane',
'HM' => 'Heardøya og McDonaldøyane',
'KM' => 'Komorane',
'KY' => 'Caymanøyane',
'LU' => 'Luxembourg',
'MH' => 'Marshalløyane',
'MP' => 'Nord-Marianane',
'MV' => 'Maldivane',
'NO' => 'Noreg',
'PH' => 'Filippinane',
'PN' => 'Pitcairn',
'SB' => 'Salomonøyane',
'SC' => 'Seychellane',
'SH' => 'Saint Helena',
'TC' => 'Turks- og Caicosøyane',
'TF' => 'Dei franske sørterritoria',
'TL' => 'Aust-Timor',
'UM' => 'USAs ytre småøyar',
'VC' => 'St. Vincent og Grenadinane',
'VG' => 'Dei britiske Jomfruøyane',
'VI' => 'Dei amerikanske Jomfruøyane',
],
];
| Nyholm/symfony | src/Symfony/Component/Intl/Resources/data/regions/nn.php | PHP | mit | 1,254 |
let x = { a: (b ? 1 : 2)};
| jimenglish81/ember-suave | tests/fixtures/rules/require-spaces-inside-object-brackets/bad/nested-object.js | JavaScript | mit | 27 |
angular.module('examples', [])
.factory('formPostData', ['$document', function($document) {
return function(url, fields) {
var form = angular.element('<form style="display: none;" method="post" action="' + url + '" target="_blank"></form>');
angular.forEach(fields, function(value, name) {
var input = angular.element('<input type="hidden" name="' + name + '">');
input.attr('value', value);
form.append(input);
});
$document.find('body').append(form);
form[0].submit();
form.remove();
};
}])
.factory('openPlunkr', ['formPostData', '$http', '$q', function(formPostData, $http, $q) {
return function(exampleFolder) {
var exampleName = 'AngularJS Example';
// Load the manifest for the example
$http.get(exampleFolder + '/manifest.json')
.then(function(response) {
return response.data;
})
.then(function(manifest) {
var filePromises = [];
// Build a pretty title for the Plunkr
var exampleNameParts = manifest.name.split('-');
exampleNameParts.unshift('AngularJS');
angular.forEach(exampleNameParts, function(part, index) {
exampleNameParts[index] = part.charAt(0).toUpperCase() + part.substr(1);
});
exampleName = exampleNameParts.join(' - ');
angular.forEach(manifest.files, function(filename) {
filePromises.push($http.get(exampleFolder + '/' + filename, { transformResponse: [] })
.then(function(response) {
// The manifests provide the production index file but Plunkr wants
// a straight index.html
if (filename === "index-production.html") {
filename = "index.html"
}
return {
name: filename,
content: response.data
};
}));
});
return $q.all(filePromises);
})
.then(function(files) {
var postData = {};
angular.forEach(files, function(file) {
postData['files[' + file.name + ']'] = file.content;
});
postData['tags[0]'] = "angularjs";
postData['tags[1]'] = "example";
postData.private = true;
postData.description = exampleName;
formPostData('http://plnkr.co/edit/?p=preview', postData);
});
};
}]); | niluka2a/angular.js | docs/app/src/examples.js | JavaScript | mit | 2,355 |
class UsersController < ApplicationController
def index
end
end
| csto/grapher | test/dummy/app/controllers/users_controller.rb | Ruby | mit | 68 |
// Generated by CoffeeScript 1.4.0
var isDefined,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__slice = [].slice,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
window.serious = {};
window.serious.Utils = {};
isDefined = function(obj) {
return typeof obj !== 'undefined' && obj !== null;
};
jQuery.fn.opacity = function(int) {
return $(this).css({
opacity: int
});
};
window.serious.Utils.clone = function(obj) {
var flags, key, newInstance;
if (!(obj != null) || typeof obj !== 'object') {
return obj;
}
if (obj instanceof Date) {
return new Date(obj.getTime());
}
if (obj instanceof RegExp) {
flags = '';
if (obj.global != null) {
flags += 'g';
}
if (obj.ignoreCase != null) {
flags += 'i';
}
if (obj.multiline != null) {
flags += 'm';
}
if (obj.sticky != null) {
flags += 'y';
}
return new RegExp(obj.source, flags);
}
newInstance = new obj.constructor();
for (key in obj) {
newInstance[key] = window.serious.Utils.clone(obj[key]);
}
return newInstance;
};
jQuery.fn.cloneTemplate = function(dict, removeUnusedField) {
var klass, nui, value;
if (removeUnusedField == null) {
removeUnusedField = false;
}
nui = $(this[0]).clone();
nui = nui.removeClass("template hidden").addClass("actual");
if (typeof dict === "object") {
for (klass in dict) {
value = dict[klass];
if (value !== null) {
nui.find(".out." + klass).html(value);
}
}
if (removeUnusedField) {
nui.find(".out").each(function() {
if ($(this).html() === "") {
return $(this).remove();
}
});
}
}
return nui;
};
Object.size = function(obj) {
var key, size;
size = 0;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
};
window.serious.States = (function() {
function States() {
this.states = {};
}
States.prototype.set = function(state, value, scope) {
if (value == null) {
value = true;
}
if (scope == null) {
scope = document;
}
this.states[state] = value;
return this._showState(state, value);
};
States.prototype._showState = function(state, value, scope) {
if (value == null) {
value = true;
}
if (scope == null) {
scope = document;
}
$(".when-" + state, scope).each(function(idx, element) {
var expected_value;
element = $(element);
expected_value = element.data('state') || true;
return $(element).toggleClass('hidden', expected_value.toString() !== value.toString());
});
return $(".when-not-" + state, scope).each(function(idx, element) {
var expected_value;
element = $(element);
expected_value = element.data('state') || true;
return $(element).toggleClass('hidden', expected_value.toString() === value.toString());
});
};
return States;
})();
window.serious.Widget = (function() {
function Widget() {
this.cloneTemplate = __bind(this.cloneTemplate, this);
this.show = __bind(this.show, this);
this.hide = __bind(this.hide, this);
this.get = __bind(this.get, this);
this.set = __bind(this.set, this);
}
Widget.bindAll = function() {
var first, firsts, _i, _len;
firsts = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (firsts) {
for (_i = 0, _len = firsts.length; _i < _len; _i++) {
first = firsts[_i];
Widget.ensureWidget($(first));
}
}
return $(".widget").each(function() {
var self;
self = $(this);
if (!self.hasClass('template') && !self.parents().hasClass('template')) {
return Widget.ensureWidget(self);
}
});
};
Widget.ensureWidget = function(ui) {
var widget, widget_class;
ui = $(ui);
if (!ui.length) {
return null;
} else if (ui[0]._widget != null) {
return ui[0]._widget;
} else {
widget_class = Widget.getWidgetClass(ui);
if (widget_class != null) {
widget = new widget_class();
widget.bindUI(ui);
return widget;
} else {
console.warn("widget not found for", ui);
return null;
}
}
};
Widget.getWidgetClass = function(ui) {
return eval("(" + $(ui).attr("data-widget") + ")");
};
Widget.prototype.bindUI = function(ui) {
var action, key, nui, value, _i, _len, _ref, _ref1, _results;
this.ui = $(ui);
if (this.ui[0]._widget) {
delete this.ui[0]._widget;
}
this.ui[0]._widget = this;
this.uis = {};
if (typeof this.UIS !== "undefined") {
_ref = this.UIS;
for (key in _ref) {
value = _ref[key];
nui = this.ui.find(value);
if (nui.length < 1) {
console.warn("uis", key, "not found in", ui);
}
this.uis[key] = nui;
}
}
if (this.ACTIONS != null) {
_ref1 = this.ACTIONS;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
action = _ref1[_i];
_results.push(this._bindClick(this.ui.find(".do[data-action=" + action + "]"), action));
}
return _results;
}
};
Widget.prototype.set = function(field, value, context) {
/* Set a value to all tag with the given data-field attribute.
Field can be a dict or a field name.
If it is a dict, the second parameter should be a context.
The default context is the widget itself.
*/
var name, _value;
if (typeof field === "object") {
context = value || this.ui;
for (name in field) {
_value = field[name];
context.find(".out[data-field=" + name + "]").html(_value);
}
} else {
context = context || this.ui;
context.find(".out[data-field=" + field + "]").html(value);
}
return context;
};
Widget.prototype.get = function(form) {
var data;
form = $(form);
data = {};
form.find('input.in').each(function() {
var input;
input = $(this);
if (!input.hasClass('template') && !input.parents().hasClass('template')) {
return data[input.attr('name')] = input.val();
}
});
return data;
};
Widget.prototype.hide = function() {
return this.ui.addClass("hidden");
};
Widget.prototype.show = function() {
return this.ui.removeClass("hidden");
};
Widget.prototype.cloneTemplate = function(template_nui, dict, removeUnusedField) {
var action, klass, nui, value, _i, _len, _ref;
if (removeUnusedField == null) {
removeUnusedField = false;
}
nui = template_nui.clone();
nui = nui.removeClass("template hidden").addClass("actual");
if (typeof dict === "object") {
for (klass in dict) {
value = dict[klass];
if (value !== null) {
nui.find(".out." + klass).html(value);
}
}
if (removeUnusedField) {
nui.find(".out").each(function() {
if ($(this).html() === "") {
return $(this).remove();
}
});
}
}
if (this.ACTIONS != null) {
_ref = this.ACTIONS;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
action = _ref[_i];
this._bindClick(nui.find(".do[data-action=" + action + "]"), action);
}
}
return nui;
};
Widget.prototype._bindClick = function(nui, action) {
var _this = this;
if ((action != null) && __indexOf.call(this.ACTIONS, action) >= 0) {
return nui.click(function(e) {
_this[action](e);
return e.preventDefault();
});
}
};
return Widget;
})();
window.serious.URL = (function() {
function URL() {
this.toString = __bind(this.toString, this);
this.fromString = __bind(this.fromString, this);
this.enableDynamicLinks = __bind(this.enableDynamicLinks, this);
this.updateUrl = __bind(this.updateUrl, this);
this.hasBeenAdded = __bind(this.hasBeenAdded, this);
this.hasChanged = __bind(this.hasChanged, this);
this.remove = __bind(this.remove, this);
this.update = __bind(this.update, this);
this.set = __bind(this.set, this);
this.onStateChanged = __bind(this.onStateChanged, this);
this.get = __bind(this.get, this);
var _this = this;
this.previousHash = [];
this.handlers = [];
this.hash = this.fromString(location.hash);
$(window).hashchange(function() {
var handler, _i, _len, _ref, _results;
_this.previousHash = window.serious.Utils.clone(_this.hash);
_this.hash = _this.fromString(location.hash);
_ref = _this.handlers;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
handler = _ref[_i];
_results.push(handler());
}
return _results;
});
}
URL.prototype.get = function(field) {
if (field == null) {
field = null;
}
if (field) {
return this.hash[field];
} else {
return this.hash;
}
};
URL.prototype.onStateChanged = function(handler) {
return this.handlers.push(handler);
};
URL.prototype.set = function(fields, silent) {
var hash, key, value;
if (silent == null) {
silent = false;
}
hash = silent ? this.hash : window.serious.Utils.clone(this.hash);
hash = [];
for (key in fields) {
value = fields[key];
if (isDefined(value)) {
hash[key] = value;
}
}
return this.updateUrl(hash);
};
URL.prototype.update = function(fields, silent) {
var hash, key, value;
if (silent == null) {
silent = false;
}
hash = silent ? this.hash : window.serious.Utils.clone(this.hash);
for (key in fields) {
value = fields[key];
if (isDefined(value)) {
hash[key] = value;
} else {
delete hash[key];
}
}
return this.updateUrl(hash);
};
URL.prototype.remove = function(key, silent) {
var hash;
if (silent == null) {
silent = false;
}
hash = silent ? this.hash : window.serious.Utils.clone(this.hash);
if (hash[key]) {
delete hash[key];
}
return this.updateUrl(hash);
};
URL.prototype.hasChanged = function(key) {
if (this.hash[key] != null) {
if (this.previousHash[key] != null) {
return this.hash[key].toString() !== this.previousHash[key].toString();
} else {
return true;
}
} else {
if (this.previousHash[key] != null) {
return true;
}
}
return false;
};
URL.prototype.hasBeenAdded = function(key) {
return console.error("not implemented");
};
URL.prototype.updateUrl = function(hash) {
if (hash == null) {
hash = null;
}
if (!hash || Object.size(hash) === 0) {
return location.hash = '_';
} else {
return location.hash = this.toString(hash);
}
};
URL.prototype.enableDynamicLinks = function(context) {
var _this = this;
if (context == null) {
context = null;
}
return $("a.internal[href]", context).click(function(e) {
var href, link;
link = $(e.currentTarget);
href = link.attr("data-href") || link.attr("href");
if (href[0] === "#") {
if (href.length > 1 && href[1] === "+") {
_this.update(_this.fromString(href.slice(2)));
} else if (href.length > 1 && href[1] === "-") {
_this.remove(_this.fromString(href.slice(2)));
} else {
_this.set(_this.fromString(href.slice(1)));
}
}
return false;
});
};
URL.prototype.fromString = function(value) {
var hash, hash_list, item, key, key_value, val, _i, _len;
value = value || location.hash;
hash = {};
value = value.replace('!', '');
hash_list = value.split("&");
for (_i = 0, _len = hash_list.length; _i < _len; _i++) {
item = hash_list[_i];
if (item != null) {
key_value = item.split("=");
if (key_value.length === 2) {
key = key_value[0].replace("#", "");
val = key_value[1].replace("#", "");
hash[key] = val;
}
}
}
return hash;
};
URL.prototype.toString = function(hash_list) {
var i, key, new_hash, value;
if (hash_list == null) {
hash_list = null;
}
hash_list = hash_list || this.hash;
new_hash = "!";
i = 0;
for (key in hash_list) {
value = hash_list[key];
if (i > 0) {
new_hash += "&";
}
new_hash += key + "=" + value;
i++;
}
return new_hash;
};
return URL;
})();
| shelsonjava/datawrapper | www/static/vendor/serious-toolkit/serious-widget.js | JavaScript | mit | 12,671 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'autoembed', 'pl', {
embeddingInProgress: 'Osadzanie wklejonego adresu URL...',
embeddingFailed: 'Ten adres URL multimediów nie może być automatycznie osadzony.'
} );
| tsipa88/ckeditor | vendor/assets/javascripts/ckeditor/plugins/autoembed/lang/pl.js | JavaScript | mit | 344 |
/*
* 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.jasper.tagplugins.jstl.core;
import org.apache.jasper.compiler.tagplugin.TagPlugin;
import org.apache.jasper.compiler.tagplugin.TagPluginContext;
public final class Choose implements TagPlugin {
@Override
public void doTag(TagPluginContext ctxt) {
// Not much to do here, much of the work will be done in the
// containing tags, <c:when> and <c:otherwise>.
ctxt.generateBody();
// See comments in When.java for the reason "}" is generated here.
ctxt.generateJavaSource("}");
}
}
| plumer/codana | tomcat_files/7.0.61/Choose.java | Java | mit | 1,382 |
import * as amqp from "amqplib";
import * as amqpConMgr from 'amqp-connection-manager';
// from README.md
const connection = amqpConMgr.connect(['amqp://localhost']);
const channelWrapper: amqpConMgr.ChannelWrapper = connection.createChannel({
json: true,
setup: async (channel: amqp.ConfirmChannel): Promise<void> => {
// `channel` here is a regular amqplib `ConfirmChannel`. Unfortunately its typings make it return a bluebird-specific promise
// tslint:disable-next-line:await-promise
await channel.assertQueue('rxQueueName', {durable: true});
}
});
connection.on("connect", (_arg: { connection: amqp.Connection, url: string }): void => undefined);
connection.on("disconnect", (_arg: { err: Error }): void => undefined);
channelWrapper.on("close", () => undefined);
channelWrapper.on("connect", () => undefined);
channelWrapper.on("error", (_error: Error) => undefined);
channelWrapper.sendToQueue("foo", Buffer.from("bar"))
.catch((error: Error): void => {
// nothing
});
// Test that plain objects are implicitly serialized.
channelWrapper.sendToQueue("foo", {a: 'bar'}).catch(_ => {});
// Checking connection options
amqpConMgr.connect(["foo", "bar"], {
findServers(callback) {
callback("x");
}
});
amqpConMgr.connect(["foo", "bar"], {
findServers(callback) {
callback(["x", "y"]);
}
});
amqpConMgr.connect(["foo", "bar"], {
findServers() {
return Promise.resolve("x");
}
});
amqpConMgr.connect(["foo", "bar"], {
findServers() {
return Promise.resolve(["x", "y"]);
}
});
amqpConMgr.connect(["foo", "bar"], {
reconnectTimeInSeconds: 123
});
amqpConMgr.connect(["foo", "bar"], {
heartbeatIntervalInSeconds: 123
});
amqpConMgr.connect(["foo", "bar"], {
connectionOptions: {
ca: "some CA",
servername: "foo.example.com"
}
});
| dsebastien/DefinitelyTyped | types/amqp-connection-manager/amqp-connection-manager-tests.ts | TypeScript | mit | 1,888 |
<?php defined('C5_EXECUTE') or die("Access Denied."); ?>
<?php $f = Loader::helper('form'); ?>
<?php $co = Loader::helper('lists/countries'); ?>
<div class="ccm-attribute-address-composer-wrapper ccm-attribute-address-<?php echo $key->getAttributeKeyID()?>">
<div class="control-group">
<?php echo $f->label($this->field('address1'), t('Address 1'))?>
<div class="controls">
<?php echo $f->text($this->field('address1'), $address1)?>
</div>
</div>
<div class="control-group">
<?php echo $f->label($this->field('address2'), t('Address 2'))?>
<div class="controls">
<?php echo $f->text($this->field('address2'), $address2)?>
</div>
</div>
<div class="control-group">
<?php echo $f->label($this->field('city'), t('City'))?>
<div class="controls">
<?php echo $f->text($this->field('city'), $city)?>
</div>
</div>
<div class="control-group ccm-attribute-address-state-province">
<?php echo $f->label($this->field('state_province'), t('State/Province'))?>
<?php
$spreq = $f->getRequestValue($this->field('state_province'));
if ($spreq != false) {
$state_province = $spreq;
}
$creq = $f->getRequestValue($this->field('country'));
if ($creq != false) {
$country = $creq;
}
?>
<div class="controls">
<?php echo $f->select($this->field('state_province_select'), array('' => t('Choose State/Province')), $state_province, array('ccm-attribute-address-field-name' => $this->field('state_province')))?>
<?php echo $f->text($this->field('state_province_text'), $state_province, array('style' => 'display: none', 'ccm-attribute-address-field-name' => $this->field('state_province')))?>
</div>
</div>
<?php
if (!$country && !$search) {
if ($akDefaultCountry != '') {
$country = $akDefaultCountry;
} else {
$country = 'US';
}
}
$countriesTmp = $co->getCountries();
$countries = array();
foreach($countriesTmp as $_key => $_value) {
if ((!$akHasCustomCountries) || ($akHasCustomCountries && in_array($_key, $akCustomCountries))) {
$countries[$_key] = $_value;
}
}
$countries = array_merge(array('' => t('Choose Country')), $countries);
?>
<div class="control-group ccm-attribute-address-country">
<?php echo $f->label($this->field('country'), t('Country'))?>
<div class="controls">
<?php echo $f->select($this->field('country'), $countries, $country); ?>
</div>
</div>
<div class="control-group">
<?php echo $f->label($this->field('postal_code'), t('Postal Code'))?>
<div class="controls">
<?php echo $f->text($this->field('postal_code'), $postal_code)?>
</div>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
$(function() {
ccm_setupAttributeTypeAddressSetupStateProvinceSelector('ccm-attribute-address-<?php echo $key->getAttributeKeyID()?>');
});
//]]>
</script> | win-k/CMSTV | concrete5/concrete/models/attribute/types/address/composer.php | PHP | mit | 2,794 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/***
*makepath.c - create path name from components
*
*
*Purpose:
* To provide support for creation of full path names from components
*
*******************************************************************************/
#include "stdafx.h"
#include "winwrap.h"
#include "utilcode.h"
#include "ex.h"
/***
*void Makepath() - build path name from components
*
*Purpose:
* create a path name from its individual components
*
*Entry:
* CQuickWSTR &szPath - Buffer for constructed path
* WCHAR *drive - pointer to drive component, may or may not contain
* trailing ':'
* WCHAR *dir - pointer to subdirectory component, may or may not include
* leading and/or trailing '/' or '\' characters
* WCHAR *fname - pointer to file base name component
* WCHAR *ext - pointer to extension component, may or may not contain
* a leading '.'.
*
*Exit:
* path - pointer to constructed path name
*
*Exceptions:
*
*******************************************************************************/
void MakePath (
__out CQuickWSTR &szPath,
__in LPCWSTR drive,
__in LPCWSTR dir,
__in LPCWSTR fname,
__in LPCWSTR ext
)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END
SIZE_T maxCount = 4 // Possible separators between components, plus null terminator
+ (drive != nullptr ? 2 : 0)
+ (dir != nullptr ? wcslen(dir) : 0)
+ (fname != nullptr ? wcslen(fname) : 0)
+ (ext != nullptr ? wcslen(ext) : 0);
LPWSTR path = szPath.AllocNoThrow(maxCount);
const WCHAR *p;
DWORD count = 0;
/* we assume that the arguments are in the following form (although we
* do not diagnose invalid arguments or illegal filenames (such as
* names longer than 8.3 or with illegal characters in them)
*
* drive:
* A ; or
* A:
* dir:
* \top\next\last\ ; or
* /top/next/last/ ; or
* either of the above forms with either/both the leading
* and trailing / or \ removed. Mixed use of '/' and '\' is
* also tolerated
* fname:
* any valid file name
* ext:
* any valid extension (none if empty or null )
*/
/* copy drive */
if (drive && *drive) {
*path++ = *drive;
*path++ = _T(':');
count += 2;
}
/* copy dir */
if ((p = dir)) {
while (*p) {
*path++ = *p++;
count++;
_ASSERTE(count < maxCount);
}
#ifdef _MBCS
if (*(p=_mbsdec(dir,p)) != _T('/') && *p != _T('\\')) {
#else /* _MBCS */
// suppress warning for the following line; this is safe but would require significant code
// delta for prefast to understand.
#ifdef _PREFAST_
#pragma warning( suppress: 26001 )
#endif
if (*(p-1) != _T('/') && *(p-1) != _T('\\')) {
#endif /* _MBCS */
*path++ = _T('\\');
count++;
_ASSERTE(count < maxCount);
}
}
/* copy fname */
if ((p = fname)) {
while (*p) {
*path++ = *p++;
count++;
_ASSERTE(count < maxCount);
}
}
/* copy ext, including 0-terminator - check to see if a '.' needs
* to be inserted.
*/
if ((p = ext)) {
if (*p && *p != _T('.')) {
*path++ = _T('.');
count++;
_ASSERTE(count < maxCount);
}
while ((*path++ = *p++)) {
count++;
_ASSERTE(count < maxCount);
}
}
else {
/* better add the 0-terminator */
*path = _T('\0');
}
szPath.Shrink(count + 1);
}
// Returns the directory for HMODULE. So, if HMODULE was for "C:\Dir1\Dir2\Filename.DLL",
// then this would return "C:\Dir1\Dir2\" (note the trailing backslash).
HRESULT GetHModuleDirectory(
__in HMODULE hMod,
SString& wszPath)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
CANNOT_TAKE_LOCK;
}
CONTRACTL_END;
DWORD dwRet = WszGetModuleFileName(hMod, wszPath);
if (dwRet == 0)
{ // Some other error.
return HRESULT_FROM_GetLastError();
}
CopySystemDirectory(wszPath, wszPath);
return S_OK;
}
//
// Returns path name from a file name.
// Example: For input "C:\Windows\System.dll" returns "C:\Windows\".
// Warning: The input file name string might be destroyed.
//
// Arguments:
// pPathString - [in] SString with file name
//
// pBuffer - [out] SString .
//
// Return Value:
// S_OK - Output buffer contains path name.
// other errors - If Sstring throws.
//
HRESULT CopySystemDirectory(const SString& pPathString,
SString& pbuffer)
{
HRESULT hr = S_OK;
EX_TRY
{
pbuffer.Set(pPathString);
SString::Iterator iter = pbuffer.End();
if (pbuffer.FindBack(iter,DIRECTORY_SEPARATOR_CHAR_W))
{
iter++;
pbuffer.Truncate(iter);
}
else
{
hr = E_UNEXPECTED;
}
}
EX_CATCH_HRESULT(hr);
return hr;
}
| poizan42/coreclr | src/utilcode/makepath.cpp | C++ | mit | 6,015 |
/* Collator.java -- Perform locale dependent String comparisons.
Copyright (C) 1998, 1999, 2000, 2001, 2004, 2005 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package java.text;
import gnu.java.locale.LocaleHelper;
import java.text.spi.CollatorProvider;
import java.util.Comparator;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.ServiceLoader;
/**
* This class is the abstract superclass of classes which perform
* locale dependent <code>String</code> comparisons. A caller requests
* an instance of <code>Collator</code> for a particular locale using
* the <code>getInstance()</code> static method in this class. That method
* will return a locale specific subclass of <code>Collator</code> which
* can be used to perform <code>String</code> comparisons for that locale.
* If a subclass of <code>Collator</code> cannot be located for a particular
* locale, a default instance for the current locale will be returned.
*
* In addition to setting the correct locale, there are two additional
* settings that can be adjusted to affect <code>String</code> comparisons:
* strength and decomposition. The strength value determines the level
* of signficance of character differences required for them to sort
* differently. (For example, whether or not capital letters are considered
* different from lower case letters). The decomposition value affects how
* variants of the same character are treated for sorting purposes. (For
* example, whether or not an accent is signficant or not). These settings
* are described in detail in the documentation for the methods and values
* that are related to them.
*
* @author Tom Tromey (tromey@cygnus.com)
* @author Aaron M. Renn (arenn@urbanophile.com)
* @date March 18, 1999
*/
public abstract class Collator implements Comparator<Object>, Cloneable
{
/**
* This constant is a strength value which indicates that only primary
* differences between characters will be considered signficant. As an
* example, two completely different English letters such as 'a' and 'b'
* are considered to have a primary difference.
*/
public static final int PRIMARY = 0;
/**
* This constant is a strength value which indicates that only secondary
* or primary differences between characters will be considered
* significant. An example of a secondary difference between characters
* are instances of the same letter with different accented forms.
*/
public static final int SECONDARY = 1;
/**
* This constant is a strength value which indicates that tertiary,
* secondary, and primary differences will be considered during sorting.
* An example of a tertiary difference is capitalization of a given letter.
* This is the default value for the strength setting.
*/
public static final int TERTIARY = 2;
/**
* This constant is a strength value which indicates that any difference
* at all between character values are considered significant.
*/
public static final int IDENTICAL = 3;
/**
* This constant indicates that accented characters won't be decomposed
* when performing comparisons. This will yield the fastest results, but
* will only work correctly in call cases for languages which do not
* use accents such as English.
*/
public static final int NO_DECOMPOSITION = 0;
/**
* This constant indicates that only characters which are canonical variants
* in Unicode 2.0 will be decomposed prior to performing comparisons. This
* will cause accented languages to be sorted correctly. This is the
* default decomposition value.
*/
public static final int CANONICAL_DECOMPOSITION = 1;
/**
* This constant indicates that both canonical variants and compatibility
* variants in Unicode 2.0 will be decomposed prior to performing
* comparisons. This is the slowest mode, but is required to get the
* correct sorting for certain languages with certain special formats.
*/
public static final int FULL_DECOMPOSITION = 2;
/**
* This method initializes a new instance of <code>Collator</code> to have
* the default strength (TERTIARY) and decomposition
* (CANONICAL_DECOMPOSITION) settings. This constructor is protected and
* is for use by subclasses only. Non-subclass callers should use the
* static <code>getInstance()</code> methods of this class to instantiate
* <code>Collation</code> objects for the desired locale.
*/
protected Collator ()
{
strength = TERTIARY;
decmp = CANONICAL_DECOMPOSITION;
}
/**
* This method compares the two <code>String</code>'s and returns an
* integer indicating whether or not the first argument is less than,
* equal to, or greater than the second argument. The comparison is
* performed according to the rules of the locale for this
* <code>Collator</code> and the strength and decomposition rules in
* effect.
*
* @param source The first object to compare
* @param target The second object to compare
*
* @return A negative integer if str1 < str2, 0 if str1 == str2, or
* a positive integer if str1 > str2.
*/
public abstract int compare (String source, String target);
/**
* This method compares the two <code>Object</code>'s and returns an
* integer indicating whether or not the first argument is less than,
* equal to, or greater than the second argument. These two objects
* must be <code>String</code>'s or an exception will be thrown.
*
* @param o1 The first object to compare
* @param o2 The second object to compare
*
* @return A negative integer if obj1 < obj2, 0 if obj1 == obj2, or
* a positive integer if obj1 > obj2.
*
* @exception ClassCastException If the arguments are not instances
* of <code>String</code>.
*/
public int compare (Object o1, Object o2)
{
return compare ((String) o1, (String) o2);
}
/**
* This method tests the specified object for equality against this
* object. This will be true if and only if the following conditions are
* met:
* <ul>
* <li>The specified object is not <code>null</code>.</li>
* <li>The specified object is an instance of <code>Collator</code>.</li>
* <li>The specified object has the same strength and decomposition
* settings as this object.</li>
* </ul>
*
* @param obj The <code>Object</code> to test for equality against
* this object.
*
* @return <code>true</code> if the specified object is equal to
* this one, <code>false</code> otherwise.
*/
public boolean equals (Object obj)
{
if (! (obj instanceof Collator))
return false;
Collator c = (Collator) obj;
return decmp == c.decmp && strength == c.strength;
}
/**
* This method tests whether the specified <code>String</code>'s are equal
* according to the collation rules for the locale of this object and
* the current strength and decomposition settings.
*
* @param source The first <code>String</code> to compare
* @param target The second <code>String</code> to compare
*
* @return <code>true</code> if the two strings are equal,
* <code>false</code> otherwise.
*/
public boolean equals (String source, String target)
{
return compare (source, target) == 0;
}
/**
* This method returns a copy of this <code>Collator</code> object.
*
* @return A duplicate of this object.
*/
public Object clone ()
{
try
{
return super.clone ();
}
catch (CloneNotSupportedException _)
{
return null;
}
}
/**
* This method returns an array of <code>Locale</code> objects which is
* the list of locales for which <code>Collator</code> objects exist.
*
* @return The list of locales for which <code>Collator</code>'s exist.
*/
public static synchronized Locale[] getAvailableLocales ()
{
return LocaleHelper.getCollatorLocales();
}
/**
* This method transforms the specified <code>String</code> into a
* <code>CollationKey</code> for faster comparisons. This is useful when
* comparisons against a string might be performed multiple times, such
* as during a sort operation.
*
* @param source The <code>String</code> to convert.
*
* @return A <code>CollationKey</code> for the specified <code>String</code>.
*/
public abstract CollationKey getCollationKey (String source);
/**
* This method returns the current decomposition setting for this
* object. This * will be one of NO_DECOMPOSITION,
* CANONICAL_DECOMPOSITION, or * FULL_DECOMPOSITION. See the
* documentation for those constants for an * explanation of this
* setting.
*
* @return The current decomposition setting.
*/
public synchronized int getDecomposition ()
{
return decmp;
}
/**
* This method returns an instance of <code>Collator</code> for the
* default locale.
*
* @return A <code>Collator</code> for the default locale.
*/
public static Collator getInstance ()
{
return getInstance (Locale.getDefault());
}
/**
* This method returns an instance of <code>Collator</code> for the
* specified locale. If no <code>Collator</code> exists for the desired
* locale, the fallback procedure described in
* {@link java.util.spi.LocaleServiceProvider} is invoked.
*
* @param loc The desired locale to load a <code>Collator</code> for.
*
* @return A <code>Collator</code> for the requested locale
*/
public static Collator getInstance (Locale loc)
{
String pattern;
try
{
ResourceBundle res =
ResourceBundle.getBundle("gnu.java.locale.LocaleInformation",
loc, ClassLoader.getSystemClassLoader());
return new RuleBasedCollator(res.getString("collation_rules"));
}
catch (MissingResourceException x)
{
/* This means runtime support for the locale
* is not available, so we check providers. */
}
catch (ParseException x)
{
throw (InternalError)new InternalError().initCause(x);
}
for (CollatorProvider p : ServiceLoader.load(CollatorProvider.class))
{
for (Locale l : p.getAvailableLocales())
{
if (l.equals(loc))
{
Collator c = p.getInstance(loc);
if (c != null)
return c;
break;
}
}
}
if (loc.equals(Locale.ROOT))
{
try
{
return new RuleBasedCollator("<0<1<2<3<4<5<6<7<8<9<A,a<b,B<c," +
"C<d,D<e,E<f,F<g,G<h,H<i,I<j,J<k,K" +
"<l,L<m,M<n,N<o,O<p,P<q,Q<r,R<s,S<t,"+
"T<u,U<v,V<w,W<x,X<y,Y<z,Z");
}
catch (ParseException x)
{
throw (InternalError)new InternalError().initCause(x);
}
}
return getInstance(LocaleHelper.getFallbackLocale(loc));
}
/**
* This method returns the current strength setting for this object. This
* will be one of PRIMARY, SECONDARY, TERTIARY, or IDENTICAL. See the
* documentation for those constants for an explanation of this setting.
*
* @return The current strength setting.
*/
public synchronized int getStrength ()
{
return strength;
}
/**
* This method returns a hash code value for this object.
*
* @return A hash value for this object.
*/
public abstract int hashCode ();
/**
* This method sets the decomposition setting for this object to the
* specified value. This must be one of NO_DECOMPOSITION,
* CANONICAL_DECOMPOSITION, or FULL_DECOMPOSITION. Otherwise an
* exception will be thrown. See the documentation for those
* contants for an explanation of this setting.
*
* @param mode The new decomposition setting.
*
* @exception IllegalArgumentException If the requested
* decomposition setting is not valid.
*/
public synchronized void setDecomposition (int mode)
{
if (mode != NO_DECOMPOSITION
&& mode != CANONICAL_DECOMPOSITION
&& mode != FULL_DECOMPOSITION)
throw new IllegalArgumentException ();
decmp = mode;
}
/**
* This method sets the strength setting for this object to the specified
* value. This must be one of PRIMARY, SECONDARY, TERTIARY, or IDENTICAL.
* Otherwise an exception is thrown. See the documentation for these
* constants for an explanation of this setting.
*
* @param strength The new strength setting.
*
* @exception IllegalArgumentException If the requested strength
* setting value is not valid.
*/
public synchronized void setStrength (int strength)
{
if (strength != PRIMARY && strength != SECONDARY
&& strength != TERTIARY && strength != IDENTICAL)
throw new IllegalArgumentException ();
this.strength = strength;
}
// Decompose a single character and append results to the buffer.
// FIXME: for libgcj this is a native method which handles
// decomposition. For Classpath, for now, it does nothing.
/*
final void decomposeCharacter (char c, StringBuffer buf)
{
buf.append (c);
}
*/
/**
* This is the current collation decomposition setting.
*/
int decmp;
/**
* This is the current collation strength setting.
*/
int strength;
}
| taciano-perez/JamVM-PH | src/classpath/java/text/Collator.java | Java | gpl-2.0 | 14,820 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Session
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Abstract.php 24594 2012-01-05 21:27:01Z matthew $
* @since Preview Release 0.2
*/
/**
* Zend_Session_Abstract
*
* @category Zend
* @package Zend_Session
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Session_Abstract
{
/**
* Whether or not session permits writing (modification of $_SESSION[])
*
* @var bool
*/
protected static $_writable = false;
/**
* Whether or not session permits reading (reading data in $_SESSION[])
*
* @var bool
*/
protected static $_readable = false;
/**
* Since expiring data is handled at startup to avoid __destruct difficulties,
* the data that will be expiring at end of this request is held here
*
* @var array
*/
protected static $_expiringData = array();
/**
* Error message thrown when an action requires modification,
* but current Zend_Session has been marked as read-only.
*/
const _THROW_NOT_WRITABLE_MSG = 'Zend_Session is currently marked as read-only.';
/**
* Error message thrown when an action requires reading session data,
* but current Zend_Session is not marked as readable.
*/
const _THROW_NOT_READABLE_MSG = 'Zend_Session is not marked as readable.';
/**
* namespaceIsset() - check to see if a namespace or a variable within a namespace is set
*
* @param string $namespace
* @param string $name
* @return bool
*/
protected static function _namespaceIsset($namespace, $name = null)
{
if (self::$_readable === false) {
/**
* @see Zend_Session_Exception
*/
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception(self::_THROW_NOT_READABLE_MSG);
}
if ($name === null) {
return ( isset($_SESSION[$namespace]) || isset(self::$_expiringData[$namespace]) );
} else {
return ( isset($_SESSION[$namespace][$name]) || isset(self::$_expiringData[$namespace][$name]) );
}
}
/**
* namespaceUnset() - unset a namespace or a variable within a namespace
*
* @param string $namespace
* @param string $name
* @throws Zend_Session_Exception
* @return void
*/
protected static function _namespaceUnset($namespace, $name = null)
{
if (self::$_writable === false) {
/**
* @see Zend_Session_Exception
*/
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception(self::_THROW_NOT_WRITABLE_MSG);
}
$name = (string) $name;
// check to see if the api wanted to remove a var from a namespace or a namespace
if ($name === '') {
unset($_SESSION[$namespace]);
unset(self::$_expiringData[$namespace]);
} else {
unset($_SESSION[$namespace][$name]);
unset(self::$_expiringData[$namespace]);
}
// if we remove the last value, remove namespace.
if (empty($_SESSION[$namespace])) {
unset($_SESSION[$namespace]);
}
}
/**
* namespaceGet() - Get $name variable from $namespace, returning by reference.
*
* @param string $namespace
* @param string $name
* @return mixed
*/
protected static function & _namespaceGet($namespace, $name = null)
{
if (self::$_readable === false) {
/**
* @see Zend_Session_Exception
*/
require_once 'Zend/Session/Exception.php';
throw new Zend_Session_Exception(self::_THROW_NOT_READABLE_MSG);
}
if ($name === null) {
if (isset($_SESSION[$namespace])) { // check session first for data requested
return $_SESSION[$namespace];
} elseif (isset(self::$_expiringData[$namespace])) { // check expiring data for data reqeusted
return self::$_expiringData[$namespace];
} else {
return $_SESSION[$namespace]; // satisfy return by reference
}
} else {
if (isset($_SESSION[$namespace][$name])) { // check session first
return $_SESSION[$namespace][$name];
} elseif (isset(self::$_expiringData[$namespace][$name])) { // check expiring data
return self::$_expiringData[$namespace][$name];
} else {
return $_SESSION[$namespace][$name]; // satisfy return by reference
}
}
}
/**
* namespaceGetAll() - Get an array containing $namespace, including expiring data.
*
* @param string $namespace
* @param string $name
* @return mixed
*/
protected static function _namespaceGetAll($namespace)
{
$currentData = (isset($_SESSION[$namespace]) && is_array($_SESSION[$namespace])) ?
$_SESSION[$namespace] : array();
$expiringData = (isset(self::$_expiringData[$namespace]) && is_array(self::$_expiringData[$namespace])) ?
self::$_expiringData[$namespace] : array();
return array_merge($currentData, $expiringData);
}
}
| MehdyOueriemi/Relais | wp-content/plugins/zend-framework/Zend/Session/Abstract.php | PHP | gpl-2.0 | 6,044 |
# -*- test-case-name: twisted.pb.test.test_promise -*-
from twisted.python import util, failure
from twisted.internet import defer
id = util.unsignedID
EVENTUAL, FULFILLED, BROKEN = range(3)
class Promise:
"""I am a promise of a future result. I am a lot like a Deferred, except
that my promised result is usually an instance. I make it possible to
schedule method invocations on this future instance, returning Promises
for the results.
Promises are always in one of three states: Eventual, Fulfilled, and
Broken. (see http://www.erights.org/elib/concurrency/refmech.html for a
pretty picture). They start as Eventual, meaning we do not yet know
whether they will resolve or not. In this state, method invocations are
queued. Eventually the Promise will be 'resolved' into either the
Fulfilled or the Broken state. Fulfilled means that the promise contains
a live object to which methods can be dispatched synchronously. Broken
promises are incapable of invoking methods: they all result in Failure.
Method invocation is always asynchronous: it always returns a Promise.
"""
# all our internal methods are private, to avoid colliding with normal
# method names that users may invoke on our eventual target.
_state = EVENTUAL
_resolution = None
def __init__(self, d):
self._watchers = []
self._pendingMethods = []
d.addCallbacks(self._ready, self._broken)
def _wait_for_resolution(self):
if self._state == EVENTUAL:
d = defer.Deferred()
self._watchers.append(d)
else:
d = defer.succeed(self._resolution)
return d
def _ready(self, resolution):
self._resolution = resolution
self._state = FULFILLED
self._run_methods()
def _broken(self, f):
self._resolution = f
self._state = BROKEN
self._run_methods()
def _invoke_method(self, name, args, kwargs):
if isinstance(self._resolution, failure.Failure):
return self._resolution
method = getattr(self._resolution, name)
res = method(*args, **kwargs)
return res
def _run_methods(self):
for (name, args, kwargs, result_deferred) in self._pendingMethods:
d = defer.maybeDeferred(self._invoke_method, name, args, kwargs)
d.addBoth(result_deferred.callback)
del self._pendingMethods
for d in self._watchers:
d.callback(self._resolution)
del self._watchers
def __repr__(self):
return "<Promise %#x>" % id(self)
def __getattr__(self, name):
if name.startswith("__"):
raise AttributeError
def newmethod(*args, **kwargs):
return self._add_method(name, args, kwargs)
return newmethod
def _add_method(self, name, args, kwargs):
if self._state == EVENTUAL:
d = defer.Deferred()
self._pendingMethods.append((name, args, kwargs, d))
else:
d = defer.maybeDeferred(self._invoke_method, name, args, kwargs)
return Promise(d)
def when(p):
"""Turn a Promise into a Deferred that will fire with the enclosed object
when it is ready. Use this when you actually need to schedule something
to happen in a synchronous fashion. Most of the time, you can just invoke
methods on the Promise as if it were immediately available."""
assert isinstance(p, Promise)
return p._wait_for_resolution()
| tquilian/exelearningTest | twisted/pb/promise.py | Python | gpl-2.0 | 3,532 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_GiftMessage
* @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Product attribute for allowing of gift messages per item
*
* @deprecated after 1.4.2.0
*
* @category Mage
* @package Mage_GiftMessage
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_GiftMessage_Model_Entity_Attribute_Backend_Boolean_Config extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
/**
* Set attribute default value if value empty
*
* @param Varien_Object $object
*/
public function afterLoad($object)
{
if(!$object->hasData($this->getAttribute()->getAttributeCode())) {
$object->setData($this->getAttribute()->getAttributeCode(), $this->getDefaultValue());
}
}
/**
* Set attribute default value if value empty
*
* @param Varien_Object $object
*/
public function beforeSave($object)
{
if($object->hasData($this->getAttribute()->getAttributeCode())
&& $object->getData($this->getAttribute()->getAttributeCode()) == $this->getDefaultValue()) {
$object->unsData($this->getAttribute()->getAttributeCode());
}
}
/**
* Validate attribute data
*
* @param Varien_Object $object
* @return boolean
*/
public function validate($object)
{
// all attribute's options
$optionsAllowed = array('0', '1', '2');
$value = $object->getData($this->getAttribute()->getAttributeCode());
return in_array($value, $optionsAllowed)? true : false;
}
}
| dvh11er/mage-cheatcode | magento/app/code/core/Mage/GiftMessage/Model/Entity/Attribute/Backend/Boolean/Config.php | PHP | gpl-2.0 | 2,455 |
package com.temenos.interaction.core.rim;
/*
* #%L
* interaction-core
* %%
* Copyright (C) 2012 - 2013 Temenos Holdings N.V.
* %%
* 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 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/>.
* #L%
*/
import java.util.Collection;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.temenos.interaction.core.hypermedia.ResourceState;
public interface ResourceInteractionModel {
/**
* The current application state.
* @return
*/
public ResourceState getCurrentState();
/**
* The path to this resource
* @return
*/
public String getResourcePath();
/**
* The path to this resource with all ancestors
* @return
*/
public String getFQResourcePath();
public ResourceInteractionModel getParent();
public Collection<ResourceInteractionModel> getChildren();
@OPTIONS
public Response options( @Context HttpHeaders headers, @PathParam("id") String id, @Context UriInfo uriInfo );
}
| ritumalhotra8/IRIS | interaction-core/src/main/java/com/temenos/interaction/core/rim/ResourceInteractionModel.java | Java | agpl-3.0 | 1,694 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.inject.client.multibindings;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* A very simple multimap implementation that supports conversion to unmodifiable map.
*/
class SimpleMultimap<K, V> extends LinkedHashMap<K, Set<V>> {
public void putItem(K key, V value) {
Set<V> set = get(key);
if (set == null) {
set = new LinkedHashSet<V>();
put(key, set);
}
set.add(value);
}
public Map<K, Set<V>> toUnmodifiable() {
for (Entry<K, Set<V>> entry : entrySet()) {
entry.setValue(Collections.unmodifiableSet(entry.getValue()));
}
return Collections.unmodifiableMap(this);
}
}
| mehdikwa/google-gin | src/com/google/gwt/inject/client/multibindings/SimpleMultimap.java | Java | apache-2.0 | 1,365 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Operator --x uses [[Default Value]]
*
* @path ch11/11.4/11.4.5/S11.4.5_A2.2_T1.js
* @description If Type(value) is Object, evaluate ToPrimitive(value, Number)
*/
//CHECK#1
var object = {valueOf: function() {return 1}};
if (--object !== 1 - 1) {
$ERROR('#1: var object = {valueOf: function() {return 1}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#1: var object = {valueOf: function() {return 1}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#2
var object = {valueOf: function() {return 1}, toString: function() {return 0}};
if (--object !== 1 - 1) {
$ERROR('#2: var object = {valueOf: function() {return 1}, toString: function() {return 0}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#2: var object = {valueOf: function() {return 1}, toString: function() {return 0}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#3
var object = {valueOf: function() {return 1}, toString: function() {return {}}};
if (--object !== 1 - 1) {
$ERROR('#3: var object = {valueOf: function() {return 1}, toString: function() {return {}}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#3: var object = {valueOf: function() {return 1}, toString: function() {return {}}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#4
try {
var object = {valueOf: function() {return 1}, toString: function() {throw "error"}};
if (--object !== 1 - 1) {
$ERROR('#4.1: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#4.1: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
}
catch (e) {
if (e === "error") {
$ERROR('#4.2: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object not throw "error"');
} else {
$ERROR('#4.3: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object not throw Error. Actual: ' + (e));
}
}
//CHECK#5
var object = {toString: function() {return 1}};
if (--object !== 1 - 1) {
$ERROR('#5.1: var object = {toString: function() {return 1}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#5.2: var object = {toString: function() {return 1}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#6
var object = {valueOf: function() {return {}}, toString: function() {return 1}}
if (--object !== 1 - 1) {
$ERROR('#6.1: var object = {valueOf: function() {return {}}, toString: function() {return 1}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#6.2: var object = {valueOf: function() {return {}}, toString: function() {return 1}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#7
try {
var object = {valueOf: function() {throw "error"}, toString: function() {return 1}};
--object;
$ERROR('#7.1: var object = {valueOf: function() {throw "error"}, toString: function() {return 1}}; --object throw "error". Actual: ' + (--object));
}
catch (e) {
if (e !== "error") {
$ERROR('#7.2: var object = {valueOf: function() {throw "error"}, toString: function() {return 1}}; --object throw "error". Actual: ' + (e));
}
}
//CHECK#8
try {
var object = {valueOf: function() {return {}}, toString: function() {return {}}};
--object;
$ERROR('#8.1: var object = {valueOf: function() {return {}}, toString: function() {return {}}}; --object throw TypeError. Actual: ' + (--object));
}
catch (e) {
if ((e instanceof TypeError) !== true) {
$ERROR('#8.2: var object = {valueOf: function() {return {}}, toString: function() {return {}}}; --object throw TypeError. Actual: ' + (e));
}
}
| hippich/typescript | tests/Fidelity/test262/suite/ch11/11.4/11.4.5/S11.4.5_A2.2_T1.js | JavaScript | apache-2.0 | 4,094 |
//////////////////////////////////////////////////////////////////////
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (C) 2003 Microsoft Corporation. All rights reserved.
//
// PreComp.cpp
//
// Stub for vc precompiled header.
//
//////////////////////////////////////////////////////////////////////
#include "globals.h"
| tavultesoft/keymanweb | windows/src/support/tsf-tip-standalone-test/precomp.cpp | C++ | apache-2.0 | 541 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* The production x *= y is the same as the production x = x * y
*
* @path ch11/11.13/11.13.2/S11.13.2_A4.1_T2.6.js
* @description Type(x) is different from Type(y) and both types vary between primitive String (primitive or object) and Undefined
*/
//CHECK#1
x = "1";
x *= undefined;
if (isNaN(x) !== true) {
$ERROR('#1: x = "1"; x *= undefined; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#2
x = undefined;
x *= "1";
if (isNaN(x) !== true) {
$ERROR('#2: x = undefined; x *= "1"; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#3
x = new String("1");
x *= undefined;
if (isNaN(x) !== true) {
$ERROR('#3: x = new String("1"); x *= undefined; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#4
x = undefined;
x *= new String("1");
if (isNaN(x) !== true) {
$ERROR('#4: x = undefined; x *= new String("1"); x === Not-a-Number. Actual: ' + (x));
}
| hippich/typescript | tests/Fidelity/test262/suite/ch11/11.13/11.13.2/S11.13.2_A4.1_T2.6.js | JavaScript | apache-2.0 | 999 |
/*
* Copyright (C) 2013 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tests;
import com.google.auto.factory.AutoFactory;
import com.google.auto.factory.Provided;
/**
* @author Gregory Kick
*/
final class MixedDepsImplementingInterfaces {
@AutoFactory(implementing = {FromInt.class, MarkerA.class})
MixedDepsImplementingInterfaces(@Provided String s, int i) {}
@AutoFactory(implementing = {FromObject.class, MarkerB.class})
MixedDepsImplementingInterfaces(Object o) {}
interface FromInt {
MixedDepsImplementingInterfaces fromInt(int i);
}
interface FromObject {
MixedDepsImplementingInterfaces fromObject(Object o);
}
interface MarkerA {}
interface MarkerB {}
}
| gk5885/auto | factory/src/test/resources/good/MixedDepsImplementingInterfaces.java | Java | apache-2.0 | 1,238 |
// =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.text.token;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.util.AttributeSource;
import com.twitter.common.text.example.TokenizerUsageExample;
import com.twitter.common.text.token.attribute.CharSequenceTermAttribute;
import com.twitter.common.text.token.attribute.TokenType;
import com.twitter.common.text.token.attribute.TokenTypeAttribute;
/**
* Abstraction to enumerate a sequence of tokens. This class represents the central abstraction in
* Twitter's text processing library, and is similar to Lucene's TokenStream, with the following
* exceptions:
*
* <ul>
* <li>This class assumes that the input text is a {@link CharSequence}.
* <li>Calls support chaining.
* <li>Instances are reusable.
* </ul>
*
* For an annotated example of how this class is used in practice, refer to
* {@link TokenizerUsageExample}.
*/
public abstract class TwitterTokenStream extends TokenStream {
private final CharSequenceTermAttribute termAttribute = addAttribute(CharSequenceTermAttribute.class);
private final TokenTypeAttribute typeAttribute = addAttribute(TokenTypeAttribute.class);
/**
* Constructs a {@code TwitterTokenStream} using the default attribute factory.
*/
public TwitterTokenStream() {
super();
}
/**
* Constructs a {@code TwitterTokenStream} using the supplied {@code AttributeFactory} for creating new
* {@code Attribute} instances.
*
* @param factory attribute factory
*/
protected TwitterTokenStream(AttributeSource.AttributeFactory factory) {
super(factory);
}
/**
* Constructs a {@code TwitterTokenStream} that uses the same attributes as the supplied one.
*
* @param input attribute source
*/
protected TwitterTokenStream(AttributeSource input) {
super(input);
}
/**
* Consumers call this method to advance the stream to the next token.
*
* @return false for end of stream; true otherwise
*/
public abstract boolean incrementToken();
/**
* Resets this {@code TwitterTokenStream} (and also downstream tokens if they exist) to parse a new
* input.
*/
public void reset(CharSequence input) {
updateInputCharSequence(input);
reset();
};
/**
* Subclasses should implement reset() to reinitiate the processing.
* Input CharSequence is available as inputCharSequence().
*/
public abstract void reset();
/**
* Converts this token stream into a list of {@code Strings}.
*
* @return the contents of the token stream as a list of {@code Strings}.
*/
public List<String> toStringList() {
List<String> tokens = Lists.newArrayList();
while (incrementToken()) {
tokens.add(term().toString());
}
return tokens;
}
/**
* Searches and returns an instance of a specified class in this TwitterTokenStream chain.
*
* @param cls class to search for
* @return instance of the class {@code cls} if found or {@code null} if not found
*/
public <T extends TwitterTokenStream> T getInstanceOf(Class<T> cls) {
Preconditions.checkNotNull(cls);
if (cls.isInstance(this)) {
return cls.cast(this);
}
return null;
}
/**
* Returns the offset of the current token.
*
* @return offset of the current token.
*/
public int offset() {
return termAttribute.getOffset();
}
/**
* Returns the length of the current token.
*
* @return length of the current token.
*/
public int length() {
return termAttribute.getLength();
}
/**
* Returns the {@code CharSequence} of the current token.
*
* @return {@code CharSequence} of the current token
*/
public CharSequence term() {
return termAttribute.getTermCharSequence();
}
/**
* Returns the input {@code CharSequence}.
*
* @return input {@code CharSequence}
*/
public CharSequence inputCharSequence() {
return termAttribute.getCharSequence();
}
/**
* Returns the type of the current token.
*
* @return type of the current token.
*/
public TokenType type() {
return typeAttribute.getType();
}
/**
* Sets the input {@code CharSequence}.
*
* @param inputCharSequence {@code CharSequence} analyzed by this
* {@code TwitterTokenStream}
*/
protected void updateInputCharSequence(CharSequence inputCharSequence) {
termAttribute.setCharSequence(inputCharSequence);
}
/**
* Updates the offset and length of the current token.
*
* @param offset new offset
* @param length new length
*/
protected void updateOffsetAndLength(int offset, int length) {
termAttribute.setOffset(offset);
termAttribute.setLength(length);
}
/**
* Updates the type of the current token.
*
* @param type new type
*/
protected void updateType(TokenType type) {
typeAttribute.setType(type);
}
@Override
public boolean equals(Object target) {
// Lucene's AttributeSource.equals() returns true if this has the same
// set of attributes as the target one. Let's make it more strict.
return this == target;
}
@Override
public int hashCode() {
return System.identityHashCode(this);
}
}
| abel-von/commons | src/java/com/twitter/common/text/token/TwitterTokenStream.java | Java | apache-2.0 | 6,183 |
/*
* Copyright 2014 NAVER Corp.
*
* 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.navercorp.pinpoint.rpc.stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Author Taejin Koo
*/
public class LoggingStreamChannelStateChangeEventHandler implements StreamChannelStateChangeEventHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void eventPerformed(StreamChannel streamChannel, StreamChannelStateCode updatedStateCode) throws Exception {
logger.info("eventPerformed streamChannel:{}, stateCode:{}", streamChannel, updatedStateCode);
}
@Override
public void exceptionCaught(StreamChannel streamChannel, StreamChannelStateCode updatedStateCode, Throwable e) {
logger.warn("exceptionCaught message:{}, streamChannel:{}, stateCode:{}", e.getMessage(), streamChannel, updatedStateCode, e);
}
}
| dawidmalina/pinpoint | rpc/src/main/java/com/navercorp/pinpoint/rpc/stream/LoggingStreamChannelStateChangeEventHandler.java | Java | apache-2.0 | 1,432 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.datafrominternet;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import com.example.android.datafrominternet.utilities.NetworkUtils;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private EditText mSearchBoxEditText;
private TextView mUrlDisplayTextView;
private TextView mSearchResultsTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSearchBoxEditText = (EditText) findViewById(R.id.et_search_box);
mUrlDisplayTextView = (TextView) findViewById(R.id.tv_url_display);
mSearchResultsTextView = (TextView) findViewById(R.id.tv_github_search_results_json);
}
/**
* This method retrieves the search text from the EditText, constructs
* the URL (using {@link NetworkUtils}) for the github repository you'd like to find, displays
* that URL in a TextView, and finally fires off an AsyncTask to perform the GET request using
* our (not yet created) {@link GithubQueryTask}
*/
private void makeGithubSearchQuery() {
String githubQuery = mSearchBoxEditText.getText().toString();
URL githubSearchUrl = NetworkUtils.buildUrl(githubQuery);
mUrlDisplayTextView.setText(githubSearchUrl.toString());
// TODO (2) Call getResponseFromHttpUrl and display the results in mSearchResultsTextView
// TODO (3) Surround the call to getResponseFromHttpUrl with a try / catch block to catch an IOException
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemThatWasClickedId = item.getItemId();
if (itemThatWasClickedId == R.id.action_search) {
makeGithubSearchQuery();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| bwirgau/androidproject | Lesson02-GitHub-Repo-Search/T02.04-Exercise-ConnectingToTheInternet/app/src/main/java/com/example/android/datafrominternet/MainActivity.java | Java | apache-2.0 | 2,821 |
package org.bouncycastle.cert.selector;
import java.io.IOException;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.util.Pack;
class MSOutlookKeyIdCalculator
{
// This is less than ideal, but it seems to be the best way of supporting this without exposing SHA-1
// as the class is only used to workout the MSOutlook Key ID, you can think of the fact it's SHA-1 as
// a coincidence...
static byte[] calculateKeyId(SubjectPublicKeyInfo info)
{
SHA1Digest dig = new SHA1Digest();
byte[] hash = new byte[dig.getDigestSize()];
byte[] spkiEnc = new byte[0];
try
{
spkiEnc = info.getEncoded(ASN1Encoding.DER);
}
catch (IOException e)
{
return new byte[0];
}
// try the outlook 2010 calculation
dig.update(spkiEnc, 0, spkiEnc.length);
dig.doFinal(hash, 0);
return hash;
}
private static abstract class GeneralDigest
{
private static final int BYTE_LENGTH = 64;
private byte[] xBuf;
private int xBufOff;
private long byteCount;
/**
* Standard constructor
*/
protected GeneralDigest()
{
xBuf = new byte[4];
xBufOff = 0;
}
/**
* Copy constructor. We are using copy constructors in place
* of the Object.clone() interface as this interface is not
* supported by J2ME.
*/
protected GeneralDigest(GeneralDigest t)
{
xBuf = new byte[t.xBuf.length];
copyIn(t);
}
protected void copyIn(GeneralDigest t)
{
System.arraycopy(t.xBuf, 0, xBuf, 0, t.xBuf.length);
xBufOff = t.xBufOff;
byteCount = t.byteCount;
}
public void update(
byte in)
{
xBuf[xBufOff++] = in;
if (xBufOff == xBuf.length)
{
processWord(xBuf, 0);
xBufOff = 0;
}
byteCount++;
}
public void update(
byte[] in,
int inOff,
int len)
{
//
// fill the current word
//
while ((xBufOff != 0) && (len > 0))
{
update(in[inOff]);
inOff++;
len--;
}
//
// process whole words.
//
while (len > xBuf.length)
{
processWord(in, inOff);
inOff += xBuf.length;
len -= xBuf.length;
byteCount += xBuf.length;
}
//
// load in the remainder.
//
while (len > 0)
{
update(in[inOff]);
inOff++;
len--;
}
}
public void finish()
{
long bitLength = (byteCount << 3);
//
// add the pad bytes.
//
update((byte)128);
while (xBufOff != 0)
{
update((byte)0);
}
processLength(bitLength);
processBlock();
}
public void reset()
{
byteCount = 0;
xBufOff = 0;
for (int i = 0; i < xBuf.length; i++)
{
xBuf[i] = 0;
}
}
protected abstract void processWord(byte[] in, int inOff);
protected abstract void processLength(long bitLength);
protected abstract void processBlock();
}
private static class SHA1Digest
extends GeneralDigest
{
private static final int DIGEST_LENGTH = 20;
private int H1, H2, H3, H4, H5;
private int[] X = new int[80];
private int xOff;
/**
* Standard constructor
*/
public SHA1Digest()
{
reset();
}
public String getAlgorithmName()
{
return "SHA-1";
}
public int getDigestSize()
{
return DIGEST_LENGTH;
}
protected void processWord(
byte[] in,
int inOff)
{
// Note: Inlined for performance
// X[xOff] = Pack.bigEndianToInt(in, inOff);
int n = in[ inOff] << 24;
n |= (in[++inOff] & 0xff) << 16;
n |= (in[++inOff] & 0xff) << 8;
n |= (in[++inOff] & 0xff);
X[xOff] = n;
if (++xOff == 16)
{
processBlock();
}
}
protected void processLength(
long bitLength)
{
if (xOff > 14)
{
processBlock();
}
X[14] = (int)(bitLength >>> 32);
X[15] = (int)(bitLength & 0xffffffff);
}
public int doFinal(
byte[] out,
int outOff)
{
finish();
Pack.intToBigEndian(H1, out, outOff);
Pack.intToBigEndian(H2, out, outOff + 4);
Pack.intToBigEndian(H3, out, outOff + 8);
Pack.intToBigEndian(H4, out, outOff + 12);
Pack.intToBigEndian(H5, out, outOff + 16);
reset();
return DIGEST_LENGTH;
}
/**
* reset the chaining variables
*/
public void reset()
{
super.reset();
H1 = 0x67452301;
H2 = 0xefcdab89;
H3 = 0x98badcfe;
H4 = 0x10325476;
H5 = 0xc3d2e1f0;
xOff = 0;
for (int i = 0; i != X.length; i++)
{
X[i] = 0;
}
}
//
// Additive constants
//
private static final int Y1 = 0x5a827999;
private static final int Y2 = 0x6ed9eba1;
private static final int Y3 = 0x8f1bbcdc;
private static final int Y4 = 0xca62c1d6;
private int f(
int u,
int v,
int w)
{
return ((u & v) | ((~u) & w));
}
private int h(
int u,
int v,
int w)
{
return (u ^ v ^ w);
}
private int g(
int u,
int v,
int w)
{
return ((u & v) | (u & w) | (v & w));
}
protected void processBlock()
{
//
// expand 16 word block into 80 word block.
//
for (int i = 16; i < 80; i++)
{
int t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16];
X[i] = t << 1 | t >>> 31;
}
//
// set up working variables.
//
int A = H1;
int B = H2;
int C = H3;
int D = H4;
int E = H5;
//
// round 1
//
int idx = 0;
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + f(B, C, D) + E + X[idx++] + Y1
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + f(B, C, D) + X[idx++] + Y1;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + f(A, B, C) + X[idx++] + Y1;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + f(E, A, B) + X[idx++] + Y1;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + f(D, E, A) + X[idx++] + Y1;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + f(C, D, E) + X[idx++] + Y1;
C = C << 30 | C >>> 2;
}
//
// round 2
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + h(B, C, D) + E + X[idx++] + Y2
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + h(B, C, D) + X[idx++] + Y2;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + h(A, B, C) + X[idx++] + Y2;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + h(E, A, B) + X[idx++] + Y2;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + h(D, E, A) + X[idx++] + Y2;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + h(C, D, E) + X[idx++] + Y2;
C = C << 30 | C >>> 2;
}
//
// round 3
//
for (int j = 0; j < 4; j++)
{
// E = rotateLeft(A, 5) + g(B, C, D) + E + X[idx++] + Y3
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + g(B, C, D) + X[idx++] + Y3;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + g(A, B, C) + X[idx++] + Y3;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + g(E, A, B) + X[idx++] + Y3;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + g(D, E, A) + X[idx++] + Y3;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + g(C, D, E) + X[idx++] + Y3;
C = C << 30 | C >>> 2;
}
//
// round 4
//
for (int j = 0; j <= 3; j++)
{
// E = rotateLeft(A, 5) + h(B, C, D) + E + X[idx++] + Y4
// B = rotateLeft(B, 30)
E += (A << 5 | A >>> 27) + h(B, C, D) + X[idx++] + Y4;
B = B << 30 | B >>> 2;
D += (E << 5 | E >>> 27) + h(A, B, C) + X[idx++] + Y4;
A = A << 30 | A >>> 2;
C += (D << 5 | D >>> 27) + h(E, A, B) + X[idx++] + Y4;
E = E << 30 | E >>> 2;
B += (C << 5 | C >>> 27) + h(D, E, A) + X[idx++] + Y4;
D = D << 30 | D >>> 2;
A += (B << 5 | B >>> 27) + h(C, D, E) + X[idx++] + Y4;
C = C << 30 | C >>> 2;
}
H1 += A;
H2 += B;
H3 += C;
H4 += D;
H5 += E;
//
// reset start of the buffer.
//
xOff = 0;
for (int i = 0; i < 16; i++)
{
X[i] = 0;
}
}
}
}
| thedrummeraki/Aki-SSL | src/org/bouncycastle/cert/selector/MSOutlookKeyIdCalculator.java | Java | apache-2.0 | 10,705 |
/* ------------------------------------------------------------------
* Copyright (C) 1998-2009 PacketVideo
*
* 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.
* -------------------------------------------------------------------
*/
/****************************************************************************************
Portions of this file are derived from the following 3GPP standard:
3GPP TS 26.173
ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec
Available from http://www.3gpp.org
(C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
Permission to distribute, modify and use this file under the standard license
terms listed above has been obtained from the copyright holder.
****************************************************************************************/
/*
------------------------------------------------------------------------------
Filename: pit_shrp.cpp
Date: 05/08/2007
------------------------------------------------------------------------------
REVISION HISTORY
Description:
------------------------------------------------------------------------------
INPUT AND OUTPUT DEFINITIONS
int16 * x, in/out: impulse response (or algebraic code)
int16 pit_lag, input : pitch lag
int16 sharp, input : pitch sharpening factor (Q15)
int16 L_subfr input : subframe size
------------------------------------------------------------------------------
FUNCTION DESCRIPTION
Performs Pitch sharpening routine
------------------------------------------------------------------------------
REQUIREMENTS
------------------------------------------------------------------------------
REFERENCES
------------------------------------------------------------------------------
PSEUDO-CODE
------------------------------------------------------------------------------
*/
/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include "pv_amr_wb_type_defs.h"
#include "pvamrwbdecoder_basic_op.h"
#include "pvamrwbdecoder_acelp.h"
/*----------------------------------------------------------------------------
; MACROS
; Define module specific macros here
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; DEFINES
; Include all pre-processor statements here. Include conditional
; compile variables also.
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; LOCAL FUNCTION DEFINITIONS
; Function Prototype declaration
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; LOCAL STORE/BUFFER/POINTER DEFINITIONS
; Variable declaration - defined here and used outside this module
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; EXTERNAL FUNCTION REFERENCES
; Declare functions defined elsewhere and referenced in this module
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
; Declare variables used in this module but defined elsewhere
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
; FUNCTION CODE
----------------------------------------------------------------------------*/
void Pit_shrp(
int16 * x, /* in/out: impulse response (or algebraic code) */
int16 pit_lag, /* input : pitch lag */
int16 sharp, /* input : pitch sharpening factor (Q15) */
int16 L_subfr /* input : subframe size */
)
{
int16 i;
int32 L_tmp;
for (i = pit_lag; i < L_subfr; i++)
{
L_tmp = mac_16by16_to_int32((int32)x[i] << 16, x[i - pit_lag], sharp);
x[i] = amr_wb_round(L_tmp);
}
return;
}
| dAck2cC2/m3e | src/frameworks/av/media/libstagefright/codecs/amrwb/src/pit_shrp.cpp | C++ | apache-2.0 | 4,898 |
package org.apache.lucene.analysis.util;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.ServiceConfigurationError;
import org.apache.lucene.util.SPIClassIterator;
/**
* Helper class for loading named SPIs from classpath (e.g. Tokenizers, TokenStreams).
* @lucene.internal
*/
final class AnalysisSPILoader<S extends AbstractAnalysisFactory> {
private volatile Map<String,Class<? extends S>> services = Collections.emptyMap();
private final Class<S> clazz;
private final String[] suffixes;
public AnalysisSPILoader(Class<S> clazz) {
this(clazz, new String[] { clazz.getSimpleName() });
}
public AnalysisSPILoader(Class<S> clazz, ClassLoader loader) {
this(clazz, new String[] { clazz.getSimpleName() }, loader);
}
public AnalysisSPILoader(Class<S> clazz, String[] suffixes) {
this(clazz, suffixes, Thread.currentThread().getContextClassLoader());
}
public AnalysisSPILoader(Class<S> clazz, String[] suffixes, ClassLoader classloader) {
this.clazz = clazz;
this.suffixes = suffixes;
// if clazz' classloader is not a parent of the given one, we scan clazz's classloader, too:
final ClassLoader clazzClassloader = clazz.getClassLoader();
if (clazzClassloader != null && !SPIClassIterator.isParentClassLoader(clazzClassloader, classloader)) {
reload(clazzClassloader);
}
reload(classloader);
}
/**
* Reloads the internal SPI list from the given {@link ClassLoader}.
* Changes to the service list are visible after the method ends, all
* iterators (e.g., from {@link #availableServices()},...) stay consistent.
*
* <p><b>NOTE:</b> Only new service providers are added, existing ones are
* never removed or replaced.
*
* <p><em>This method is expensive and should only be called for discovery
* of new service providers on the given classpath/classloader!</em>
*/
public synchronized void reload(ClassLoader classloader) {
final LinkedHashMap<String,Class<? extends S>> services =
new LinkedHashMap<>(this.services);
final SPIClassIterator<S> loader = SPIClassIterator.get(clazz, classloader);
while (loader.hasNext()) {
final Class<? extends S> service = loader.next();
final String clazzName = service.getSimpleName();
String name = null;
for (String suffix : suffixes) {
if (clazzName.endsWith(suffix)) {
name = clazzName.substring(0, clazzName.length() - suffix.length()).toLowerCase(Locale.ROOT);
break;
}
}
if (name == null) {
throw new ServiceConfigurationError("The class name " + service.getName() +
" has wrong suffix, allowed are: " + Arrays.toString(suffixes));
}
// only add the first one for each name, later services will be ignored
// this allows to place services before others in classpath to make
// them used instead of others
//
// TODO: Should we disallow duplicate names here?
// Allowing it may get confusing on collisions, as different packages
// could contain same factory class, which is a naming bug!
// When changing this be careful to allow reload()!
if (!services.containsKey(name)) {
services.put(name, service);
}
}
this.services = Collections.unmodifiableMap(services);
}
public S newInstance(String name, Map<String,String> args) {
final Class<? extends S> service = lookupClass(name);
try {
return service.getConstructor(Map.class).newInstance(args);
} catch (Exception e) {
throw new IllegalArgumentException("SPI class of type "+clazz.getName()+" with name '"+name+"' cannot be instantiated. " +
"This is likely due to a misconfiguration of the java class '" + service.getName() + "': ", e);
}
}
public Class<? extends S> lookupClass(String name) {
final Class<? extends S> service = services.get(name.toLowerCase(Locale.ROOT));
if (service != null) {
return service;
} else {
throw new IllegalArgumentException("A SPI class of type "+clazz.getName()+" with name '"+name+"' does not exist. "+
"You need to add the corresponding JAR file supporting this SPI to your classpath. "+
"The current classpath supports the following names: "+availableServices());
}
}
public Set<String> availableServices() {
return services.keySet();
}
}
| smartan/lucene | src/main/java/org/apache/lucene/analysis/util/AnalysisSPILoader.java | Java | apache-2.0 | 5,322 |
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
// here you can set theme used for your frontend application
// - template comes with: 'default', 'slate', 'spacelab' and 'cerulean'
'view' => [
'theme' => [
'pathMap' => ['@app/views' => '@webroot/themes/slate/views'],
'baseUrl' => '@web/themes/slate',
],
],
'user' => [
'identityClass' => 'common\models\UserIdentity',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
| romulolink/newTwitter | advanced/_protected/frontend/config/main.php | PHP | bsd-3-clause | 1,272 |
// Type definitions for node-hook 1.0
// Project: https://github.com/bahmutov/node-hook#readme
// Definitions by: Nathan Hardy <https://github.com/nhardy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Options {
verbose?: boolean | undefined;
}
type Transform = (source: string, filename: string) => string;
interface NodeHook {
hook: {
(extension: string, transform: Transform, options?: Options): void;
(transform: Transform, _?: undefined, options?: Options): void;
};
unhook(extension?: string): void;
}
declare const hook: NodeHook;
export = hook;
| markogresak/DefinitelyTyped | types/node-hook/index.d.ts | TypeScript | mit | 620 |
//------------------------------------------------------------------------------
// <copyright file="XmlSchemaDocumentation.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Schema {
using System.Collections;
using System.ComponentModel;
using System.Xml.Serialization;
/// <include file='doc\XmlSchemaDocumentation.uex' path='docs/doc[@for="XmlSchemaDocumentation"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSchemaDocumentation : XmlSchemaObject {
string source;
string language;
XmlNode[] markup;
static XmlSchemaSimpleType languageType = DatatypeImplementation.GetSimpleTypeFromXsdType(new XmlQualifiedName("language",XmlReservedNs.NsXs));
/// <include file='doc\XmlSchemaDocumentation.uex' path='docs/doc[@for="XmlSchemaDocumentation.Source"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("source", DataType="anyURI")]
public string Source {
get { return source; }
set { source = value; }
}
/// <include file='doc\XmlSchemaDocumentation.uex' path='docs/doc[@for="XmlSchemaDocumentation.Language"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("xml:lang")]
public string Language {
get { return language; }
set { language = (string)languageType.Datatype.ParseValue(value, (XmlNameTable) null, (IXmlNamespaceResolver) null); }
}
/// <include file='doc\XmlSchemaDocumentation.uex' path='docs/doc[@for="XmlSchemaDocumentation.Markup"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlText(), XmlAnyElement]
public XmlNode[] Markup {
get { return markup; }
set { markup = value; }
}
}
}
| sekcheong/referencesource | System.Xml/System/Xml/Schema/XmlSchemaDocumentation.cs | C# | mit | 2,231 |
/*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* 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.
*/
/// <reference path="../_references.ts"/>
module powerbi.visuals {
export interface BasicShapeDataViewObjects extends DataViewObjects {
general: BasicShapeDataViewObject;
line: LineObject;
fill: FillObject;
lockAspect: LockAspectObject;
rotation: RotationObject;
}
export interface LineObject extends DataViewObject {
lineColor: Fill;
roundEdge: number;
weight: number;
transparency: number;
}
export interface FillObject extends DataViewObject {
transparency: number;
fillColor: Fill;
show: boolean;
}
export interface LockAspectObject extends DataViewObject {
show: boolean;
}
export interface RotationObject extends DataViewObject {
angle: number;
}
export interface BasicShapeDataViewObject extends DataViewObject {
shapeType: string;
shapeSvg: string;
}
export interface BasicShapeData {
shapeType: string;
lineColor: string;
lineTransparency: number;
lineWeight: number;
showFill: boolean;
fillColor: string;
shapeTransparency: number;
lockAspectRatio: boolean;
roundEdge: number;
angle: number;
}
export class BasicShapeVisual implements IVisual {
private currentViewport: IViewport;
private element: JQuery;
private data: BasicShapeData;
private selection: D3.Selection;
public static DefaultShape: string = powerbi.basicShapeType.rectangle;
public static DefaultStrokeColor: string = '#00B8AA';
public static DefaultFillColor: string = '#E6E6E6';
public static DefaultFillTransValue: number = 100;
public static DefaultWeightValue: number = 3;
public static DefaultLineTransValue: number = 100;
public static DefaultRoundEdgeValue: number = 0;
public static DefaultAngle: number = 0;
/**property for the shape line color */
get shapeType(): string {
return this.data ? this.data.shapeType : BasicShapeVisual.DefaultShape;
}
set shapeType(shapeType: string) {
this.data.shapeType = shapeType;
}
/**property for the shape line color */
get lineColor(): string {
return this.data ? this.data.lineColor : BasicShapeVisual.DefaultStrokeColor;
}
set lineColor(color: string) {
this.data.lineColor = color;
}
/**property for the shape line transparency */
get lineTransparency(): number {
return this.data ? this.data.lineTransparency : BasicShapeVisual.DefaultLineTransValue;
}
set lineTransparency(trans: number) {
this.data.lineTransparency = trans;
}
/**property for the shape line weight */
get lineWeight(): number {
return this.data ? this.data.lineWeight : BasicShapeVisual.DefaultWeightValue;
}
set lineWeight(weight: number) {
this.data.lineWeight = weight;
}
/**property for the shape round edge */
get roundEdge(): number {
return this.data ? this.data.roundEdge : BasicShapeVisual.DefaultRoundEdgeValue;
}
set roundEdge(roundEdge: number) {
this.data.roundEdge = roundEdge;
}
/**property for showing the fill properties */
get showFill(): boolean {
return this.data ? this.data.showFill : true;
}
set showFill(show: boolean) {
this.data.showFill = show;
}
/**property for the shape line color */
get fillColor(): string {
return this.data ? this.data.fillColor : BasicShapeVisual.DefaultFillColor;
}
set fillColor(color: string) {
this.data.fillColor = color;
}
/**property for the shape fill transparency */
get shapeTransparency(): number {
return this.data ? this.data.shapeTransparency : BasicShapeVisual.DefaultFillTransValue;
}
set shapeTransparency(trans: number) {
this.data.shapeTransparency = trans;
}
/**property for showing the lock aspect ratio */
get lockAspectRatio(): boolean {
return this.data ? this.data.lockAspectRatio : false;
}
set lockAspectRatio(show: boolean) {
this.data.lockAspectRatio = show;
}
/**property for the shape angle */
get angle(): number {
return this.data ? this.data.angle : BasicShapeVisual.DefaultAngle;
}
set angle(angle: number) {
this.data.angle = angle;
}
public init(options: VisualInitOptions) {
this.element = options.element;
this.selection = d3.select(this.element.context);
this.currentViewport = options.viewport;
}
public constructor(options?: VisualInitOptions) {
}
public update(options: VisualUpdateOptions): void {
debug.assertValue(options, 'options');
this.currentViewport = options.viewport;
let dataViews = options.dataViews;
if (!_.isEmpty(dataViews)) {
let dataView = options.dataViews[0];
if (dataView.metadata && dataView.metadata.objects) {
let dataViewObject = <BasicShapeDataViewObjects>options.dataViews[0].metadata.objects;
this.data = this.getDataFromDataView(dataViewObject);
}
}
this.render();
}
private getDataFromDataView(dataViewObject: BasicShapeDataViewObjects): BasicShapeData {
if (dataViewObject) {
return {
shapeType: dataViewObject.general !== undefined && dataViewObject.general.shapeType !== undefined ? dataViewObject.general.shapeType : this.shapeType,
lineColor: dataViewObject.line !== undefined && dataViewObject.line.lineColor !== undefined ? dataViewObject.line.lineColor.solid.color : this.lineColor,
lineTransparency: dataViewObject.line !== undefined && dataViewObject.line.transparency !== undefined ? dataViewObject.line.transparency : this.lineTransparency,
lineWeight: dataViewObject.line !== undefined && dataViewObject.line.weight !== undefined ? dataViewObject.line.weight : this.lineWeight,
roundEdge: dataViewObject.line !== undefined && dataViewObject.line.roundEdge !== undefined ? dataViewObject.line.roundEdge : this.roundEdge,
shapeTransparency: dataViewObject.fill !== undefined && dataViewObject.fill.transparency !== undefined ? dataViewObject.fill.transparency : this.shapeTransparency,
fillColor: dataViewObject.fill !== undefined && dataViewObject.fill.fillColor !== undefined ? dataViewObject.fill.fillColor.solid.color : this.fillColor,
showFill: dataViewObject.fill !== undefined && dataViewObject.fill.show !== undefined ? dataViewObject.fill.show : this.showFill,
lockAspectRatio: dataViewObject.lockAspect !== undefined && dataViewObject.lockAspect.show !== undefined ? dataViewObject.lockAspect.show : this.lockAspectRatio,
angle: dataViewObject.rotation !== undefined && dataViewObject.rotation.angle !== undefined ? dataViewObject.rotation.angle : this.angle
};
}
return null;
}
public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstance[] {
let objectInstances: VisualObjectInstance[] = [];
switch (options.objectName) {
case 'line':
let instance: VisualObjectInstance = {
selector: null,
properties: {
lineColor: this.lineColor,
transparency: this.lineTransparency,
weight: this.lineWeight
},
objectName: options.objectName
};
if (this.data.shapeType === powerbi.basicShapeType.rectangle) {
instance.properties['roundEdge'] = this.roundEdge;
}
objectInstances.push(instance);
return objectInstances;
case 'fill':
objectInstances.push({
selector: null,
properties: {
show: this.showFill,
fillColor: this.fillColor,
transparency: this.shapeTransparency
},
objectName: options.objectName
});
return objectInstances;
case 'lockAspect':
objectInstances.push({
selector: null,
properties: {
show: this.lockAspectRatio
},
objectName: options.objectName
});
return objectInstances;
case 'rotation':
objectInstances.push({
selector: null,
properties: {
angle: this.angle
},
objectName: options.objectName
});
return objectInstances;
}
return null;
}
public render(): void {
this.selection.html('');
switch (this.shapeType) {
case powerbi.basicShapeType.rectangle:
shapeFactory.createRectangle(
this.data, this.currentViewport.height, this.currentViewport.width, this.selection, this.angle);
break;
case powerbi.basicShapeType.oval:
shapeFactory.createOval(
this.data, this.currentViewport.height, this.currentViewport.width, this.selection, this.angle);
break;
case powerbi.basicShapeType.line:
shapeFactory.createLine(
this.data, this.currentViewport.height, this.currentViewport.width, this.selection, this.angle);
break;
case powerbi.basicShapeType.arrow:
shapeFactory.createUpArrow(
this.data, this.currentViewport.height, this.currentViewport.width, this.selection, this.angle);
break;
case powerbi.basicShapeType.triangle:
shapeFactory.createTriangle(
this.data, this.currentViewport.height, this.currentViewport.width, this.selection, this.angle);
break;
default:
break;
}
}
}
}
| vinnytheviking/PowerBI-visuals | src/Clients/Visuals/visuals/basicShape.ts | TypeScript | mit | 12,416 |
// Type definitions for @webpack-blocks/assets 2.0
// Project: https://github.com/andywer/webpack-blocks/tree/master/packages/assets
// Definitions by: Max Boguslavskiy <https://github.com/maxbogus>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.7
import { Block } from 'webpack-blocks';
export namespace css {
type UrlFilter = (url: string, resourcePath: string) => boolean;
type ImportFilter = (parseImport: ParseImportOptions, resourcePath: string) => boolean;
type GetLocalIdent = (context: any, localIdentName: any, localName: any, options: any) => string;
type NameFunction = (file: string) => any;
type PathFunction = (url: string, resourcePath: string, context: string) => any;
interface ParseImportOptions {
url: string;
media: string;
}
interface ModuleOptions {
mode?: string | undefined;
localIdentName?: string | undefined;
context?: string | undefined;
hashPrefix?: string | undefined;
getLocalIdent?: GetLocalIdent | undefined;
localIdentRegExp?: string | RegExp | undefined;
/**
* 0 => no loaders (default);
* 1 => postcss-loader;
* 2 => postcss-loader, sass-loader
*/
importLoaders?: 0 | 1 | 2 | undefined;
localsConvention?: 'asIs' | 'camelCase' | 'camelCaseOnly' | 'dashes' | 'dashesOnly' | undefined;
onlyLocals?: boolean | undefined;
}
interface CssOptions {
url?: boolean | UrlFilter | undefined;
import?: boolean | ImportFilter | undefined;
modules?: boolean | string | ModuleOptions | undefined;
sourceMap?: boolean | undefined;
}
interface FileOptions {
name?: string | NameFunction | undefined;
outputPath?: string | PathFunction | undefined;
publicPath?: string | PathFunction | undefined;
postTransformPublicPath?: ((p: string) => string) | undefined;
context?: string | undefined;
emitFile?: boolean | undefined;
regExp?: RegExp | undefined;
}
interface UrlOptions {
fallback?: string | undefined;
limit?: number | boolean | string | undefined;
mimetype?: string | undefined;
}
function modules(options?: ModuleOptions): any;
}
export function css(options?: css.CssOptions): Block;
export function file(options?: css.FileOptions): Block;
export function url(options?: css.UrlOptions): Block;
| markogresak/DefinitelyTyped | types/webpack-blocks__assets/index.d.ts | TypeScript | mit | 2,486 |
import * as moment from 'moment';
export const dateFormat = 'DD/MM/YYYY';
export const datePickerFormat = 'dd/mm/yy';
export const minDate = moment('1900-01-01').toDate();
| glamb/TCMS-Frontend | node_modules/awesome-typescript-loader/issues/product-designer/src/constants/env.ts | TypeScript | mit | 173 |
'use strict';
// There's an example D script here to showcase a "slow" handler where it's
// wildcard'd by the route name. In "real life" you'd probably start with a
// d script that breaks down the route -start and -done, and then you'd want
// to see which handler is taking longest from there.
//
// $ node demo.js
// $ curl localhost:9080/foo/bar
// $ sudo ./handler-timing.d
// ^C
//
// handler-6
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseAccept
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseAuthorization
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseDate
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseQueryString
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseUrlEncodedBody
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// sendResult
// value ------------- Distribution ------------- count
// 1 | 0
// 2 |@@@@ 1
// 4 | 0
// 8 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9
// 16 | 0
//
// slowHandler
// value ------------- Distribution ------------- count
// 64 | 0
// 128 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9
// 256 |@@@@ 1
// 512 | 0
//
// getfoo
// value ------------- Distribution ------------- count
// 64 | 0
// 128 |@@@@ 1
// 256 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9
// 512 | 0
var restify = require('../../lib');
var Logger = require('bunyan');
///--- Globals
var NAME = 'exampleapp';
///--- Mainline
var log = new Logger({
name: NAME,
level: 'trace',
service: NAME,
serializers: restify.bunyan.serializers
});
var server = restify.createServer({
name: NAME,
Logger: log,
formatters: {
'application/foo': function (req, res, body, cb) {
if (body instanceof Error) {
body = body.stack;
} else if (Buffer.isBuffer(body)) {
body = body.toString('base64');
} else {
switch (typeof body) {
case 'boolean':
case 'number':
case 'string':
body = body.toString();
break;
case 'undefined':
body = '';
break;
default:
body = body === null ? '' :
'Demoing application/foo formatter; ' +
JSON.stringify(body);
break;
}
}
return cb(null, body);
}
}
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.authorizationParser());
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.urlEncodedBodyParser());
server.use(function slowHandler(req, res, next) {
setTimeout(function () {
next();
}, 250);
});
server.get({url: '/foo/:id', name: 'GetFoo'}, function (req, res, next) {
next();
}, function sendResult(req, res, next) {
res.contentType = 'application/foo';
res.send({
hello: req.params.id
});
next();
});
server.head('/foo/:id', function (req, res, next) {
res.send({
hello: req.params.id
});
next();
});
server.put('/foo/:id', function (req, res, next) {
res.send({
hello: req.params.id
});
next();
});
server.post('/foo/:id', function (req, res, next) {
res.json(201, req.params);
next();
});
server.del('/foo/:id', function (req, res, next) {
res.send(204);
next();
});
server.on('after', function (req, res, name) {
req.log.info('%s just finished: %d.', name, res.code);
});
server.on('NotFound', function (req, res) {
res.send(404, req.url + ' was not found');
});
server.listen(9080, function () {
log.info('listening: %s', server.url);
});
| mboudreau/node-restify | examples/dtrace/demo.js | JavaScript | mit | 5,705 |
// Type definitions for parallel.js
// Project: https://github.com/parallel-js/parallel.js#readme
// Definitions by: Josh Baldwin <https://github.com/jbaldwin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/*
Copyright(c) 2013 Josh Baldwin https://github.com/jbaldwin/parallel.d.ts
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.
*/
interface ParallelOptions {
/**
* This is the path to the file eval.js. This is required when running in node, and required for some browsers (IE 10) in order to work around cross-domain restrictions for web workers. Defaults to the same location as parallel.js in node environments, and null in the browser.
**/
evalPath?: string | undefined;
/**
* The maximum number of permitted worker threads. This will default to 4, or the number of cpus on your computer if you're running node.
**/
maxWorkers?: number | undefined;
/**
* If webworkers are not available, whether or not to fall back to synchronous processing using setTimeout. Defaults to true.
**/
synchronous?: boolean | undefined;
}
declare class Parallel<T> {
/**
* This is the constructor. Use it to new up any parallel jobs. The constructor takes an array of data you want to operate on. This data will be held in memory until you finish your job, and can be accessed via the .data attribute of your job.
* The object returned by the Parallel constructor is meant to be chained, so you can produce a chain of operations on the provided data.
* @param data This is the data you wish to operate on. Will often be an array, but the only restrictions are that your values are serializable as JSON.
* @param opts Some options for your job.
**/
constructor(data: T, opts?: ParallelOptions);
/**
* Data
**/
public data: T;
/**
* This function will spawn a new process on a worker thread. Pass it the function you want to call. Your function will receive one argument, which is the current data. The value returned from your spawned function will update the current data.
* @param fn A function to execute on a worker thread. Receives the wrapped data as an argument. The value returned will be assigned to the wrapped data.
* @return Parallel instance.
**/
public spawn(fn: (data: T) => T): Parallel<T>;
/**
* Map will apply the supplied function to every element in the wrapped data. Parallel will spawn one worker for each array element in the data, or the supplied maxWorkers argument. The values returned will be stored for further processing.
* @param fn A function to apply. Receives the wrapped data as an argument. The value returned will be assigned to the wrapped data.
* @return Parallel instance.
**/
public map<N>(fn: (data: N) => N): Parallel<T>;
/**
* Reduce applies an operation to every member of the wrapped data, and returns a scalar value produced by the operation. Use it for combining the results of a map operation, by summing numbers for example. This takes a reducing function, which gets an argument, data, an array of the stored value, and the current element.
* @param fn A function to apply. Receives the stored value and current element as argument. The value returned will be stored as the current value for the next iteration. Finally, the current value will be assigned to current data.
* @return Parallel instance.
**/
public reduce<N>(fn: (data: N[]) => N): Parallel<T>;
/**
* The functions given to then are called after the last requested operation has finished. success receives the resulting data object, while fail will receive an error object.
* @param success A function that gets called upon successful completion. Receives the wrapped data as an argument.
* @param fail A function that gets called if the job fails. The function is passed an error object.
* @return Parallel instance.
**/
public then(success: (data: T) => void, fail?: (e: Error) => void): Parallel<T>;
/**
* If you have state that you want to share between your main thread and worker threads, this is how. Require takes either a string or a function. A string should point to a file name. NOte that in order to use require with a file name as an argument, you have to provide the evalPath property in the options object.
* @param state Shared state function or js file.
* @return Parallel instance.
**/
public require(file: string): Parallel<T>;
/**
* @see require
**/
public require(fn: Function): Parallel<T>;
}
/* commonjs binding for npm use */
declare module "paralleljs" {
export = Parallel;
}
| markogresak/DefinitelyTyped | types/paralleljs/index.d.ts | TypeScript | mit | 5,682 |
//---------------------------------------------------------------------
// <copyright file="Perspective.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Diagnostics;
using System.Linq;
namespace System.Data.Metadata.Edm
{
using System.Collections.Generic;
/// <summary>
/// Internal helper class for query
/// </summary>
internal abstract class Perspective
{
#region Constructors
/// <summary>
/// Creates a new instance of perspective class so that query can work
/// ignorant of all spaces
/// </summary>
/// <param name="metadataWorkspace">runtime metadata container</param>
/// <param name="targetDataspace">target dataspace for the perspective</param>
internal Perspective(MetadataWorkspace metadataWorkspace,
DataSpace targetDataspace)
{
EntityUtil.CheckArgumentNull(metadataWorkspace, "metadataWorkspace");
m_metadataWorkspace = metadataWorkspace;
m_targetDataspace = targetDataspace;
}
#endregion
#region Fields
private MetadataWorkspace m_metadataWorkspace;
private DataSpace m_targetDataspace;
#endregion
#region Methods
/// <summary>
/// Given the type in the target space and the member name in the source space,
/// get the corresponding member in the target space
/// For e.g. consider a Conceptual Type 'Foo' with a member 'Bar' and a CLR type
/// 'XFoo' with a member 'YBar'. If one has a reference to Foo one can
/// invoke GetMember(Foo,"YBar") to retrieve the member metadata for bar
/// </summary>
/// <param name="type">The type in the target perspective</param>
/// <param name="memberName">the name of the member in the source perspective</param>
/// <param name="ignoreCase">Whether to do case-sensitive member look up or not</param>
/// <param name="outMember">returns the member in target space, if a match is found</param>
internal virtual bool TryGetMember(StructuralType type, String memberName, bool ignoreCase, out EdmMember outMember)
{
EntityUtil.CheckArgumentNull(type, "type");
EntityUtil.CheckStringArgument(memberName, "memberName");
outMember = null;
return type.Members.TryGetValue(memberName, ignoreCase, out outMember);
}
internal bool TryGetEnumMember(EnumType type, String memberName, bool ignoreCase, out EnumMember outMember)
{
EntityUtil.CheckArgumentNull(type, "type");
EntityUtil.CheckStringArgument(memberName, "memberName");
outMember = null;
return type.Members.TryGetValue(memberName, ignoreCase, out outMember);
}
/// <summary>
/// Returns the extent in the target space, for the given entity container.
/// </summary>
/// <param name="entityContainer">name of the entity container in target space</param>
/// <param name="extentName">name of the extent</param>
/// <param name="ignoreCase">Whether to do case-sensitive member look up or not</param>
/// <param name="outSet">extent in target space, if a match is found</param>
/// <returns>returns true, if a match is found otherwise returns false</returns>
internal bool TryGetExtent(EntityContainer entityContainer, String extentName, bool ignoreCase, out EntitySetBase outSet)
{
// There are no entity containers in the OSpace. So there is no mapping involved.
// Hence the name should be a valid name in the CSpace.
return entityContainer.BaseEntitySets.TryGetValue(extentName, ignoreCase, out outSet);
}
/// <summary>
/// Returns the function import in the target space, for the given entity container.
/// </summary>
internal bool TryGetFunctionImport(EntityContainer entityContainer, String functionImportName, bool ignoreCase, out EdmFunction functionImport)
{
// There are no entity containers in the OSpace. So there is no mapping involved.
// Hence the name should be a valid name in the CSpace.
functionImport = null;
if (ignoreCase)
{
functionImport = entityContainer.FunctionImports.Where(fi => String.Equals(fi.Name, functionImportName, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
}
else
{
functionImport = entityContainer.FunctionImports.Where(fi => fi.Name == functionImportName).SingleOrDefault();
}
return functionImport != null;
}
/// <summary>
/// Get the default entity container
/// returns null for any perspective other
/// than the CLR perspective
/// </summary>
/// <returns>The default container</returns>
internal virtual EntityContainer GetDefaultContainer()
{
return null;
}
/// <summary>
/// Get an entity container based upon the strong name of the container
/// If no entity container is found, returns null, else returns the first one/// </summary>
/// <param name="name">name of the entity container</param>
/// <param name="ignoreCase">true for case-insensitive lookup</param>
/// <param name="entityContainer">returns the entity container if a match is found</param>
/// <returns>returns true if a match is found, otherwise false</returns>
internal virtual bool TryGetEntityContainer(string name, bool ignoreCase, out EntityContainer entityContainer)
{
return MetadataWorkspace.TryGetEntityContainer(name, ignoreCase, TargetDataspace, out entityContainer);
}
/// <summary>
/// Gets a type with the given name in the target space.
/// </summary>
/// <param name="fullName">full name of the type</param>
/// <param name="ignoreCase">true for case-insensitive lookup</param>
/// <param name="typeUsage">TypeUsage for the type</param>
/// <returns>returns true if a match was found, otherwise false</returns>
internal abstract bool TryGetTypeByName(string fullName, bool ignoreCase, out TypeUsage typeUsage);
/// <summary>
/// Returns overloads of a function with the given name in the target space.
/// </summary>
/// <param name="namespaceName">namespace of the function</param>
/// <param name="functionName">name of the function</param>
/// <param name="ignoreCase">true for case-insensitive lookup</param>
/// <param name="functionOverloads">function overloads</param>
/// <returns>returns true if a match was found, otherwise false</returns>
internal bool TryGetFunctionByName(string namespaceName, string functionName, bool ignoreCase, out IList<EdmFunction> functionOverloads)
{
EntityUtil.CheckStringArgument(namespaceName, "namespaceName");
EntityUtil.CheckStringArgument(functionName, "functionName");
var fullName = namespaceName + "." + functionName;
// First look for a model-defined function in the target space.
ItemCollection itemCollection = m_metadataWorkspace.GetItemCollection(m_targetDataspace);
IList<EdmFunction> overloads =
m_targetDataspace == DataSpace.SSpace ?
((StoreItemCollection)itemCollection).GetCTypeFunctions(fullName, ignoreCase) :
itemCollection.GetFunctions(fullName, ignoreCase);
if (m_targetDataspace == DataSpace.CSpace)
{
// Then look for a function import.
if (overloads == null || overloads.Count == 0)
{
EntityContainer entityContainer;
if (this.TryGetEntityContainer(namespaceName, /*ignoreCase:*/ false, out entityContainer))
{
EdmFunction functionImport;
if (this.TryGetFunctionImport(entityContainer, functionName, /*ignoreCase:*/ false, out functionImport))
{
overloads = new EdmFunction[] { functionImport };
}
}
}
// Last, look in SSpace.
if (overloads == null || overloads.Count == 0)
{
ItemCollection storeItemCollection;
if (m_metadataWorkspace.TryGetItemCollection(DataSpace.SSpace, out storeItemCollection))
{
overloads = ((StoreItemCollection)storeItemCollection).GetCTypeFunctions(fullName, ignoreCase);
}
}
}
functionOverloads = (overloads != null && overloads.Count > 0) ? overloads : null;
return functionOverloads != null;
}
/// <summary>
/// Return the metadata workspace
/// </summary>
internal MetadataWorkspace MetadataWorkspace
{
get
{
return m_metadataWorkspace;
}
}
/// <summary>
/// returns the primitive type for a given primitive type kind.
/// </summary>
/// <param name="primitiveTypeKind"></param>
/// <param name="primitiveType"></param>
/// <returns></returns>
internal virtual bool TryGetMappedPrimitiveType(PrimitiveTypeKind primitiveTypeKind, out PrimitiveType primitiveType)
{
primitiveType = m_metadataWorkspace.GetMappedPrimitiveType(primitiveTypeKind, DataSpace.CSpace);
return (null != primitiveType);
}
//
// This property will be needed to construct keys for transient types
//
/// <summary>
/// Returns the target dataspace for this perspective
/// </summary>
internal DataSpace TargetDataspace
{
get
{
return m_targetDataspace;
}
}
#endregion
}
}
| sekcheong/referencesource | System.Data.Entity/System/Data/Metadata/Perspective.cs | C# | mit | 10,452 |
/**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.powermax.internal;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
/**
* The {@link PowermaxBinding} class defines common constants, which are
* used across the whole binding.
*
* @author Laurent Garnier - Initial contribution
*/
public class PowermaxBindingConstants {
public static final String BINDING_ID = "powermax";
// List of all Thing Type UIDs
public static final ThingTypeUID BRIDGE_TYPE_SERIAL = new ThingTypeUID(BINDING_ID, "serial");
public static final ThingTypeUID BRIDGE_TYPE_IP = new ThingTypeUID(BINDING_ID, "ip");
public static final ThingTypeUID THING_TYPE_ZONE = new ThingTypeUID(BINDING_ID, "zone");
public static final ThingTypeUID THING_TYPE_X10 = new ThingTypeUID(BINDING_ID, "x10");
// All supported Bridge types
public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_TYPES_UIDS = Collections
.unmodifiableSet(Stream.of(BRIDGE_TYPE_SERIAL, BRIDGE_TYPE_IP).collect(Collectors.toSet()));
// All supported Thing types
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
.unmodifiableSet(Stream.of(THING_TYPE_ZONE, THING_TYPE_X10).collect(Collectors.toSet()));
// List of all Channel ids
public static final String MODE = "mode";
public static final String TROUBLE = "trouble";
public static final String ALERT_IN_MEMORY = "alert_in_memory";
public static final String SYSTEM_STATUS = "system_status";
public static final String READY = "ready";
public static final String WITH_ZONES_BYPASSED = "with_zones_bypassed";
public static final String ALARM_ACTIVE = "alarm_active";
public static final String SYSTEM_ARMED = "system_armed";
public static final String ARM_MODE = "arm_mode";
public static final String TRIPPED = "tripped";
public static final String LAST_TRIP = "last_trip";
public static final String BYPASSED = "bypassed";
public static final String ARMED = "armed";
public static final String LOW_BATTERY = "low_battery";
public static final String PGM_STATUS = "pgm_status";
public static final String X10_STATUS = "x10_status";
public static final String EVENT_LOG = "event_log_%s";
public static final String UPDATE_EVENT_LOGS = "update_event_logs";
public static final String DOWNLOAD_SETUP = "download_setup";
}
| theoweiss/openhab2 | bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/PowermaxBindingConstants.java | Java | epl-1.0 | 2,871 |
/**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.lifx.internal.protocol;
import java.nio.ByteBuffer;
import org.openhab.binding.lifx.internal.fields.Field;
import org.openhab.binding.lifx.internal.fields.UInt16Field;
import org.openhab.binding.lifx.internal.fields.UInt32Field;
/**
* @author Tim Buckley - Initial Contribution
* @author Karel Goderis - Enhancement for the V2 LIFX Firmware and LAN Protocol Specification
*/
public class SetDimAbsoluteRequest extends Packet {
public static final int TYPE = 0x68;
public static final Field<Integer> FIELD_DIM = new UInt16Field().little();
public static final Field<Long> FIELD_DURATION = new UInt32Field().little();
private int dim;
private long duration;
public int getDim() {
return dim;
}
public long getDuration() {
return duration;
}
public SetDimAbsoluteRequest() {
}
public SetDimAbsoluteRequest(int dim, long duration) {
this.dim = dim;
this.duration = duration;
}
@Override
public int packetType() {
return TYPE;
}
@Override
protected int packetLength() {
return 6;
}
@Override
protected void parsePacket(ByteBuffer bytes) {
dim = FIELD_DIM.value(bytes);
duration = FIELD_DURATION.value(bytes);
}
@Override
protected ByteBuffer packetBytes() {
return ByteBuffer.allocate(packetLength()).put(FIELD_DIM.bytes(dim)).put(FIELD_DURATION.bytes(duration));
}
@Override
public int[] expectedResponses() {
return new int[] {};
}
}
| clinique/openhab2 | bundles/org.openhab.binding.lifx/src/main/java/org/openhab/binding/lifx/internal/protocol/SetDimAbsoluteRequest.java | Java | epl-1.0 | 1,951 |
/***************************************************************************
qgsattributeformeditorwidget.cpp
-------------------------------
Date : March 2016
Copyright : (C) 2016 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 "qgsattributeformeditorwidget.h"
#include "qgsattributeform.h"
#include "qgsmultiedittoolbutton.h"
#include "qgssearchwidgettoolbutton.h"
#include "qgseditorwidgetwrapper.h"
#include "qgssearchwidgetwrapper.h"
#include "qgsattributeeditorcontext.h"
#include "qgseditorwidgetregistry.h"
#include "qgsaggregatetoolbutton.h"
#include "qgsgui.h"
#include "qgsvectorlayerjoinbuffer.h"
#include "qgsvectorlayerutils.h"
#include <QLayout>
#include <QLabel>
#include <QStackedWidget>
QgsAttributeFormEditorWidget::QgsAttributeFormEditorWidget( QgsEditorWidgetWrapper *editorWidget, const QString &widgetType, QgsAttributeForm *form )
: QgsAttributeFormWidget( editorWidget, form )
, mWidgetType( widgetType )
, mEditorWidget( editorWidget )
, mForm( form )
, mMultiEditButton( new QgsMultiEditToolButton() )
, mBlockValueUpdate( false )
, mIsMixed( false )
, mIsChanged( false )
{
mConstraintResultLabel = new QLabel( this );
mConstraintResultLabel->setObjectName( QStringLiteral( "ConstraintStatus" ) );
mConstraintResultLabel->setSizePolicy( QSizePolicy::Fixed, mConstraintResultLabel->sizePolicy().verticalPolicy() );
mMultiEditButton->setField( mEditorWidget->field() );
mAggregateButton = new QgsAggregateToolButton();
mAggregateButton->setType( editorWidget->field().type() );
connect( mAggregateButton, &QgsAggregateToolButton::aggregateChanged, this, &QgsAttributeFormEditorWidget::onAggregateChanged );
if ( mEditorWidget->widget() )
{
mEditorWidget->widget()->setObjectName( mEditorWidget->field().name() );
}
connect( mEditorWidget, &QgsEditorWidgetWrapper::valuesChanged, this, &QgsAttributeFormEditorWidget::editorWidgetValuesChanged );
connect( mMultiEditButton, &QgsMultiEditToolButton::resetFieldValueTriggered, this, &QgsAttributeFormEditorWidget::resetValue );
connect( mMultiEditButton, &QgsMultiEditToolButton::setFieldValueTriggered, this, &QgsAttributeFormEditorWidget::setFieldTriggered );
mMultiEditButton->setField( mEditorWidget->field() );
updateWidgets();
}
QgsAttributeFormEditorWidget::~QgsAttributeFormEditorWidget()
{
//there's a chance these widgets are not currently added to the layout, so have no parent set
delete mMultiEditButton;
}
void QgsAttributeFormEditorWidget::createSearchWidgetWrappers( const QgsAttributeEditorContext &context )
{
Q_ASSERT( !mWidgetType.isEmpty() );
const QVariantMap config = mEditorWidget->config();
const int fieldIdx = mEditorWidget->fieldIdx();
QgsSearchWidgetWrapper *sww = QgsGui::editorWidgetRegistry()->createSearchWidget( mWidgetType, layer(), fieldIdx, config,
searchWidgetFrame(), context );
setSearchWidgetWrapper( sww );
searchWidgetFrame()->layout()->addWidget( mAggregateButton );
if ( sww->supportedFlags() & QgsSearchWidgetWrapper::Between ||
sww->supportedFlags() & QgsSearchWidgetWrapper::IsNotBetween )
{
// create secondary widget for between type searches
QgsSearchWidgetWrapper *sww2 = QgsGui::editorWidgetRegistry()->createSearchWidget( mWidgetType, layer(), fieldIdx, config,
searchWidgetFrame(), context );
addAdditionalSearchWidgetWrapper( sww2 );
}
}
void QgsAttributeFormEditorWidget::setConstraintStatus( const QString &constraint, const QString &description, const QString &err, QgsEditorWidgetWrapper::ConstraintResult result )
{
switch ( result )
{
case QgsEditorWidgetWrapper::ConstraintResultFailHard:
mConstraintResultLabel->setText( QStringLiteral( "<font color=\"#FF9800\">%1</font>" ).arg( QChar( 0x2718 ) ) );
mConstraintResultLabel->setToolTip( description.isEmpty() ? QStringLiteral( "<b>%1</b>: %2" ).arg( constraint, err ) : description );
break;
case QgsEditorWidgetWrapper::ConstraintResultFailSoft:
mConstraintResultLabel->setText( QStringLiteral( "<font color=\"#FFC107\">%1</font>" ).arg( QChar( 0x2718 ) ) );
mConstraintResultLabel->setToolTip( description.isEmpty() ? QStringLiteral( "<b>%1</b>: %2" ).arg( constraint, err ) : description );
break;
case QgsEditorWidgetWrapper::ConstraintResultPass:
mConstraintResultLabel->setText( QStringLiteral( "<font color=\"#259B24\">%1</font>" ).arg( QChar( 0x2714 ) ) );
mConstraintResultLabel->setToolTip( description );
break;
}
}
void QgsAttributeFormEditorWidget::setConstraintResultVisible( bool editable )
{
mConstraintResultLabel->setHidden( !editable );
}
QgsEditorWidgetWrapper *QgsAttributeFormEditorWidget::editorWidget() const
{
return mEditorWidget;
}
void QgsAttributeFormEditorWidget::setIsMixed( bool mixed )
{
if ( mEditorWidget && mixed )
mEditorWidget->showIndeterminateState();
mMultiEditButton->setIsMixed( mixed );
mIsMixed = mixed;
}
void QgsAttributeFormEditorWidget::changesCommitted()
{
if ( mEditorWidget )
{
mPreviousValue = mEditorWidget->value();
mPreviousAdditionalValues = mEditorWidget->additionalFieldValues();
}
setIsMixed( false );
mMultiEditButton->changesCommitted();
mIsChanged = false;
}
void QgsAttributeFormEditorWidget::initialize( const QVariant &initialValue, bool mixedValues, const QVariantList &additionalFieldValues )
{
if ( mEditorWidget )
{
mBlockValueUpdate = true;
mEditorWidget->setValues( initialValue, additionalFieldValues );
mBlockValueUpdate = false;
}
mPreviousValue = initialValue;
mPreviousAdditionalValues = additionalFieldValues;
setIsMixed( mixedValues );
mMultiEditButton->setIsChanged( false );
mIsChanged = false;
updateWidgets();
}
QVariant QgsAttributeFormEditorWidget::currentValue() const
{
return mEditorWidget->value();
}
void QgsAttributeFormEditorWidget::editorWidgetValuesChanged( const QVariant &value, const QVariantList &additionalFieldValues )
{
if ( mBlockValueUpdate )
return;
mIsChanged = true;
switch ( mode() )
{
case DefaultMode:
case SearchMode:
case AggregateSearchMode:
break;
case MultiEditMode:
mMultiEditButton->setIsChanged( true );
}
Q_NOWARN_DEPRECATED_PUSH
emit valueChanged( value );
Q_NOWARN_DEPRECATED_POP
emit valuesChanged( value, additionalFieldValues );
}
void QgsAttributeFormEditorWidget::resetValue()
{
mIsChanged = false;
mBlockValueUpdate = true;
if ( mEditorWidget )
mEditorWidget->setValues( mPreviousValue, mPreviousAdditionalValues );
mBlockValueUpdate = false;
switch ( mode() )
{
case DefaultMode:
case SearchMode:
case AggregateSearchMode:
break;
case MultiEditMode:
{
mMultiEditButton->setIsChanged( false );
if ( mEditorWidget && mIsMixed )
mEditorWidget->showIndeterminateState();
break;
}
}
}
void QgsAttributeFormEditorWidget::setFieldTriggered()
{
mIsChanged = true;
}
void QgsAttributeFormEditorWidget::onAggregateChanged()
{
for ( QgsSearchWidgetWrapper *searchWidget : searchWidgetWrappers() )
searchWidget->setAggregate( mAggregateButton->aggregate() );
}
void QgsAttributeFormEditorWidget::updateWidgets()
{
//first update the tool buttons
bool hasMultiEditButton = ( editPage()->layout()->indexOf( mMultiEditButton ) >= 0 );
const int fieldIndex = mEditorWidget->fieldIdx();
bool fieldReadOnly = false;
QgsFeature feature;
auto it = layer()->getSelectedFeatures();
while ( it.nextFeature( feature ) )
{
fieldReadOnly |= !QgsVectorLayerUtils::fieldIsEditable( layer(), fieldIndex, feature );
}
if ( hasMultiEditButton )
{
if ( mode() != MultiEditMode || fieldReadOnly )
{
editPage()->layout()->removeWidget( mMultiEditButton );
mMultiEditButton->setParent( nullptr );
}
}
else
{
if ( mode() == MultiEditMode && !fieldReadOnly )
{
editPage()->layout()->addWidget( mMultiEditButton );
}
}
switch ( mode() )
{
case DefaultMode:
case MultiEditMode:
{
stack()->setCurrentWidget( editPage() );
editPage()->layout()->addWidget( mConstraintResultLabel );
break;
}
case AggregateSearchMode:
{
mAggregateButton->setVisible( true );
stack()->setCurrentWidget( searchPage() );
break;
}
case SearchMode:
{
mAggregateButton->setVisible( false );
stack()->setCurrentWidget( searchPage() );
break;
}
}
}
| minorua/QGIS | src/gui/qgsattributeformeditorwidget.cpp | C++ | gpl-2.0 | 9,238 |
using System;
using System.Collections.Generic;
using Server.Items;
namespace Server.Mobiles
{
public class SBWeaver: SBInfo
{
private List<GenericBuyInfo> m_BuyInfo = new InternalBuyInfo();
private IShopSellInfo m_SellInfo = new InternalSellInfo();
public SBWeaver()
{
}
public override IShopSellInfo SellInfo { get { return m_SellInfo; } }
public override List<GenericBuyInfo> BuyInfo { get { return m_BuyInfo; } }
public class InternalBuyInfo : List<GenericBuyInfo>
{
public InternalBuyInfo()
{
Add( new GenericBuyInfo( typeof( Dyes ), 8, 20, 0xFA9, 0 ) );
Add( new GenericBuyInfo( typeof( DyeTub ), 8, 20, 0xFAB, 0 ) );
Add( new GenericBuyInfo( typeof( UncutCloth ), 3, 20, 0x1761, 0 ) );
Add( new GenericBuyInfo( typeof( UncutCloth ), 3, 20, 0x1762, 0 ) );
Add( new GenericBuyInfo( typeof( UncutCloth ), 3, 20, 0x1763, 0 ) );
Add( new GenericBuyInfo( typeof( UncutCloth ), 3, 20, 0x1764, 0 ) );
Add( new GenericBuyInfo( typeof( BoltOfCloth ), 100, 20, 0xf9B, 0 ) );
Add( new GenericBuyInfo( typeof( BoltOfCloth ), 100, 20, 0xf9C, 0 ) );
Add( new GenericBuyInfo( typeof( BoltOfCloth ), 100, 20, 0xf96, 0 ) );
Add( new GenericBuyInfo( typeof( BoltOfCloth ), 100, 20, 0xf97, 0 ) );
Add( new GenericBuyInfo( typeof( DarkYarn ), 18, 20, 0xE1D, 0 ) );
Add( new GenericBuyInfo( typeof( LightYarn ), 18, 20, 0xE1E, 0 ) );
Add( new GenericBuyInfo( typeof( LightYarnUnraveled ), 18, 20, 0xE1F, 0 ) );
Add( new GenericBuyInfo( typeof( Scissors ), 11, 20, 0xF9F, 0 ) );
}
}
public class InternalSellInfo : GenericSellInfo
{
public InternalSellInfo()
{
Add( typeof( Scissors ), 6 );
Add( typeof( Dyes ), 4 );
Add( typeof( DyeTub ), 4 );
Add( typeof( UncutCloth ), 1 );
Add( typeof( BoltOfCloth ), 50 );
Add( typeof( LightYarnUnraveled ), 9 );
Add( typeof( LightYarn ), 9 );
Add( typeof( DarkYarn ), 9 );
}
}
}
} | ggobbe/hyel | Scripts/Mobiles/Vendors/SBInfo/SBWeaver.cs | C# | gpl-2.0 | 2,048 |
/****************************************************************************
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
#include "renderer/CCPrimitive.h"
#include "renderer/CCVertexIndexBuffer.h"
NS_CC_BEGIN
Primitive* Primitive::create(VertexData* verts, IndexBuffer* indices, int type)
{
auto result = new (std::nothrow) Primitive();
if( result && result->init(verts, indices, type))
{
result->autorelease();
return result;
}
CC_SAFE_DELETE(result);
return nullptr;
}
const VertexData* Primitive::getVertexData() const
{
return _verts;
}
const IndexBuffer* Primitive::getIndexData() const
{
return _indices;
}
Primitive::Primitive()
: _verts(nullptr)
, _indices(nullptr)
, _type(GL_POINTS)
, _start(0)
, _count(0)
{
}
Primitive::~Primitive()
{
CC_SAFE_RELEASE_NULL(_verts);
CC_SAFE_RELEASE_NULL(_indices);
}
bool Primitive::init(VertexData* verts, IndexBuffer* indices, int type)
{
if( nullptr == verts ) return false;
if(verts != _verts)
{
CC_SAFE_RELEASE(_verts);
CC_SAFE_RETAIN(verts);
_verts = verts;
}
if(indices != _indices)
{
CC_SAFE_RETAIN(indices);
CC_SAFE_RELEASE(_indices);
_indices = indices;
}
_type = type;
return true;
}
void Primitive::draw()
{
if(_verts)
{
_verts->use();
if(_indices!= nullptr)
{
GLenum type = (_indices->getType() == IndexBuffer::IndexType::INDEX_TYPE_SHORT_16) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indices->getVBO());
size_t offset = _start * _indices->getSizePerIndex();
glDrawElements((GLenum)_type, _count, type, (GLvoid*)offset);
}
else
{
glDrawArrays((GLenum)_type, _start, _count);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
}
void Primitive::setStart(int start)
{
_start = start;
}
void Primitive::setCount(int count)
{
_count = count;
}
NS_CC_END
| soniyj/basement | src/Cocos2d-x/Colby/cocos2d/cocos/renderer/CCPrimitive.cpp | C++ | gpl-2.0 | 3,255 |
// ImagePixel.cpp: implementation of the CImagePixel class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ImagePixel.h"
#include "Image.h"
CImagePixel::CImagePixel()
{
m_pInput=NULL;
}
CImagePixel::CImagePixel(CImage* pInput)
{
m_pInput=pInput;
Init(pInput);
}
CImagePixel::~CImagePixel()
{
}
void CImagePixel::Init(CImage* pInput)
{
m_pInput=pInput;
m_pCPP.resize(m_pInput->GetHeight());
for(int i=0; i<m_pInput->GetHeight(); i++)
{
m_pCPP[i]=m_pInput->GetPixel(0, i);
}
}
CPixelRGB8 CImagePixel::GetPixel(float x, float y, int& count)
{
///< bilinear filtering getpixel
CPixelRGB8 color;
int x1,y1,x2,y2;
x1=(int)x;
x2=x1+1;
y1=(int)y;
y2=y1+1;
count=1;
// 4°³ Çȼ¿Áß Çϳª¶óµµ ¹Û¿¡ ÀÖ´Â °æ¿ì
if(x1<0 || x2>=m_pInput->GetWidth() || y1<0 || y2>=m_pInput->GetHeight())
{
count=0;
color=CPixelRGB8 (0,0,0);
}
// ¸ðµÎ ¾È¿¡ Àִ°æ¿ì
else
{
CPixelRGB8 c1,c2,c3,c4;
float errx=x-x1;
float erry=y-y1;
float ex1=(1.f-errx)*(1.f-errx);
float ex2=errx*errx;
float ey1=(1.f-erry)*(1.f-erry);
float ey2=erry*erry;
// p1: x1,y1
// p2: x1,y2
// p3: x2,y1
// p4: y2,y2
float w1,w2,w3,w4;
w1=ex1+ey1;
w2=ex1+ey2;
w3=ex2+ey1;
w4=ex2+ey2;
float sum=w1+w2+w3+w4;
w1/=sum;
w2/=sum;
w3/=sum;
w4/=sum;
count=4;
c1=GetPixel(x1,y1);
c2=GetPixel(x1,y2);
c3=GetPixel(x2,y1);
c4=GetPixel(x2,y2);
color=CPixelRGB8 (int((c1.R)*w1+(c2.R)*w2+(c3.R)*w3+(c4.R)*w4),
int((c1.G)*w1+(c2.G)*w2+(c3.G)*w3+(c4.G)*w4),
int((c1.B)*w1+(c2.B)*w2+(c3.B)*w3+(c4.B)*w4));
}
return color;
}
void CImagePixel::SetPixel(float fx, float fy, CPixelRGB8 color)
{
int width=m_pInput->GetWidth();
int height=m_pInput->GetHeight();
int x,y;
x=int(fx*width);
y=int(fy*height);
if(x<0) x=0;
if(y<0) y=0;
if(x>=width) x=width-1;
if(y>=height) y=height-1;
SetPixel(x,y,color);
}
void CImagePixel::DrawHorizLine(int x, int y, int width, CPixelRGB8 color)
{
{
std::vector<CPixelRGB8 *> & inputptr=m_pCPP;
if(x<0) return;
if(x>=m_pInput->GetWidth()) return;
if(y<0) return;
if(y>=m_pInput->GetHeight()) return;
if (x+width>=m_pInput->GetWidth())
width=m_pInput->GetWidth()-x-1;
for(int i=x; i<x+width; i++)
{
inputptr[y][i]=color;
}
}
}
void CImagePixel::DrawVertLine(int x, int y, int height, CPixelRGB8 color,bool bDotted)
{
int step=1;
if(bDotted) step=3;
std::vector<CPixelRGB8 *> & inputptr=(m_pCPP);
if(x<0) return;
if(x>=m_pInput->GetWidth()) return;
if(y<0) return;
if(y>=m_pInput->GetHeight()) return;
if (y+height>=m_pInput->GetHeight())
height=m_pInput->GetHeight()-y-1;
for(int j=y; j<y+height; j+=step)
{
inputptr[j][x]=color;
}
}
void CImagePixel::DrawLineBox(const TRect& rect, CPixelRGB8 color)
{
DrawHorizLine(rect.left, rect.top, rect.Width(), color);
DrawHorizLine(rect.left, rect.bottom-1, rect.Width(), color);
DrawVertLine(rect.left, rect.top, rect.Height(), color);
DrawVertLine(rect.right-1, rect.top, rect.Height(), color);
}
void CImagePixel::DrawBox(const TRect& _rect, CPixelRGB8 sColor)
{
TRect rect=_rect;
if(rect.left> rect.right) std::swap(rect.left, rect.right);
if(rect.top> rect.bottom) std::swap(rect.top, rect.bottom);
if(rect.left<0) rect.left=0;
if(rect.top<0) rect.top=0;
if(rect.bottom>Height())rect.bottom=Height();
if(rect.right>Width())rect.right=Width();
{
std::vector<CPixelRGB8 *> & inputptr=m_pCPP;
/*
// easy to read version
for(int j=rect.top; j<rect.bottom; j++)
{
CPixelRGB8* ptr=inputptr[j];
for(int i=rect.left; i<rect.right; i++)
{
memcpy(&ptr[i],&sColor,sizeof(CPixelRGB8));
}
}
*/
// fast version
CPixelRGB8* aBuffer;
int width=rect.right-rect.left;
if(width>0)
{
aBuffer=new CPixelRGB8[width];
for(int i=0; i<width; i++)
aBuffer[i]=sColor;
for(int j=rect.top; j<rect.bottom; j++)
{
CPixelRGB8* ptr=inputptr[j];
memcpy(&ptr[rect.left],aBuffer, sizeof(CPixelRGB8)*(width));
}
delete[] aBuffer;
}
}
}
void CImagePixel::Clear(CPixelRGB8 color)
{
int width=m_pInput->GetWidth();
int height=m_pInput->GetHeight();
DrawBox(TRect(0,0, width, height), color);
}
void CImagePixel::DrawPattern(int x, int y, const CImagePixel& patternPixel, bool bUseColorKey, CPixelRGB8 sColorkey, bool bOverideColor, CPixelRGB8 overrideColor)
{
int imageWidth=m_pInput->GetWidth();
int imageHeight=m_pInput->GetHeight();
int patternWidth=patternPixel.m_pInput->GetWidth();
int patternHeight=patternPixel.m_pInput->GetHeight();
int imagex, imagey;
if(bUseColorKey)
{
if(bOverideColor)
{
float ovR=float((overrideColor.R))/255.f;
float ovG=float((overrideColor.G))/255.f;
float ovB=float((overrideColor.B))/255.f;
for(int j=0; j<patternHeight; j++)
for(int i=0; i<patternWidth; i++)
{
imagex=x+i; imagey=y+j;
if(imagex>=0 && imagex<imageWidth && imagey>=0 && imagey <imageHeight)
{
if(memcmp(&patternPixel.GetPixel(i,j),&sColorkey, sizeof(CPixelRGB8))!=0)
{
// SetPixel( imagex, imagey, overrideColor);
CPixelRGB8& c=Pixel(imagex, imagey);
CPixelRGB8& cc=patternPixel.Pixel(i,j);
c.R=cc.R*ovR;
c.G=cc.G*ovG;
c.B=cc.B*ovB;
}
}
}
}
else
{
for(int j=0; j<patternHeight; j++)
for(int i=0; i<patternWidth; i++)
{
imagex=x+i; imagey=y+j;
if(imagex>=0 && imagex<imageWidth && imagey>=0 && imagey <imageHeight)
{
if(memcmp(&patternPixel.Pixel(i,j),&sColorkey, sizeof(CPixelRGB8))!=0)
GetPixel(imagex,imagey)=patternPixel.GetPixel(i,j);
}
}
}
}
else
{
ASSERT(!bOverideColor);
for(int j=0; j<patternHeight; j++)
{
CPixelRGB8* target=&GetPixel(x,y+j);
CPixelRGB8* source=&patternPixel.Pixel(0,j);
memcpy(target,source, sizeof(CPixelRGB8)*patternWidth);
}
}
}
void CImagePixel::DrawPattern(int x, int y, CImage* pPattern, bool bUseColorkey, CPixelRGB8 colorkey, bool bOverideColor, CPixelRGB8 overrideColor)
{
CImagePixel patternPixel(pPattern);
DrawPattern(x,y,patternPixel,bUseColorkey,colorkey,bOverideColor,overrideColor);
}
void CImagePixel::DrawLine(int x1, int y1, int x2, int y2, CPixelRGB8 color) //!< inputptr, inputptr2Áß Çϳª´Â NULL·Î ÁÙ°Í.
{
int dx,dy,x,y,x_end,p,const1,const2,y_end;
int delta;
dx=abs(x1-x2);
dy=abs(y1-y2);
if (((y1-y2)>0 && (x1-x2)>0 ) || (y1-y2)<0 && (x1-x2)<0)
{
delta=1; //±â¿ï±â >0
}
else
{
delta=-1; //±â¿ï±â <0
}
if(dx>dy) //±â¿ï±â 0 < |m| <=1
{
p=2*dy-dx;
const1=2*dy;
const2=2*(dy-dx);
if(x1>x2)
{
x=x2;y=y2;
x_end=x1;
}
else
{
x=x1;y=y1;
x_end=x2;
}
SetPixel( x,y, color);
while(x<x_end)
{
x=x+1;
if(p<0)
{
p=p+const1;
}
else
{
y=y+delta;
p=p+const2;
}
SetPixel( x,y, color);
} //±â¿ï±â |m| > 1
}
else
{
p=2*dx-dy;
const1=2*dx;
const2=2*(dx-dy);
if(y1>y2)
{
y=y2;x=x2;
y_end=y1;
}
else
{
y=y1;x=x1;
y_end=y2;
}
SetPixel( x,y, color);
while(y<y_end)
{
y=y+1;
if(p<0)
{
p=p+const1;
}
else
{
x=x+delta;
p=p+const2;
}
SetPixel( x,y, color);
}
}
}
void CImagePixel::DrawSubPattern(int x, int y, const CImagePixel& patternPixel, const TRect& patternRect, bool bUseColorKey, CPixelRGB8 sColorkey)
{
int imageWidth=m_pInput->GetWidth();
int imageHeight=m_pInput->GetHeight();
int patternWidth=patternPixel.m_pInput->GetWidth();
int patternHeight=patternPixel.m_pInput->GetHeight();
ASSERT(patternRect.right<=patternWidth);
ASSERT(patternRect.top<=patternHeight);
int imagex, imagey;
if(bUseColorKey)
{
for(int j=patternRect.top; j<patternRect.bottom; j++)
for(int i=patternRect.left; i<patternRect.right; i++)
{
imagex=x+i-patternRect.left; imagey=y+j-patternRect.top;
if(imagex>=0 && imagex<imageWidth && imagey>=0 && imagey <imageHeight)
{
if(memcmp(&patternPixel.Pixel(i,j),&sColorkey, sizeof(CPixelRGB8))!=0)
Pixel(imagex,imagey)=patternPixel.Pixel(i,j);
}
}
}
else
{
TRect rect=patternRect;
if(x<0)
{
rect.left-=x;
x-=x;
}
if(x+rect.Width()>imageWidth)
{
int delta=x+rect.Width()-imageWidth;
rect.right-=delta;
}
if(rect.Width()>0)
{
for(int j=rect.top; j<rect.bottom; j++)
{
imagey=y+j-rect.top;
if(imagey>=0 && imagey <imageHeight)
{
CPixelRGB8* target=&Pixel(x,imagey);
CPixelRGB8* source=&patternPixel.Pixel(rect.left,j);
memcpy(target,source, sizeof(CPixelRGB8)*rect.Width());
}
}
}
}
}
void CImagePixel::DrawText(int x, int y, const char* str, bool bUserColorKey, CPixelRGB8 colorkey)
{
static CImage* pText=NULL;
if(!pText)
{
pText=new CImage();
pText->Load("resource/default/ascii.bmp");
}
CImage& cText=*pText;
CImagePixel patternPixel(&cText);
#define FONT_HEIGHT 16
#define FONT_WIDTH 8
int len=strlen(str);
for(int i=0; i<len; i++)
{
char c=str[i];
int code=(c-' ');
ASSERT(code>=0 && code<32*3);
int left=code%32*FONT_WIDTH ;
int top=code/32*FONT_HEIGHT;
DrawSubPattern(x+i*FONT_WIDTH , y, patternPixel, TRect(left,top,left+FONT_WIDTH , top+FONT_HEIGHT), bUserColorKey, colorkey);
}
}
| kwangkim/papercrop | image/ImagePixel.cpp | C++ | gpl-2.0 | 9,646 |
"""
Boolean geometry utilities.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
import sys
__author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
__credits__ = 'Art of Illusion <http://www.artofillusion.org/>'
__date__ = '$Date: 2008/02/05 $'
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
def _getAccessibleAttribute(attributeName):
'Get the accessible attribute.'
if attributeName in globalAccessibleAttributeDictionary:
return globalAccessibleAttributeDictionary[attributeName]
return None
def continuous(valueString):
'Print continuous.'
sys.stdout.write(str(valueString))
return valueString
def line(valueString):
'Print line.'
print(valueString)
return valueString
globalAccessibleAttributeDictionary = {'continuous' : continuous, 'line' : line}
| dob71/x2swn | skeinforge/fabmetheus_utilities/geometry/geometry_utilities/evaluate_fundamentals/print.py | Python | gpl-3.0 | 984 |
<?php
/**
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Maintenance
*/
require_once __DIR__ . '/Maintenance.php';
/**
* @ingroup Maintenance
*/
class PageExists extends Maintenance {
public function __construct() {
parent::__construct();
$this->addDescription( 'Report whether a specific page exists' );
$this->addArg( 'title', 'Page title to check whether it exists' );
}
public function execute() {
$titleArg = $this->getArg();
$title = Title::newFromText( $titleArg );
$pageExists = $title && $title->exists();
$text = '';
$code = 0;
if ( $pageExists ) {
$text = "{$title} exists.";
} else {
$text = "{$titleArg} doesn't exist.";
$code = 1;
}
$this->output( $text );
$this->error( '', $code );
}
}
$maintClass = "PageExists";
require_once RUN_MAINTENANCE_IF_MAIN;
| Electro-Light/ElectroLight-WebSite | wiki/maintenance/pageExists.php | PHP | gpl-3.0 | 1,549 |
<?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
namespace Mautic\CoreBundle\Helper;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Class TrackingPixelHelper
*/
class TrackingPixelHelper
{
/**
* @param Request $request
*
* @return Response
*/
public static function getResponse(Request $request)
{
ignore_user_abort(true);
//turn off gzip compression
if (function_exists('apache_setenv')) {
apache_setenv('no-gzip', 1);
}
ini_set('zlib.output_compression', 0);
$response = new Response();
//removing any content encoding like gzip etc.
$response->headers->set('Content-encoding', 'none');
//check to ses if request is a POST
if ($request->getMethod() == 'GET') {
//return 1x1 pixel transparent gif
$response->headers->set('Content-type', 'image/gif');
//avoid cache time on browser side
$response->headers->set('Content-Length', '42');
$response->headers->set('Cache-Control', 'private, no-cache, no-cache=Set-Cookie, proxy-revalidate');
$response->headers->set('Expires', 'Wed, 11 Jan 2000 12:59:00 GMT');
$response->headers->set('Last-Modified', 'Wed, 11 Jan 2006 12:59:00 GMT');
$response->headers->set('Pragma', 'no-cache');
$response->setContent(self::getImage());
} else {
$response->setContent(' ');
}
return $response;
}
/**
* @return string
*/
public static function getImage()
{
return sprintf('%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%',71,73,70,56,57,97,1,0,1,0,128,255,0,192,192,192,0,0,0,33,249,4,1,0,0,0,0,44,0,0,0,0,1,0,1,0,0,2,2,68,1,0,59);
}
}
| MAT978/mautic | app/bundles/CoreBundle/Helper/TrackingPixelHelper.php | PHP | gpl-3.0 | 2,052 |
<?php
$_['heading_title'] = '欢迎访问 %s';
?> | Foboy/GogoDesginer | upload/catalog/language/zh-CN/module/welcome.php | PHP | gpl-3.0 | 49 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* 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/>
*/
package com.shatteredpixel.shatteredpixeldungeon.items.armor.glyphs;
import com.watabou.noosa.Camera;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Buff;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Roots;
import com.shatteredpixel.shatteredpixeldungeon.effects.CellEmitter;
import com.shatteredpixel.shatteredpixeldungeon.effects.particles.EarthParticle;
import com.shatteredpixel.shatteredpixeldungeon.items.armor.Armor;
import com.shatteredpixel.shatteredpixeldungeon.items.armor.Armor.Glyph;
import com.shatteredpixel.shatteredpixeldungeon.plants.Earthroot;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSprite;
import com.shatteredpixel.shatteredpixeldungeon.sprites.ItemSprite.Glowing;
import com.watabou.utils.Random;
public class Entanglement extends Glyph {
private static final String TXT_ENTANGLEMENT = "%s of entanglement";
private static ItemSprite.Glowing GREEN = new ItemSprite.Glowing( 0x448822 );
@Override
public int proc( Armor armor, Char attacker, Char defender, int damage ) {
int level = Math.max( 0, armor.level );
if (Random.Int( 4 ) == 0) {
Buff.prolong( defender, Roots.class, 5 - level / 5 );
Buff.affect( defender, Earthroot.Armor.class ).level( 5 * (level + 1) );
CellEmitter.bottom( defender.pos ).start( EarthParticle.FACTORY, 0.05f, 8 );
Camera.main.shake( 1, 0.4f );
}
return damage;
}
@Override
public String name( String weaponName) {
return String.format( TXT_ENTANGLEMENT, weaponName );
}
@Override
public Glowing glowing() {
return GREEN;
}
}
| fictionalfridge/shattered-pixel-dungeon | src/com/shatteredpixel/shatteredpixeldungeon/items/armor/glyphs/Entanglement.java | Java | gpl-3.0 | 2,360 |