text
stringlengths 2
99.9k
| meta
dict |
---|---|
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#include <metal_stdlib>
#include <simd/simd.h>
using namespace metal;
struct myBlock
{
int a;
float b[1];
};
// Implementation of the GLSL mod() function, which is slightly different than Metal fmod()
template<typename Tx, typename Ty>
inline Tx mod(Tx x, Ty y)
{
return x - y * floor(x / y);
}
kernel void main0(device myBlock& myStorage [[buffer(0)]], uint3 gl_LocalInvocationID [[thread_position_in_threadgroup]])
{
myStorage.a = (myStorage.a + 1) % 256;
myStorage.b[gl_LocalInvocationID.x] = mod(myStorage.b[gl_LocalInvocationID.x] + 0.0199999995529651641845703125, 1.0);
}
| {
"pile_set_name": "Github"
} |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
CodeMirror.defineExtension("addPanel", function(node, options) {
options = options || {};
if (!this.state.panels) initPanels(this);
var info = this.state.panels;
var wrapper = info.wrapper;
var cmWrapper = this.getWrapperElement();
if (options.after instanceof Panel && !options.after.cleared) {
wrapper.insertBefore(node, options.before.node.nextSibling);
} else if (options.before instanceof Panel && !options.before.cleared) {
wrapper.insertBefore(node, options.before.node);
} else if (options.replace instanceof Panel && !options.replace.cleared) {
wrapper.insertBefore(node, options.replace.node);
options.replace.clear();
} else if (options.position == "bottom") {
wrapper.appendChild(node);
} else if (options.position == "before-bottom") {
wrapper.insertBefore(node, cmWrapper.nextSibling);
} else if (options.position == "after-top") {
wrapper.insertBefore(node, cmWrapper);
} else {
wrapper.insertBefore(node, wrapper.firstChild);
}
var height = (options && options.height) || node.offsetHeight;
this._setSize(null, info.heightLeft -= height);
info.panels++;
return new Panel(this, node, options, height);
});
function Panel(cm, node, options, height) {
this.cm = cm;
this.node = node;
this.options = options;
this.height = height;
this.cleared = false;
}
Panel.prototype.clear = function() {
if (this.cleared) return;
this.cleared = true;
var info = this.cm.state.panels;
this.cm._setSize(null, info.heightLeft += this.height);
info.wrapper.removeChild(this.node);
if (--info.panels == 0) removePanels(this.cm);
};
Panel.prototype.changed = function(height) {
var newHeight = height == null ? this.node.offsetHeight : height;
var info = this.cm.state.panels;
this.cm._setSize(null, info.height += (newHeight - this.height));
this.height = newHeight;
};
function initPanels(cm) {
var wrap = cm.getWrapperElement();
var style = window.getComputedStyle ? window.getComputedStyle(wrap) : wrap.currentStyle;
var height = parseInt(style.height);
var info = cm.state.panels = {
setHeight: wrap.style.height,
heightLeft: height,
panels: 0,
wrapper: document.createElement("div")
};
wrap.parentNode.insertBefore(info.wrapper, wrap);
var hasFocus = cm.hasFocus();
info.wrapper.appendChild(wrap);
if (hasFocus) cm.focus();
cm._setSize = cm.setSize;
if (height != null) cm.setSize = function(width, newHeight) {
if (newHeight == null) return this._setSize(width, newHeight);
info.setHeight = newHeight;
if (typeof newHeight != "number") {
var px = /^(\d+\.?\d*)px$/.exec(newHeight);
if (px) {
newHeight = Number(px[1]);
} else {
info.wrapper.style.height = newHeight;
newHeight = info.wrapper.offsetHeight;
info.wrapper.style.height = "";
}
}
cm._setSize(width, info.heightLeft += (newHeight - height));
height = newHeight;
};
}
function removePanels(cm) {
var info = cm.state.panels;
cm.state.panels = null;
var wrap = cm.getWrapperElement();
info.wrapper.parentNode.replaceChild(wrap, info.wrapper);
wrap.style.height = info.setHeight;
cm.setSize = cm._setSize;
cm.setSize();
}
});
| {
"pile_set_name": "Github"
} |
/* SPDX-License-Identifier: GPL-2.0 */
/*
* Copyright (C) 2019 ARM Limited
*
* Utility macro to ease definition of testcases toggling mode EL
*/
#define DEFINE_TESTCASE_MANGLE_PSTATE_INVALID_MODE(_mode) \
\
static int mangle_invalid_pstate_run(struct tdescr *td, siginfo_t *si, \
ucontext_t *uc) \
{ \
ASSERT_GOOD_CONTEXT(uc); \
\
uc->uc_mcontext.pstate &= ~PSR_MODE_MASK; \
uc->uc_mcontext.pstate |= PSR_MODE_EL ## _mode; \
\
return 1; \
} \
\
struct tdescr tde = { \
.sanity_disabled = true, \
.name = "MANGLE_PSTATE_INVALID_MODE_EL"#_mode, \
.descr = "Mangling uc_mcontext INVALID MODE EL"#_mode, \
.sig_trig = SIGUSR1, \
.sig_ok = SIGSEGV, \
.run = mangle_invalid_pstate_run, \
}
| {
"pile_set_name": "Github"
} |
#include <string.h>
#include "perf_regs.h"
#include "thread.h"
#include "map.h"
#include "event.h"
#include "debug.h"
#include "tests/tests.h"
#include "arch-tests.h"
#define STACK_SIZE 8192
static int sample_ustack(struct perf_sample *sample,
struct thread *thread, u64 *regs)
{
struct stack_dump *stack = &sample->user_stack;
struct map *map;
unsigned long sp;
u64 stack_size, *buf;
buf = malloc(STACK_SIZE);
if (!buf) {
pr_debug("failed to allocate sample uregs data\n");
return -1;
}
sp = (unsigned long) regs[PERF_REG_X86_SP];
map = map_groups__find(thread->mg, MAP__VARIABLE, (u64) sp);
if (!map) {
pr_debug("failed to get stack map\n");
free(buf);
return -1;
}
stack_size = map->end - sp;
stack_size = stack_size > STACK_SIZE ? STACK_SIZE : stack_size;
memcpy(buf, (void *) sp, stack_size);
stack->data = (char *) buf;
stack->size = stack_size;
return 0;
}
int test__arch_unwind_sample(struct perf_sample *sample,
struct thread *thread)
{
struct regs_dump *regs = &sample->user_regs;
u64 *buf;
buf = malloc(sizeof(u64) * PERF_REGS_MAX);
if (!buf) {
pr_debug("failed to allocate sample uregs data\n");
return -1;
}
perf_regs_load(buf);
regs->abi = PERF_SAMPLE_REGS_ABI;
regs->regs = buf;
regs->mask = PERF_REGS_MASK;
return sample_ustack(sample, thread, buf);
}
| {
"pile_set_name": "Github"
} |
var assert = require('assert');
var cookie = require('..');
suite('parse');
test('basic', function() {
assert.deepEqual({ foo: 'bar' }, cookie.parse('foo=bar'));
assert.deepEqual({ foo: '123' }, cookie.parse('foo=123'));
});
test('ignore spaces', function() {
assert.deepEqual({ FOO: 'bar', baz: 'raz' },
cookie.parse('FOO = bar; baz = raz'));
});
test('escaping', function() {
assert.deepEqual({ foo: 'bar=123456789&name=Magic+Mouse' },
cookie.parse('foo="bar=123456789&name=Magic+Mouse"'));
assert.deepEqual({ email: ' ",;/' },
cookie.parse('email=%20%22%2c%3b%2f'));
});
test('ignore escaping error and return original value', function() {
assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar'));
});
test('ignore non values', function() {
assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar;HttpOnly;Secure'));
});
test('unencoded', function() {
assert.deepEqual({ foo: 'bar=123456789&name=Magic+Mouse' },
cookie.parse('foo="bar=123456789&name=Magic+Mouse"',{
decode: function(value) { return value; }
}));
assert.deepEqual({ email: '%20%22%2c%3b%2f' },
cookie.parse('email=%20%22%2c%3b%2f',{
decode: function(value) { return value; }
}));
})
| {
"pile_set_name": "Github"
} |
//-----------------------------------------------------------------------
// <copyright file="ShardCoordinator.cs" company="Akka.NET Project">
// Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using Akka.Actor;
using Akka.Event;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
namespace Akka.Cluster.Sharding
{
using ShardId = String;
internal interface IShardCoordinator
{
PersistentShardCoordinator.State CurrentState { get; set; }
ClusterShardingSettings Settings { get; }
IShardAllocationStrategy AllocationStrategy { get; }
IActorContext Context { get; }
ICancelable RebalanceTask { get; }
Cluster Cluster { get; }
IActorRef Self { get; }
IActorRef Sender { get; }
ILoggingAdapter Log { get; }
ImmutableDictionary<string, ICancelable> UnAckedHostShards { get; set; }
ImmutableDictionary<string, ImmutableHashSet<IActorRef>> RebalanceInProgress { get; set; }
// regions that have requested handoff, for graceful shutdown
ImmutableHashSet<IActorRef> GracefullShutdownInProgress { get; set; }
ImmutableHashSet<IActorRef> AliveRegions { get; set; }
ImmutableHashSet<IActorRef> RegionTerminationInProgress { get; set; }
TimeSpan RemovalMargin { get; }
void Update<TEvent>(TEvent e, Action<TEvent> handler) where TEvent : PersistentShardCoordinator.IDomainEvent;
bool HasAllRegionsRegistered();
}
internal static class ShardCoordinator
{
#region shared part
internal static void Cancel<TCoordinator>(this TCoordinator coordinator) where TCoordinator : IShardCoordinator
{
coordinator.RebalanceTask.Cancel();
coordinator.Cluster.Unsubscribe(coordinator.Self);
}
static bool IsMember<TCoordinator>(this TCoordinator coordinator, IActorRef region) where TCoordinator : IShardCoordinator
{
var addr = region.Path.Address;
return addr == coordinator.Self.Path.Address || coordinator.Cluster.ReadView.Members.Any(m => m.Address == addr && m.Status == MemberStatus.Up);
}
internal static bool Active<TCoordinator>(this TCoordinator coordinator, object message) where TCoordinator : IShardCoordinator
{
switch (message)
{
case PersistentShardCoordinator.Register msg: HandleRegister(coordinator, msg); return true;
case PersistentShardCoordinator.RegisterProxy msg: HandleRegisterProxy(coordinator, msg); return true;
case PersistentShardCoordinator.GetShardHome msg:
{
if (!HandleGetShardHome(coordinator, msg))
{
var shard = msg.Shard;
// location not known, yet
var activeRegions = coordinator.CurrentState.Regions.RemoveRange(coordinator.GracefullShutdownInProgress);
if (activeRegions.Count != 0)
{
var getShardHomeSender = coordinator.Sender;
var regionTask = coordinator.AllocationStrategy.AllocateShard(getShardHomeSender, shard, activeRegions);
// if task completed immediately, just continue
if (regionTask.IsCompleted && !regionTask.IsFaulted)
ContinueGetShardHome(coordinator, shard, regionTask.Result, getShardHomeSender);
else
regionTask.PipeTo(coordinator.Self,
success: region => new PersistentShardCoordinator.AllocateShardResult(shard, region, getShardHomeSender),
failure: _ => new PersistentShardCoordinator.AllocateShardResult(shard, null, getShardHomeSender));
}
}
return true;
}
case PersistentShardCoordinator.AllocateShardResult msg: HandleAllocateShardResult(coordinator, msg); return true;
case PersistentShardCoordinator.ShardStarted msg: HandleShardStated(coordinator, msg); return true;
case ResendShardHost msg: HandleResendShardHost(coordinator, msg); return true;
case RebalanceTick _: HandleRebalanceTick(coordinator); return true;
case PersistentShardCoordinator.RebalanceResult msg: ContinueRebalance(coordinator, msg.Shards); return true;
case RebalanceDone msg: HandleRebalanceDone(coordinator, msg.Shard, msg.Ok); return true;
case PersistentShardCoordinator.GracefulShutdownRequest msg: HandleGracefulShutdownRequest(coordinator, msg); return true;
case GetClusterShardingStats msg: HandleGetClusterShardingStats(coordinator, msg); return true;
case PersistentShardCoordinator.ShardHome _:
// On rebalance, we send ourselves a GetShardHome message to reallocate a
// shard. This receive handles the "response" from that message. i.e. Ignores it.
return true;
case ClusterEvent.ClusterShuttingDown msg:
coordinator.Log.Debug("Shutting down shard coordinator");
// can't stop because supervisor will start it again,
// it will soon be stopped when singleton is stopped
coordinator.Context.Become(ShuttingDown);
return true;
case GetCurrentRegions _:
var regions = coordinator.CurrentState.Regions.Keys
.Select(region => string.IsNullOrEmpty(region.Path.Address.Host) ? coordinator.Cluster.SelfAddress : region.Path.Address)
.ToImmutableHashSet();
coordinator.Sender.Tell(new CurrentRegions(regions));
return true;
case ClusterEvent.CurrentClusterState _:
/* ignore */
return true;
case Terminate _:
coordinator.Log.Debug("Received termination message");
coordinator.Context.Stop(coordinator.Self);
return true;
default: return ReceiveTerminated(coordinator, message);
}
}
private static void AllocateShardHomesForRememberEntities<TCoordinator>(this TCoordinator coordinator) where TCoordinator : IShardCoordinator
{
if (coordinator.Settings.RememberEntities && coordinator.CurrentState.UnallocatedShards.Count > 0)
{
foreach (var unallocatedShard in coordinator.CurrentState.UnallocatedShards)
{
coordinator.Self.Tell(new PersistentShardCoordinator.GetShardHome(unallocatedShard));
}
}
}
private static void SendHostShardMessage<TCoordinator>(this TCoordinator coordinator, String shard, IActorRef region) where TCoordinator : IShardCoordinator
{
region.Tell(new PersistentShardCoordinator.HostShard(shard));
var cancel = coordinator.Context.System.Scheduler.ScheduleTellOnceCancelable(
coordinator.Settings.TunningParameters.ShardStartTimeout,
coordinator.Self,
new ResendShardHost(shard, region),
coordinator.Self);
coordinator.UnAckedHostShards = coordinator.UnAckedHostShards.SetItem(shard, cancel);
}
/// <summary>
/// TBD
/// </summary>
public static void StateInitialized<TCoordinator>(this TCoordinator coordinator) where TCoordinator : IShardCoordinator
{
foreach (var entry in coordinator.CurrentState.Shards)
SendHostShardMessage(coordinator, entry.Key, entry.Value);
AllocateShardHomesForRememberEntities(coordinator);
}
internal static void WatchStateActors<TCoordinator>(this TCoordinator coordinator) where TCoordinator : IShardCoordinator
{
// Optimization:
// Consider regions that don't belong to the current cluster to be terminated.
// This is an optimization that makes it operational faster and reduces the
// amount of lost messages during startup.
var nodes = coordinator.Cluster.ReadView.Members.Select(x => x.Address).ToImmutableHashSet();
foreach (var entry in coordinator.CurrentState.Regions)
{
var a = entry.Key.Path.Address;
if (a.HasLocalScope || nodes.Contains(a))
coordinator.Context.Watch(entry.Key);
else
RegionTerminated(coordinator, entry.Key); // not part of the cluster
}
foreach (var proxy in coordinator.CurrentState.RegionProxies)
{
var a = proxy.Path.Address;
if (a.HasLocalScope || nodes.Contains(a))
coordinator.Context.Watch(proxy);
else
RegionProxyTerminated(coordinator, proxy); // not part of the cluster
}
// Let the quick (those not involving failure detection) Terminated messages
// be processed before starting to reply to GetShardHome.
// This is an optimization that makes it operational faster and reduces the
// amount of lost messages during startup.
coordinator.Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromMilliseconds(500), coordinator.Self, PersistentShardCoordinator.StateInitialized.Instance, ActorRefs.NoSender);
}
internal static bool ReceiveTerminated<TCoordinator>(this TCoordinator coordinator, object message) where TCoordinator : IShardCoordinator
{
switch (message)
{
case Terminated terminated:
var terminatedRef = terminated.ActorRef;
if (coordinator.CurrentState.Regions.ContainsKey(terminatedRef))
{
if (coordinator.RemovalMargin != TimeSpan.Zero && terminated.AddressTerminated &&
coordinator.AliveRegions.Contains(terminatedRef))
{
coordinator.Context.System.Scheduler.ScheduleTellOnce(coordinator.RemovalMargin, coordinator.Self,
new DelayedShardRegionTerminated(terminatedRef), coordinator.Self);
coordinator.RegionTerminationInProgress = coordinator.RegionTerminationInProgress.Add(terminatedRef);
}
else
RegionTerminated(coordinator, terminatedRef);
}
else if (coordinator.CurrentState.RegionProxies.Contains(terminatedRef))
RegionProxyTerminated(coordinator, terminatedRef);
return true;
case DelayedShardRegionTerminated msg:
RegionTerminated(coordinator, msg.Region);
return true;
}
return false;
}
private static void HandleGracefulShutdownRequest<TCoordinator>(this TCoordinator coordinator, PersistentShardCoordinator.GracefulShutdownRequest request) where TCoordinator : IShardCoordinator
{
if (!coordinator.GracefullShutdownInProgress.Contains(request.ShardRegion))
{
if (coordinator.CurrentState.Regions.TryGetValue(request.ShardRegion, out var shards))
{
coordinator.Log.Debug("Graceful shutdown of region [{0}] with shards [{1}]", request.ShardRegion, string.Join(", ", shards));
coordinator.GracefullShutdownInProgress = coordinator.GracefullShutdownInProgress.Add(request.ShardRegion);
ContinueRebalance(coordinator, shards.ToImmutableHashSet());
}
else
{
coordinator.Log.Debug("Unknown region requested graceful shutdown [{0}]", request.ShardRegion);
}
}
}
private static void HandleRebalanceDone<TCoordinator>(this TCoordinator coordinator, string shard, bool ok) where TCoordinator : IShardCoordinator
{
if (ok)
coordinator.Log.Debug("Rebalance shard [{0}] completed successfully", shard);
else
coordinator.Log.Warning("Rebalance shard [{0}] didn't complete within [{1}]", shard, coordinator.Settings.TunningParameters.HandOffTimeout);
// The shard could have been removed by ShardRegionTerminated
if (coordinator.CurrentState.Shards.TryGetValue(shard, out var region))
{
if (ok)
coordinator.Update(new PersistentShardCoordinator.ShardHomeDeallocated(shard), e =>
{
coordinator.CurrentState = coordinator.CurrentState.Updated(e);
coordinator.ClearRebalanceInProgress(shard);
AllocateShardHomesForRememberEntities(coordinator);
});
else
{
// rebalance not completed, graceful shutdown will be retried
coordinator.GracefullShutdownInProgress = coordinator.GracefullShutdownInProgress.Remove(region);
coordinator.ClearRebalanceInProgress(shard);
}
}
else
{
coordinator.ClearRebalanceInProgress(shard);
}
}
private static void ClearRebalanceInProgress<TCoordinator>(this TCoordinator coordinator, string shard) where TCoordinator : IShardCoordinator
{
if (coordinator.RebalanceInProgress.TryGetValue(shard, out var pendingGetShardHome))
{
var msg = new PersistentShardCoordinator.GetShardHome(shard);
foreach (var sender in pendingGetShardHome)
{
coordinator.Self.Tell(msg, sender);
}
coordinator.RebalanceInProgress = coordinator.RebalanceInProgress.Remove(shard);
}
}
private static void DeferGetShardHomeRequest<TCoordinator>(this TCoordinator coordinator, string shard, IActorRef from) where TCoordinator : IShardCoordinator
{
coordinator.Log.Debug("GetShardHome [{0}] request from [{1}] deferred, because rebalance is in progress for this shard. It will be handled when rebalance is done.", shard, from);
var pending = coordinator.RebalanceInProgress.TryGetValue(shard, out var prev)
? prev
: ImmutableHashSet<IActorRef>.Empty;
coordinator.RebalanceInProgress = coordinator.RebalanceInProgress.SetItem(shard, pending.Add(from));
}
private static void HandleRebalanceTick<TCoordinator>(this TCoordinator coordinator) where TCoordinator : IShardCoordinator
{
if (coordinator.CurrentState.Regions.Count != 0)
{
var shardsTask = coordinator.AllocationStrategy.Rebalance(coordinator.CurrentState.Regions, coordinator.RebalanceInProgress.Keys.ToImmutableHashSet());
if (shardsTask.IsCompleted && !shardsTask.IsFaulted)
ContinueRebalance(coordinator, shardsTask.Result);
else
shardsTask.ContinueWith(t => !(t.IsFaulted || t.IsCanceled)
? new PersistentShardCoordinator.RebalanceResult(t.Result)
: new PersistentShardCoordinator.RebalanceResult(ImmutableHashSet<ShardId>.Empty), TaskContinuationOptions.ExecuteSynchronously)
.PipeTo(coordinator.Self);
}
}
private static void HandleResendShardHost<TCoordinator>(this TCoordinator coordinator, ResendShardHost resend) where TCoordinator : IShardCoordinator
{
if (coordinator.CurrentState.Shards.TryGetValue(resend.Shard, out var region) && region.Equals(resend.Region))
SendHostShardMessage(coordinator, resend.Shard, region);
}
private static void HandleShardStated<TCoordinator>(this TCoordinator coordinator, PersistentShardCoordinator.ShardStarted message) where TCoordinator : IShardCoordinator
{
var shard = message.Shard;
if (coordinator.UnAckedHostShards.TryGetValue(shard, out var cancel))
{
cancel.Cancel();
coordinator.UnAckedHostShards = coordinator.UnAckedHostShards.Remove(shard);
}
}
private static void HandleAllocateShardResult<TCoordinator>(this TCoordinator coordinator, PersistentShardCoordinator.AllocateShardResult allocateResult) where TCoordinator : IShardCoordinator
{
if (allocateResult.ShardRegion == null)
coordinator.Log.Debug("Shard [{0}] allocation failed. It will be retried", allocateResult.Shard);
else
ContinueGetShardHome(coordinator, allocateResult.Shard, allocateResult.ShardRegion, allocateResult.GetShardHomeSender);
}
internal static bool HandleGetShardHome<TCoordinator>(this TCoordinator coordinator, PersistentShardCoordinator.GetShardHome getShardHome) where TCoordinator : IShardCoordinator
{
var shard = getShardHome.Shard;
if (coordinator.RebalanceInProgress.ContainsKey(shard))
{
coordinator.DeferGetShardHomeRequest(shard, coordinator.Sender);
return true;
}
else if (!coordinator.HasAllRegionsRegistered())
{
coordinator.Log.Debug("GetShardHome [{0}] request ignored, because not all regions have registered yet.", shard);
return true;
}
else
{
if (coordinator.CurrentState.Shards.TryGetValue(shard, out var region))
{
if (coordinator.RegionTerminationInProgress.Contains(region))
coordinator.Log.Debug("GetShardHome [{0}] request ignored, due to region [{1}] termination in progress.", shard, region);
else
coordinator.Sender.Tell(new PersistentShardCoordinator.ShardHome(shard, region));
return true;
}
else
{
return false;
}
}
}
private static void RegionTerminated<TCoordinator>(this TCoordinator coordinator, IActorRef terminatedRef) where TCoordinator : IShardCoordinator
{
if (coordinator.CurrentState.Regions.TryGetValue(terminatedRef, out var shards))
{
coordinator.Log.Debug("ShardRegion terminated: [{0}]", terminatedRef);
coordinator.RegionTerminationInProgress = coordinator.RegionTerminationInProgress.Add(terminatedRef);
foreach (var shard in shards)
coordinator.Self.Tell(new PersistentShardCoordinator.GetShardHome(shard));
coordinator.Update(new PersistentShardCoordinator.ShardRegionTerminated(terminatedRef), e =>
{
coordinator.CurrentState = coordinator.CurrentState.Updated(e);
coordinator.GracefullShutdownInProgress = coordinator.GracefullShutdownInProgress.Remove(terminatedRef);
coordinator.RegionTerminationInProgress = coordinator.RegionTerminationInProgress.Remove(terminatedRef);
coordinator.AliveRegions = coordinator.AliveRegions.Remove(terminatedRef);
AllocateShardHomesForRememberEntities(coordinator);
});
}
}
private static void RegionProxyTerminated<TCoordinator>(this TCoordinator coordinator, IActorRef proxyRef) where TCoordinator : IShardCoordinator
{
if (coordinator.CurrentState.RegionProxies.Contains(proxyRef))
{
coordinator.Log.Debug("ShardRegion proxy terminated: [{0}]", proxyRef);
coordinator.Update(new PersistentShardCoordinator.ShardRegionProxyTerminated(proxyRef), e => coordinator.CurrentState = coordinator.CurrentState.Updated(e));
}
}
private static void HandleRegisterProxy<TCoordinator>(this TCoordinator coordinator, PersistentShardCoordinator.RegisterProxy registerProxy) where TCoordinator : IShardCoordinator
{
var proxy = registerProxy.ShardRegionProxy;
coordinator.Log.Debug("ShardRegion proxy registered: [{0}]", proxy);
if (coordinator.CurrentState.RegionProxies.Contains(proxy))
proxy.Tell(new PersistentShardCoordinator.RegisterAck(coordinator.Self));
else
{
var context = coordinator.Context;
var self = coordinator.Self;
coordinator.Update(new PersistentShardCoordinator.ShardRegionProxyRegistered(proxy), e =>
{
coordinator.CurrentState = coordinator.CurrentState.Updated(e);
context.Watch(proxy);
proxy.Tell(new PersistentShardCoordinator.RegisterAck(self));
});
}
}
private static void HandleRegister<TCoordinator>(this TCoordinator coordinator, PersistentShardCoordinator.Register message) where TCoordinator : IShardCoordinator
{
var region = message.ShardRegion;
if (IsMember(coordinator, region))
{
coordinator.Log.Debug("ShardRegion registered: [{0}]", region);
coordinator.AliveRegions = coordinator.AliveRegions.Add(region);
if (coordinator.CurrentState.Regions.ContainsKey(region))
{
region.Tell(new PersistentShardCoordinator.RegisterAck(coordinator.Self));
AllocateShardHomesForRememberEntities(coordinator);
}
else
{
var context = coordinator.Context;
var self = coordinator.Self;
coordinator.GracefullShutdownInProgress = coordinator.GracefullShutdownInProgress.Remove(region);
coordinator.Update(new PersistentShardCoordinator.ShardRegionRegistered(region), e =>
{
coordinator.CurrentState = coordinator.CurrentState.Updated(e);
context.Watch(region);
region.Tell(new PersistentShardCoordinator.RegisterAck(self));
AllocateShardHomesForRememberEntities(coordinator);
});
}
}
else coordinator.Log.Debug("ShardRegion [{0}] was not registered since the coordinator currently does not know about a node of that region", region);
}
private static void HandleGetClusterShardingStats<TCoordinator>(this TCoordinator coordinator, GetClusterShardingStats message) where TCoordinator : IShardCoordinator
{
var sender = coordinator.Sender;
Task.WhenAll(
coordinator.AliveRegions.Select(regionActor => regionActor.Ask<ShardRegionStats>(GetShardRegionStats.Instance, message.Timeout).ContinueWith(r => (regionActor, r.Result), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion))
).ContinueWith(allRegionStats =>
{
if (allRegionStats.IsCanceled)
return new ClusterShardingStats(ImmutableDictionary<Address, ShardRegionStats>.Empty);
if (allRegionStats.IsFaulted)
throw allRegionStats.Exception; //TODO check if this is the right way
var regions = allRegionStats.Result.ToImmutableDictionary(i =>
{
Address regionAddress = i.Item1.Path.Address;
Address address = (regionAddress.HasLocalScope && regionAddress.System == coordinator.Cluster.SelfAddress.System) ? coordinator.Cluster.SelfAddress : regionAddress;
return address;
}, j => j.Item2);
return new ClusterShardingStats(regions);
}, TaskContinuationOptions.ExecuteSynchronously).PipeTo(sender);
}
private static bool ShuttingDown(object message)
{
// ignore all
return true;
}
private static void ContinueRebalance<TCoordinator>(this TCoordinator coordinator, IImmutableSet<ShardId> shards) where TCoordinator : IShardCoordinator
{
if (coordinator.Log.IsInfoEnabled && (shards.Count > 0 || !coordinator.RebalanceInProgress.IsEmpty))
{
coordinator.Log.Info("Starting rebalance for shards [{0}]. Current shards rebalancing: [{1}]",
string.Join(",", shards),
string.Join(",", coordinator.RebalanceInProgress.Keys));
}
foreach (var shard in shards)
{
if (!coordinator.RebalanceInProgress.ContainsKey(shard))
{
if (coordinator.CurrentState.Shards.TryGetValue(shard, out var rebalanceFromRegion))
{
coordinator.RebalanceInProgress = coordinator.RebalanceInProgress.SetItem(shard, ImmutableHashSet<IActorRef>.Empty);
coordinator.Log.Debug("Rebalance shard [{0}] from [{1}]", shard, rebalanceFromRegion);
var regions = coordinator.CurrentState.Regions.Keys.Union(coordinator.CurrentState.RegionProxies);
coordinator.Context.ActorOf(RebalanceWorker.Props(shard, rebalanceFromRegion, coordinator.Settings.TunningParameters.HandOffTimeout, regions)
.WithDispatcher(coordinator.Context.Props.Dispatcher));
}
else
coordinator.Log.Debug("Rebalance of non-existing shard [{0}] is ignored", shard);
}
}
}
private static void ContinueGetShardHome<TCoordinator>(this TCoordinator coordinator, string shard, IActorRef region, IActorRef getShardHomeSender) where TCoordinator : IShardCoordinator
{
if (!coordinator.RebalanceInProgress.ContainsKey(shard))
{
if (coordinator.CurrentState.Shards.TryGetValue(shard, out var aref))
{
getShardHomeSender.Tell(new PersistentShardCoordinator.ShardHome(shard, aref));
}
else
{
if (coordinator.CurrentState.Regions.ContainsKey(region) && !coordinator.GracefullShutdownInProgress.Contains(region))
{
coordinator.Update(new PersistentShardCoordinator.ShardHomeAllocated(shard, region), e =>
{
coordinator.CurrentState = coordinator.CurrentState.Updated(e);
coordinator.Log.Debug("Shard [{0}] allocated at [{1}]", e.Shard, e.Region);
SendHostShardMessage(coordinator, e.Shard, e.Region);
getShardHomeSender.Tell(new PersistentShardCoordinator.ShardHome(e.Shard, e.Region));
});
}
else
coordinator.Log.Debug("Allocated region {0} for shard [{1}] is not (any longer) one of the registered regions", region, shard);
}
}
else
{
coordinator.DeferGetShardHomeRequest(shard, getShardHomeSender);
}
}
#endregion
}
}
| {
"pile_set_name": "Github"
} |
{
"Keys" : ["image/*"]
}
| {
"pile_set_name": "Github"
} |
#import <Foundation/Foundation.h>
@interface PodsDummy_Pods : NSObject
@end
@implementation PodsDummy_Pods
@end
| {
"pile_set_name": "Github"
} |
(ns lux.compiler.parallel
(:require (clojure [string :as string]
[set :as set]
[template :refer [do-template]])
clojure.core.match
clojure.core.match.array
(lux [base :as & :refer [|let |do return* return |case]])))
;; [Utils]
(def ^:private !state! (ref {}))
(def ^:private get-compiler
(fn [compiler]
(return* compiler compiler)))
;; [Exports]
(defn setup!
"Must always call this function before using parallel compilation to make sure that the state that is being tracked is in proper shape."
[]
(dosync (ref-set !state! {})))
(defn parallel-compilation [compile-module*]
(fn [module-name]
(|do [compiler get-compiler
:let [[task new?] (dosync (if-let [existing-task (get @!state! module-name)]
(&/T [existing-task false])
(let [new-task (promise)]
(do (alter !state! assoc module-name new-task)
(&/T [new-task true])))))
_ (when new?
(.start (new Thread
(fn []
(let [out-str (with-out-str
(try (|case (&/run-state (compile-module* module-name)
compiler)
(&/$Right post-compiler _)
(deliver task (&/$Right post-compiler))
(&/$Left ?error)
(deliver task (&/$Left ?error)))
(catch Throwable ex
(.printStackTrace ex)
(deliver task (&/$Left "")))))]
(&/|log! out-str))))))]]
(return task))))
| {
"pile_set_name": "Github"
} |
# Connect Session Store using Sequelize
[](https://travis-ci.org/mweibel/connect-session-sequelize)
connect-session-sequelize is a SQL session store using [Sequelize.js](http://sequelizejs.com).
# Installation
Please note that the most recent version requires **express 4.** If you use _express 3_ you should install version 0.0.5 and follow [the instructions in the previous README](https://github.com/mweibel/connect-session-sequelize/blob/7a446de5a7a2ebc562d288a22896d55f0fbe6e5d/README.md).
```
$ npm install connect-session-sequelize
```
# Options
- `db` a successfully connected Sequelize instance
- `table` _(optional)_ a table/model which has already been imported to your Sequelize instance, this can be used if you want to use a specific table in your db
- `modelKey` _(optional)_ a string for the key in sequelize's models-object but it is also the name of the class to which it references (conventionally written in Camelcase) that's why it is "Session" by default if `table` is not defined.
- `tableName` _(optional)_ a string for naming the generated table if `table` is not defined.
Default is the value of `modelKey`.
- `extendDefaultFields` _(optional)_ a way add custom data to table columns. Useful if using a custom model definition
- `disableTouch` _(optional)_ When true, the store will not update the db when receiving a touch() call. This can be useful in limiting db writes and introducing more manual control of session updates.
# Usage
With connect
```javascript
const connect = require("connect");
// for express, just call it with 'require('connect-session-sequelize')(session.Store)'
const SequelizeStore = require("connect-session-sequelize")(
connect.session.Store
);
connect().use(
connect.session({
store: new SequelizeStore(options),
secret: "CHANGEME",
})
);
```
With express 4:
```javascript
// load dependencies
var express = require("express");
var Sequelize = require("sequelize");
var session = require("express-session");
// initalize sequelize with session store
var SequelizeStore = require("connect-session-sequelize")(session.Store);
// create database, ensure 'sqlite3' in your package.json
var sequelize = new Sequelize("database", "username", "password", {
dialect: "sqlite",
storage: "./session.sqlite",
});
// configure express
var app = express();
app.use(
session({
secret: "keyboard cat",
store: new SequelizeStore({
db: sequelize,
}),
resave: false, // we support the touch method so per the express-session docs this should be set to false
proxy: true, // if you do SSL outside of node.
})
);
// continue as normal
```
If you want SequelizeStore to create/sync the database table for you, you can call `sync()` against an instance of `SequelizeStore` - this will run a sequelize `sync()` operation on the model for an initialized SequelizeStore object:
```javascript
var myStore = new SequelizeStore({
db: sequelize,
});
app.use(
session({
secret: "keyboard cat",
store: myStore,
resave: false,
proxy: true,
})
);
myStore.sync();
```
# Session expiry
Session records are automatically expired and removed from the database on an interval. The `cookie.expires` property is used to set session expiry time. If that property doesn't exist, a default expiry of 24 hours is used. Expired session are removed from the database every 15 minutes by default. That interval as well as the default expiry time can be set as store options:
```javascript
new SequelizeStore({
...
checkExpirationInterval: 15 * 60 * 1000, // The interval at which to cleanup expired sessions in milliseconds.
expiration: 24 * 60 * 60 * 1000 // The maximum age (in milliseconds) of a valid session.
});
```
## Expiration interval cleanup: `stopExpiringSessions`
As expirations are checked on an interval timer, `connect-session-sequelize` can keep your process from exiting. This can be problematic e.g. in testing when it is known that the application code will no longer be used, but the test script never terminates. If you know that the process will no longer be used, you can manually clean up the interval by calling the `stopExpiringSessions` method:
```js
// assuming you have set up a typical session store, for example:
var myStore = new SequelizeStore({
db: sequelize,
});
// you can stop expiring sessions (cancel the interval). Example using Mocha:
after("clean up resources", () => {
myStore.stopExpiringSessions();
});
```
# Add custom field(s) as a column
The `extendDefaultFields` can be used to add custom fields to the session table. These fields will be read-only as they will be inserted only when the session is first created as `defaults`. Make sure to return an object which contains unmodified `data` and `expires` properties, or else the module functionality will be broken:
```javascript
sequelize.define("Session", {
sid: {
type: Sequelize.STRING,
primaryKey: true,
},
userId: Sequelize.STRING,
expires: Sequelize.DATE,
data: Sequelize.TEXT,
});
function extendDefaultFields(defaults, session) {
return {
data: defaults.data,
expires: defaults.expires,
userId: session.userId,
};
}
var store = new SequelizeStore({
db: sequelize,
table: "Session",
extendDefaultFields: extendDefaultFields,
});
```
# Contributing/Reporting Bugs
Try to replicate your issue using [mweibel/connect-session-sequelize-example](https://github.com/mweibel/connect-session-sequelize-example/) and add that as a link to your issue.
This way it's much simpler to reproduce and help you.
# License
MIT
| {
"pile_set_name": "Github"
} |
import bar from './sub/index.js';
export { foo } from './sub/index.js';
const baz = { bar };
export { baz };
| {
"pile_set_name": "Github"
} |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if c {
init {
{
enum A {
struct c {
extension NSData {
let NSManagedObject {
class C {
{
}
deinit {
class
case ,
| {
"pile_set_name": "Github"
} |
<?xml version='1.0' ?>
<Plugin id='31326'>
<Command id='16' name='exitwindows'>
<Help>Performs logoff, reboot, shutdown or poweroff of the target computer.</Help>
<Input>
<Option name='logoff' optional='false' group='exittype'>
<Set data='type' value='1'/>
</Option>
<Option name='poweroff' optional='false' group='exittype'>
<Set data='type' value='2'/>
</Option>
<Option name='reboot' optional='false' group='exittype'>
<Set data='type' value='3'/>
</Option>
<Option name='shutdown' optional='false' group='exittype'>
<Set data='type' value='4'/>
</Option>
</Input>
<Output>
<Data name='type' type='uint8_t'/>
</Output>
</Command>
</Plugin>
| {
"pile_set_name": "Github"
} |
# foul-balls
This folder contains the data behind the story [We Watched 906 Foul Balls To Find Out Where The Most Dangerous Ones Land](https://fivethirtyeight.com/features/we-watched-906-foul-balls-to-find-out-where-the-most-dangerous-ones-land/).
`foul-balls.csv` contains 906 foul balls collected from the most foul-heavy day at each of the the 10 stadiums that produced the most foul balls, as of June 5, 2019. Batted-ball data is from [Baseball Savant](https://baseballsavant.mlb.com/statcast_search?hfPT=&hfAB=&hfBBT=&hfPR=foul%7C&hfZ=&stadium=&hfBBL=&hfNewZones=&hfGT=R%7C&hfC=&hfSea=2019%7C&hfSit=&player_type=pitcher&hfOuts=&opponent=&pitcher_throws=&batter_stands=&hfSA=&game_date_gt=&game_date_lt=2019-06-05&hfInfield=&team=&position=&hfOutfield=&hfRO=&home_road=&hfFlag=&hfPull=&metric_1=&hfInn=&min_pitches=0&min_results=0&group_by=venue&sort_col=pitches&player_event_sort=h_launch_speed&sort_order=desc&min_pas=0#results).
Column | Description
-------|-------------
`matchup` | The two teams that played
`game_date`| Date of the most foul-heavy day at each stadium
`type_of_hit` | Fly, grounder, line drive, pop up or batter hits self
`exit_velocity` | Recorded exit velocity of each hit -- blank if not provided
`predicted_zone` | The zone we predicted the foul ball would land in by gauging angles
`camera_zone` | The zone that the foul ball landed in, confirmed by footage
`used_zone` | The zone used for analysis
| {
"pile_set_name": "Github"
} |
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\common.props" />
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>Abp.RedisCache.ProtoBuf</AssemblyName>
<PackageId>Abp.RedisCache.ProtoBuf</PackageId>
<PackageTags>asp.net;asp.net mvc;boilerplate;application framework;web framework;framework;domain driven design;Redis;Caching;Protobuf</PackageTags>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
<RootNamespace>Abp</RootNamespace>
<Description>Abp.RedisCache.ProtoBuf</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Abp.RedisCache\Abp.RedisCache.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="protobuf-net" Version="2.4.6" />
</ItemGroup>
</Project>
| {
"pile_set_name": "Github"
} |
import PropTypes from 'prop-types'
import get from 'lodash.get'
import React, { useEffect, useRef, useState } from 'react'
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import { CopyToClipboard } from 'react-copy-to-clipboard'
import { clearAllBodyScrollLocks, disableBodyScroll } from 'body-scroll-lock'
import useWindowsUtils from '../../utils/WindowsUtils'
function Popover({ shareUrl, open, onClose }) {
const [button, setButton] = useState('Copy')
const wrapper = useRef(null)
const input = useRef(null)
const link = useRef(null)
const windowsUtils = useWindowsUtils()
useEffect(() => {
const clickOutside = event => {
const children = get(wrapper, 'current')
if (children && !children.contains(event.target)) {
onClose()
}
}
document.addEventListener('mousedown', clickOutside)
if (get(input, 'current')) {
get(input, 'current').focus()
}
return () => {
document.removeEventListener('mousedown', clickOutside)
}
}, [onClose, input])
const onEnter = () => {
setButton('Copy')
}
useEffect(() => {
if (get(wrapper, 'current') && open) {
disableBodyScroll(get(wrapper, 'current'))
}
return () => {
clearAllBodyScrollLocks()
}
}, [wrapper, open])
const onCopy = () => {
setButton('Copied!')
input.current.focus()
setTimeout(() => {
onClose()
}, 1000)
}
const urlToShare = `${windowsUtils.origin}/#!${shareUrl}`
return (
<>
<TransitionGroup component={null}>
{open && (
<CSSTransition onEnter={onEnter} classNames='popup' timeout={300}>
<div className='popup-share'>
<div className='popop-share-container' ref={wrapper}>
<div className='popup-header'>
<h1>Share your configuration</h1>
</div>
<div className='popup-content'>
{/* eslint-disable-next-line */}
<label htmlFor='input-share'>
Use this link to share the current configuration. Attributes
can be removed from the URL if you want to rely on our
defaults.
</label>
<div className='control'>
<input
onFocus={event => {
event.target.select()
}}
id='input-share'
className={`input ${
button === 'Copied!' ? 'padding-lg' : ''
}`}
onKeyDown={event => {
if (event.key === 'Escape') {
onClose()
}
}}
readOnly
value={urlToShare}
ref={input}
/>
<CopyToClipboard onCopy={onCopy} text={urlToShare}>
<a
href='/#'
onClick={e => {
e.preventDefault()
}}
className='button'
ref={link}
>
<span className='button-content' tabIndex='-1'>
<span>{button}</span>
</span>
</a>
</CopyToClipboard>
</div>
</div>
<div className='popup-action'>
<a
href='/#'
onClick={e => {
e.preventDefault()
onClose()
}}
className='button'
>
<span className='button-content' tabIndex='-1'>
<span>Close</span>
<span className='secondary desktop-only'>ESC</span>
</span>
</a>
</div>
</div>
</div>
</CSSTransition>
)}
</TransitionGroup>
</>
)
}
Popover.propTypes = {
shareUrl: PropTypes.string.isRequired,
open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
}
export default Popover
| {
"pile_set_name": "Github"
} |
<?php
/**
* @file
* Test organic groups access module.
*/
/**
* Test OG access.
*/
class OgAccessTestCase extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => 'Organic groups access',
'description' => 'Test the visibility of nodes that are handled by organic groups access.',
'group' => 'Organic groups access',
);
}
function setUp() {
parent::setUp('entity', 'og', 'og_access');
node_access_rebuild();
}
/**
* Group with access field .
*/
function testOgAccess() {
$user1 = $this->drupalCreateUser();
$user2 = $this->drupalCreateUser();
$this->drupalLogin($user1);
// Create group and group content node types.
$group_type = $this->drupalCreateContentType();
og_create_field(OG_GROUP_FIELD, 'node', $group_type->type);
og_create_field(OG_ACCESS_FIELD, 'node', $group_type->type);
// Create a group node and enable access.
$settings = array();
$settings['type'] = $group_type->type;
$settings[OG_GROUP_FIELD][LANGUAGE_NONE][0]['value'] = 1;
$settings[OG_ACCESS_FIELD][LANGUAGE_NONE][0]['value'] = 1;
$group_node = $this->drupalCreateNode($settings);
$group = og_get_group('node', $group_node->nid);
// Assert the user is a group member.
$this->assertTrue(og_is_member($group->gid, 'user', $user1), t('User is a group member.'));
// Assert the user can view the group.
$this->drupalGet('node/' . $group_node->nid);
$this->assertResponse('200', t('Group member can view group node.'));
// Assert another user is not a group member.
$this->drupalLogin($user2);
$this->assertFalse(og_is_member($group->gid, 'user', $user2), t('User is not a group member.'));
// Assert non-member can't view the group.
$this->drupalGet('node/' . $group_node->nid);
$this->assertResponse('403', t('Non group member can not view group node.'));
}
/**
* Group with access field and group content with default definition.
*/
function testOgContentAccessDefault() {
$user1 = $this->drupalCreateUser();
$user2 = $this->drupalCreateUser();
$this->drupalLogin($user1);
// Create group and group content node types.
$group_type = $this->drupalCreateContentType();
og_create_field(OG_GROUP_FIELD, 'node', $group_type->type);
og_create_field(OG_ACCESS_FIELD, 'node', $group_type->type);
$group_content_type = $this->drupalCreateContentType();
og_create_field(OG_AUDIENCE_FIELD, 'node', $group_content_type->type);
og_create_field(OG_CONTENT_ACCESS_FIELD, 'node', $group_content_type->type);
// Create a group node and enable access.
$settings = array();
$settings['type'] = $group_type->type;
$settings[OG_GROUP_FIELD][LANGUAGE_NONE][0]['value'] = 1;
$settings[OG_ACCESS_FIELD][LANGUAGE_NONE][0]['value'] = 1;
$group_node = $this->drupalCreateNode($settings);
$group = og_get_group('node', $group_node->nid);
// Create a group content node and set default access.
$settings = array();
$settings['type'] = $group_content_type->type;
$settings[OG_AUDIENCE_FIELD][LANGUAGE_NONE][0]['gid'] = $group->gid;
$settings[OG_CONTENT_ACCESS_FIELD][LANGUAGE_NONE][0]['value'] = OG_CONTENT_ACCESS_DEFAULT;
$group_content_node = $this->drupalCreateNode($settings);
// Assert the user can view the group.
// Assert the user is a group member.
$this->assertTrue(og_is_member($group->gid, 'user', $user1), t('User is a group member.'));
$this->drupalGet('node/' . $group_content_node->nid);
$this->assertResponse('200', t('Group member can view group node.'));
// Assert another user is not a group member.
$this->drupalLogin($user2);
$this->assertFalse(og_is_member($group->gid, 'user', $user2), t('User is not a group member.'));
// Assert non-member can't view the group.
$this->drupalGet('node/' . $group_content_node->nid);
$this->assertResponse('403', t('Non group member can not view group node.'));
}
/**
* Group with access field and group content with different definition from
* the group.
*/
function testOgContentAccessNotDefault() {
$user1 = $this->drupalCreateUser();
$user2 = $this->drupalCreateUser();
$this->drupalLogin($user1);
// Create group and group content node types.
$group_type = $this->drupalCreateContentType();
og_create_field(OG_GROUP_FIELD, 'node', $group_type->type);
og_create_field(OG_ACCESS_FIELD, 'node', $group_type->type);
$group_content_type = $this->drupalCreateContentType();
og_create_field(OG_AUDIENCE_FIELD, 'node', $group_content_type->type);
og_create_field(OG_CONTENT_ACCESS_FIELD, 'node', $group_content_type->type);
// Test group content access, one time when the group is set to be public,
// and one time set to private.
foreach (array(0, 1) as $state) {
// Make sure user1 is logged in.
$this->drupalLogin($user1);
// Create a group node and enable access.
$settings = array();
$settings['type'] = $group_type->type;
$settings[OG_GROUP_FIELD][LANGUAGE_NONE][0]['value'] = 1;
$settings[OG_ACCESS_FIELD][LANGUAGE_NONE][0]['value'] = $state;
$group_node = $this->drupalCreateNode($settings);
$group = og_get_group('node', $group_node->nid);
// Create a group content node and set public access.
$settings = array();
$settings['type'] = $group_content_type->type;
$settings[OG_AUDIENCE_FIELD][LANGUAGE_NONE][0]['gid'] = $group->gid;
$settings[OG_CONTENT_ACCESS_FIELD][LANGUAGE_NONE][0]['value'] = OG_CONTENT_ACCESS_PUBLIC;
$public_node = $this->drupalCreateNode($settings);
// Create a group content node and set private access.
$settings[OG_CONTENT_ACCESS_FIELD][LANGUAGE_NONE][0]['value'] = OG_CONTENT_ACCESS_PRIVATE;
$private_node = $this->drupalCreateNode($settings);
// Assert the user can view the group.
$this->assertTrue(og_is_member($group->gid, 'user', $user1), t('User is a group member.'));
$this->drupalGet('node/' . $public_node->nid);
$this->assertResponse('200', t('Group member can view public group node.'));
$this->drupalGet('node/' . $private_node->nid);
$this->assertResponse('200', t('Group member can view private group node.'));
// Assert another user is not a group member.
$this->drupalLogin($user2);
$this->assertFalse(og_is_member($group->gid, 'user', $user2), t('User is not a group member.'));
// Assert non-member can't view the group.
$this->drupalGet('node/' . $public_node->nid);
$this->assertResponse('200', t('Non group member can view public group node.'));
$this->drupalGet('node/' . $private_node->nid);
$this->assertResponse('403', t('Non group member can not view private group node.'));
}
}
/**
* Test "Strict private" variable enabled or disabled.
*/
function testOgStrictPrivate() {
$user1 = $this->drupalCreateUser();
$user2 = $this->drupalCreateUser();
$this->drupalLogin($user1);
// Create group and group content node types.
$group_type = $this->drupalCreateContentType();
og_create_field(OG_GROUP_FIELD, 'node', $group_type->type);
og_create_field(OG_ACCESS_FIELD, 'node', $group_type->type);
$group_content_type = $this->drupalCreateContentType();
og_create_field(OG_AUDIENCE_FIELD, 'node', $group_content_type->type);
og_create_field(OG_CONTENT_ACCESS_FIELD, 'node', $group_content_type->type);
// Create a group node and set as private.
$settings = array();
$settings['type'] = $group_type->type;
$settings[OG_GROUP_FIELD][LANGUAGE_NONE][0]['value'] = 1;
$settings[OG_ACCESS_FIELD][LANGUAGE_NONE][0]['value'] = 1;
$group_node1 = $this->drupalCreateNode($settings);
$group1 = og_get_group('node', $group_node1->nid);
// Create a group node and set as public.
$settings[OG_ACCESS_FIELD][LANGUAGE_NONE][0]['value'] = 0;
$group_node2 = $this->drupalCreateNode($settings);
$group2 = og_get_group('node', $group_node2->nid);
// Create a group content node and set default access.
$settings = array();
$settings['type'] = $group_content_type->type;
$settings[OG_AUDIENCE_FIELD][LANGUAGE_NONE][0]['gid'] = $group1->gid;
$settings[OG_AUDIENCE_FIELD][LANGUAGE_NONE][1]['gid'] = $group2->gid;
$settings[OG_CONTENT_ACCESS_FIELD][LANGUAGE_NONE][0]['value'] = OG_CONTENT_ACCESS_DEFAULT;
$node = $this->drupalCreateNode($settings);
// Assert the user can view the group.
$this->assertTrue(og_is_member($group1->gid, 'user', $user1), t('User is a group member.'));
$this->drupalGet('node/' . $node->nid);
$this->assertResponse('200', t('Group member can view public group node.'));
// Assert another user is not a group member.
$this->drupalLogin($user2);
$this->assertFalse(og_is_member($group1->gid, 'user', $user2), t('User is not a group member.'));
// Strict private enabled.
variable_set('group_access_strict_private', 1);
$this->drupalGet('node/' . $node->nid);
$this->assertResponse('403', t('Non group member can not view group node when "strict private" is enabled.'));
// Assert all groups were registered in {node_access}.
$records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node->nid))->fetchAll();
$this->assertEqual(count($records), 2, t('Returned the correct number of rows.'));
$this->assertEqual($records[0]->realm, 'group_access_authenticated', t('Grant realm is correct for public group content.'));
$this->assertEqual($records[0]->gid, $group1->gid, t('First gid is the first group ID.'));
$this->assertEqual($records[1]->gid, $group2->gid, t('Second gid is the second group ID.'));
// Strict private enabled.
variable_set('group_access_strict_private', 0);
node_access_rebuild();
$this->drupalGet('node/' . $node->nid);
$this->assertResponse('200', t('Non group member can view public group node.'));
// Assert "all" realm was registered in {node_access}.
$records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node->nid))->fetchAll();
$this->assertEqual(count($records), 1, t('Returned the correct number of rows.'));
$this->assertEqual($records[0]->realm, 'all', t('Grant realm is correct for public group content.'));
}
} | {
"pile_set_name": "Github"
} |
import * as fs from 'fs'
import * as path from 'path'
import * as express from 'express'
import * as LRU from 'lru-cache'
import waitParcel from './configs/wait-parcel'
const favicon = require('serve-favicon')
const compression = require('compression')
const microcache = require('route-cache')
const Mute = require('mute')
const Youch = require('youch')
// const unmute = Mute() // 静音局,禁用掉 Webpack 抛弃的 API 信息。
import { createBundleRenderer } from 'vue-server-renderer'
const resolve = (file: string) => path.resolve(__dirname, file)
const isProd = process.env.NODE_ENV === 'prod'
const useMicroCache = process.env.MICRO_CACHE !== 'false'
const app = express()
const cache = LRU({
max: 1000,
maxAge: 1000 * 60 * 15
})
function createRenderer(bundle: any, options: any) {
return createBundleRenderer(
bundle,
Object.assign(options, {
cache,
basedir: resolve('./dist'),
runInNewContext: false
})
)
}
let renderer: any
let readyPromise: Promise<any>
const templatePath = resolve('src/index.template.html')
if (isProd) {
const template = fs.readFileSync(templatePath, 'utf-8')
const bundle = require(resolve('./dist/vue-ssr-server-bundle.json'))
const clientManifest = require(resolve('./dist/vue-ssr-client-manifest.json'))
renderer = createRenderer(bundle, {
template,
clientManifest
})
} else {
readyPromise = waitParcel(app, templatePath, (bundle: any, options: any) => {
renderer = createRenderer(bundle, options)
})
}
const serve = (path: string, cache: boolean) =>
express.static(resolve(path), {
maxAge: cache && isProd ? 1000 * 60 * 60 * 24 * 30 : 0
})
app.use(compression({ threshold: 0 }))
app.use(favicon('./public/favicon.ico'))
app.use('/dist', serve('./dist', true))
app.use('/public', serve('./public', true))
app.use('/manifest.json', serve('./manifest.json', true))
app.use('/service-worker.js', serve('./dist/service-worker.js', false))
app.use(
microcache.cacheSeconds(1, (req: any) => useMicroCache && req.originalUrl)
)
const handleError = (err: any, req: any, res: any) => {
if (err.url) {
res.redirect(err.url)
} else if (err.code === 404) {
res.status(404).send(err)
} else {
const youch = new Youch(err, req)
youch.toHTML().then(html => {
res.writeHead(200, { 'content-type': 'text/html' })
res.write(html)
res.end()
})
console.error(`error during render : ${req.url}`)
console.error(err.stack)
}
}
function render(req: any, res: any) {
// const s = Date.now()
res.setHeader('Content-Type', 'text/html')
const context = {
title: 'App',
url: req.url
}
renderer.renderToString(context, (err: any, html: string) => {
if (err) {
return handleError(err, req, res)
}
res.send(html)
if (!isProd) {
// console.log(`whole request: ${Date.now() - s}ms`)
}
})
}
app.get(
'*',
isProd
? render
: (req, res) => {
readyPromise.then(() => render(req, res))
}
)
const port = process.env.PORT || 4000
app.listen(port, () => {
// unmute() // 取消静音
console.log(`server started at http://localhost:${port}`)
})
| {
"pile_set_name": "Github"
} |
package network
// Copyright (c) Microsoft and contributors. 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// ExpressRoutePortsClient is the network Client
type ExpressRoutePortsClient struct {
BaseClient
}
// NewExpressRoutePortsClient creates an instance of the ExpressRoutePortsClient client.
func NewExpressRoutePortsClient(subscriptionID string) ExpressRoutePortsClient {
return NewExpressRoutePortsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewExpressRoutePortsClientWithBaseURI creates an instance of the ExpressRoutePortsClient client using a custom
// endpoint. Use this when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure
// stack).
func NewExpressRoutePortsClientWithBaseURI(baseURI string, subscriptionID string) ExpressRoutePortsClient {
return ExpressRoutePortsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate creates or updates the specified ExpressRoutePort resource.
// Parameters:
// resourceGroupName - the name of the resource group.
// expressRoutePortName - the name of the ExpressRoutePort resource.
// parameters - parameters supplied to the create ExpressRoutePort operation.
func (client ExpressRoutePortsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters ExpressRoutePort) (result ExpressRoutePortsCreateOrUpdateFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.CreateOrUpdate")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, expressRoutePortName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
result, err = client.CreateOrUpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "CreateOrUpdate", result.Response(), "Failure sending request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client ExpressRoutePortsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters ExpressRoutePort) (*http.Request, error) {
pathParameters := map[string]interface{}{
"expressRoutePortName": autorest.Encode("path", expressRoutePortName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-03-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
parameters.Etag = nil
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRoutePortsClient) CreateOrUpdateSender(req *http.Request) (future ExpressRoutePortsCreateOrUpdateFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
future.Future, err = azure.NewFutureFromResponse(resp)
return
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client ExpressRoutePortsClient) CreateOrUpdateResponder(resp *http.Response) (result ExpressRoutePort, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the specified ExpressRoutePort resource.
// Parameters:
// resourceGroupName - the name of the resource group.
// expressRoutePortName - the name of the ExpressRoutePort resource.
func (client ExpressRoutePortsClient) Delete(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRoutePortsDeleteFuture, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.Delete")
defer func() {
sc := -1
if result.Response() != nil {
sc = result.Response().StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.DeletePreparer(ctx, resourceGroupName, expressRoutePortName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Delete", nil, "Failure preparing request")
return
}
result, err = client.DeleteSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Delete", result.Response(), "Failure sending request")
return
}
return
}
// DeletePreparer prepares the Delete request.
func (client ExpressRoutePortsClient) DeletePreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"expressRoutePortName": autorest.Encode("path", expressRoutePortName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-03-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRoutePortsClient) DeleteSender(req *http.Request) (future ExpressRoutePortsDeleteFuture, err error) {
var resp *http.Response
resp, err = client.Send(req, azure.DoRetryWithRegistration(client.Client))
if err != nil {
return
}
future.Future, err = azure.NewFutureFromResponse(resp)
return
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client ExpressRoutePortsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get retrieves the requested ExpressRoutePort resource.
// Parameters:
// resourceGroupName - the name of the resource group.
// expressRoutePortName - the name of ExpressRoutePort.
func (client ExpressRoutePortsClient) Get(ctx context.Context, resourceGroupName string, expressRoutePortName string) (result ExpressRoutePort, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.GetPreparer(ctx, resourceGroupName, expressRoutePortName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client ExpressRoutePortsClient) GetPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"expressRoutePortName": autorest.Encode("path", expressRoutePortName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-03-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRoutePortsClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ExpressRoutePortsClient) GetResponder(resp *http.Response) (result ExpressRoutePort, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List list all the ExpressRoutePort resources in the specified subscription.
func (client ExpressRoutePortsClient) List(ctx context.Context) (result ExpressRoutePortListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.List")
defer func() {
sc := -1
if result.erplr.Response.Response != nil {
sc = result.erplr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.erplr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "List", resp, "Failure sending request")
return
}
result.erplr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client ExpressRoutePortsClient) ListPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-03-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/ExpressRoutePorts", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRoutePortsClient) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client ExpressRoutePortsClient) ListResponder(resp *http.Response) (result ExpressRoutePortListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client ExpressRoutePortsClient) listNextResults(ctx context.Context, lastResults ExpressRoutePortListResult) (result ExpressRoutePortListResult, err error) {
req, err := lastResults.expressRoutePortListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client ExpressRoutePortsClient) ListComplete(ctx context.Context) (result ExpressRoutePortListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.List")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.List(ctx)
return
}
// ListByResourceGroup list all the ExpressRoutePort resources in the specified resource group.
// Parameters:
// resourceGroupName - the name of the resource group.
func (client ExpressRoutePortsClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ExpressRoutePortListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.ListByResourceGroup")
defer func() {
sc := -1
if result.erplr.Response.Response != nil {
sc = result.erplr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listByResourceGroupNextResults
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "ListByResourceGroup", nil, "Failure preparing request")
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.erplr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "ListByResourceGroup", resp, "Failure sending request")
return
}
result.erplr, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "ListByResourceGroup", resp, "Failure responding to request")
}
return
}
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client ExpressRoutePortsClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-03-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRoutePortsClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client ExpressRoutePortsClient) ListByResourceGroupResponder(resp *http.Response) (result ExpressRoutePortListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByResourceGroupNextResults retrieves the next set of results, if any.
func (client ExpressRoutePortsClient) listByResourceGroupNextResults(ctx context.Context, lastResults ExpressRoutePortListResult) (result ExpressRoutePortListResult, err error) {
req, err := lastResults.expressRoutePortListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listByResourceGroupNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required.
func (client ExpressRoutePortsClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ExpressRoutePortListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.ListByResourceGroup")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListByResourceGroup(ctx, resourceGroupName)
return
}
// UpdateTags update ExpressRoutePort tags.
// Parameters:
// resourceGroupName - the name of the resource group.
// expressRoutePortName - the name of the ExpressRoutePort resource.
// parameters - parameters supplied to update ExpressRoutePort resource tags.
func (client ExpressRoutePortsClient) UpdateTags(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters TagsObject) (result ExpressRoutePort, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/ExpressRoutePortsClient.UpdateTags")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
req, err := client.UpdateTagsPreparer(ctx, resourceGroupName, expressRoutePortName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "UpdateTags", nil, "Failure preparing request")
return
}
resp, err := client.UpdateTagsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "UpdateTags", resp, "Failure sending request")
return
}
result, err = client.UpdateTagsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.ExpressRoutePortsClient", "UpdateTags", resp, "Failure responding to request")
}
return
}
// UpdateTagsPreparer prepares the UpdateTags request.
func (client ExpressRoutePortsClient) UpdateTagsPreparer(ctx context.Context, resourceGroupName string, expressRoutePortName string, parameters TagsObject) (*http.Request, error) {
pathParameters := map[string]interface{}{
"expressRoutePortName": autorest.Encode("path", expressRoutePortName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2020-03-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateTagsSender sends the UpdateTags request. The method will close the
// http.Response Body if it receives an error.
func (client ExpressRoutePortsClient) UpdateTagsSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// UpdateTagsResponder handles the response to the UpdateTags request. The method always
// closes the http.Response Body.
func (client ExpressRoutePortsClient) UpdateTagsResponder(resp *http.Response) (result ExpressRoutePort, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| {
"pile_set_name": "Github"
} |
//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2011-05-22 GONG Chen <[email protected]>
//
#ifndef RIME_CANDIDATE_H_
#define RIME_CANDIDATE_H_
#include <rime/common.h>
namespace rime {
class Candidate {
public:
Candidate() = default;
Candidate(const string type,
size_t start,
size_t end,
double quality = 0.)
: type_(type), start_(start), end_(end), quality_(quality) {}
virtual ~Candidate() = default;
static an<Candidate>
GetGenuineCandidate(const an<Candidate>& cand);
static vector<of<Candidate>>
GetGenuineCandidates(const an<Candidate>& cand);
// recognized by translators in learning phase
const string& type() const { return type_; }
// [start, end) mark a range in the input that the candidate corresponds to
size_t start() const { return start_; }
size_t end() const { return end_; }
double quality() const { return quality_; }
// candidate text to commit
virtual const string& text() const = 0;
// (optional)
virtual string comment() const { return string(); }
// text shown in the preedit area, replacing input string (optional)
virtual string preedit() const { return string(); }
void set_type(const string& type) { type_ = type; }
void set_start(size_t start) { start_ = start; }
void set_end(size_t end) { end_ = end; }
void set_quality(double quality) { quality_ = quality; }
private:
string type_;
size_t start_ = 0;
size_t end_ = 0;
double quality_ = 0.;
};
using CandidateQueue = list<of<Candidate>>;
using CandidateList = vector<of<Candidate>>;
// useful implimentations
class SimpleCandidate : public Candidate {
public:
SimpleCandidate() = default;
SimpleCandidate(const string type,
size_t start,
size_t end,
const string& text,
const string& comment = string(),
const string& preedit = string())
: Candidate(type, start, end),
text_(text), comment_(comment), preedit_(preedit) {}
const string& text() const { return text_; }
string comment() const { return comment_; }
string preedit() const { return preedit_; }
void set_text(const string& text) { text_ = text; }
void set_comment(const string& comment) { comment_ = comment; }
void set_preedit(const string& preedit) { preedit_ = preedit; }
protected:
string text_;
string comment_;
string preedit_;
};
class ShadowCandidate : public Candidate {
public:
ShadowCandidate(const an<Candidate>& item,
const string& type,
const string& text = string(),
const string& comment = string())
: Candidate(type, item->start(), item->end(), item->quality()),
text_(text), comment_(comment),
item_(item) {}
const string& text() const {
return text_.empty() ? item_->text() : text_;
}
string comment() const {
return comment_.empty() ? item_->comment() : comment_;
}
string preedit() const {
return item_->preedit();
}
const an<Candidate>& item() const { return item_; }
protected:
string text_;
string comment_;
an<Candidate> item_;
};
class UniquifiedCandidate : public Candidate {
public:
UniquifiedCandidate(const an<Candidate>& item,
const string& type,
const string& text = string(),
const string& comment = string())
: Candidate(type, item->start(), item->end(), item->quality()),
text_(text), comment_(comment) {
Append(item);
}
const string& text() const {
return text_.empty() && !items_.empty() ?
items_.front()->text() : text_;
}
string comment() const {
return comment_.empty() && !items_.empty() ?
items_.front()->comment() : comment_;
}
string preedit() const {
return !items_.empty() ? items_.front()->preedit() : string();
}
void Append(an<Candidate> item) {
items_.push_back(item);
if (quality() < item->quality())
set_quality(item->quality());
}
const CandidateList& items() const { return items_; }
protected:
string text_;
string comment_;
CandidateList items_;
};
} // namespace rime
#endif // RIME_CANDIDATE_H_
| {
"pile_set_name": "Github"
} |
import Point from '../Point'
import Collections from '../../../../../java/util/Collections'
import GeometryCollection from '../GeometryCollection'
import ArrayList from '../../../../../java/util/ArrayList'
import GeometryFilter from '../GeometryFilter'
export default class PointExtracter {
constructor() {
PointExtracter.constructor_.apply(this, arguments)
}
static constructor_() {
this._pts = null
const pts = arguments[0]
this._pts = pts
}
static getPoints() {
if (arguments.length === 1) {
const geom = arguments[0]
if (geom instanceof Point)
return Collections.singletonList(geom)
return PointExtracter.getPoints(geom, new ArrayList())
} else if (arguments.length === 2) {
const geom = arguments[0], list = arguments[1]
if (geom instanceof Point)
list.add(geom)
else if (geom instanceof GeometryCollection)
geom.apply(new PointExtracter(list))
return list
}
}
filter(geom) {
if (geom instanceof Point) this._pts.add(geom)
}
get interfaces_() {
return [GeometryFilter]
}
}
| {
"pile_set_name": "Github"
} |
package ro.isdc.wro.maven.plugin.factory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static ro.isdc.wro.model.resource.processor.factory.ConfigurableProcessorsFactory.PARAM_POST_PROCESSORS;
import static ro.isdc.wro.model.resource.processor.factory.ConfigurableProcessorsFactory.PARAM_PRE_PROCESSORS;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.Validate;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import ro.isdc.wro.WroRuntimeException;
import ro.isdc.wro.config.Context;
import ro.isdc.wro.config.jmx.ConfigConstants;
import ro.isdc.wro.extensions.model.factory.SmartWroModelFactory;
import ro.isdc.wro.manager.WroManager;
import ro.isdc.wro.manager.factory.standalone.StandaloneContext;
import ro.isdc.wro.maven.plugin.manager.factory.ConfigurableWroManagerFactory;
import ro.isdc.wro.model.factory.ConfigurableModelFactory;
import ro.isdc.wro.model.factory.XmlModelFactory;
import ro.isdc.wro.model.resource.processor.ResourcePreProcessor;
import ro.isdc.wro.model.resource.processor.decorator.ExtensionsAwareProcessorDecorator;
import ro.isdc.wro.model.resource.processor.decorator.ProcessorDecorator;
import ro.isdc.wro.model.resource.processor.factory.ConfigurableProcessorsFactory;
import ro.isdc.wro.model.resource.processor.factory.ProcessorsFactory;
import ro.isdc.wro.model.resource.processor.impl.css.CssImportPreProcessor;
import ro.isdc.wro.model.resource.processor.impl.css.CssMinProcessor;
import ro.isdc.wro.model.resource.processor.impl.css.CssVariablesProcessor;
import ro.isdc.wro.model.resource.processor.impl.js.JSMinProcessor;
import ro.isdc.wro.util.AbstractDecorator;
/**
* @author Alex Objelean
*/
public class TestConfigurableWroManagerFactory {
@Mock
private FilterConfig mockFilterConfig;
@Mock
private ServletContext mockServletContext;
private ProcessorsFactory processorsFactory;
@Mock
private HttpServletRequest mockRequest;
@Mock
private HttpServletResponse mockResponse;
private ConfigurableWroManagerFactory victim;
private void initFactory(final FilterConfig filterConfig) {
initFactory(filterConfig, new Properties());
}
private void initFactory(final FilterConfig filterConfig, final Properties properties) {
Validate.notNull(properties);
Context.set(Context.webContext(mockRequest, mockResponse, filterConfig));
victim = new ConfigurableWroManagerFactory() {
@Override
protected Properties createProperties() {
return properties;
}
};
final StandaloneContext context = new StandaloneContext();
context.setWroFile(new File("/path/to/file"));
victim.initialize(context);
// create one instance for test
final WroManager manager = victim.create();
processorsFactory = manager.getProcessorsFactory();
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
// init context
Context.set(Context.webContext(mockRequest, mockResponse, mockFilterConfig));
Mockito.when(mockFilterConfig.getServletContext()).thenReturn(mockServletContext);
}
@After
public void tearDown() {
Context.unset();
}
@Test
public void testProcessorsExecutionOrder() {
final Properties props = createProperties(PARAM_PRE_PROCESSORS, JSMinProcessor.ALIAS + ","
+ CssImportPreProcessor.ALIAS + "," + CssVariablesProcessor.ALIAS);
initFactory(mockFilterConfig, props);
final Collection<ResourcePreProcessor> list = processorsFactory.getPreProcessors();
Assert.assertFalse(list.isEmpty());
final Iterator<ResourcePreProcessor> iterator = list.iterator();
assertEquals(JSMinProcessor.class, getProcessor(iterator.next()).getClass());
assertEquals(CssImportPreProcessor.class, getProcessor(iterator.next()).getClass());
assertEquals(CssVariablesProcessor.class, getProcessor(iterator.next()).getClass());
}
private Properties createProperties(final String key, final String value) {
final Properties props = new Properties();
props.setProperty(key, value);
return props;
}
@Test
public void testWithEmptyPreProcessors() {
Mockito.when(mockFilterConfig.getInitParameter(ConfigurableProcessorsFactory.PARAM_PRE_PROCESSORS)).thenReturn("");
initFactory(mockFilterConfig);
assertTrue(processorsFactory.getPreProcessors().isEmpty());
}
@Test(expected = WroRuntimeException.class)
public void cannotUseInvalidPreProcessorsSet() {
initFactory(mockFilterConfig, createProperties(PARAM_PRE_PROCESSORS, "INVALID1,INVALID2"));
processorsFactory.getPreProcessors();
}
@Test
public void testWhenValidPreProcessorsSet() {
initFactory(mockFilterConfig, createProperties(PARAM_PRE_PROCESSORS, "cssUrlRewriting"));
assertEquals(1, processorsFactory.getPreProcessors().size());
}
@Test
public void testWithEmptyPostProcessors() {
Mockito.when(mockFilterConfig.getInitParameter(ConfigurableProcessorsFactory.PARAM_POST_PROCESSORS)).thenReturn("");
initFactory(mockFilterConfig);
assertTrue(processorsFactory.getPostProcessors().isEmpty());
}
@Test(expected = WroRuntimeException.class)
public void cannotUseInvalidPostProcessorsSet() {
initFactory(mockFilterConfig, createProperties(PARAM_POST_PROCESSORS, "INVALID1,INVALID2"));
processorsFactory.getPostProcessors();
}
@Test
public void testWhenValidPostProcessorsSet() {
initFactory(mockFilterConfig, createProperties(PARAM_POST_PROCESSORS, "cssMinJawr, jsMin, cssVariables"));
assertEquals(3, processorsFactory.getPostProcessors().size());
}
@Test
public void testConfigPropertiesWithValidPreProcessor() {
final Properties configProperties = new Properties();
configProperties.setProperty(ConfigurableProcessorsFactory.PARAM_PRE_PROCESSORS, "cssMin");
initFactory(mockFilterConfig, configProperties);
assertEquals(1, processorsFactory.getPreProcessors().size());
assertEquals(CssMinProcessor.class,
getProcessor(processorsFactory.getPreProcessors().iterator().next()).getClass());
}
@Test
public void testConfigPropertiesWithValidPostProcessor() {
final Properties configProperties = new Properties();
configProperties.setProperty(ConfigurableProcessorsFactory.PARAM_POST_PROCESSORS, "jsMin");
initFactory(mockFilterConfig, configProperties);
assertEquals(1, processorsFactory.getPostProcessors().size());
assertEquals(
JSMinProcessor.class,
((ProcessorDecorator) processorsFactory.getPostProcessors().iterator().next()).getDecoratedObject().getClass());
}
@Test
public void testConfigPropertiesWithMultipleValidPostProcessor() {
final Properties configProperties = new Properties();
configProperties.setProperty(ConfigurableProcessorsFactory.PARAM_POST_PROCESSORS, "jsMin, cssMin");
initFactory(mockFilterConfig, configProperties);
assertEquals(2, processorsFactory.getPostProcessors().size());
assertEquals(JSMinProcessor.class,
getProcessor(processorsFactory.getPostProcessors().iterator().next()).getClass());
}
/**
* @return the processor instance which is not a decorator based on provided processor.
*/
private Object getProcessor(final Object processor) {
return processor instanceof ProcessorDecorator ? ((ProcessorDecorator) processor).getOriginalDecoratedObject()
: processor;
}
@Test(expected = WroRuntimeException.class)
public void testConfigPropertiesWithInvalidPreProcessor() {
final Properties configProperties = new Properties();
configProperties.setProperty(PARAM_PRE_PROCESSORS, "INVALID");
initFactory(mockFilterConfig, configProperties);
processorsFactory.getPreProcessors();
}
public void shouldUseExtensionAwareProcessorWhenProcessorNameContainsDotCharacter() {
final Properties configProperties = new Properties();
configProperties.setProperty(PARAM_PRE_PROCESSORS, "jsMin.js");
initFactory(mockFilterConfig, configProperties);
assertEquals(1, processorsFactory.getPreProcessors().size());
assertTrue(processorsFactory.getPreProcessors().iterator().next() instanceof ExtensionsAwareProcessorDecorator);
}
@Test(expected = WroRuntimeException.class)
public void testConfigPropertiesWithInvalidPostProcessor() {
final Properties configProperties = new Properties();
configProperties.setProperty(PARAM_POST_PROCESSORS, "INVALID");
initFactory(mockFilterConfig, configProperties);
processorsFactory.getPostProcessors();
}
@Test
public void shouldUseCorrectDefaultModelFactory() {
initFactory(mockFilterConfig, new Properties());
final ConfigurableModelFactory configurableModelFactory = (ConfigurableModelFactory) AbstractDecorator.getOriginalDecoratedObject(victim.create().getModelFactory());
assertEquals(SmartWroModelFactory.class, configurableModelFactory.getConfiguredStrategy().getClass());
}
@Test
public void shouldUseConfiguredModelFactory() {
final Properties props = createProperties(ConfigurableModelFactory.KEY, XmlModelFactory.ALIAS);
initFactory(mockFilterConfig, props);
final ConfigurableModelFactory configurableModelFactory = (ConfigurableModelFactory) AbstractDecorator.getOriginalDecoratedObject(victim.create().getModelFactory());
assertEquals(XmlModelFactory.class, configurableModelFactory.getConfiguredStrategy().getClass());
}
@Test
public void shouldUseConfiguredParallelPreProcessingFlagFromExtraConfigFile() {
final Properties props = createProperties(ConfigConstants.parallelPreprocessing.name(), Boolean.TRUE.toString());
initFactory(mockFilterConfig, props);
assertTrue(Context.get().getConfig().isParallelPreprocessing());
}
}
| {
"pile_set_name": "Github"
} |
---
title: "C6244 | Microsoft Docs"
ms.date: 11/15/2016
ms.prod: "visual-studio-dev14"
ms.technology: vs-ide-code-analysis
ms.topic: reference
f1_keywords:
- "C6244"
helpviewer_keywords:
- "C6244"
ms.assetid: ce2c853d-3354-40f2-a8c5-569f6e4bfc0a
caps.latest.revision: 14
author: corob-msft
ms.author: corob
manager: jillfra
---
# C6244
[!INCLUDE[vs2017banner](../includes/vs2017banner.md)]
warning C6244: local declaration of \<variable> hides previous declaration at \<line> of \<file>
This warning indicates that a declaration has the same name as a declaration at an outer scope and hides the previous declaration. You will not be able to refer to the previous declaration from inside the local scope. Any intended use of the previous declaration will end up using the local declaration This warning only identifies a scope overlap and not lifetime overlap.
## Example
The following code generates this warning:
```
#include <stdlib.h>
#pragma warning(push)
// disable warning C4101: unreferenced local variable
#pragma warning(disable: 4101)
int i;
void f();
void (*pf)();
void test()
{
// Hide global int with local function pointer
void (*i)(); //Warning: 6244
// Hide global function pointer with an int
int pf; //Warning: 6244
}
#pragma warning(pop)
```
To correct this warning, use the following sample code:
```
#include <stdlib.h>
#pragma warning(push)
// disable warning C4101: unreferenced local variable
#pragma warning(disable: 4101)
int g_i; // modified global variable name
void g_f(); // modified global function name
void (*f_pf)(); // modified global function pointer name
void test()
{
void (*i)();
int pf;
}
#pragma warning(pop)
```
When dealing with memory allocation, review code to determine whether an allocation was saved in one variable and freed by another variable.
| {
"pile_set_name": "Github"
} |
/*
*******************************************************************************
*
* Copyright (C) 1999-2005, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: GUISupport.h
*
* created on: 11/06/2001
* created by: Eric R. Mader
*/
#ifndef __GUISUPPORT_H
#define __GUISUPPORT_H
class GUISupport
{
public:
GUISupport() {};
virtual ~GUISupport() {};
virtual void postErrorMessage(const char *message, const char *title) = 0;
};
#endif
| {
"pile_set_name": "Github"
} |
/*
* fs/cifs/fscache.c - CIFS filesystem cache interface
*
* Copyright (c) 2010 Novell, Inc.
* Author(s): Suresh Jayaraman <[email protected]>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "fscache.h"
#include "cifsglob.h"
#include "cifs_debug.h"
#include "cifs_fs_sb.h"
/*
* Key layout of CIFS server cache index object
*/
struct cifs_server_key {
struct {
uint16_t family; /* address family */
__be16 port; /* IP port */
} hdr;
union {
struct in_addr ipv4_addr;
struct in6_addr ipv6_addr;
};
} __packed;
/*
* Get a cookie for a server object keyed by {IPaddress,port,family} tuple
*/
void cifs_fscache_get_client_cookie(struct TCP_Server_Info *server)
{
const struct sockaddr *sa = (struct sockaddr *) &server->dstaddr;
const struct sockaddr_in *addr = (struct sockaddr_in *) sa;
const struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *) sa;
struct cifs_server_key key;
uint16_t key_len = sizeof(key.hdr);
memset(&key, 0, sizeof(key));
/*
* Should not be a problem as sin_family/sin6_family overlays
* sa_family field
*/
key.hdr.family = sa->sa_family;
switch (sa->sa_family) {
case AF_INET:
key.hdr.port = addr->sin_port;
key.ipv4_addr = addr->sin_addr;
key_len += sizeof(key.ipv4_addr);
break;
case AF_INET6:
key.hdr.port = addr6->sin6_port;
key.ipv6_addr = addr6->sin6_addr;
key_len += sizeof(key.ipv6_addr);
break;
default:
cifs_dbg(VFS, "Unknown network family '%d'\n", sa->sa_family);
server->fscache = NULL;
return;
}
server->fscache =
fscache_acquire_cookie(cifs_fscache_netfs.primary_index,
&cifs_fscache_server_index_def,
&key, key_len,
NULL, 0,
server, 0, true);
cifs_dbg(FYI, "%s: (0x%p/0x%p)\n",
__func__, server, server->fscache);
}
void cifs_fscache_release_client_cookie(struct TCP_Server_Info *server)
{
cifs_dbg(FYI, "%s: (0x%p/0x%p)\n",
__func__, server, server->fscache);
fscache_relinquish_cookie(server->fscache, NULL, false);
server->fscache = NULL;
}
void cifs_fscache_get_super_cookie(struct cifs_tcon *tcon)
{
struct TCP_Server_Info *server = tcon->ses->server;
char *sharename;
sharename = extract_sharename(tcon->treeName);
if (IS_ERR(sharename)) {
cifs_dbg(FYI, "%s: couldn't extract sharename\n", __func__);
tcon->fscache = NULL;
return;
}
tcon->fscache =
fscache_acquire_cookie(server->fscache,
&cifs_fscache_super_index_def,
sharename, strlen(sharename),
&tcon->resource_id, sizeof(tcon->resource_id),
tcon, 0, true);
kfree(sharename);
cifs_dbg(FYI, "%s: (0x%p/0x%p)\n",
__func__, server->fscache, tcon->fscache);
}
void cifs_fscache_release_super_cookie(struct cifs_tcon *tcon)
{
cifs_dbg(FYI, "%s: (0x%p)\n", __func__, tcon->fscache);
fscache_relinquish_cookie(tcon->fscache, &tcon->resource_id, false);
tcon->fscache = NULL;
}
static void cifs_fscache_acquire_inode_cookie(struct cifsInodeInfo *cifsi,
struct cifs_tcon *tcon)
{
struct cifs_fscache_inode_auxdata auxdata;
memset(&auxdata, 0, sizeof(auxdata));
auxdata.eof = cifsi->server_eof;
auxdata.last_write_time_sec = cifsi->vfs_inode.i_mtime.tv_sec;
auxdata.last_change_time_sec = cifsi->vfs_inode.i_ctime.tv_sec;
auxdata.last_write_time_nsec = cifsi->vfs_inode.i_mtime.tv_nsec;
auxdata.last_change_time_nsec = cifsi->vfs_inode.i_ctime.tv_nsec;
cifsi->fscache =
fscache_acquire_cookie(tcon->fscache,
&cifs_fscache_inode_object_def,
&cifsi->uniqueid, sizeof(cifsi->uniqueid),
&auxdata, sizeof(auxdata),
cifsi, cifsi->vfs_inode.i_size, true);
}
static void cifs_fscache_enable_inode_cookie(struct inode *inode)
{
struct cifsInodeInfo *cifsi = CIFS_I(inode);
struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
struct cifs_tcon *tcon = cifs_sb_master_tcon(cifs_sb);
if (cifsi->fscache)
return;
if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE))
return;
cifs_fscache_acquire_inode_cookie(cifsi, tcon);
cifs_dbg(FYI, "%s: got FH cookie (0x%p/0x%p)\n",
__func__, tcon->fscache, cifsi->fscache);
}
void cifs_fscache_release_inode_cookie(struct inode *inode)
{
struct cifs_fscache_inode_auxdata auxdata;
struct cifsInodeInfo *cifsi = CIFS_I(inode);
if (cifsi->fscache) {
memset(&auxdata, 0, sizeof(auxdata));
auxdata.eof = cifsi->server_eof;
auxdata.last_write_time_sec = cifsi->vfs_inode.i_mtime.tv_sec;
auxdata.last_change_time_sec = cifsi->vfs_inode.i_ctime.tv_sec;
auxdata.last_write_time_nsec = cifsi->vfs_inode.i_mtime.tv_nsec;
auxdata.last_change_time_nsec = cifsi->vfs_inode.i_ctime.tv_nsec;
cifs_dbg(FYI, "%s: (0x%p)\n", __func__, cifsi->fscache);
fscache_relinquish_cookie(cifsi->fscache, &auxdata, false);
cifsi->fscache = NULL;
}
}
static void cifs_fscache_disable_inode_cookie(struct inode *inode)
{
struct cifsInodeInfo *cifsi = CIFS_I(inode);
if (cifsi->fscache) {
cifs_dbg(FYI, "%s: (0x%p)\n", __func__, cifsi->fscache);
fscache_uncache_all_inode_pages(cifsi->fscache, inode);
fscache_relinquish_cookie(cifsi->fscache, NULL, true);
cifsi->fscache = NULL;
}
}
void cifs_fscache_set_inode_cookie(struct inode *inode, struct file *filp)
{
if ((filp->f_flags & O_ACCMODE) != O_RDONLY)
cifs_fscache_disable_inode_cookie(inode);
else
cifs_fscache_enable_inode_cookie(inode);
}
void cifs_fscache_reset_inode_cookie(struct inode *inode)
{
struct cifsInodeInfo *cifsi = CIFS_I(inode);
struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
struct cifs_tcon *tcon = cifs_sb_master_tcon(cifs_sb);
struct fscache_cookie *old = cifsi->fscache;
if (cifsi->fscache) {
/* retire the current fscache cache and get a new one */
fscache_relinquish_cookie(cifsi->fscache, NULL, true);
cifs_fscache_acquire_inode_cookie(cifsi, tcon);
cifs_dbg(FYI, "%s: new cookie 0x%p oldcookie 0x%p\n",
__func__, cifsi->fscache, old);
}
}
int cifs_fscache_release_page(struct page *page, gfp_t gfp)
{
if (PageFsCache(page)) {
struct inode *inode = page->mapping->host;
struct cifsInodeInfo *cifsi = CIFS_I(inode);
cifs_dbg(FYI, "%s: (0x%p/0x%p)\n",
__func__, page, cifsi->fscache);
if (!fscache_maybe_release_page(cifsi->fscache, page, gfp))
return 0;
}
return 1;
}
static void cifs_readpage_from_fscache_complete(struct page *page, void *ctx,
int error)
{
cifs_dbg(FYI, "%s: (0x%p/%d)\n", __func__, page, error);
if (!error)
SetPageUptodate(page);
unlock_page(page);
}
/*
* Retrieve a page from FS-Cache
*/
int __cifs_readpage_from_fscache(struct inode *inode, struct page *page)
{
int ret;
cifs_dbg(FYI, "%s: (fsc:%p, p:%p, i:0x%p\n",
__func__, CIFS_I(inode)->fscache, page, inode);
ret = fscache_read_or_alloc_page(CIFS_I(inode)->fscache, page,
cifs_readpage_from_fscache_complete,
NULL,
GFP_KERNEL);
switch (ret) {
case 0: /* page found in fscache, read submitted */
cifs_dbg(FYI, "%s: submitted\n", __func__);
return ret;
case -ENOBUFS: /* page won't be cached */
case -ENODATA: /* page not in cache */
cifs_dbg(FYI, "%s: %d\n", __func__, ret);
return 1;
default:
cifs_dbg(VFS, "unknown error ret = %d\n", ret);
}
return ret;
}
/*
* Retrieve a set of pages from FS-Cache
*/
int __cifs_readpages_from_fscache(struct inode *inode,
struct address_space *mapping,
struct list_head *pages,
unsigned *nr_pages)
{
int ret;
cifs_dbg(FYI, "%s: (0x%p/%u/0x%p)\n",
__func__, CIFS_I(inode)->fscache, *nr_pages, inode);
ret = fscache_read_or_alloc_pages(CIFS_I(inode)->fscache, mapping,
pages, nr_pages,
cifs_readpage_from_fscache_complete,
NULL,
mapping_gfp_mask(mapping));
switch (ret) {
case 0: /* read submitted to the cache for all pages */
cifs_dbg(FYI, "%s: submitted\n", __func__);
return ret;
case -ENOBUFS: /* some pages are not cached and can't be */
case -ENODATA: /* some pages are not cached */
cifs_dbg(FYI, "%s: no page\n", __func__);
return 1;
default:
cifs_dbg(FYI, "unknown error ret = %d\n", ret);
}
return ret;
}
void __cifs_readpage_to_fscache(struct inode *inode, struct page *page)
{
struct cifsInodeInfo *cifsi = CIFS_I(inode);
int ret;
cifs_dbg(FYI, "%s: (fsc: %p, p: %p, i: %p)\n",
__func__, cifsi->fscache, page, inode);
ret = fscache_write_page(cifsi->fscache, page,
cifsi->vfs_inode.i_size, GFP_KERNEL);
if (ret != 0)
fscache_uncache_page(cifsi->fscache, page);
}
void __cifs_fscache_readpages_cancel(struct inode *inode, struct list_head *pages)
{
cifs_dbg(FYI, "%s: (fsc: %p, i: %p)\n",
__func__, CIFS_I(inode)->fscache, inode);
fscache_readpages_cancel(CIFS_I(inode)->fscache, pages);
}
void __cifs_fscache_invalidate_page(struct page *page, struct inode *inode)
{
struct cifsInodeInfo *cifsi = CIFS_I(inode);
struct fscache_cookie *cookie = cifsi->fscache;
cifs_dbg(FYI, "%s: (0x%p/0x%p)\n", __func__, page, cookie);
fscache_wait_on_page_write(cookie, page);
fscache_uncache_page(cookie, page);
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2016 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.robotframework.ide.eclipse.main.plugin.tableeditor.assist;
import java.util.List;
import java.util.Optional;
import org.eclipse.nebula.widgets.nattable.data.IRowDataProvider;
import org.rf.ide.core.environment.IRuntimeEnvironment;
import org.rf.ide.core.testdata.text.read.recognizer.RobotToken;
import org.robotframework.ide.eclipse.main.plugin.assist.AssistProposal;
import org.robotframework.ide.eclipse.main.plugin.assist.AssistProposalPredicate;
import org.robotframework.ide.eclipse.main.plugin.assist.AssistProposalPredicates;
import org.robotframework.ide.eclipse.main.plugin.assist.DisableSettingReservedWordProposals;
import org.robotframework.ide.eclipse.main.plugin.assist.ForLoopReservedWordsProposals;
import org.robotframework.ide.eclipse.main.plugin.assist.GherkinReservedWordProposals;
import org.robotframework.ide.eclipse.main.plugin.model.RobotKeywordCall;
import org.robotframework.red.jface.assist.AssistantContext;
import org.robotframework.red.jface.assist.RedContentProposal;
import org.robotframework.red.jface.assist.RedContentProposalProvider;
import org.robotframework.red.nattable.edit.AssistanceSupport.NatTableAssistantContext;
import com.google.common.collect.Streams;
public class CodeReservedWordsProposalsProvider implements RedContentProposalProvider {
private final IRuntimeEnvironment environment;
private final IRowDataProvider<?> dataProvider;
public CodeReservedWordsProposalsProvider(final IRuntimeEnvironment environment,
final IRowDataProvider<?> dataProvider) {
this.environment = environment;
this.dataProvider = dataProvider;
}
@Override
public boolean shouldShowProposals(final AssistantContext context) {
return true;
}
@Override
public RedContentProposal[] getProposals(final String contents, final int position,
final AssistantContext context) {
final NatTableAssistantContext tableContext = (NatTableAssistantContext) context;
final String prefix = contents.substring(0, position);
final List<? extends AssistProposal> loopsProposals = new ForLoopReservedWordsProposals(
createForLoopsPredicate(tableContext)).getReservedWordProposals(prefix);
final List<? extends AssistProposal> gherkinProposals = new GherkinReservedWordProposals(
createGherkinPredicate(tableContext)).getReservedWordProposals(prefix);
final List<? extends AssistProposal> disableSettingProposals = new DisableSettingReservedWordProposals(
createDisableSettingPredicate(tableContext)).getReservedWordProposals(prefix);
return Streams.concat(loopsProposals.stream(), gherkinProposals.stream(), disableSettingProposals.stream())
.map(proposal -> GherkinReservedWordProposals.GHERKIN_ELEMENTS.contains(proposal.getLabel())
? new AssistProposalAdapter(environment, proposal, " ")
: new AssistProposalAdapter(environment, proposal, p -> true))
.toArray(RedContentProposal[]::new);
}
private AssistProposalPredicate<String> createForLoopsPredicate(final NatTableAssistantContext context) {
final Object tableElement = dataProvider.getRowObject(context.getRow());
if (tableElement instanceof RobotKeywordCall) {
final List<RobotToken> tokens = ((RobotKeywordCall) tableElement).getLinkedElement().getElementTokens();
final Optional<RobotToken> firstTokenInLine = tokens.stream().findFirst();
return AssistProposalPredicates.forLoopReservedWordsPredicate(context.getColumn() + 1, firstTokenInLine);
} else {
return AssistProposalPredicates.alwaysFalse();
}
}
private AssistProposalPredicate<String> createGherkinPredicate(final NatTableAssistantContext context) {
final Object tableElement = dataProvider.getRowObject(context.getRow());
return tableElement instanceof RobotKeywordCall
? AssistProposalPredicates.gherkinReservedWordsPredicate(context.getColumn() + 1)
: AssistProposalPredicates.alwaysFalse();
}
private AssistProposalPredicate<String> createDisableSettingPredicate(final NatTableAssistantContext context) {
final Object tableElement = dataProvider.getRowObject(context.getRow());
if (tableElement instanceof RobotKeywordCall) {
final List<RobotToken> tokens = ((RobotKeywordCall) tableElement).getLinkedElement().getElementTokens();
final Optional<RobotToken> firstTokenInLine = tokens.stream().findFirst();
return AssistProposalPredicates.disableSettingReservedWordPredicate(context.getColumn() + 1,
firstTokenInLine);
} else {
return AssistProposalPredicates.alwaysFalse();
}
}
}
| {
"pile_set_name": "Github"
} |
// author: Jannik Strötgen
// email: [email protected]
// date: 2015-03-24
// This file contains normalization information for date words.
"monday","1"
"tuesday","2"
"wednesday","3"
"thursday","4"
"friday","5"
"saturday","6"
"sunday","7"
"Monday","1"
"Tuesday","2"
"Wednesday","3"
"Thursday","4"
"Friday","5"
"Saturday","6"
"Sunday","7"
| {
"pile_set_name": "Github"
} |
// Generated by CoffeeScript 1.6.3
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jade: {
dev: {
options: {
pretty: true
},
files: {
'temp/_template.html': 'src/abn_tree_template.jade',
'test/tests_page.html': 'test/tests_page.jade'
}
},
bs2_ng115_test_page: {
files: {
'test/bs2_ng115_test_page.html': 'test/test_page.jade'
},
options: {
pretty: true,
data: {
bs: "2",
ng: "1.1.5"
}
}
},
bs3_ng115_test_page: {
files: {
'test/bs3_ng115_test_page.html': 'test/test_page.jade'
},
options: {
pretty: true,
data: {
bs: "3",
ng: "1.1.5"
}
}
},
bs2_ng120_test_page: {
files: {
'test/bs2_ng120_test_page.html': 'test/test_page.jade'
},
options: {
pretty: true,
data: {
bs: "2",
ng: "1.2.12"
}
}
},
bs3_ng120_test_page: {
files: {
'test/bs3_ng120_test_page.html': 'test/test_page.jade'
},
options: {
pretty: true,
data: {
bs: "3",
ng: "1.2.12"
}
}
}
},
"string-replace": {
dev: {
files: {
'temp/_directive.coffee': 'src/abn_tree_directive.coffee'
},
options: {
replacements: [
{
pattern: "{html}",
replacement_old: "<h1>i am the replacement!</h1>",
replacement: function(match, p1, offset, string) {
return grunt.file.read('temp/_template.html');
}
}
]
}
}
},
coffee: {
dev: {
options: {
bare: false
},
files: {
'dist/abn_tree_directive.js': 'temp/_directive.coffee',
'test/test_page.js': 'test/test_page.coffee'
}
}
},
watch: {
jade: {
files: ['**/*.jade'],
tasks: ['jade', 'string-replace'],
options: {
livereload: true
}
},
css: {
files: ['**/*.css'],
tasks: [],
options: {
livereload: true
}
},
coffee: {
files: ['**/*.coffee'],
tasks: ['jade', 'string-replace', 'coffee'],
options: {
livereload: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-jade');
grunt.loadNpmTasks('grunt-contrib-coffee');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-string-replace');
return grunt.registerTask('default', ['jade', 'string-replace', 'coffee', 'watch']);
};
| {
"pile_set_name": "Github"
} |
["do",
["`", "Utility Functions"],
["def", "_cmp_seqs", ["fn", ["a", "b"],
["if", ["not", ["=", ["count", "a"], ["count", "b"]]],
false,
["if", ["empty?", "a"],
true,
["if", ["equal?", ["get", "a", 0], ["get", "b", 0]],
["_cmp_seqs", ["rest", "a"], ["rest", "b"]],
false]]]]],
["def", "_check_hash_map_keys", ["fn", ["ks", "a", "b"],
["if", ["empty?", "ks"],
true,
["let", ["k", ["first", "ks"]],
["if", ["equal?", ["get", "a", "k"], ["get", "b", "k"]],
["_check_hash_map_keys", ["rest", "ks"], "a", "b"],
false]]]]],
["def", "_cmp_hash_maps", ["fn", ["a", "b"],
["let", ["aks", ["keys", "a"]],
["if", ["not", ["=", ["count", "aks"], ["count", ["keys", "b"]]]],
false,
["_check_hash_map_keys", "aks", "a", "b"]]]]],
["def", "equal?", ["fn", ["a", "b"],
["if", ["sequential?", "a"],
["if", ["sequential?", "b"],
["_cmp_seqs", "a", "b"],
false],
["if", ["map?", "a"],
["if", ["map?", "b"],
["_cmp_hash_maps", "a", "b"],
false],
["if", ["symbol?", "a"],
["if", ["symbol?", "b"],
["=", ["get", "a", ["`", "val"]], ["get", "b", ["`", "val"]]],
false],
["=", "a", "b"]]]]]],
["def", "_clone", ["fn", ["obj"],
["if", ["list?", "obj"],
["slice", "obj", 0],
["if", ["vector?", "obj"],
["let", ["new-obj", ["slice", "obj", 0]],
["do",
["set", "new-obj", ["`", "__vector?__"], true],
"new-obj"]],
["if", ["map?", "obj"],
["let", ["new-obj", ["hash-map"]],
["do",
["map", ["fn", ["k"],
["if", [".", "obj", ["`", "hasOwnProperty"], "k"],
["set", "new-obj", "k", ["get", "obj", "k"]],
null]],
["keys", "obj"]],
"new-obj"]],
["if", ["malfunc?", "obj"],
["let", ["new-obj", ["malfunc", ["get", "obj", ["`", "fn"]],
["get", "obj", ["`", "ast"]],
["get", "obj", ["`", "env"]],
["get", "obj", ["`", "params"]]]],
["do",
["set", "new-obj", ["`", "macro?"], ["get", "obj", ["`", "macro?"]]],
["set", "new-obj", ["`", "__meta__"], ["get", "obj", ["`", "__meta__"]]],
"new-obj"]],
["throw", "clone of unsupported type"]]]]]]],
["def", "clone", ["fn", ["obj"],
["let", ["new-obj", ["_clone", "obj"]],
["do",
[".", "Object", ["`", "defineProperty"], "new-obj", ["`", "__meta__"],
{"enumerable": false, "writable": true}],
"new-obj"]]]],
["def", "assoc!", ["fn", ["a", "b", "c"], ["do", ["set", "a", "b", "c"], "a"]]],
["def", "assocs!", ["fn", ["hm", "kvs"],
["if", ["empty?", "kvs"],
"hm",
["do",
["assoc!", "hm", ["get", "kvs", 0], ["get", "kvs", 1]],
["assocs!", "hm", ["slice", "kvs", 2]]]]]],
["def", "Symbol", ["fn", [], null]],
["def", "symbol", ["fn", ["name"],
["assoc!", ["new", "Symbol"], ["`", "val"], "name"]]],
["def", "symbol?", ["fn", ["a"],
["isa", "a", "Symbol"]]],
["def", "keyword", ["fn", ["name"],
["str", ["`", "\u029e"], "name"]]],
["def", "keyword?", ["fn", ["kw"],
["and", ["=", ["`", "[object String]"], ["classOf", "kw"]],
["=", ["`", "\u029e"], ["get", "kw", 0]]]]],
["`", "Override some list defs to account for Vectors"],
["def", "sequential?", ["fn", ["a"],
[".", "Array", ["`", "isArray"], "a"]]],
["def", "list?", ["fn", ["a"],
["if", [".", "Array", ["`", "isArray"], "a"],
["if", [".-", "a", ["`", "__vector?__"]],
false,
true],
false]]],
["def", "empty?", ["fn", ["a"],
["if", ["sequential?", "a"],
["if", ["=", 0, [".-", "a", ["`", "length"]]],
true,
false],
["=", "a", null]]]],
["def", "vectorl", ["fn", ["lst"],
["let", ["vec", ["slice", "lst", 0]],
["do",
["set", "vec", ["`", "__vector?__"], true],
"vec"]]]],
["def", "vector", ["fn", ["&", "args"], ["vectorl", "args"]]],
["def", "vector?", ["fn", ["a"],
["if", [".", "Array", ["`", "isArray"], "a"],
["if", [".-", "a", ["`", "__vector?__"]],
true,
false],
false]]],
["def", "HashMap", ["fn", [], null]],
["def", "hash-map", ["fn", ["&", "a"],
["assocs!", ["new", "HashMap"], "a"]]],
["def", "map?", ["fn", ["a"],
["isa", "a", "HashMap"]]],
["def", "MalFunc", ["fn", [], null]],
["def", "malfunc", ["fn", ["fn", "ast", "env", "params"],
["assocs!", ["new", "MalFunc"],
["list", ["`", "fn"], "fn",
["`", "ast"], "ast",
["`", "env"], "env",
["`", "params"], "params",
["`", "macro?"], false]]]],
["def", "malfunc?", ["fn", ["a"],
["isa", "a", "MalFunc"]]],
["def", "Atom", ["fn", [], null]],
["def", "atom", ["fn", ["a"],
["let", ["atm", ["new", "Atom"]],
["do",
["set", "atm", ["`", "val"], "a"],
"atm"]]]],
["def", "atom?", ["fn", ["a"],
["isa", "a", "Atom"]]],
null
]
| {
"pile_set_name": "Github"
} |
package cli
import (
"errors"
"flag"
"reflect"
"strings"
"syscall"
)
// Context is a type that is passed through to
// each Handler action in a cli application. Context
// can be used to retrieve context-specific Args and
// parsed command-line options.
type Context struct {
App *App
Command Command
shellComplete bool
flagSet *flag.FlagSet
setFlags map[string]bool
parentContext *Context
}
// NewContext creates a new context. For use in when invoking an App or Command action.
func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context {
c := &Context{App: app, flagSet: set, parentContext: parentCtx}
if parentCtx != nil {
c.shellComplete = parentCtx.shellComplete
}
return c
}
// NumFlags returns the number of flags set
func (c *Context) NumFlags() int {
return c.flagSet.NFlag()
}
// Set sets a context flag to a value.
func (c *Context) Set(name, value string) error {
c.setFlags = nil
return c.flagSet.Set(name, value)
}
// GlobalSet sets a context flag to a value on the global flagset
func (c *Context) GlobalSet(name, value string) error {
globalContext(c).setFlags = nil
return globalContext(c).flagSet.Set(name, value)
}
// IsSet determines if the flag was actually set
func (c *Context) IsSet(name string) bool {
if c.setFlags == nil {
c.setFlags = make(map[string]bool)
c.flagSet.Visit(func(f *flag.Flag) {
c.setFlags[f.Name] = true
})
c.flagSet.VisitAll(func(f *flag.Flag) {
if _, ok := c.setFlags[f.Name]; ok {
return
}
c.setFlags[f.Name] = false
})
// XXX hack to support IsSet for flags with EnvVar
//
// There isn't an easy way to do this with the current implementation since
// whether a flag was set via an environment variable is very difficult to
// determine here. Instead, we intend to introduce a backwards incompatible
// change in version 2 to add `IsSet` to the Flag interface to push the
// responsibility closer to where the information required to determine
// whether a flag is set by non-standard means such as environment
// variables is avaliable.
//
// See https://github.com/urfave/cli/issues/294 for additional discussion
flags := c.Command.Flags
if c.Command.Name == "" { // cannot == Command{} since it contains slice types
if c.App != nil {
flags = c.App.Flags
}
}
for _, f := range flags {
eachName(f.GetName(), func(name string) {
if isSet, ok := c.setFlags[name]; isSet || !ok {
return
}
val := reflect.ValueOf(f)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
envVarValue := val.FieldByName("EnvVar")
if !envVarValue.IsValid() {
return
}
eachName(envVarValue.String(), func(envVar string) {
envVar = strings.TrimSpace(envVar)
if _, ok := syscall.Getenv(envVar); ok {
c.setFlags[name] = true
return
}
})
})
}
}
return c.setFlags[name]
}
// GlobalIsSet determines if the global flag was actually set
func (c *Context) GlobalIsSet(name string) bool {
ctx := c
if ctx.parentContext != nil {
ctx = ctx.parentContext
}
for ; ctx != nil; ctx = ctx.parentContext {
if ctx.IsSet(name) {
return true
}
}
return false
}
// FlagNames returns a slice of flag names used in this context.
func (c *Context) FlagNames() (names []string) {
for _, flag := range c.Command.Flags {
name := strings.Split(flag.GetName(), ",")[0]
if name == "help" {
continue
}
names = append(names, name)
}
return
}
// GlobalFlagNames returns a slice of global flag names used by the app.
func (c *Context) GlobalFlagNames() (names []string) {
for _, flag := range c.App.Flags {
name := strings.Split(flag.GetName(), ",")[0]
if name == "help" || name == "version" {
continue
}
names = append(names, name)
}
return
}
// Parent returns the parent context, if any
func (c *Context) Parent() *Context {
return c.parentContext
}
// value returns the value of the flag coressponding to `name`
func (c *Context) value(name string) interface{} {
return c.flagSet.Lookup(name).Value.(flag.Getter).Get()
}
// Args contains apps console arguments
type Args []string
// Args returns the command line arguments associated with the context.
func (c *Context) Args() Args {
args := Args(c.flagSet.Args())
return args
}
// NArg returns the number of the command line arguments.
func (c *Context) NArg() int {
return len(c.Args())
}
// Get returns the nth argument, or else a blank string
func (a Args) Get(n int) string {
if len(a) > n {
return a[n]
}
return ""
}
// First returns the first argument, or else a blank string
func (a Args) First() string {
return a.Get(0)
}
// Tail returns the rest of the arguments (not the first one)
// or else an empty string slice
func (a Args) Tail() []string {
if len(a) >= 2 {
return []string(a)[1:]
}
return []string{}
}
// Present checks if there are any arguments present
func (a Args) Present() bool {
return len(a) != 0
}
// Swap swaps arguments at the given indexes
func (a Args) Swap(from, to int) error {
if from >= len(a) || to >= len(a) {
return errors.New("index out of range")
}
a[from], a[to] = a[to], a[from]
return nil
}
func globalContext(ctx *Context) *Context {
if ctx == nil {
return nil
}
for {
if ctx.parentContext == nil {
return ctx
}
ctx = ctx.parentContext
}
}
func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
if ctx.parentContext != nil {
ctx = ctx.parentContext
}
for ; ctx != nil; ctx = ctx.parentContext {
if f := ctx.flagSet.Lookup(name); f != nil {
return ctx.flagSet
}
}
return nil
}
func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
switch ff.Value.(type) {
case *StringSlice:
default:
set.Set(name, ff.Value.String())
}
}
func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
visited := make(map[string]bool)
set.Visit(func(f *flag.Flag) {
visited[f.Name] = true
})
for _, f := range flags {
parts := strings.Split(f.GetName(), ",")
if len(parts) == 1 {
continue
}
var ff *flag.Flag
for _, name := range parts {
name = strings.Trim(name, " ")
if visited[name] {
if ff != nil {
return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
}
ff = set.Lookup(name)
}
}
if ff == nil {
continue
}
for _, name := range parts {
name = strings.Trim(name, " ")
if !visited[name] {
copyFlag(name, ff, set)
}
}
}
return nil
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* ThemeController.php
*
* PHP version 7
*
* @category Controllers
* @package App\Http\Controllers
* @author XE Developers <[email protected]>
* @copyright 2020 Copyright XEHub Corp. <https://www.xehub.io>
* @license http://www.gnu.org/licenses/lgpl-3.0-standalone.html LGPL
* @link https://xpressengine.io
*/
namespace App\Http\Controllers;
use File;
use Xpressengine\Http\Request;
use Xpressengine\Support\Exceptions\FileAccessDeniedHttpException;
use Xpressengine\Theme\Exceptions\NotSupportSettingException;
use Xpressengine\Theme\ThemeEntityInterface;
use Xpressengine\Theme\ThemeHandler;
/**
* Class ThemeController
*
* @category Controllers
* @package App\Http\Controllers
* @author XE Developers <[email protected]>
* @copyright 2020 Copyright XEHub Corp. <https://www.xehub.io>
* @license http://www.gnu.org/licenses/lgpl-3.0-standalone.html LGPL
* @link https://xpressengine.io
*
* @deprecated since 3.0.4 instead use ThemeSettingsController
*/
class ThemeController extends Controller
{
/**
* Show the edit form for the theme.
*
* @param Request $request request
* @param ThemeHandler $themeHandler ThemeHandler instance
* @return \Xpressengine\Presenter\Presentable
*/
public function edit(Request $request, ThemeHandler $themeHandler)
{
$this->validate($request, ['theme' => 'required']);
$themeId = $request->get('theme');
$fileName = $request->get('file');
$theme = \XeTheme::getTheme($themeId);
/** @var ThemeEntityInterface $theme */
$files = $theme->getEditFiles();
if (empty($files)) {
return \XePresenter::make('theme.edit', [
'theme' => $theme,
'files' => $files,
]);
}
if ($fileName === null) {
$fileName = key($files);
}
$filePath = realpath($files[$fileName]);
$editFile = [
'fileName' => $fileName,
'path' => $filePath,
];
if ($themeHandler->hasCache($filePath)) {
$editFile['hasCache'] = true;
$fileContent = file_get_contents($themeHandler->getCachePath($filePath));
} else {
$editFile['hasCache'] = false;
$fileContent = file_get_contents($filePath);
}
$editFile['content'] = $fileContent;
return \XePresenter::make('theme.edit', [
'theme' => $theme,
'files' => $files,
'editFile' => $editFile
]);
}
/**
* Update theme.
*
* @param Request $request request
* @param ThemeHandler $themeHandler ThemeHandler instance
* @return \Illuminate\Http\RedirectResponse
*/
public function update(Request $request, ThemeHandler $themeHandler)
{
$themeId = $request->get('theme');
$fileName = $request->get('file');
$reset = $request->get('reset');
$content = $request->get('content');
$theme = $themeHandler->getTheme($themeId);
$files = $theme->getEditFiles();
$filePath = realpath($files[$fileName]);
$cachePath = $themeHandler->getCachePath($filePath);
$cacheDir = dirname($cachePath);
File::makeDirectory($cacheDir, 0755, true, true);
try {
if ($reset === 'Y') {
File::delete($cachePath);
} else {
file_put_contents($cachePath, $content);
}
} catch (\Exception $e) {
throw new FileAccessDeniedHttpException();
}
return redirect()->back()->with('alert', ['type' => 'success', 'message' => xe_trans('xe::saved')]);
}
/**
* Create new setting for the theme.
*
* @param Request $request request
* @param ThemeHandler $themeHandler ThemeHandler instance
* @return \Illuminate\Http\RedirectResponse
*/
public function createSetting(Request $request, ThemeHandler $themeHandler)
{
$instanceId = $request->get('theme');
$title = $request->get('title');
$theme = $themeHandler->getTheme($instanceId);
if (!$theme->hasSetting()) {
throw new NotSupportSettingException();
}
$configs = $themeHandler->getThemeConfigList($theme->getId());
$last = array_pop($configs);
$lastId = $last->name;
$prefix = $themeHandler->getConfigId($theme->getId());
$id = str_replace([$prefix, $themeHandler->configDelimiter], '', $lastId);
$id = (int)$id + 1;
$newId = $instanceId.$themeHandler->configDelimiter.$id;
$themeHandler->setThemeConfig($newId, '_configTitle', $title);
return redirect()->back()->with('alert', ['type' => 'success', 'message' => xe_trans('xe::wasCreated')]);
}
/**
* Show the edit form for the setting.
*
* @param Request $request request
* @param ThemeHandler $themeHandler ThemeHandler instance
* @return \Xpressengine\Presenter\Presentable
*/
public function editSetting(Request $request, ThemeHandler $themeHandler)
{
$this->validate($request, [
'theme' => 'required',
]);
$themeId = $request->get('theme');
$theme = $themeHandler->getTheme($themeId);
if (!$theme->hasSetting()) {
throw new NotSupportSettingException();
}
$config = $theme->setting();
return \XePresenter::make('theme.config', compact('theme', 'config'));
}
/**
* Update setting.
*
* @param Request $request request
* @param ThemeHandler $themeHandler ThemeHandler instance
* @return \Illuminate\Http\RedirectResponse
*/
public function updateSetting(Request $request, ThemeHandler $themeHandler)
{
$this->validate($request, [
'theme' => 'required',
]);
// beta.24 에서 laravel 5.5 가 적용된 이후
// 공백('')값이 "ConvertEmptyStringsToNull" middleware 에 의해
// null 로 변환됨. config 에 "set" 메서드를 통해 값을 갱신하는 경우
// null 인 값은 변경사항에서 제외 시키므로 값이 공백상태로 넘겨져야 함.
// 파일의 경우 $request->all() 호출시 내부적으로 다시 merge 하며
// null 값이 유지됨.
$request->merge(array_map(function ($v) {
return is_null($v) ? '' : $v;
}, $request->all()));
$themeId = $request->get('theme');
$theme = $themeHandler->getTheme($themeId);
if(!$theme->hasSetting()) {
throw new NotSupportSettingException();
}
$configInfo = $request->only('_configTitle', '_configId');
$inputs = $request->except('_token', '_method');
$inputs['_configId'] = $themeId;
// 해당 테마에게 config를 가공할 수 있는 기회를 준다.
$config = $theme->resolveSetting($inputs);
$config = array_merge($configInfo, $config);
$themeHandler->setThemeConfig($config['_configId'], $config);
return redirect()->back()->with('alert', ['type' => 'success', 'message' => xe_trans('xe::saved')]);
}
/**
* Delete setting.
*
* @param Request $request request
* @param ThemeHandler $themeHandler ThemeHandler instance
* @return \Illuminate\Http\RedirectResponse
*/
public function deleteSetting(Request $request, ThemeHandler $themeHandler)
{
$themeId = $request->get('theme');
$theme = $themeHandler->getTheme($themeId);
$config = $theme->setting();
$theme->deleteSetting($config);
$themeHandler->deleteThemeConfig($themeId);
return redirect()->route('settings.setting.theme')
->with('alert', ['type' => 'success', 'message' => xe_trans('xe::deleted')]);
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) 2015 Yusuke Suzuki <[email protected]>
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.
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 <COPYRIGHT HOLDER> 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 { Syntax } from 'estraverse';
import Map from 'es6-map';
import Reference from './reference';
import Variable from './variable';
import Definition from './definition';
import assert from 'assert';
function isStrictScope(scope, block, isMethodDefinition, useDirective) {
var body, i, iz, stmt, expr;
// When upper scope is exists and strict, inner scope is also strict.
if (scope.upper && scope.upper.isStrict) {
return true;
}
// ArrowFunctionExpression's scope is always strict scope.
if (block.type === Syntax.ArrowFunctionExpression) {
return true;
}
if (isMethodDefinition) {
return true;
}
if (scope.type === 'class' || scope.type === 'module') {
return true;
}
if (scope.type === 'block' || scope.type === 'switch') {
return false;
}
if (scope.type === 'function') {
if (block.type === Syntax.Program) {
body = block;
} else {
body = block.body;
}
} else if (scope.type === 'global') {
body = block;
} else {
return false;
}
// Search 'use strict' directive.
if (useDirective) {
for (i = 0, iz = body.body.length; i < iz; ++i) {
stmt = body.body[i];
if (stmt.type !== Syntax.DirectiveStatement) {
break;
}
if (stmt.raw === '"use strict"' || stmt.raw === '\'use strict\'') {
return true;
}
}
} else {
for (i = 0, iz = body.body.length; i < iz; ++i) {
stmt = body.body[i];
if (stmt.type !== Syntax.ExpressionStatement) {
break;
}
expr = stmt.expression;
if (expr.type !== Syntax.Literal || typeof expr.value !== 'string') {
break;
}
if (expr.raw != null) {
if (expr.raw === '"use strict"' || expr.raw === '\'use strict\'') {
return true;
}
} else {
if (expr.value === 'use strict') {
return true;
}
}
}
}
return false;
}
function registerScope(scopeManager, scope) {
var scopes;
scopeManager.scopes.push(scope);
scopes = scopeManager.__nodeToScope.get(scope.block);
if (scopes) {
scopes.push(scope);
} else {
scopeManager.__nodeToScope.set(scope.block, [ scope ]);
}
}
function shouldBeStatically(def) {
return (
(def.type === Variable.ClassName) ||
(def.type === Variable.Variable && def.parent.kind !== 'var')
);
}
/**
* @class Scope
*/
export default class Scope {
constructor(scopeManager, type, upperScope, block, isMethodDefinition) {
/**
* One of 'TDZ', 'module', 'block', 'switch', 'function', 'catch', 'with', 'function', 'class', 'global'.
* @member {String} Scope#type
*/
this.type = type;
/**
* The scoped {@link Variable}s of this scope, as <code>{ Variable.name
* : Variable }</code>.
* @member {Map} Scope#set
*/
this.set = new Map();
/**
* The tainted variables of this scope, as <code>{ Variable.name :
* boolean }</code>.
* @member {Map} Scope#taints */
this.taints = new Map();
/**
* Generally, through the lexical scoping of JS you can always know
* which variable an identifier in the source code refers to. There are
* a few exceptions to this rule. With 'global' and 'with' scopes you
* can only decide at runtime which variable a reference refers to.
* Moreover, if 'eval()' is used in a scope, it might introduce new
* bindings in this or its parent scopes.
* All those scopes are considered 'dynamic'.
* @member {boolean} Scope#dynamic
*/
this.dynamic = this.type === 'global' || this.type === 'with';
/**
* A reference to the scope-defining syntax node.
* @member {esprima.Node} Scope#block
*/
this.block = block;
/**
* The {@link Reference|references} that are not resolved with this scope.
* @member {Reference[]} Scope#through
*/
this.through = [];
/**
* The scoped {@link Variable}s of this scope. In the case of a
* 'function' scope this includes the automatic argument <em>arguments</em> as
* its first element, as well as all further formal arguments.
* @member {Variable[]} Scope#variables
*/
this.variables = [];
/**
* Any variable {@link Reference|reference} found in this scope. This
* includes occurrences of local variables as well as variables from
* parent scopes (including the global scope). For local variables
* this also includes defining occurrences (like in a 'var' statement).
* In a 'function' scope this does not include the occurrences of the
* formal parameter in the parameter list.
* @member {Reference[]} Scope#references
*/
this.references = [];
/**
* For 'global' and 'function' scopes, this is a self-reference. For
* other scope types this is the <em>variableScope</em> value of the
* parent scope.
* @member {Scope} Scope#variableScope
*/
this.variableScope =
(this.type === 'global' || this.type === 'function' || this.type === 'module') ? this : upperScope.variableScope;
/**
* Whether this scope is created by a FunctionExpression.
* @member {boolean} Scope#functionExpressionScope
*/
this.functionExpressionScope = false;
/**
* Whether this is a scope that contains an 'eval()' invocation.
* @member {boolean} Scope#directCallToEvalScope
*/
this.directCallToEvalScope = false;
/**
* @member {boolean} Scope#thisFound
*/
this.thisFound = false;
this.__left = [];
/**
* Reference to the parent {@link Scope|scope}.
* @member {Scope} Scope#upper
*/
this.upper = upperScope;
/**
* Whether 'use strict' is in effect in this scope.
* @member {boolean} Scope#isStrict
*/
this.isStrict = isStrictScope(this, block, isMethodDefinition, scopeManager.__useDirective());
/**
* List of nested {@link Scope}s.
* @member {Scope[]} Scope#childScopes
*/
this.childScopes = [];
if (this.upper) {
this.upper.childScopes.push(this);
}
this.__declaredVariables = scopeManager.__declaredVariables;
registerScope(scopeManager, this);
}
__shouldStaticallyClose(scopeManager) {
return (!this.dynamic || scopeManager.__isOptimistic());
}
__shouldStaticallyCloseForGlobal(ref) {
// On global scope, let/const/class declarations should be resolved statically.
var name = ref.identifier.name;
if (!this.set.has(name)) {
return false;
}
var variable = this.set.get(name);
var defs = variable.defs;
return defs.length > 0 && defs.every(shouldBeStatically);
}
__staticCloseRef(ref) {
if (!this.__resolve(ref)) {
this.__delegateToUpperScope(ref);
}
}
__dynamicCloseRef(ref) {
// notify all names are through to global
let current = this;
do {
current.through.push(ref);
current = current.upper;
} while (current);
}
__globalCloseRef(ref) {
// let/const/class declarations should be resolved statically.
// others should be resolved dynamically.
if (this.__shouldStaticallyCloseForGlobal(ref)) {
this.__staticCloseRef(ref);
} else {
this.__dynamicCloseRef(ref);
}
}
__close(scopeManager) {
var closeRef;
if (this.__shouldStaticallyClose(scopeManager)) {
closeRef = this.__staticCloseRef;
} else if (this.type !== 'global') {
closeRef = this.__dynamicCloseRef;
} else {
closeRef = this.__globalCloseRef;
}
// Try Resolving all references in this scope.
for (let i = 0, iz = this.__left.length; i < iz; ++i) {
let ref = this.__left[i];
closeRef.call(this, ref);
}
this.__left = null;
return this.upper;
}
__resolve(ref) {
var variable, name;
name = ref.identifier.name;
if (this.set.has(name)) {
variable = this.set.get(name);
variable.references.push(ref);
variable.stack = variable.stack && ref.from.variableScope === this.variableScope;
if (ref.tainted) {
variable.tainted = true;
this.taints.set(variable.name, true);
}
ref.resolved = variable;
return true;
}
return false;
}
__delegateToUpperScope(ref) {
if (this.upper) {
this.upper.__left.push(ref);
}
this.through.push(ref);
}
__addDeclaredVariablesOfNode(variable, node) {
if (node == null) {
return;
}
var variables = this.__declaredVariables.get(node);
if (variables == null) {
variables = [];
this.__declaredVariables.set(node, variables);
}
if (variables.indexOf(variable) === -1) {
variables.push(variable);
}
}
__defineGeneric(name, set, variables, node, def) {
var variable;
variable = set.get(name);
if (!variable) {
variable = new Variable(name, this);
set.set(name, variable);
variables.push(variable);
}
if (def) {
variable.defs.push(def);
if (def.type !== Variable.TDZ) {
this.__addDeclaredVariablesOfNode(variable, def.node);
this.__addDeclaredVariablesOfNode(variable, def.parent);
}
}
if (node) {
variable.identifiers.push(node);
}
}
__define(node, def) {
if (node && node.type === Syntax.Identifier) {
this.__defineGeneric(
node.name,
this.set,
this.variables,
node,
def);
}
}
__referencing(node, assign, writeExpr, maybeImplicitGlobal, partial, init) {
// because Array element may be null
if (!node || node.type !== Syntax.Identifier) {
return;
}
// Specially handle like `this`.
if (node.name === 'super') {
return;
}
let ref = new Reference(node, this, assign || Reference.READ, writeExpr, maybeImplicitGlobal, !!partial, !!init);
this.references.push(ref);
this.__left.push(ref);
}
__detectEval() {
var current;
current = this;
this.directCallToEvalScope = true;
do {
current.dynamic = true;
current = current.upper;
} while (current);
}
__detectThis() {
this.thisFound = true;
}
__isClosed() {
return this.__left === null;
}
/**
* returns resolved {Reference}
* @method Scope#resolve
* @param {Esprima.Identifier} ident - identifier to be resolved.
* @return {Reference}
*/
resolve(ident) {
var ref, i, iz;
assert(this.__isClosed(), 'Scope should be closed.');
assert(ident.type === Syntax.Identifier, 'Target should be identifier.');
for (i = 0, iz = this.references.length; i < iz; ++i) {
ref = this.references[i];
if (ref.identifier === ident) {
return ref;
}
}
return null;
}
/**
* returns this scope is static
* @method Scope#isStatic
* @return {boolean}
*/
isStatic() {
return !this.dynamic;
}
/**
* returns this scope has materialized arguments
* @method Scope#isArgumentsMaterialized
* @return {boolean}
*/
isArgumentsMaterialized() {
return true;
}
/**
* returns this scope has materialized `this` reference
* @method Scope#isThisMaterialized
* @return {boolean}
*/
isThisMaterialized() {
return true;
}
isUsedName(name) {
if (this.set.has(name)) {
return true;
}
for (var i = 0, iz = this.through.length; i < iz; ++i) {
if (this.through[i].identifier.name === name) {
return true;
}
}
return false;
}
}
export class GlobalScope extends Scope {
constructor(scopeManager, block) {
super(scopeManager, 'global', null, block, false);
this.implicit = {
set: new Map(),
variables: [],
/**
* List of {@link Reference}s that are left to be resolved (i.e. which
* need to be linked to the variable they refer to).
* @member {Reference[]} Scope#implicit#left
*/
left: []
};
}
__close(scopeManager) {
let implicit = [];
for (let i = 0, iz = this.__left.length; i < iz; ++i) {
let ref = this.__left[i];
if (ref.__maybeImplicitGlobal && !this.set.has(ref.identifier.name)) {
implicit.push(ref.__maybeImplicitGlobal);
}
}
// create an implicit global variable from assignment expression
for (let i = 0, iz = implicit.length; i < iz; ++i) {
let info = implicit[i];
this.__defineImplicit(info.pattern,
new Definition(
Variable.ImplicitGlobalVariable,
info.pattern,
info.node,
null,
null,
null
));
}
this.implicit.left = this.__left;
return super.__close(scopeManager);
}
__defineImplicit(node, def) {
if (node && node.type === Syntax.Identifier) {
this.__defineGeneric(
node.name,
this.implicit.set,
this.implicit.variables,
node,
def);
}
}
}
export class ModuleScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, 'module', upperScope, block, false);
}
}
export class FunctionExpressionNameScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, 'function-expression-name', upperScope, block, false);
this.__define(block.id,
new Definition(
Variable.FunctionName,
block.id,
block,
null,
null,
null
));
this.functionExpressionScope = true;
}
}
export class CatchScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, 'catch', upperScope, block, false);
}
}
export class WithScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, 'with', upperScope, block, false);
}
__close(scopeManager) {
if (this.__shouldStaticallyClose(scopeManager)) {
return super.__close(scopeManager);
}
for (let i = 0, iz = this.__left.length; i < iz; ++i) {
let ref = this.__left[i];
ref.tainted = true;
this.__delegateToUpperScope(ref);
}
this.__left = null;
return this.upper;
}
}
export class TDZScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, 'TDZ', upperScope, block, false);
}
}
export class BlockScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, 'block', upperScope, block, false);
}
}
export class SwitchScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, 'switch', upperScope, block, false);
}
}
export class FunctionScope extends Scope {
constructor(scopeManager, upperScope, block, isMethodDefinition) {
super(scopeManager, 'function', upperScope, block, isMethodDefinition);
// section 9.2.13, FunctionDeclarationInstantiation.
// NOTE Arrow functions never have an arguments objects.
if (this.block.type !== Syntax.ArrowFunctionExpression) {
this.__defineArguments();
}
}
isArgumentsMaterialized() {
// TODO(Constellation)
// We can more aggressive on this condition like this.
//
// function t() {
// // arguments of t is always hidden.
// function arguments() {
// }
// }
if (this.block.type === Syntax.ArrowFunctionExpression) {
return false;
}
if (!this.isStatic()) {
return true;
}
let variable = this.set.get('arguments');
assert(variable, 'Always have arguments variable.');
return variable.tainted || variable.references.length !== 0;
}
isThisMaterialized() {
if (!this.isStatic()) {
return true;
}
return this.thisFound;
}
__defineArguments() {
this.__defineGeneric(
'arguments',
this.set,
this.variables,
null,
null);
this.taints.set('arguments', true);
}
}
export class ForScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, 'for', upperScope, block, false);
}
}
export class ClassScope extends Scope {
constructor(scopeManager, upperScope, block) {
super(scopeManager, 'class', upperScope, block, false);
}
}
/* vim: set sw=4 ts=4 et tw=80 : */
| {
"pile_set_name": "Github"
} |
<!--
~ Copyright 2016-2020 Open Food Facts
~
~ 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
~
~ https://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.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="1944dp"
android:height="1049dp"
android:viewportWidth="1944"
android:viewportHeight="1049">
<path
android:pathData="M180.69,-0L1763.41,-0C1863.16,-0 1943.46,80.3 1943.46,180.05L1943.46,812.53C1943.46,912.28 1863.16,992.58 1763.41,992.58L180.69,992.58C80.94,992.58 0.64,912.28 0.64,812.53L0.64,180.05C0.64,80.3 80.94,-0 180.69,-0Z"
android:strokeWidth="1"
android:fillColor="#FFFFFF"
android:fillType="evenOdd"
android:strokeColor="#00000000"/>
<path
android:pathData="M291.49,357.79l363.03,0l0,586.31l-363.03,0z"
android:strokeWidth="1"
android:fillColor="#038141"
android:fillType="evenOdd"
android:strokeColor="#00000000"/>
<path
android:pathData="M1348.7,357.79l363.03,0l0,586.31l-363.03,0z"
android:strokeWidth="1"
android:fillColor="#E63E11"
android:fillType="evenOdd"
android:strokeColor="#00000000"/>
<path
android:pathData="M217.62,357.79L308.27,357.79C383.72,357.79 444.46,418.53 444.46,493.98L444.46,807.91C444.46,883.36 383.72,944.11 308.27,944.11L217.62,944.11C142.17,944.11 81.43,883.36 81.43,807.91L81.43,493.98C81.43,418.53 142.17,357.79 217.62,357.79Z"
android:strokeWidth="1"
android:fillColor="#038141"
android:fillType="evenOdd"
android:strokeColor="#00000000"/>
<path
android:pathData="M1170.96,357.79l363.03,0l0,586.31l-363.03,0z"
android:strokeWidth="1"
android:fillColor="#EE8100"
android:fillType="evenOdd"
android:strokeColor="#00000000"/>
<path
android:pathData="M1236.6,789.04L1236.6,523.24L1335.81,523.24C1357.78,523.24 1376.99,526.73 1393.47,533.72C1409.94,540.71 1423.66,550.19 1434.65,562.17C1445.88,574.15 1454.24,588.25 1459.73,604.47C1465.47,620.45 1468.34,637.54 1468.34,655.76C1468.34,675.98 1465.22,694.32 1458.98,710.79C1452.74,727.02 1443.76,740.99 1432.03,752.72C1420.54,764.2 1406.57,773.19 1390.1,779.68C1373.87,785.92 1355.78,789.04 1335.81,789.04L1236.6,789.04L1236.6,789.04ZM1405.82,655.76C1405.82,644.03 1404.2,633.42 1400.95,623.94C1397.96,614.21 1393.47,605.85 1387.48,598.86C1381.49,591.87 1374.12,586.5 1365.39,582.76C1356.65,579.02 1346.79,577.14 1335.81,577.14L1298,577.14L1298,735.13L1335.81,735.13C1347.04,735.13 1357.03,733.13 1365.76,729.14C1374.5,725.15 1381.74,719.65 1387.48,712.67C1393.47,705.43 1397.96,697.07 1400.95,687.58C1404.2,677.85 1405.82,667.24 1405.82,655.76L1405.82,655.76Z"
android:strokeWidth="1"
android:fillColor="#FFFFFF"
android:fillAlpha="0.44606414"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M788.26,357.79l383.32,0l0,586.31l-383.32,0z"
android:strokeWidth="1"
android:fillColor="#FECB02"
android:fillType="evenOdd"
android:strokeColor="#00000000"/>
<path
android:pathData="M806.87,357.79l-363.03,0l0,586.31l363.03,0z"
android:strokeWidth="1"
android:fillColor="#85BB2F"
android:fillType="evenOdd"
android:strokeColor="#00000000"/>
<path
android:pathData="M830.4,642.41C830.4,626.44 833.4,610.59 839.39,594.87C845.38,578.89 854.11,564.67 865.59,552.19C877.08,539.71 891.05,529.6 907.52,521.86C924,514.13 942.71,510.26 963.68,510.26C988.64,510.26 1010.23,515.62 1028.45,526.36C1046.91,537.09 1060.64,551.06 1069.63,568.29L1022.46,601.23C1019.46,594.24 1015.59,588.5 1010.85,584.01C1006.36,579.27 1001.37,575.52 995.88,572.78C990.38,569.78 984.77,567.79 979.03,566.79C973.29,565.54 967.67,564.92 962.18,564.92C950.45,564.92 940.22,567.29 931.48,572.03C922.75,576.77 915.51,582.89 909.77,590.37C904.03,597.86 899.79,606.35 897.04,615.83C894.3,625.31 892.92,634.92 892.92,644.66C892.92,655.14 894.55,665.25 897.79,674.98C901.04,684.71 905.65,693.32 911.64,700.81C917.88,708.3 925.24,714.29 933.73,718.78C942.47,723.02 952.2,725.15 962.93,725.15C968.42,725.15 974.04,724.52 979.78,723.27C985.77,721.78 991.38,719.66 996.62,716.91C1002.11,713.92 1007.11,710.17 1011.6,705.68C1016.09,700.94 1019.71,695.2 1022.46,688.46L1072.62,718.03C1068.63,727.77 1062.64,736.5 1054.65,744.24C1046.91,751.98 1037.93,758.47 1027.7,763.71C1017.46,768.95 1006.61,772.94 995.13,775.69C983.65,778.43 972.41,779.8 961.43,779.8C942.22,779.8 924.5,775.94 908.27,768.2C892.3,760.21 878.45,749.73 866.72,736.75C855.24,723.77 846.25,709.05 839.76,692.58C833.52,676.1 830.4,659.38 830.4,642.41L830.4,642.41Z"
android:strokeWidth="1"
android:fillColor="#FFFFFF"
android:fillAlpha="0.44606414"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M735.23,711.67C735.23,723.15 732.86,733.13 728.11,741.62C723.37,750.1 716.88,757.22 708.65,762.96C700.41,768.45 690.8,772.69 679.82,775.69C668.84,778.43 657.23,779.8 645,779.8L515.47,779.8L515.47,514L663.35,514C672.58,514 680.94,516 688.43,519.99C695.92,523.99 702.28,529.23 707.52,535.72C712.77,541.95 716.76,549.19 719.5,557.43C722.5,565.42 724,573.65 724,582.14C724,594.87 720.75,606.85 714.26,618.08C708.02,629.31 698.54,637.79 685.81,643.53C701.04,648.03 713.01,656.01 721.75,667.49C730.74,678.97 735.23,693.7 735.23,711.67L735.23,711.67ZM672.71,699.31C672.71,691.08 670.34,684.09 665.59,678.35C660.85,672.61 654.86,669.74 647.63,669.74L576.87,669.74L576.87,727.77L645,727.77C652.99,727.77 659.6,725.15 664.85,719.91C670.09,714.66 672.71,707.8 672.71,699.31L672.71,699.31ZM576.87,566.41L576.87,621.45L637.14,621.45C643.88,621.45 649.87,619.2 655.11,614.71C660.35,610.21 662.97,603.23 662.97,593.74C662.97,585.01 660.6,578.27 655.86,573.53C651.37,568.78 645.88,566.41 639.39,566.41L576.87,566.41Z"
android:strokeWidth="1"
android:fillColor="#FFFFFF"
android:fillAlpha="0.44606414"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M235.24,514L290.65,514L387.61,779.8L324.71,779.8L304.12,720.28L221.39,720.28L201.17,779.8L138.28,779.8L235.24,514ZM294.02,677.98L262.94,584.01L231.12,677.98L294.02,677.98Z"
android:strokeWidth="1"
android:fillColor="#FFFFFF"
android:fillAlpha="0.44606414"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M1669.56,357.79L1760.2,357.79C1835.65,357.79 1896.39,418.53 1896.39,493.98L1896.39,807.91C1896.39,883.36 1835.65,944.11 1760.2,944.11L1669.56,944.11C1594.11,944.11 1533.36,883.36 1533.36,807.91L1533.36,493.98C1533.36,418.53 1594.11,357.79 1669.56,357.79Z"
android:strokeWidth="1"
android:fillColor="#E63E11"
android:fillType="evenOdd"
android:strokeColor="#00000000"/>
<path
android:pathData="M1332.81,281.62L1372.14,281.62C1480.83,281.62 1568.34,369.12 1568.34,477.82L1568.34,821.76C1568.34,930.46 1480.83,1017.97 1372.14,1017.97L1332.81,1017.97C1224.11,1017.97 1136.6,930.46 1136.6,821.76L1136.6,477.82C1136.6,369.12 1224.11,281.62 1332.81,281.62L1332.81,281.62Z"
android:strokeLineJoin="round"
android:strokeWidth="61.0317879"
android:fillColor="#0039FF"
android:fillAlpha="0.6297376"
android:strokeColor="#FFFFFF"
android:fillType="evenOdd"
android:strokeLineCap="round"/>
<path
android:pathData="M1839.13,725.9l0,53.91l-186.81,0l0,-265.8l183.44,0l0,53.91l-122.04,0l0,51.66l104.82,0l0,49.79l-104.82,0l0,56.53z"
android:strokeWidth="1"
android:fillColor="#FFFFFF"
android:fillAlpha="0.44606414"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M1332.81,281.62L1372.14,281.62C1480.83,281.62 1568.34,369.12 1568.34,477.82L1568.34,821.76C1568.34,930.46 1480.83,1017.97 1372.14,1017.97L1332.81,1017.97C1224.11,1017.97 1136.6,930.46 1136.6,821.76L1136.6,477.82C1136.6,369.12 1224.11,281.62 1332.81,281.62L1332.81,281.62Z"
android:strokeWidth="1"
android:fillColor="#EE8100"
android:fillType="evenOdd"
android:strokeColor="#00000000"/>
<path
android:pathData="M1212.35,832.19L1212.35,481.75L1332.32,481.75C1358.89,481.75 1382.13,486.36 1402.05,495.57C1421.97,504.79 1438.57,517.29 1451.85,533.09C1465.43,548.88 1475.54,567.47 1482.19,588.86C1489.13,609.92 1492.6,632.46 1492.6,656.48C1492.6,683.13 1488.83,707.32 1481.28,729.03C1473.73,750.42 1462.87,768.85 1448.68,784.31C1434.8,799.45 1417.89,811.3 1397.97,819.85C1378.35,828.08 1356.47,832.19 1332.32,832.19L1212.35,832.19ZM1416.99,656.48C1416.99,641.01 1415.03,627.03 1411.1,614.52C1407.48,601.69 1402.05,590.67 1394.8,581.46C1387.56,572.24 1378.66,565.17 1368.09,560.23C1357.53,555.3 1345.6,552.83 1332.32,552.83L1286.6,552.83L1286.6,761.12L1332.32,761.12C1345.91,761.12 1357.98,758.48 1368.54,753.22C1379.11,747.95 1387.86,740.72 1394.8,731.5C1402.05,721.96 1407.48,710.94 1411.1,698.43C1415.03,685.6 1416.99,671.61 1416.99,656.48Z"
android:strokeWidth="1"
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M156.61,163.15l0,76.83l-31.03,0l0,-134.35l24.22,0l62.63,78.91l0,-78.91l31.03,0l0,134.35l-24.98,0l-61.88,-76.83z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M327.06,213.48C332.36,213.48 336.84,212.41 340.5,210.26C344.15,207.99 347.12,205.03 349.39,201.37C351.66,197.71 353.24,193.55 354.12,188.88C355.13,184.09 355.63,179.23 355.63,174.31L355.63,105.62L386.67,105.62L386.67,174.31C386.67,183.65 385.47,192.35 383.07,200.43C380.8,208.5 377.21,215.56 372.29,221.62C367.49,227.67 361.31,232.47 353.74,236C346.3,239.41 337.4,241.11 327.06,241.11C316.34,241.11 307.19,239.28 299.62,235.62C292.05,231.96 285.87,227.11 281.08,221.05C276.41,214.87 272.94,207.74 270.67,199.67C268.53,191.59 267.45,183.14 267.45,174.31L267.45,105.62L298.49,105.62L298.49,174.31C298.49,179.48 298.99,184.4 300,189.07C301.01,193.74 302.65,197.9 304.92,201.56C307.19,205.22 310.09,208.12 313.62,210.26C317.28,212.41 321.76,213.48 327.06,213.48L327.06,213.48Z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M512.9,132.87l-40.87,0l0,107.1l-31.03,0l0,-107.1l-41.06,0l0,-27.25l112.97,0z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M528.05,239.97L528.05,105.62L588.61,105.62C594.91,105.62 600.72,106.95 606.02,109.6C611.44,112.25 616.11,115.71 620.02,120C623.93,124.29 626.96,129.15 629.1,134.57C631.37,140 632.51,145.49 632.51,151.04C632.51,155.2 632,159.24 630.99,163.15C629.98,166.93 628.53,170.53 626.64,173.93C624.75,177.34 622.42,180.43 619.64,183.21C616.99,185.85 613.96,188.13 610.56,190.02L640.08,239.97L605.07,239.97L579.33,196.64L559.09,196.64L559.09,239.97L528.05,239.97ZM559.09,169.58L587.47,169.58C591.13,169.58 594.28,167.88 596.93,164.47C599.58,160.94 600.91,156.46 600.91,151.04C600.91,145.49 599.39,141.07 596.36,137.79C593.34,134.51 590.06,132.87 586.53,132.87L559.09,132.87L559.09,169.58L559.09,169.58Z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M654.82,239.97l0,-134.35l31.03,0l0,134.35l-31.03,0z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M709.09,201.56l0,-27.25l58.28,0l0,27.25z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M871.07,144.98C870.69,144.48 869.37,143.53 867.1,142.14C864.82,140.76 861.99,139.3 858.58,137.79C855.17,136.28 851.45,134.95 847.42,133.82C843.38,132.68 839.34,132.11 835.31,132.11C824.2,132.11 818.65,135.84 818.65,143.28C818.65,145.55 819.22,147.44 820.36,148.96C821.62,150.47 823.38,151.86 825.65,153.12C828.05,154.25 831.02,155.33 834.55,156.34C838.08,157.34 842.18,158.48 846.85,159.74C853.28,161.51 859.08,163.46 864.26,165.61C869.43,167.63 873.78,170.21 877.31,173.37C880.97,176.39 883.75,180.11 885.64,184.53C887.66,188.95 888.67,194.24 888.67,200.43C888.67,207.99 887.22,214.43 884.31,219.73C881.54,224.9 877.82,229.12 873.15,232.4C868.48,235.56 863.12,237.89 857.07,239.41C851.01,240.79 844.77,241.49 838.33,241.49C833.41,241.49 828.37,241.11 823.19,240.35C818.02,239.6 812.98,238.52 808.06,237.14C803.14,235.62 798.34,233.86 793.68,231.84C789.13,229.82 784.91,227.48 781,224.84L794.62,197.78C795.13,198.41 796.77,199.61 799.54,201.37C802.32,203.14 805.72,204.9 809.76,206.67C813.92,208.44 818.53,210.01 823.57,211.4C828.62,212.79 833.73,213.48 838.9,213.48C849.88,213.48 855.36,210.14 855.36,203.45C855.36,200.93 854.54,198.85 852.9,197.21C851.26,195.57 848.99,194.12 846.09,192.86C843.19,191.47 839.72,190.21 835.68,189.07C831.77,187.94 827.48,186.67 822.82,185.29C816.63,183.39 811.27,181.38 806.73,179.23C802.19,176.96 798.41,174.37 795.38,171.47C792.48,168.57 790.27,165.23 788.76,161.44C787.37,157.66 786.67,153.24 786.67,148.2C786.67,141.13 788,134.89 790.65,129.47C793.3,124.04 796.89,119.5 801.43,115.84C805.97,112.06 811.21,109.22 817.14,107.33C823.19,105.43 829.57,104.49 836.25,104.49C840.92,104.49 845.52,104.93 850.06,105.81C854.61,106.69 858.96,107.83 863.12,109.22C867.28,110.61 871.13,112.18 874.66,113.95C878.32,115.71 881.67,117.48 884.69,119.25L871.07,144.98L871.07,144.98Z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M899.12,171.66C899.12,163.59 900.63,155.58 903.66,147.63C906.69,139.56 911.1,132.37 916.91,126.06C922.71,119.75 929.77,114.64 938.1,110.73C946.43,106.82 955.89,104.87 966.48,104.87C979.1,104.87 990.01,107.58 999.22,113C1008.55,118.43 1015.49,125.49 1020.03,134.2L996.19,150.85C994.68,147.32 992.72,144.41 990.33,142.14C988.06,139.75 985.53,137.85 982.76,136.47C979.98,134.95 977.14,133.94 974.24,133.44C971.34,132.81 968.5,132.49 965.73,132.49C959.8,132.49 954.63,133.69 950.21,136.09C945.79,138.49 942.14,141.58 939.23,145.36C936.33,149.14 934.19,153.43 932.8,158.23C931.41,163.02 930.72,167.88 930.72,172.8C930.72,178.1 931.54,183.21 933.18,188.13C934.82,193.05 937.15,197.4 940.18,201.18C943.33,204.97 947.06,207.99 951.35,210.27C955.76,212.41 960.68,213.48 966.11,213.48C968.88,213.48 971.72,213.17 974.62,212.54C977.65,211.78 980.49,210.71 983.14,209.32C985.91,207.81 988.43,205.91 990.7,203.64C992.98,201.25 994.8,198.34 996.19,194.94L1021.55,209.89C1019.53,214.81 1016.5,219.22 1012.47,223.13C1008.55,227.04 1004.01,230.32 998.84,232.97C993.67,235.62 988.18,237.64 982.38,239.03C976.58,240.42 970.9,241.11 965.35,241.11C955.63,241.11 946.68,239.15 938.48,235.24C930.4,231.21 923.4,225.91 917.47,219.35C911.67,212.79 907.13,205.35 903.85,197.02C900.7,188.69 899.12,180.24 899.12,171.66L899.12,171.66Z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M1094.34,241.11C1084.38,241.11 1075.29,239.15 1067.09,235.24C1058.89,231.33 1051.89,226.22 1046.09,219.92C1040.29,213.48 1035.74,206.17 1032.46,197.97C1029.31,189.77 1027.73,181.31 1027.73,172.61C1027.73,163.78 1029.37,155.26 1032.65,147.06C1036.06,138.86 1040.73,131.67 1046.66,125.49C1052.71,119.18 1059.84,114.2 1068.04,110.54C1076.24,106.76 1085.2,104.87 1094.91,104.87C1104.88,104.87 1113.96,106.82 1122.16,110.73C1130.36,114.64 1137.36,119.81 1143.16,126.25C1148.97,132.68 1153.44,140 1156.6,148.2C1159.75,156.4 1161.33,164.72 1161.33,173.18C1161.33,182.01 1159.62,190.52 1156.22,198.72C1152.94,206.92 1148.33,214.18 1142.41,220.48C1136.48,226.66 1129.41,231.65 1121.21,235.43C1113.01,239.22 1104.06,241.11 1094.34,241.11L1094.34,241.11ZM1059.33,172.99C1059.33,178.16 1060.09,183.21 1061.61,188.13C1063.12,192.92 1065.33,197.21 1068.23,200.99C1071.26,204.78 1074.98,207.81 1079.39,210.08C1083.81,212.35 1088.85,213.48 1094.53,213.48C1100.46,213.48 1105.63,212.28 1110.05,209.89C1114.46,207.49 1118.12,204.4 1121.02,200.61C1123.92,196.7 1126.07,192.35 1127.46,187.56C1128.97,182.64 1129.73,177.65 1129.73,172.61C1129.73,167.44 1128.97,162.45 1127.46,157.66C1125.94,152.74 1123.67,148.45 1120.64,144.79C1117.62,141.01 1113.9,138.04 1109.48,135.9C1105.19,133.63 1100.21,132.49 1094.53,132.49C1088.6,132.49 1083.43,133.69 1079.01,136.09C1074.73,138.36 1071.07,141.39 1068.04,145.17C1065.14,148.96 1062.93,153.31 1061.42,158.23C1060.03,163.02 1059.33,167.94 1059.33,172.99L1059.33,172.99Z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M1179.26,239.97L1179.26,105.62L1239.81,105.62C1246.12,105.62 1251.92,106.95 1257.22,109.6C1262.65,112.25 1267.31,115.71 1271.22,120C1275.14,124.29 1278.16,129.15 1280.31,134.57C1282.58,140 1283.71,145.49 1283.71,151.04C1283.71,155.2 1283.21,159.24 1282.2,163.15C1281.19,166.93 1279.74,170.53 1277.85,173.93C1275.95,177.34 1273.62,180.43 1270.85,183.21C1268.2,185.85 1265.17,188.13 1261.76,190.02L1291.28,239.97L1256.28,239.97L1230.54,196.64L1210.29,196.64L1210.29,239.97L1179.26,239.97L1179.26,239.97ZM1210.29,169.58L1238.68,169.58C1242.34,169.58 1245.49,167.88 1248.14,164.47C1250.79,160.94 1252.11,156.46 1252.11,151.04C1252.11,145.49 1250.6,141.07 1247.57,137.79C1244.54,134.51 1241.26,132.87 1237.73,132.87L1210.29,132.87L1210.29,169.58L1210.29,169.58Z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
<path
android:pathData="M1400.45,212.72l0,27.25l-94.42,0l0,-134.35l92.72,0l0,27.25l-61.69,0l0,26.11l52.98,0l0,25.17l-52.98,0l0,28.57z"
android:strokeWidth="1"
android:fillColor="#7D7D7D"
android:fillType="nonZero"
android:strokeColor="#00000000"/>
</vector>
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.boot.convert;
import java.io.IOException;
import org.springframework.boot.origin.Origin;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.io.InputStreamSource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
/**
* {@link Converter} to convert from an {@link InputStreamSource} to a {@code byte[]}.
*
* @author Phillip Webb
*/
class InputStreamSourceToByteArrayConverter implements Converter<InputStreamSource, byte[]> {
@Override
public byte[] convert(InputStreamSource source) {
try {
return FileCopyUtils.copyToByteArray(source.getInputStream());
}
catch (IOException ex) {
throw new IllegalStateException("Unable to read from " + getName(source), ex);
}
}
private String getName(InputStreamSource source) {
Origin origin = Origin.from(source);
if (origin != null) {
return origin.toString();
}
if (source instanceof Resource) {
return ((Resource) source).getDescription();
}
return "input stream source";
}
}
| {
"pile_set_name": "Github"
} |
---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Information to reproduce the behavior, including:
1. Git commit id
2. IEEE 802.15.4 hardware platform
3. Build steps
4. Network topology
**Expected behavior**
A clear and concise description of what you expected to happen.
**Console/log output**
If applicable, add console/log output to help explain your problem.
**Additional context**
Add any other context about the problem here.
| {
"pile_set_name": "Github"
} |
/*
* Real Audio 1.0 (14.4K)
*
* Copyright (c) 2008 Vitor Sessak
* Copyright (c) 2003 Nick Kurshev
* Based on public domain decoder at http://www.honeypot.net/audio
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "libavutil/channel_layout.h"
#include "avcodec.h"
#include "get_bits.h"
#include "internal.h"
#include "ra144.h"
static av_cold int ra144_decode_init(AVCodecContext * avctx)
{
RA144Context *ractx = avctx->priv_data;
ractx->avctx = avctx;
ff_audiodsp_init(&ractx->adsp);
ractx->lpc_coef[0] = ractx->lpc_tables[0];
ractx->lpc_coef[1] = ractx->lpc_tables[1];
avctx->channels = 1;
avctx->channel_layout = AV_CH_LAYOUT_MONO;
avctx->sample_fmt = AV_SAMPLE_FMT_S16;
return 0;
}
static void do_output_subblock(RA144Context *ractx, const int16_t *lpc_coefs,
int gval, GetBitContext *gb)
{
int cba_idx = get_bits(gb, 7); // index of the adaptive CB, 0 if none
int gain = get_bits(gb, 8);
int cb1_idx = get_bits(gb, 7);
int cb2_idx = get_bits(gb, 7);
ff_subblock_synthesis(ractx, lpc_coefs, cba_idx, cb1_idx, cb2_idx, gval,
gain);
}
/** Uncompress one block (20 bytes -> 160*2 bytes). */
static int ra144_decode_frame(AVCodecContext * avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
static const uint8_t sizes[LPC_ORDER] = {6, 5, 5, 4, 4, 3, 3, 3, 3, 2};
unsigned int refl_rms[NBLOCKS]; // RMS of the reflection coefficients
int16_t block_coefs[NBLOCKS][LPC_ORDER]; // LPC coefficients of each sub-block
unsigned int lpc_refl[LPC_ORDER]; // LPC reflection coefficients of the frame
int i, j;
int ret;
int16_t *samples;
unsigned int energy;
RA144Context *ractx = avctx->priv_data;
GetBitContext gb;
if (buf_size < FRAME_SIZE) {
av_log(avctx, AV_LOG_ERROR,
"Frame too small (%d bytes). Truncated file?\n", buf_size);
*got_frame_ptr = 0;
return AVERROR_INVALIDDATA;
}
/* get output buffer */
frame->nb_samples = NBLOCKS * BLOCKSIZE;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
samples = (int16_t *)frame->data[0];
init_get_bits8(&gb, buf, FRAME_SIZE);
for (i = 0; i < LPC_ORDER; i++)
lpc_refl[i] = ff_lpc_refl_cb[i][get_bits(&gb, sizes[i])];
ff_eval_coefs(ractx->lpc_coef[0], lpc_refl);
ractx->lpc_refl_rms[0] = ff_rms(lpc_refl);
energy = ff_energy_tab[get_bits(&gb, 5)];
refl_rms[0] = ff_interp(ractx, block_coefs[0], 1, 1, ractx->old_energy);
refl_rms[1] = ff_interp(ractx, block_coefs[1], 2,
energy <= ractx->old_energy,
ff_t_sqrt(energy*ractx->old_energy) >> 12);
refl_rms[2] = ff_interp(ractx, block_coefs[2], 3, 0, energy);
refl_rms[3] = ff_rescale_rms(ractx->lpc_refl_rms[0], energy);
ff_int_to_int16(block_coefs[3], ractx->lpc_coef[0]);
for (i=0; i < NBLOCKS; i++) {
do_output_subblock(ractx, block_coefs[i], refl_rms[i], &gb);
for (j=0; j < BLOCKSIZE; j++)
*samples++ = av_clip_int16(ractx->curr_sblock[j + 10] << 2);
}
ractx->old_energy = energy;
ractx->lpc_refl_rms[1] = ractx->lpc_refl_rms[0];
FFSWAP(unsigned int *, ractx->lpc_coef[0], ractx->lpc_coef[1]);
*got_frame_ptr = 1;
return FRAME_SIZE;
}
AVCodec ff_ra_144_decoder = {
.name = "real_144",
.long_name = NULL_IF_CONFIG_SMALL("RealAudio 1.0 (14.4K)"),
.type = AVMEDIA_TYPE_AUDIO,
.id = AV_CODEC_ID_RA_144,
.priv_data_size = sizeof(RA144Context),
.init = ra144_decode_init,
.decode = ra144_decode_frame,
.capabilities = AV_CODEC_CAP_DR1,
};
| {
"pile_set_name": "Github"
} |
<?php
/**
* Allows multiple validators to attempt to validate attribute.
*
* Composite is just what it sounds like: a composite of many validators.
* This means that multiple HTMLPurifier_AttrDef objects will have a whack
* at the string. If one of them passes, that's what is returned. This is
* especially useful for CSS values, which often are a choice between
* an enumerated set of predefined values or a flexible data type.
*/
class HTMLPurifier_AttrDef_CSS_Composite extends HTMLPurifier_AttrDef
{
/**
* List of objects that may process strings.
* @type HTMLPurifier_AttrDef[]
* @todo Make protected
*/
public $defs;
/**
* @param HTMLPurifier_AttrDef[] $defs List of HTMLPurifier_AttrDef objects
*/
public function __construct($defs)
{
$this->defs = $defs;
}
/**
* @param string $string
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return bool|string
*/
public function validate($string, $config, $context)
{
foreach ($this->defs as $i => $def) {
$result = $this->defs[$i]->validate($string, $config, $context);
if ($result !== false) {
return $result;
}
}
return false;
}
}
// vim: et sw=4 sts=4
| {
"pile_set_name": "Github"
} |
/*
* twemproxy - A fast and lightweight proxy for memcached protocol.
* Copyright (C) 2011 Twitter, 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.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <nc_core.h>
#include <nc_conf.h>
#include <nc_signal.h>
#include <nc_sentinel.h>
#include <nc_whitelist.h>
#define NC_CONF_PATH "conf/nutcracker.yml"
#define NC_WHITELIST_PATH "conf/whitelist"
#define NC_LOG_DEFAULT LOG_NOTICE
#define NC_LOG_MIN LOG_EMERG
#define NC_LOG_MAX LOG_PVERB
#define NC_LOG_PATH NULL
#define NC_STATS_PORT STATS_PORT
#define NC_STATS_ADDR STATS_ADDR
#define NC_STATS_INTERVAL STATS_INTERVAL
#define NC_SENTINEL_PORT SENTINEL_PORT
#define NC_SENTINEL_ADDR SENTINEL_ADDR
#define NC_SERVER_RECONNECT_INTERVAL SERVER_RECONNECT_INTERVAL
#define NC_PID_FILE NULL
#define NC_MBUF_SIZE MBUF_SIZE
#define NC_MBUF_MIN_SIZE MBUF_MIN_SIZE
#define NC_MBUF_MAX_SIZE MBUF_MAX_SIZE
static int show_help;
static int show_version;
static int test_conf;
static int daemonize;
static int describe_stats;
static struct option long_options[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'V' },
{ "test-conf", no_argument, NULL, 't' },
{ "daemonize", no_argument, NULL, 'd' },
{ "describe-stats", no_argument, NULL, 'D' },
{ "verbose", required_argument, NULL, 'v' },
{ "output", required_argument, NULL, 'o' },
{ "conf-file", required_argument, NULL, 'c' },
{ "whitelist-file", required_argument, NULL, 'w' },
{ "stats-port", required_argument, NULL, 's' },
{ "stats-interval", required_argument, NULL, 'i' },
{ "stats-addr", required_argument, NULL, 'a' },
{ "sentinel-port", required_argument, NULL, 'S' },
{ "server-interval", required_argument, NULL, 'I' },
{ "sentinel-addr", required_argument, NULL, 'A' },
{ "pid-file", required_argument, NULL, 'p' },
{ "mbuf-size", required_argument, NULL, 'm' },
{ NULL, 0, NULL, 0 }
};
static char short_options[] = "hVtdDv:o:c:w:s:i:a:S:I:A:p:m:";
static rstatus_t
nc_daemonize(int dump_core)
{
rstatus_t status;
pid_t pid, sid;
int fd;
pid = fork();
switch (pid) {
case -1:
log_error("fork() failed: %s", strerror(errno));
return NC_ERROR;
case 0:
break;
default:
/* parent terminates */
_exit(0);
}
/* 1st child continues and becomes the session leader */
sid = setsid();
if (sid < 0) {
log_error("setsid() failed: %s", strerror(errno));
return NC_ERROR;
}
if (signal(SIGHUP, SIG_IGN) == SIG_ERR) {
log_error("signal(SIGHUP, SIG_IGN) failed: %s", strerror(errno));
return NC_ERROR;
}
pid = fork();
switch (pid) {
case -1:
log_error("fork() failed: %s", strerror(errno));
return NC_ERROR;
case 0:
break;
default:
/* 1st child terminates */
_exit(0);
}
/* 2nd child continues */
/* change working directory */
if (dump_core == 0) {
status = chdir("/");
if (status < 0) {
log_error("chdir(\"/\") failed: %s", strerror(errno));
return NC_ERROR;
}
}
/* clear file mode creation mask */
umask(0);
/* redirect stdin, stdout and stderr to "/dev/null" */
fd = open("/dev/null", O_RDWR);
if (fd < 0) {
log_error("open(\"/dev/null\") failed: %s", strerror(errno));
return NC_ERROR;
}
status = dup2(fd, STDIN_FILENO);
if (status < 0) {
log_error("dup2(%d, STDIN) failed: %s", fd, strerror(errno));
close(fd);
return NC_ERROR;
}
status = dup2(fd, STDOUT_FILENO);
if (status < 0) {
log_error("dup2(%d, STDOUT) failed: %s", fd, strerror(errno));
close(fd);
return NC_ERROR;
}
status = dup2(fd, STDERR_FILENO);
if (status < 0) {
log_error("dup2(%d, STDERR) failed: %s", fd, strerror(errno));
close(fd);
return NC_ERROR;
}
if (fd > STDERR_FILENO) {
status = close(fd);
if (status < 0) {
log_error("close(%d) failed: %s", fd, strerror(errno));
return NC_ERROR;
}
}
return NC_OK;
}
static void
nc_print_run(struct instance *nci)
{
loga("nutcracker-%s started on pid %d", NC_VERSION_STRING, nci->pid);
loga("run, rabbit run / dig that hole, forget the sun / "
"and when at last the work is done / don't sit down / "
"it's time to dig another one");
}
static void
nc_print_done(void)
{
loga("done, rabbit done");
}
static void
nc_show_usage(void)
{
log_stderr(
"Usage: nutcracker [-?hVdDt] [-v verbosity level] [-o output file]" CRLF
" [-c conf file] [-s stats port] [-a stats addr]" CRLF
" [-i stats interval] [-S sentinel port]" CRLF
" [-I server reconnect interval] [-A sentinel addr]" CRLF
" [-p pid file] [-m mbuf size]" CRLF
" [-w whitelist name]" CRLF
"");
log_stderr(
"Options:" CRLF
" -h, --help : this help" CRLF
" -V, --version : show version and exit" CRLF
" -t, --test-conf : test configuration for syntax errors and exit" CRLF
" -d, --daemonize : run as a daemon" CRLF
" -D, --describe-stats : print stats description and exit");
log_stderr(
" -v, --verbosity=N : set logging level (default: %d, min: %d, max: %d)" CRLF
" -o, --output=S : set logging file (default: %s)" CRLF
" -c, --conf-file=S : set configuration file (default: %s)" CRLF
" -s, --stats-port=N : set stats monitoring port (default: %d)" CRLF
" -a, --stats-addr=S : set stats monitoring ip (default: %s)" CRLF
" -i, --stats-interval=N : set stats aggregation interval in msec (default: %d msec)" CRLF
" -S, --sentinel-port=N : set sentinel server port (default: %d)" CRLF
" -A, --sentinel-addr=S : set sentinel server ip (default: %s)" CRLF
" -I, --server-interval=N : set server reconnect interval in msec (default: %d msec)" CRLF
" -p, --pid-file=S : set pid file (default: %s)" CRLF
" -m, --mbuf-size=N : set size of mbuf chunk in bytes (default: %d bytes)" CRLF
" -w, --whitelist_file=S : set whitelist filename (defaualt :%s)" CRLF
"",
NC_LOG_DEFAULT, NC_LOG_MIN, NC_LOG_MAX,
NC_LOG_PATH != NULL ? NC_LOG_PATH : "stderr",
NC_CONF_PATH,
NC_STATS_PORT, NC_STATS_ADDR, NC_STATS_INTERVAL,
NC_SENTINEL_PORT, NC_SENTINEL_ADDR, NC_SERVER_RECONNECT_INTERVAL,
NC_PID_FILE != NULL ? NC_PID_FILE : "off",
NC_MBUF_SIZE,NC_WHITELIST_PATH);
}
static rstatus_t
nc_create_pidfile(struct instance *nci)
{
char pid[NC_UINTMAX_MAXLEN];
int fd, pid_len;
ssize_t n;
fd = open(nci->pid_filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
log_error("opening pid file '%s' failed: %s", nci->pid_filename,
strerror(errno));
return NC_ERROR;
}
nci->pidfile = 1;
pid_len = nc_snprintf(pid, NC_UINTMAX_MAXLEN, "%d", nci->pid);
n = nc_write(fd, pid, pid_len);
if (n < 0) {
log_error("write to pid file '%s' failed: %s", nci->pid_filename,
strerror(errno));
return NC_ERROR;
}
close(fd);
return NC_OK;
}
static void
nc_remove_pidfile(struct instance *nci)
{
int status;
status = unlink(nci->pid_filename);
if (status < 0) {
log_error("unlink of pid file '%s' failed, ignored: %s",
nci->pid_filename, strerror(errno));
}
}
static void
nc_set_default_options(struct instance *nci)
{
int status;
nci->ctx = NULL;
nci->log_level = NC_LOG_DEFAULT;
nci->log_filename = NC_LOG_PATH;
nci->conf_filename = NC_CONF_PATH;
nci->whitelist_filename = NC_WHITELIST_PATH;
nci->stats_port = NC_STATS_PORT;
nci->stats_addr = NC_STATS_ADDR;
nci->stats_interval = NC_STATS_INTERVAL;
nci->sentinel_port = NC_SENTINEL_PORT;
nci->sentinel_addr = NC_SENTINEL_ADDR;
nci->server_reconnect_interval = NC_SERVER_RECONNECT_INTERVAL;
status = nc_gethostname(nci->hostname, NC_MAXHOSTNAMELEN);
if (status < 0) {
log_warn("gethostname failed, ignored: %s", strerror(errno));
nc_snprintf(nci->hostname, NC_MAXHOSTNAMELEN, "unknown");
}
nci->hostname[NC_MAXHOSTNAMELEN - 1] = '\0';
nci->mbuf_chunk_size = NC_MBUF_SIZE;
nci->pid = (pid_t)-1;
nci->pid_filename = NULL;
nci->pidfile = 0;
nci->whitelist=0;
}
static rstatus_t
nc_get_options(int argc, char **argv, struct instance *nci)
{
int c, value;
opterr = 0;
for (;;) {
c = getopt_long(argc, argv, short_options, long_options, NULL);
if (c == -1) {
/* no more options */
break;
}
switch (c) {
case 'h':
show_version = 1;
show_help = 1;
break;
case 'V':
show_version = 1;
break;
case 't':
test_conf = 1;
break;
case 'd':
daemonize = 1;
break;
case 'D':
describe_stats = 1;
show_version = 1;
break;
case 'v':
value = nc_atoi(optarg, strlen(optarg));
if (value < 0) {
log_stderr("nutcracker: option -v requires a number");
return NC_ERROR;
}
nci->log_level = value;
break;
case 'o':
nci->log_filename = optarg;
break;
case 'c':
nci->conf_filename = optarg;
break;
case 'w':
nci->whitelist = 1;
nci->whitelist_filename = optarg;
break;
case 's':
value = nc_atoi(optarg, strlen(optarg));
if (value < 0) {
log_stderr("nutcracker: option -s requires a number");
return NC_ERROR;
}
if (!nc_valid_port(value)) {
log_stderr("nutcracker: option -s value %d is not a valid "
"port", value);
return NC_ERROR;
}
nci->stats_port = (uint16_t)value;
break;
case 'i':
value = nc_atoi(optarg, strlen(optarg));
if (value < 0) {
log_stderr("nutcracker: option -i requires a number");
return NC_ERROR;
}
nci->stats_interval = value;
break;
case 'a':
nci->stats_addr = optarg;
break;
case 'S':
value = nc_atoi(optarg, strlen(optarg));
if (value < 0) {
log_stderr("nutcracker: option -S requires a number");
return NC_ERROR;
}
if (!nc_valid_port(value)) {
log_stderr("nutcracker: option -S value %d is not a valid "
"port", value);
return NC_ERROR;
}
nci->sentinel_port = (uint16_t)value;
break;
case 'I':
value = nc_atoi(optarg, strlen(optarg));
if (value < 0) {
log_stderr("nutcracker: option -I requires a number");
return NC_ERROR;
}
nci->server_reconnect_interval = value;
break;
case 'A':
nci->sentinel_addr = optarg;
break;
case 'p':
nci->pid_filename = optarg;
break;
case 'm':
value = nc_atoi(optarg, strlen(optarg));
if (value <= 0) {
log_stderr("nutcracker: option -m requires a non-zero number");
return NC_ERROR;
}
if (value < NC_MBUF_MIN_SIZE || value > NC_MBUF_MAX_SIZE) {
log_stderr("nutcracker: mbuf chunk size must be between %zu and"
" %zu bytes", NC_MBUF_MIN_SIZE, NC_MBUF_MAX_SIZE);
return NC_ERROR;
}
nci->mbuf_chunk_size = (size_t)value;
break;
case '?':
switch (optopt) {
case 'o':
case 'c':
case 'w':
case 'p':
log_stderr("nutcracker: option -%c requires a file name",
optopt);
break;
case 'm':
case 'v':
case 's':
case 'i':
case 'S':
case 'I':
log_stderr("nutcracker: option -%c requires a number", optopt);
break;
case 'a':
case 'A':
log_stderr("nutcracker: option -%c requires a string", optopt);
break;
default:
log_stderr("nutcracker: invalid option -- '%c'", optopt);
break;
}
return NC_ERROR;
default:
log_stderr("nutcracker: invalid option -- '%c'", optopt);
return NC_ERROR;
}
}
return NC_OK;
}
/*
* Returns true if configuration file has a valid syntax, otherwise
* returns false
*/
static bool
nc_test_conf(struct instance *nci)
{
struct conf *cf;
cf = conf_create(nci->conf_filename);
if (cf == NULL) {
log_stderr("nutcracker: configuration file '%s' syntax is invalid",
nci->conf_filename);
return false;
}
conf_destroy(cf);
log_stderr("nutcracker: configuration file '%s' syntax is ok",
nci->conf_filename);
return true;
}
static rstatus_t
nc_pre_run(struct instance *nci)
{
rstatus_t status;
status = log_init(nci->log_level, nci->log_filename);
if (status != NC_OK) {
return status;
}
if (daemonize) {
status = nc_daemonize(1);
if (status != NC_OK) {
return status;
}
}
nci->pid = getpid();
status = signal_init();
if (status != NC_OK) {
return status;
}
if (nci->pid_filename) {
status = nc_create_pidfile(nci);
if (status != NC_OK) {
return status;
}
}
nc_print_run(nci);
return NC_OK;
}
static void
nc_post_run(struct instance *nci)
{
if (nci->pidfile) {
nc_remove_pidfile(nci);
}
signal_deinit();
nc_print_done();
log_deinit();
}
static void
nc_run(struct instance *nci)
{
rstatus_t status;
struct context *ctx;
ctx = core_start(nci);
if (ctx == NULL) {
return;
}
/* whitelist thread */
nc_get_whitelist(nci);
/* run rabbit run */
for (;;) {
status = core_loop(ctx);
if (status != NC_OK) {
break;
}
}
core_stop(ctx);
}
int
main(int argc, char **argv)
{
rstatus_t status;
struct instance nci;
nc_set_default_options(&nci);
status = nc_get_options(argc, argv, &nci);
if (status != NC_OK) {
nc_show_usage();
exit(1);
}
if (show_version) {
log_stderr("This is nutcracker-%s" CRLF, NC_VERSION_STRING);
if (show_help) {
nc_show_usage();
}
if (describe_stats) {
stats_describe();
}
exit(0);
}
if (test_conf) {
if (!nc_test_conf(&nci)) {
exit(1);
}
exit(0);
}
status = nc_pre_run(&nci);
if (status != NC_OK) {
nc_post_run(&nci);
exit(1);
}
nc_run(&nci);
nc_post_run(&nci);
exit(1);
}
| {
"pile_set_name": "Github"
} |
package com.arcgis.apps.pulsegraphic;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.arcgis.apps.pulsegraphic", appContext.getPackageName());
}
}
| {
"pile_set_name": "Github"
} |
import numpy as np
import os
import subprocess
import sys
import nibabel as nib
def saveImageToANewNiiWithHeaderFromOther( normalizedImageNpArray,
outputFilepath,
originalImageProxy,
dtypeToSaveOutput) : #the proxy
hdr_for_orig_image = originalImageProxy.header
affine_trans_to_ras = originalImageProxy.affine
#Nifti Constructor. data is the image itself, dimensions x,y,z,time. The second argument is the affine RAS transf.
newNormImg = nib.Nifti1Image(normalizedImageNpArray, affine_trans_to_ras)
newNormImg.set_data_dtype(np.dtype(dtypeToSaveOutput))
newNormImg.header.set_zooms(hdr_for_orig_image.get_zooms()[:3])
print("Saving image to:"),outputFilepath
nib.save(newNormImg, outputFilepath)
print("Done.")
#simple subtract mean divide std.
def do_normalization(windowTitle,
pathToMainFolderWithSubjects,
subjectsToProcess,
channelToNormalizeFilepath, roiFilepath,
saveOutput,
prefixToAddToOutp,
dtypeToSaveOutput,
saveNormalizationPlots,
lowHighCutoffPercentile, # Can be None
lowHighCutoffTimesTheStd, # Can be None
cutoffAtWholeImgMean,
) :
for i in range(1) :
srcProxy = nib.load(channelToNormalizeFilepath)
srcImgNpArr = np.asarray(srcProxy.get_data(), dtype=dtypeToSaveOutput)
boolPixelsWithIntBelowZero = srcImgNpArr<0
numVoxelsIntBelowZero = np.sum(boolPixelsWithIntBelowZero)
if numVoxelsIntBelowZero != 0:
srcImgNpArr[boolPixelsWithIntBelowZero] = 0; #because for instance in Christian's background was -1.
meanIntSrcImg = np.mean(srcImgNpArr); stdIntSrcImg = np.std(srcImgNpArr); maxIntSrcImg = np.max(srcImgNpArr)
roiProxy = nib.load(roiFilepath)
roiNpArr = np.asarray(roiProxy.get_data())
boolRoiMask = roiNpArr>0
srcIntsUnderRoi = srcImgNpArr[boolRoiMask] # This gets flattened automatically. It's a vector array.
meanIntInRoi = np.mean(srcIntsUnderRoi); stdIntInRoi = np.std(srcIntsUnderRoi); maxIntInRoi = np.max(srcIntsUnderRoi)
print("\t(in ROI) Intensity Mean:", meanIntInRoi, ", Std :", stdIntInRoi, ", Max: "), maxIntInRoi
### Normalize ###
print("\t...Normalizing...")
boolMaskForStatsCalc = boolRoiMask
meanForNorm = meanIntInRoi
stdForNorm = stdIntInRoi
print("\t\t*Stats for normalization changed to: Mean=", meanForNorm, ", Std="), stdForNorm
if lowHighCutoffPercentile is not None and lowHighCutoffPercentile != [] :
lowCutoff = np.percentile(srcIntsUnderRoi, lowHighCutoffPercentile[0]);
boolOverLowCutoff = srcImgNpArr > lowCutoff
highCutoff = np.percentile(srcIntsUnderRoi, lowHighCutoffPercentile[1]);
boolBelowHighCutoff = srcImgNpArr < highCutoff
print("\t\tCutting off intensities with [percentiles] (within Roi). Cutoffs: Min=", lowCutoff ,", High="), highCutoff
boolMaskForStatsCalc = boolMaskForStatsCalc * boolOverLowCutoff * boolBelowHighCutoff
meanForNorm = np.mean(srcImgNpArr[boolMaskForStatsCalc])
stdForNorm = np.std(srcImgNpArr[boolMaskForStatsCalc])
print("\t\t*Stats for normalization changed to: Mean=", meanForNorm, ", Std="), stdForNorm
if lowHighCutoffTimesTheStd is not None and lowHighCutoffTimesTheStd != [] :
lowCutoff = meanIntInRoi - lowHighCutoffTimesTheStd[0] * stdIntInRoi;
boolOverLowCutoff = srcImgNpArr > lowCutoff
highCutoff = meanIntInRoi + lowHighCutoffTimesTheStd[1] * stdIntInRoi;
boolBelowHighCutoff = srcImgNpArr < highCutoff
print("\t\tCutting off intensities with [std] (within Roi). Cutoffs: Min=", lowCutoff ,", High="), highCutoff
# The next 2 lines are for monitoring only. Could be deleted
boolInRoiAndWithinCutoff = boolRoiMask * boolOverLowCutoff * boolBelowHighCutoff
print("\t\t(In Roi, within THIS cutoff) Intensities Mean="), np.mean(srcImgNpArr[boolInRoiAndWithinCutoff]),", Std=", np.std(srcImgNpArr[boolInRoiAndWithinCutoff])
boolMaskForStatsCalc = boolMaskForStatsCalc * boolOverLowCutoff * boolBelowHighCutoff
meanForNorm = np.mean(srcImgNpArr[boolMaskForStatsCalc])
stdForNorm = np.std(srcImgNpArr[boolMaskForStatsCalc])
print("\t\t*Stats for normalization changed to: Mean=", meanForNorm, ", Std="), stdForNorm
if cutoffAtWholeImgMean :
lowCutoff = meanIntSrcImg; boolOverLowCutoff = srcImgNpArr > lowCutoff
print("\t\tCutting off intensities with [below wholeImageMean for air]. Cutoff: Min="), lowCutoff
boolMaskForStatsCalc = boolMaskForStatsCalc * boolOverLowCutoff
meanForNorm = np.mean(srcImgNpArr[boolMaskForStatsCalc])
stdForNorm = np.std(srcImgNpArr[boolMaskForStatsCalc])
print("\t\t*Stats for normalization changed to: Mean=", meanForNorm, ", Std="), stdForNorm
# Apply the normalization
normImgNpArr = srcImgNpArr - meanForNorm
normImgNpArr = normImgNpArr / (1.0*stdForNorm)
print("\tImage was normalized using: Mean=", meanForNorm, ", Std="), stdForNorm
### Save output ###
if saveOutput:
outputFilepath = channelToNormalizeFilepath
print(outputFilepath)
print("\tSaving normalized output to: "),outputFilepath
saveImageToANewNiiWithHeaderFromOther(normImgNpArr, outputFilepath, srcProxy, dtypeToSaveOutput)
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0
/*
* Copyright (c) 2011-2017, The Linux Foundation
*/
#include <linux/slab.h>
#include <linux/pm_runtime.h>
#include "slimbus.h"
/**
* slim_msg_response() - Deliver Message response received from a device to the
* framework.
*
* @ctrl: Controller handle
* @reply: Reply received from the device
* @len: Length of the reply
* @tid: Transaction ID received with which framework can associate reply.
*
* Called by controller to inform framework about the response received.
* This helps in making the API asynchronous, and controller-driver doesn't need
* to manage 1 more table other than the one managed by framework mapping TID
* with buffers
*/
void slim_msg_response(struct slim_controller *ctrl, u8 *reply, u8 tid, u8 len)
{
struct slim_msg_txn *txn;
struct slim_val_inf *msg;
unsigned long flags;
spin_lock_irqsave(&ctrl->txn_lock, flags);
txn = idr_find(&ctrl->tid_idr, tid);
spin_unlock_irqrestore(&ctrl->txn_lock, flags);
if (txn == NULL)
return;
msg = txn->msg;
if (msg == NULL || msg->rbuf == NULL) {
dev_err(ctrl->dev, "Got response to invalid TID:%d, len:%d\n",
tid, len);
return;
}
slim_free_txn_tid(ctrl, txn);
memcpy(msg->rbuf, reply, len);
if (txn->comp)
complete(txn->comp);
/* Remove runtime-pm vote now that response was received for TID txn */
pm_runtime_mark_last_busy(ctrl->dev);
pm_runtime_put_autosuspend(ctrl->dev);
}
EXPORT_SYMBOL_GPL(slim_msg_response);
/**
* slim_alloc_txn_tid() - Allocate a tid to txn
*
* @ctrl: Controller handle
* @txn: transaction to be allocated with tid.
*
* Return: zero on success with valid txn->tid and error code on failures.
*/
int slim_alloc_txn_tid(struct slim_controller *ctrl, struct slim_msg_txn *txn)
{
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&ctrl->txn_lock, flags);
ret = idr_alloc_cyclic(&ctrl->tid_idr, txn, 0,
SLIM_MAX_TIDS, GFP_ATOMIC);
if (ret < 0) {
spin_unlock_irqrestore(&ctrl->txn_lock, flags);
return ret;
}
txn->tid = ret;
spin_unlock_irqrestore(&ctrl->txn_lock, flags);
return 0;
}
EXPORT_SYMBOL_GPL(slim_alloc_txn_tid);
/**
* slim_free_txn_tid() - Freee tid of txn
*
* @ctrl: Controller handle
* @txn: transaction whose tid should be freed
*/
void slim_free_txn_tid(struct slim_controller *ctrl, struct slim_msg_txn *txn)
{
unsigned long flags;
spin_lock_irqsave(&ctrl->txn_lock, flags);
idr_remove(&ctrl->tid_idr, txn->tid);
spin_unlock_irqrestore(&ctrl->txn_lock, flags);
}
EXPORT_SYMBOL_GPL(slim_free_txn_tid);
/**
* slim_do_transfer() - Process a SLIMbus-messaging transaction
*
* @ctrl: Controller handle
* @txn: Transaction to be sent over SLIMbus
*
* Called by controller to transmit messaging transactions not dealing with
* Interface/Value elements. (e.g. transmittting a message to assign logical
* address to a slave device
*
* Return: -ETIMEDOUT: If transmission of this message timed out
* (e.g. due to bus lines not being clocked or driven by controller)
*/
int slim_do_transfer(struct slim_controller *ctrl, struct slim_msg_txn *txn)
{
DECLARE_COMPLETION_ONSTACK(done);
bool need_tid = false, clk_pause_msg = false;
int ret, timeout;
/*
* do not vote for runtime-PM if the transactions are part of clock
* pause sequence
*/
if (ctrl->sched.clk_state == SLIM_CLK_ENTERING_PAUSE &&
(txn->mt == SLIM_MSG_MT_CORE &&
txn->mc >= SLIM_MSG_MC_BEGIN_RECONFIGURATION &&
txn->mc <= SLIM_MSG_MC_RECONFIGURE_NOW))
clk_pause_msg = true;
if (!clk_pause_msg) {
ret = pm_runtime_get_sync(ctrl->dev);
if (ctrl->sched.clk_state != SLIM_CLK_ACTIVE) {
dev_err(ctrl->dev, "ctrl wrong state:%d, ret:%d\n",
ctrl->sched.clk_state, ret);
goto slim_xfer_err;
}
}
need_tid = slim_tid_txn(txn->mt, txn->mc);
if (need_tid) {
ret = slim_alloc_txn_tid(ctrl, txn);
if (ret)
return ret;
if (!txn->msg->comp)
txn->comp = &done;
else
txn->comp = txn->comp;
}
ret = ctrl->xfer_msg(ctrl, txn);
if (!ret && need_tid && !txn->msg->comp) {
unsigned long ms = txn->rl + HZ;
timeout = wait_for_completion_timeout(txn->comp,
msecs_to_jiffies(ms));
if (!timeout) {
ret = -ETIMEDOUT;
slim_free_txn_tid(ctrl, txn);
}
}
if (ret)
dev_err(ctrl->dev, "Tx:MT:0x%x, MC:0x%x, LA:0x%x failed:%d\n",
txn->mt, txn->mc, txn->la, ret);
slim_xfer_err:
if (!clk_pause_msg && (!need_tid || ret == -ETIMEDOUT)) {
/*
* remove runtime-pm vote if this was TX only, or
* if there was error during this transaction
*/
pm_runtime_mark_last_busy(ctrl->dev);
pm_runtime_put_autosuspend(ctrl->dev);
}
return ret;
}
EXPORT_SYMBOL_GPL(slim_do_transfer);
static int slim_val_inf_sanity(struct slim_controller *ctrl,
struct slim_val_inf *msg, u8 mc)
{
if (!msg || msg->num_bytes > 16 ||
(msg->start_offset + msg->num_bytes) > 0xC00)
goto reterr;
switch (mc) {
case SLIM_MSG_MC_REQUEST_VALUE:
case SLIM_MSG_MC_REQUEST_INFORMATION:
if (msg->rbuf != NULL)
return 0;
break;
case SLIM_MSG_MC_CHANGE_VALUE:
case SLIM_MSG_MC_CLEAR_INFORMATION:
if (msg->wbuf != NULL)
return 0;
break;
case SLIM_MSG_MC_REQUEST_CHANGE_VALUE:
case SLIM_MSG_MC_REQUEST_CLEAR_INFORMATION:
if (msg->rbuf != NULL && msg->wbuf != NULL)
return 0;
break;
}
reterr:
if (msg)
dev_err(ctrl->dev, "Sanity check failed:msg:offset:0x%x, mc:%d\n",
msg->start_offset, mc);
return -EINVAL;
}
static u16 slim_slicesize(int code)
{
static const u8 sizetocode[16] = {
0, 1, 2, 3, 3, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7
};
code = clamp(code, 1, (int)ARRAY_SIZE(sizetocode));
return sizetocode[code - 1];
}
/**
* slim_xfer_msg() - Transfer a value info message on slim device
*
* @sbdev: slim device to which this msg has to be transfered
* @msg: value info message pointer
* @mc: message code of the message
*
* Called by drivers which want to transfer a vlaue or info elements.
*
* Return: -ETIMEDOUT: If transmission of this message timed out
*/
int slim_xfer_msg(struct slim_device *sbdev, struct slim_val_inf *msg,
u8 mc)
{
DEFINE_SLIM_LDEST_TXN(txn_stack, mc, 6, sbdev->laddr, msg);
struct slim_msg_txn *txn = &txn_stack;
struct slim_controller *ctrl = sbdev->ctrl;
int ret;
u16 sl;
if (!ctrl)
return -EINVAL;
ret = slim_val_inf_sanity(ctrl, msg, mc);
if (ret)
return ret;
sl = slim_slicesize(msg->num_bytes);
dev_dbg(ctrl->dev, "SB xfer msg:os:%x, len:%d, MC:%x, sl:%x\n",
msg->start_offset, msg->num_bytes, mc, sl);
txn->ec = ((sl | (1 << 3)) | ((msg->start_offset & 0xFFF) << 4));
switch (mc) {
case SLIM_MSG_MC_REQUEST_CHANGE_VALUE:
case SLIM_MSG_MC_CHANGE_VALUE:
case SLIM_MSG_MC_REQUEST_CLEAR_INFORMATION:
case SLIM_MSG_MC_CLEAR_INFORMATION:
txn->rl += msg->num_bytes;
default:
break;
}
if (slim_tid_txn(txn->mt, txn->mc))
txn->rl++;
return slim_do_transfer(ctrl, txn);
}
EXPORT_SYMBOL_GPL(slim_xfer_msg);
static void slim_fill_msg(struct slim_val_inf *msg, u32 addr,
size_t count, u8 *rbuf, u8 *wbuf)
{
msg->start_offset = addr;
msg->num_bytes = count;
msg->rbuf = rbuf;
msg->wbuf = wbuf;
msg->comp = NULL;
}
/**
* slim_read() - Read SLIMbus value element
*
* @sdev: client handle.
* @addr: address of value element to read.
* @count: number of bytes to read. Maximum bytes allowed are 16.
* @val: will return what the value element value was
*
* Return: -EINVAL for Invalid parameters, -ETIMEDOUT If transmission of
* this message timed out (e.g. due to bus lines not being clocked
* or driven by controller)
*/
int slim_read(struct slim_device *sdev, u32 addr, size_t count, u8 *val)
{
struct slim_val_inf msg;
slim_fill_msg(&msg, addr, count, val, NULL);
return slim_xfer_msg(sdev, &msg, SLIM_MSG_MC_REQUEST_VALUE);
}
EXPORT_SYMBOL_GPL(slim_read);
/**
* slim_readb() - Read byte from SLIMbus value element
*
* @sdev: client handle.
* @addr: address in the value element to read.
*
* Return: byte value of value element.
*/
int slim_readb(struct slim_device *sdev, u32 addr)
{
int ret;
u8 buf;
ret = slim_read(sdev, addr, 1, &buf);
if (ret < 0)
return ret;
else
return buf;
}
EXPORT_SYMBOL_GPL(slim_readb);
/**
* slim_write() - Write SLIMbus value element
*
* @sdev: client handle.
* @addr: address in the value element to write.
* @count: number of bytes to write. Maximum bytes allowed are 16.
* @val: value to write to value element
*
* Return: -EINVAL for Invalid parameters, -ETIMEDOUT If transmission of
* this message timed out (e.g. due to bus lines not being clocked
* or driven by controller)
*/
int slim_write(struct slim_device *sdev, u32 addr, size_t count, u8 *val)
{
struct slim_val_inf msg;
slim_fill_msg(&msg, addr, count, NULL, val);
return slim_xfer_msg(sdev, &msg, SLIM_MSG_MC_CHANGE_VALUE);
}
EXPORT_SYMBOL_GPL(slim_write);
/**
* slim_writeb() - Write byte to SLIMbus value element
*
* @sdev: client handle.
* @addr: address of value element to write.
* @value: value to write to value element
*
* Return: -EINVAL for Invalid parameters, -ETIMEDOUT If transmission of
* this message timed out (e.g. due to bus lines not being clocked
* or driven by controller)
*
*/
int slim_writeb(struct slim_device *sdev, u32 addr, u8 value)
{
return slim_write(sdev, addr, 1, &value);
}
EXPORT_SYMBOL_GPL(slim_writeb);
| {
"pile_set_name": "Github"
} |
publishedPluginVersion=1.23.0
pluginVersion=1.24.0-pre2
pluginName=readonlyrest
| {
"pile_set_name": "Github"
} |
{
"type": "Feature",
"bbox": [-10.0, -10.0, 10.0, 10.0],
"properties": {
"foo": "hi",
"bar": "bye",
"stroke-width": 1
},
"geometry": {
"type": "MultiLineString",
"coordinates": [
[ [100.0, 0.0], [101.0, 1.0] ],
[ [102.0, 2.0], [103.0, 3.0] ]
]
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_H_
#define CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_H_
#include <stdint.h>
#include <map>
#include <utility>
#include <vector>
#include "base/macros.h"
#include "base/strings/string16.h"
#include "base/strings/string_split.h"
#include "build/build_config.h"
#include "content/common/content_export.h"
#include "third_party/WebKit/public/web/WebAXEnums.h"
#include "ui/accessibility/ax_node.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_text_utils.h"
// Set PLATFORM_HAS_NATIVE_ACCESSIBILITY_IMPL if this platform has
// a platform-specific subclass of BrowserAccessibility and
// BrowserAccessibilityManager.
#undef PLATFORM_HAS_NATIVE_ACCESSIBILITY_IMPL
#if defined(OS_WIN)
#define PLATFORM_HAS_NATIVE_ACCESSIBILITY_IMPL 1
#endif
#if defined(OS_MACOSX)
#define PLATFORM_HAS_NATIVE_ACCESSIBILITY_IMPL 1
#endif
#if defined(OS_ANDROID) && !defined(USE_AURA)
#define PLATFORM_HAS_NATIVE_ACCESSIBILITY_IMPL 1
#endif
#if defined(OS_LINUX) && defined(USE_X11) && !defined(OS_CHROMEOS)
#define PLATFORM_HAS_NATIVE_ACCESSIBILITY_IMPL 1
#endif
#if defined(OS_MACOSX) && __OBJC__
@class BrowserAccessibilityCocoa;
#endif
namespace content {
class BrowserAccessibilityManager;
#if defined(OS_WIN)
class BrowserAccessibilityWin;
#elif defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_X11)
class BrowserAccessibilityAuraLinux;
#endif
////////////////////////////////////////////////////////////////////////////////
//
// BrowserAccessibility
//
// A BrowserAccessibility object represents one node in the accessibility
// tree on the browser side. It exactly corresponds to one WebAXObject from
// Blink. It's owned by a BrowserAccessibilityManager.
//
// There are subclasses of BrowserAccessibility for each platform where
// we implement native accessibility APIs. This base class is used occasionally
// for tests.
//
////////////////////////////////////////////////////////////////////////////////
class CONTENT_EXPORT BrowserAccessibility {
public:
// Creates a platform specific BrowserAccessibility. Ownership passes to the
// caller.
static BrowserAccessibility* Create();
virtual ~BrowserAccessibility();
static BrowserAccessibility* GetFromUniqueID(int32_t unique_id);
// Called only once, immediately after construction. The constructor doesn't
// take any arguments because in the Windows subclass we use a special
// function to construct a COM object.
virtual void Init(BrowserAccessibilityManager* manager, ui::AXNode* node);
// Called after the object is first initialized and again every time
// its data changes.
virtual void OnDataChanged() {}
virtual void OnSubtreeWillBeDeleted() {}
// Called when the location changed.
virtual void OnLocationChanged() {}
// This is called when the platform-specific attributes for a node need
// to be recomputed, which may involve firing native events, due to a
// change other than an update from OnAccessibilityEvents.
virtual void UpdatePlatformAttributes() {}
// Return true if this object is equal to or a descendant of |ancestor|.
bool IsDescendantOf(const BrowserAccessibility* ancestor) const;
// Returns true if this object is used only for representing text.
bool IsTextOnlyObject() const;
// Returns true if this is a leaf node on this platform, meaning any
// children should not be exposed to this platform's native accessibility
// layer. Each platform subclass should implement this itself.
// The definition of a leaf may vary depending on the platform,
// but a leaf node should never have children that are focusable or
// that might send notifications.
virtual bool PlatformIsLeaf() const;
// Returns the number of children of this object, or 0 if PlatformIsLeaf()
// returns true.
uint32_t PlatformChildCount() const;
// Return a pointer to the child at the given index, or NULL for an
// invalid index. Returns NULL if PlatformIsLeaf() returns true.
BrowserAccessibility* PlatformGetChild(uint32_t child_index) const;
// Returns true if an ancestor of this node (not including itself) is a
// leaf node, meaning that this node is not actually exposed to the
// platform.
bool PlatformIsChildOfLeaf() const;
// If this object is exposed to the platform, returns this object. Otherwise,
// returns the platform leaf under which this object is found.
BrowserAccessibility* GetClosestPlatformObject() const;
BrowserAccessibility* GetPreviousSibling() const;
BrowserAccessibility* GetNextSibling() const;
bool IsPreviousSiblingOnSameLine() const;
bool IsNextSiblingOnSameLine() const;
// Returns nullptr if there are no children.
BrowserAccessibility* PlatformDeepestFirstChild() const;
// Returns nullptr if there are no children.
BrowserAccessibility* PlatformDeepestLastChild() const;
// Returns nullptr if there are no children.
BrowserAccessibility* InternalDeepestFirstChild() const;
// Returns nullptr if there are no children.
BrowserAccessibility* InternalDeepestLastChild() const;
// Returns the bounds of this object in coordinates relative to the
// top-left corner of the overall web area.
gfx::Rect GetLocalBoundsRect() const;
// Returns the bounds of this object in screen coordinates.
gfx::Rect GetGlobalBoundsRect() const;
// Returns the bounds of the given range in coordinates relative to the
// top-left corner of the overall web area. Only valid when the
// role is WebAXRoleStaticText.
gfx::Rect GetLocalBoundsForRange(int start, int len) const;
// Same as GetLocalBoundsForRange, in screen coordinates. Only valid when
// the role is WebAXRoleStaticText.
gfx::Rect GetGlobalBoundsForRange(int start, int len) const;
// This is to handle the cases such as ARIA textbox, where the value should
// be calculated from the object's inner text.
virtual base::string16 GetValue() const;
// Starting at the given character offset, locates the start of the next or
// previous line and returns its character offset.
int GetLineStartBoundary(int start,
ui::TextBoundaryDirection direction) const;
// Starting at the given character offset, locates the start of the next or
// previous word and returns its character offset.
// In case there is no word boundary before or after the given offset, it
// returns one past the last character.
// If the given offset is already at the start of a word, returns the start
// of the next word if the search is forwards, and the given offset if it is
// backwards.
// If the start offset is equal to -1 and the search is in the forwards
// direction, returns the start boundary of the first word.
// Start offsets that are not in the range -1 to text length are invalid.
int GetWordStartBoundary(int start,
ui::TextBoundaryDirection direction) const;
// Returns the deepest descendant that contains the specified point
// (in global screen coordinates).
BrowserAccessibility* BrowserAccessibilityForPoint(const gfx::Point& point);
// Marks this object for deletion, releases our reference to it, and
// nulls out the pointer to the underlying AXNode. May not delete
// the object immediately due to reference counting.
//
// Reference counting is used on some platforms because the
// operating system may hold onto a reference to a BrowserAccessibility
// object even after we're through with it. When a BrowserAccessibility
// has had Destroy() called but its reference count is not yet zero,
// instance_active() returns false and queries on this object return failure.
virtual void Destroy();
// Subclasses should override this to support platform reference counting.
virtual void NativeAddReference() { }
// Subclasses should override this to support platform reference counting.
virtual void NativeReleaseReference();
//
// Accessors
//
BrowserAccessibilityManager* manager() const { return manager_; }
bool instance_active() const { return node_ && manager_; }
ui::AXNode* node() const { return node_; }
int32_t unique_id() const { return unique_id_; }
// These access the internal accessibility tree, which doesn't necessarily
// reflect the accessibility tree that should be exposed on each platform.
// Use PlatformChildCount and PlatformGetChild to implement platform
// accessibility APIs.
uint32_t InternalChildCount() const;
BrowserAccessibility* InternalGetChild(uint32_t child_index) const;
BrowserAccessibility* InternalGetParent() const;
BrowserAccessibility* GetParent() const;
int32_t GetIndexInParent() const;
int32_t GetId() const;
const ui::AXNodeData& GetData() const;
gfx::Rect GetLocation() const;
int32_t GetRole() const;
int32_t GetState() const;
typedef base::StringPairs HtmlAttributes;
const HtmlAttributes& GetHtmlAttributes() const;
// Returns true if this is a native platform-specific object, vs a
// cross-platform generic object. Don't call ToBrowserAccessibilityXXX if
// IsNative returns false.
virtual bool IsNative() const;
// Accessing accessibility attributes:
//
// There are dozens of possible attributes for an accessibility node,
// but only a few tend to apply to any one object, so we store them
// in sparse arrays of <attribute id, attribute value> pairs, organized
// by type (bool, int, float, string, int list).
//
// There are three accessors for each type of attribute: one that returns
// true if the attribute is present and false if not, one that takes a
// pointer argument and returns true if the attribute is present (if you
// need to distinguish between the default value and a missing attribute),
// and another that returns the default value for that type if the
// attribute is not present. In addition, strings can be returned as
// either std::string or base::string16, for convenience.
bool HasBoolAttribute(ui::AXBoolAttribute attr) const;
bool GetBoolAttribute(ui::AXBoolAttribute attr) const;
bool GetBoolAttribute(ui::AXBoolAttribute attr, bool* value) const;
bool HasFloatAttribute(ui::AXFloatAttribute attr) const;
float GetFloatAttribute(ui::AXFloatAttribute attr) const;
bool GetFloatAttribute(ui::AXFloatAttribute attr, float* value) const;
bool HasInheritedStringAttribute(ui::AXStringAttribute attribute) const;
const std::string& GetInheritedStringAttribute(
ui::AXStringAttribute attribute) const;
bool GetInheritedStringAttribute(ui::AXStringAttribute attribute,
std::string* value) const;
base::string16 GetInheritedString16Attribute(
ui::AXStringAttribute attribute) const;
bool GetInheritedString16Attribute(ui::AXStringAttribute attribute,
base::string16* value) const;
bool HasIntAttribute(ui::AXIntAttribute attribute) const;
int GetIntAttribute(ui::AXIntAttribute attribute) const;
bool GetIntAttribute(ui::AXIntAttribute attribute, int* value) const;
bool HasStringAttribute(
ui::AXStringAttribute attribute) const;
const std::string& GetStringAttribute(ui::AXStringAttribute attribute) const;
bool GetStringAttribute(ui::AXStringAttribute attribute,
std::string* value) const;
base::string16 GetString16Attribute(
ui::AXStringAttribute attribute) const;
bool GetString16Attribute(ui::AXStringAttribute attribute,
base::string16* value) const;
bool HasIntListAttribute(ui::AXIntListAttribute attribute) const;
const std::vector<int32_t>& GetIntListAttribute(
ui::AXIntListAttribute attribute) const;
bool GetIntListAttribute(ui::AXIntListAttribute attribute,
std::vector<int32_t>* value) const;
// Retrieve the value of a html attribute from the attribute map and
// returns true if found.
bool GetHtmlAttribute(const char* attr, base::string16* value) const;
bool GetHtmlAttribute(const char* attr, std::string* value) const;
// Utility method to handle special cases for ARIA booleans, tristates and
// booleans which have a "mixed" state.
//
// Warning: the term "Tristate" is used loosely by the spec and here,
// as some attributes support a 4th state.
//
// The following attributes are appropriate to use with this method:
// aria-selected (selectable)
// aria-grabbed (grabbable)
// aria-expanded (expandable)
// aria-pressed (toggleable/pressable) -- supports 4th "mixed" state
// aria-checked (checkable) -- supports 4th "mixed state"
bool GetAriaTristate(const char* attr_name,
bool* is_defined,
bool* is_mixed) const;
base::string16 GetFontFamily() const;
base::string16 GetLanguage() const;
virtual base::string16 GetText() const;
// Returns true if the bit corresponding to the given state enum is 1.
bool HasState(ui::AXState state_enum) const;
// Returns true if this node is an cell or an table header.
bool IsCellOrTableHeaderRole() const;
// Returns true if the caret is active on this object.
bool HasCaret() const;
// True if this is a web area, and its grandparent is a presentational iframe.
bool IsWebAreaForPresentationalIframe() const;
virtual bool IsClickable() const;
bool IsControl() const;
bool IsMenuRelated() const;
bool IsRangeControl() const;
bool IsSimpleTextControl() const;
// Indicates if this object is at the root of a rich edit text control.
bool IsRichTextControl() const;
// If an object is focusable but has no accessible name, use this
// to compute a name from its descendants.
std::string ComputeAccessibleNameFromDescendants();
protected:
BrowserAccessibility();
// The manager of this tree of accessibility objects.
BrowserAccessibilityManager* manager_;
// The underlying node.
ui::AXNode* node_;
// A unique ID, since node IDs are frame-local.
int32_t unique_id_;
private:
// |GetInnerText| recursively includes all the text from descendants such as
// text found in any embedded object. In contrast, |GetText| might include a
// special character in the place of every embedded object instead of its
// text, depending on the platform.
base::string16 GetInnerText() const;
// If a bounding rectangle is empty, compute it based on the union of its
// children, since most accessibility APIs don't like elements with no
// bounds, but "virtual" elements in the accessibility tree that don't
// correspond to a layed-out element sometimes don't have bounds.
void FixEmptyBounds(gfx::Rect* bounds) const;
// Convert the bounding rectangle of an element (which is relative to
// its nearest scrollable ancestor) to local bounds (which are relative
// to the top of the web accessibility tree).
gfx::Rect ElementBoundsToLocalBounds(gfx::Rect bounds) const;
DISALLOW_COPY_AND_ASSIGN(BrowserAccessibility);
};
} // namespace content
#endif // CONTENT_BROWSER_ACCESSIBILITY_BROWSER_ACCESSIBILITY_H_
| {
"pile_set_name": "Github"
} |
{
"name": "pause-stream",
"version": "0.0.11",
"description": "a ThroughStream that strictly buffers all readable events when paused.",
"main": "index.js",
"directories": {
"test": "test"
},
"devDependencies": {
"stream-tester": "0.0.2",
"stream-spec": "~0.2.0"
},
"scripts": {
"test": "node test/index.js && node test/pause-end.js"
},
"repository": {
"type": "git",
"url": "git://github.com/dominictarr/pause-stream.git"
},
"keywords": [
"stream",
"pipe",
"pause",
"drain",
"buffer"
],
"author": {
"name": "Dominic Tarr",
"email": "[email protected]",
"url": "dominictarr.com"
},
"license": [
"MIT",
"Apache2"
],
"dependencies": {
"through": "~2.3"
},
"readme": "# PauseStream\n\nThis is a `Stream` that will strictly buffer when paused.\nConnect it to anything you need buffered.\n\n``` js\n var ps = require('pause-stream')();\n\n badlyBehavedStream.pipe(ps.pause())\n\n aLittleLater(function (err, data) {\n ps.pipe(createAnotherStream(data))\n ps.resume()\n })\n```\n\n`PauseStream` will buffer whenever paused.\nit will buffer when yau have called `pause` manually.\nbut also when it's downstream `dest.write()===false`.\nit will attempt to drain the buffer when you call resume\nor the downstream emits `'drain'`\n\n`PauseStream` is tested using [stream-spec](https://github.com/dominictarr/stream-spec)\nand [stream-tester](https://github.com/dominictarr/stream-tester)\n\nThis is now the default case of \n[through](https://github.com/dominictarr/through)\n\nhttps://github.com/dominictarr/pause-stream/commit/4a6fe3dc2c11091b1efbfde912e0473719ed9cc0\n",
"readmeFilename": "readme.markdown",
"bugs": {
"url": "https://github.com/dominictarr/pause-stream/issues"
},
"homepage": "https://github.com/dominictarr/pause-stream",
"_id": "[email protected]",
"dist": {
"shasum": "a3cd8be2c6b2b80081f5b8dcb56549d49f7483ac"
},
"_from": "[email protected]",
"_resolved": "https://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz"
}
| {
"pile_set_name": "Github"
} |
[
{
"directory": "${path}",
"command": "g++ -c -o main.o main.c -Wall -DDEBUG -Dvariable=value",
"file": "${path}/main.c"
}
,
{
"directory": "${path}",
"command": "cc -c -o clean-one.o clean-one.c -Wall -DDEBUG \"-Dvariable=value with space\" -Iinclude",
"file": "${path}/clean-one.c"
}
,
{
"directory": "${path}",
"command": "g++ -c -o clean-two.o clean-two.c -Wall -DDEBUG -Dvariable=value -I ./include",
"file": "${path}/clean-two.c"
}
]
| {
"pile_set_name": "Github"
} |
package com.zenjava.test;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class SecondaryMain extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(new Scene(new Label("Hello World 2!")));
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
| {
"pile_set_name": "Github"
} |
<?php
namespace SlmQueueTest\Worker\Event;
use PHPUnit\Framework\TestCase;
use SlmQueue\Queue\QueueInterface;
use SlmQueue\Worker\Event\BootstrapEvent;
use SlmQueue\Worker\WorkerInterface;
class WorkerEventTest extends TestCase
{
protected $queue;
protected $worker;
protected $event;
public function setUp(): void
{
$this->queue = $this->createMock(QueueInterface::class);
$this->worker = $this->createMock(WorkerInterface::class);
$this->event = new BootstrapEvent($this->worker, $this->queue);
}
public function testSetsWorkerAsTarget()
{
static::assertEquals($this->worker, $this->event->getWorker());
}
public function testWorkerEventGetsQueue()
{
static::assertEquals($this->queue, $this->event->getQueue());
}
}
| {
"pile_set_name": "Github"
} |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.TeamsApp;
import com.microsoft.graph.requests.extensions.ITeamsAppDefinitionCollectionRequestBuilder;
import com.microsoft.graph.requests.extensions.ITeamsAppDefinitionRequestBuilder;
import java.util.Arrays;
import java.util.EnumSet;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Teams App With Reference Request Builder.
*/
public interface ITeamsAppWithReferenceRequestBuilder extends IRequestBuilder {
/**
* Creates the request
*
* @param requestOptions the options for this request
* @return the ITeamsAppWithReferenceRequest instance
*/
ITeamsAppWithReferenceRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions);
/**
* Creates the request with specific options instead of the existing options
*
* @param requestOptions the options for this request
* @return the ITeamsAppWithReferenceRequest instance
*/
ITeamsAppWithReferenceRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions);
ITeamsAppReferenceRequestBuilder reference();
}
| {
"pile_set_name": "Github"
} |
/*=========================================================================
*
* Copyright RTK Consortium
*
* 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.txt
*
* 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.
*
*=========================================================================*/
#ifndef rtkWarpFourDToProjectionStackImageFilter_hxx
#define rtkWarpFourDToProjectionStackImageFilter_hxx
#include "rtkWarpFourDToProjectionStackImageFilter.h"
namespace rtk
{
template <typename VolumeSeriesType, typename ProjectionStackType>
WarpFourDToProjectionStackImageFilter<VolumeSeriesType, ProjectionStackType>::WarpFourDToProjectionStackImageFilter()
{
this->SetNumberOfRequiredInputs(3);
this->m_ForwardProjectionFilter = WarpForwardProjectionImageFilterType::New();
if (std::is_same<VolumeSeriesType, CPUVolumeSeriesType>::value)
itkWarningMacro("The warp Forward project image filter exists only in CUDA. Ignoring the displacement vector field "
"and using CPU Joseph forward projection");
}
template <typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter<VolumeSeriesType, ProjectionStackType>::SetDisplacementField(
const DVFSequenceImageType * DisplacementField)
{
this->SetNthInput(2, const_cast<DVFSequenceImageType *>(DisplacementField));
}
template <typename VolumeSeriesType, typename ProjectionStackType>
typename WarpFourDToProjectionStackImageFilter<VolumeSeriesType,
ProjectionStackType>::DVFSequenceImageType::ConstPointer
WarpFourDToProjectionStackImageFilter<VolumeSeriesType, ProjectionStackType>::GetDisplacementField()
{
return static_cast<const DVFSequenceImageType *>(this->itk::ProcessObject::GetInput(2));
}
template <typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter<VolumeSeriesType, ProjectionStackType>::SetSignal(
const std::vector<double> signal)
{
this->m_Signal = signal;
this->Modified();
}
template <typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter<VolumeSeriesType, ProjectionStackType>::GenerateOutputInformation()
{
m_DVFInterpolatorFilter = CPUDVFInterpolatorType::New();
if (m_UseCudaCyclicDeformation)
{
if (std::is_same<VolumeSeriesType, CPUVolumeSeriesType>::value)
itkGenericExceptionMacro(<< "UseCudaCyclicDeformation option only available with itk::CudaImage.");
m_DVFInterpolatorFilter = CudaCyclicDeformationImageFilterType::New();
}
#ifdef RTK_USE_CUDA
if (!std::is_same<VolumeSeriesType, CPUVolumeSeriesType>::value)
{
CudaWarpForwardProjectionImageFilter * wfp;
wfp = dynamic_cast<CudaWarpForwardProjectionImageFilter *>(this->m_ForwardProjectionFilter.GetPointer());
using CudaDVFImageType = itk::CudaImage<VectorForDVF, VolumeSeriesType::ImageDimension - 1>;
CudaDVFImageType * cudvf;
cudvf = dynamic_cast<CudaDVFImageType *>(m_DVFInterpolatorFilter->GetOutput());
wfp->SetDisplacementField(cudvf);
}
#endif
m_DVFInterpolatorFilter->SetSignalVector(m_Signal);
m_DVFInterpolatorFilter->SetInput(this->GetDisplacementField());
m_DVFInterpolatorFilter->SetFrame(0);
Superclass::GenerateOutputInformation();
}
template <typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter<VolumeSeriesType, ProjectionStackType>::GenerateInputRequestedRegion()
{
// Input 0 is the stack of projections we update
typename ProjectionStackType::Pointer inputPtr0 = const_cast<ProjectionStackType *>(this->GetInput(0));
if (!inputPtr0)
{
return;
}
inputPtr0->SetRequestedRegion(this->GetOutput()->GetRequestedRegion());
// Input 1 is the volume series
typename VolumeSeriesType::Pointer inputPtr1 = static_cast<VolumeSeriesType *>(this->itk::ProcessObject::GetInput(1));
inputPtr1->SetRequestedRegionToLargestPossibleRegion();
// Input 2 is the sequence of DVFs
typename DVFSequenceImageType::Pointer inputPtr2 =
static_cast<DVFSequenceImageType *>(this->itk::ProcessObject::GetInput(2));
inputPtr2->SetRequestedRegionToLargestPossibleRegion();
}
template <typename VolumeSeriesType, typename ProjectionStackType>
void
WarpFourDToProjectionStackImageFilter<VolumeSeriesType, ProjectionStackType>::GenerateData()
{
int ProjectionStackDimension = ProjectionStackType::ImageDimension;
int NumberProjs = this->GetInputProjectionStack()->GetRequestedRegion().GetSize(ProjectionStackDimension - 1);
int FirstProj = this->GetInputProjectionStack()->GetRequestedRegion().GetIndex(ProjectionStackDimension - 1);
bool firstProjectionProcessed = false;
// Process the projections in order
for (int proj = FirstProj; proj < FirstProj + NumberProjs; proj++)
{
// After the first update, we need to use the output as input.
if (firstProjectionProcessed)
{
typename ProjectionStackType::Pointer pimg = this->m_PasteFilter->GetOutput();
pimg->DisconnectPipeline();
this->m_PasteFilter->SetDestinationImage(pimg);
}
// Update the paste region
this->m_PasteRegion.SetIndex(ProjectionStackDimension - 1, proj);
// Set the projection stack source
this->m_ConstantProjectionStackSource->SetIndex(this->m_PasteRegion.GetIndex());
// Set the Paste Filter. Since its output has been disconnected
// we need to set its RequestedRegion manually (it will never
// be updated by a downstream filter)
this->m_PasteFilter->SetSourceRegion(this->m_PasteRegion);
this->m_PasteFilter->SetDestinationIndex(this->m_PasteRegion.GetIndex());
this->m_PasteFilter->GetOutput()->SetRequestedRegion(
this->m_PasteFilter->GetDestinationImage()->GetLargestPossibleRegion());
// Set the Interpolation filter
this->m_InterpolationFilter->SetProjectionNumber(proj);
// Set the DVF interpolator
m_DVFInterpolatorFilter->SetFrame(proj);
// Update the last filter
this->m_PasteFilter->Update();
// Update condition
firstProjectionProcessed = true;
}
// Graft its output
this->GraftOutput(this->m_PasteFilter->GetOutput());
// Release the data in internal filters
this->m_DVFInterpolatorFilter->GetOutput()->ReleaseData();
}
} // namespace rtk
#endif
| {
"pile_set_name": "Github"
} |
using NUnit.Framework;
using VkNet.Enums.Filters;
using VkNet.Enums.SafetyEnums;
namespace VkNet.Tests.Enum.SafetyEnums
{
[TestFixture]
public class SafetyEnumsTest
{
[Test]
public void NullTest()
{
var result = AppFilter.FromJsonString("");
Assert.That(result == null);
}
[Test]
public void AppFilterTest()
{
// get test
Assert.That(AppFilter.Installed.ToString(), Is.EqualTo("installed"));
Assert.That(AppFilter.Featured.ToString(), Is.EqualTo("featured"));
// parse test
Assert.That(AppFilter.FromJsonString("installed"), Is.EqualTo(AppFilter.Installed));
Assert.That(AppFilter.FromJsonString("featured"), Is.EqualTo(AppFilter.Featured));
}
[Test]
public void AppPlatformsTest()
{
// get test
Assert.That(AppPlatforms.Ios.ToString(), Is.EqualTo("ios"));
Assert.That(AppPlatforms.Android.ToString(), Is.EqualTo("android"));
Assert.That(AppPlatforms.WinPhone.ToString(), Is.EqualTo("winphone"));
Assert.That(AppPlatforms.Web.ToString(), Is.EqualTo("web"));
// parse test
Assert.That(AppPlatforms.FromJsonString("ios"), Is.EqualTo(AppPlatforms.Ios));
Assert.That(AppPlatforms.FromJsonString("android"), Is.EqualTo(AppPlatforms.Android));
Assert.That(AppPlatforms.FromJsonString("winphone"), Is.EqualTo(AppPlatforms.WinPhone));
Assert.That(AppPlatforms.FromJsonString("web"), Is.EqualTo(AppPlatforms.Web));
}
[Test]
public void AppRatingTypeTest()
{
// get test
Assert.That(AppRatingType.Level.ToString(), Is.EqualTo("level"));
Assert.That(AppRatingType.Points.ToString(), Is.EqualTo("points"));
// parse test
Assert.That(AppRatingType.FromJsonString("level"), Is.EqualTo(AppRatingType.Level));
Assert.That(AppRatingType.FromJsonString("points"), Is.EqualTo(AppRatingType.Points));
}
[Test]
public void AppRequestTypeTest()
{
// get test
Assert.That(AppRequestType.Invite.ToString(), Is.EqualTo("invite"));
Assert.That(AppRequestType.Request.ToString(), Is.EqualTo("request"));
// parse test
Assert.That(AppRequestType.FromJsonString("invite"), Is.EqualTo(AppRequestType.Invite));
Assert.That(AppRequestType.FromJsonString("request")
, Is.EqualTo(AppRequestType.Request));
}
[Test]
public void AppSortTest()
{
// get test
Assert.That(AppSort.PopularToday.ToString(), Is.EqualTo("popular_today"));
Assert.That(AppSort.Visitors.ToString(), Is.EqualTo("visitors"));
Assert.That(AppSort.CreateDate.ToString(), Is.EqualTo("create_date"));
Assert.That(AppSort.GrowthRate.ToString(), Is.EqualTo("growth_rate"));
Assert.That(AppSort.PopularWeek.ToString(), Is.EqualTo("popular_week"));
// parse test
Assert.That(AppSort.FromJsonString("popular_today"), Is.EqualTo(AppSort.PopularToday));
Assert.That(AppSort.FromJsonString("visitors"), Is.EqualTo(AppSort.Visitors));
Assert.That(AppSort.FromJsonString("create_date"), Is.EqualTo(AppSort.CreateDate));
Assert.That(AppSort.FromJsonString("growth_rate"), Is.EqualTo(AppSort.GrowthRate));
Assert.That(AppSort.FromJsonString("popular_week"), Is.EqualTo(AppSort.PopularWeek));
}
[Test]
public void ChangeNameStatusTest()
{
// get test
Assert.That(ChangeNameStatus.Processing.ToString(), Is.EqualTo("processing"));
Assert.That(ChangeNameStatus.Declined.ToString(), Is.EqualTo("declined"));
Assert.That(ChangeNameStatus.Success.ToString(), Is.EqualTo("success"));
Assert.That(ChangeNameStatus.WasAccepted.ToString(), Is.EqualTo("was_accepted"));
Assert.That(ChangeNameStatus.WasDeclined.ToString(), Is.EqualTo("was_declined"));
// parse test
Assert.That(ChangeNameStatus.FromJsonString("processing")
, Is.EqualTo(ChangeNameStatus.Processing));
Assert.That(ChangeNameStatus.FromJsonString("declined")
, Is.EqualTo(ChangeNameStatus.Declined));
Assert.That(ChangeNameStatus.FromJsonString("success")
, Is.EqualTo(ChangeNameStatus.Success));
Assert.That(ChangeNameStatus.FromJsonString("was_accepted")
, Is.EqualTo(ChangeNameStatus.WasAccepted));
Assert.That(ChangeNameStatus.FromJsonString("was_declined")
, Is.EqualTo(ChangeNameStatus.WasDeclined));
}
[Test]
public void CommentObjectTypeTest()
{
// get test
Assert.That(CommentObjectType.Post.ToString(), Is.EqualTo("post"));
Assert.That(CommentObjectType.Photo.ToString(), Is.EqualTo("photo"));
Assert.That(CommentObjectType.Video.ToString(), Is.EqualTo("video"));
Assert.That(CommentObjectType.Topic.ToString(), Is.EqualTo("topic"));
Assert.That(CommentObjectType.Note.ToString(), Is.EqualTo("note"));
// parse test
Assert.That(CommentObjectType.FromJsonString("post")
, Is.EqualTo(CommentObjectType.Post));
Assert.That(CommentObjectType.FromJsonString("photo")
, Is.EqualTo(CommentObjectType.Photo));
Assert.That(CommentObjectType.FromJsonString("video")
, Is.EqualTo(CommentObjectType.Video));
Assert.That(CommentObjectType.FromJsonString("topic")
, Is.EqualTo(CommentObjectType.Topic));
Assert.That(CommentObjectType.FromJsonString("note")
, Is.EqualTo(CommentObjectType.Note));
}
[Test]
public void CommentsSortTest()
{
// get test
Assert.That(CommentsSort.Asc.ToString(), Is.EqualTo("asc"));
Assert.That(CommentsSort.Desc.ToString(), Is.EqualTo("desc"));
// parse test
Assert.That(CommentsSort.FromJsonString("asc"), Is.EqualTo(CommentsSort.Asc));
Assert.That(CommentsSort.FromJsonString("desc"), Is.EqualTo(CommentsSort.Desc));
}
[Test]
public void DeactivatedTest()
{
// get test
Assert.That(Deactivated.Deleted.ToString(), Is.EqualTo("deleted"));
Assert.That(Deactivated.Banned.ToString(), Is.EqualTo("banned"));
Assert.That(Deactivated.Activated.ToString(), Is.EqualTo("activated"));
// parse test
Assert.That(Deactivated.FromJsonString("deleted"), Is.EqualTo(Deactivated.Deleted));
Assert.That(Deactivated.FromJsonString("banned"), Is.EqualTo(Deactivated.Banned));
Assert.That(Deactivated.FromJsonString("activated"), Is.EqualTo(Deactivated.Activated));
}
[Test]
public void DisplayTest()
{
// get test
Assert.That(Display.Page.ToString(), Is.EqualTo("page"));
Assert.That(Display.Popup.ToString(), Is.EqualTo("popup"));
Assert.That(Display.Mobile.ToString(), Is.EqualTo("mobile"));
// parse test
Assert.That(Display.FromJsonString("page"), Is.EqualTo(Display.Page));
Assert.That(Display.FromJsonString("popup"), Is.EqualTo(Display.Popup));
Assert.That(Display.FromJsonString("mobile"), Is.EqualTo(Display.Mobile));
}
[Test]
public void FeedTypeTest()
{
// get test
Assert.That(FeedType.Photo.ToString(), Is.EqualTo("photo"));
Assert.That(FeedType.PhotoTag.ToString(), Is.EqualTo("photo_tag"));
// parse test
Assert.That(FeedType.FromJsonString("photo"), Is.EqualTo(FeedType.Photo));
Assert.That(FeedType.FromJsonString("photo_tag"), Is.EqualTo(FeedType.PhotoTag));
}
[Test]
public void FriendsFilterTest()
{
// get test
Assert.That(FriendsFilter.Mutual.ToString(), Is.EqualTo("mutual"));
Assert.That(FriendsFilter.Contacts.ToString(), Is.EqualTo("contacts"));
Assert.That(FriendsFilter.MutualContacts.ToString(), Is.EqualTo("mutual_contacts"));
// parse test
Assert.That(FriendsFilter.FromJsonString("mutual"), Is.EqualTo(FriendsFilter.Mutual));
Assert.That(FriendsFilter.FromJsonString("contacts")
, Is.EqualTo(FriendsFilter.Contacts));
Assert.That(FriendsFilter.FromJsonString("mutual_contacts")
, Is.EqualTo(FriendsFilter.MutualContacts));
}
[Test]
public void FriendsOrderTest()
{
// get test
Assert.That(FriendsOrder.Name.ToString(), Is.EqualTo("name"));
Assert.That(FriendsOrder.Hints.ToString(), Is.EqualTo("hints"));
Assert.That(FriendsOrder.Random.ToString(), Is.EqualTo("random"));
// parse test
Assert.That(FriendsOrder.FromJsonString("name"), Is.EqualTo(FriendsOrder.Name));
Assert.That(FriendsOrder.FromJsonString("hints"), Is.EqualTo(FriendsOrder.Hints));
Assert.That(FriendsOrder.FromJsonString("random"), Is.EqualTo(FriendsOrder.Random));
}
[Test]
public void GroupsSortTest()
{
// get test
Assert.That(GroupsSort.IdAsc.ToString(), Is.EqualTo("id_asc"));
Assert.That(GroupsSort.IdDesc.ToString(), Is.EqualTo("id_desc"));
Assert.That(GroupsSort.TimeAsc.ToString(), Is.EqualTo("time_asc"));
Assert.That(GroupsSort.TimeDesc.ToString(), Is.EqualTo("time_desc"));
// parse test
Assert.That(GroupsSort.FromJsonString("id_asc"), Is.EqualTo(GroupsSort.IdAsc));
Assert.That(GroupsSort.FromJsonString("id_desc"), Is.EqualTo(GroupsSort.IdDesc));
Assert.That(GroupsSort.FromJsonString("time_asc"), Is.EqualTo(GroupsSort.TimeAsc));
Assert.That(GroupsSort.FromJsonString("time_desc"), Is.EqualTo(GroupsSort.TimeDesc));
}
[Test]
public void GroupTypeTest()
{
// get test
Assert.That(GroupType.Page.ToString(), Is.EqualTo("page"));
Assert.That(GroupType.Group.ToString(), Is.EqualTo("group"));
Assert.That(GroupType.Event.ToString(), Is.EqualTo("event"));
Assert.That(GroupType.Undefined.ToString(), Is.EqualTo("undefined"));
// parse test
Assert.That(GroupType.FromJsonString("page"), Is.EqualTo(GroupType.Page));
Assert.That(GroupType.FromJsonString("group"), Is.EqualTo(GroupType.Group));
Assert.That(GroupType.FromJsonString("event"), Is.EqualTo(GroupType.Event));
Assert.That(GroupType.FromJsonString("undefined"), Is.EqualTo(GroupType.Undefined));
}
[Test]
public void LikeObjectTypeTest()
{
// get test
Assert.That(LikeObjectType.Post.ToString(), Is.EqualTo("post"));
Assert.That(LikeObjectType.Comment.ToString(), Is.EqualTo("comment"));
Assert.That(LikeObjectType.Photo.ToString(), Is.EqualTo("photo"));
Assert.That(LikeObjectType.Audio.ToString(), Is.EqualTo("audio"));
Assert.That(LikeObjectType.Video.ToString(), Is.EqualTo("video"));
Assert.That(LikeObjectType.Note.ToString(), Is.EqualTo("note"));
Assert.That(LikeObjectType.PhotoComment.ToString(), Is.EqualTo("photo_comment"));
Assert.That(LikeObjectType.VideoComment.ToString(), Is.EqualTo("video_comment"));
Assert.That(LikeObjectType.TopicComment.ToString(), Is.EqualTo("topic_comment"));
Assert.That(LikeObjectType.SitePage.ToString(), Is.EqualTo("sitepage"));
Assert.That(LikeObjectType.Market.ToString(), Is.EqualTo("market"));
Assert.That(LikeObjectType.MarketComment.ToString(), Is.EqualTo("market_comment"));
// parse test
Assert.That(LikeObjectType.FromJsonString("post"), Is.EqualTo(LikeObjectType.Post));
Assert.That(LikeObjectType.FromJsonString("comment")
, Is.EqualTo(LikeObjectType.Comment));
Assert.That(LikeObjectType.FromJsonString("photo"), Is.EqualTo(LikeObjectType.Photo));
Assert.That(LikeObjectType.FromJsonString("audio"), Is.EqualTo(LikeObjectType.Audio));
Assert.That(LikeObjectType.FromJsonString("video"), Is.EqualTo(LikeObjectType.Video));
Assert.That(LikeObjectType.FromJsonString("note"), Is.EqualTo(LikeObjectType.Note));
Assert.That(LikeObjectType.FromJsonString("photo_comment")
, Is.EqualTo(LikeObjectType.PhotoComment));
Assert.That(LikeObjectType.FromJsonString("video_comment")
, Is.EqualTo(LikeObjectType.VideoComment));
Assert.That(LikeObjectType.FromJsonString("topic_comment")
, Is.EqualTo(LikeObjectType.TopicComment));
Assert.That(LikeObjectType.FromJsonString("sitepage")
, Is.EqualTo(LikeObjectType.SitePage));
Assert.That(LikeObjectType.FromJsonString("market"), Is.EqualTo(LikeObjectType.Market));
Assert.That(LikeObjectType.FromJsonString("market_comment")
, Is.EqualTo(LikeObjectType.MarketComment));
}
[Test]
public void LikesFilterTest()
{
// get test
Assert.That(LikesFilter.Likes.ToString(), Is.EqualTo("likes"));
Assert.That(LikesFilter.Copies.ToString(), Is.EqualTo("copies"));
// parse test
Assert.That(LikesFilter.FromJsonString("likes"), Is.EqualTo(LikesFilter.Likes));
Assert.That(LikesFilter.FromJsonString("copies"), Is.EqualTo(LikesFilter.Copies));
}
[Test]
public void LinkAccessTypeTest()
{
// get test
Assert.That(LinkAccessType.NotBanned.ToString(), Is.EqualTo("not_banned"));
Assert.That(LinkAccessType.Banned.ToString(), Is.EqualTo("banned"));
Assert.That(LinkAccessType.Processing.ToString(), Is.EqualTo("processing"));
// parse test
Assert.That(LinkAccessType.FromJsonString("not_banned")
, Is.EqualTo(LinkAccessType.NotBanned));
Assert.That(LinkAccessType.FromJsonString("banned"), Is.EqualTo(LinkAccessType.Banned));
Assert.That(LinkAccessType.FromJsonString("processing")
, Is.EqualTo(LinkAccessType.Processing));
}
[Test]
public void MediaTypeTest()
{
// get test
Assert.That(MediaType.Photo.ToString(), Is.EqualTo("photo"));
Assert.That(MediaType.Video.ToString(), Is.EqualTo("video"));
Assert.That(MediaType.Audio.ToString(), Is.EqualTo("audio"));
Assert.That(MediaType.Doc.ToString(), Is.EqualTo("doc"));
Assert.That(MediaType.Link.ToString(), Is.EqualTo("link"));
Assert.That(MediaType.Market.ToString(), Is.EqualTo("market"));
Assert.That(MediaType.Wall.ToString(), Is.EqualTo("wall"));
Assert.That(MediaType.Share.ToString(), Is.EqualTo("share"));
Assert.That(MediaType.Graffiti.ToString(), Is.EqualTo("graffiti"));
// parse test
Assert.That(MediaType.FromJsonString("photo"), Is.EqualTo(MediaType.Photo));
Assert.That(MediaType.FromJsonString("video"), Is.EqualTo(MediaType.Video));
Assert.That(MediaType.FromJsonString("audio"), Is.EqualTo(MediaType.Audio));
Assert.That(MediaType.FromJsonString("doc"), Is.EqualTo(MediaType.Doc));
Assert.That(MediaType.FromJsonString("link"), Is.EqualTo(MediaType.Link));
Assert.That(MediaType.FromJsonString("market"), Is.EqualTo(MediaType.Market));
Assert.That(MediaType.FromJsonString("wall"), Is.EqualTo(MediaType.Wall));
Assert.That(MediaType.FromJsonString("share"), Is.EqualTo(MediaType.Share));
Assert.That(MediaType.FromJsonString("graffiti"), Is.EqualTo(MediaType.Graffiti));
}
[Test]
public void NameCaseTest()
{
// get test
Assert.That(NameCase.Nom.ToString(), Is.EqualTo("nom"));
Assert.That(NameCase.Gen.ToString(), Is.EqualTo("gen"));
Assert.That(NameCase.Dat.ToString(), Is.EqualTo("dat"));
Assert.That(NameCase.Acc.ToString(), Is.EqualTo("acc"));
Assert.That(NameCase.Ins.ToString(), Is.EqualTo("ins"));
Assert.That(NameCase.Abl.ToString(), Is.EqualTo("abl"));
// parse test
Assert.That(NameCase.FromJsonString("nom"), Is.EqualTo(NameCase.Nom));
Assert.That(NameCase.FromJsonString("gen"), Is.EqualTo(NameCase.Gen));
Assert.That(NameCase.FromJsonString("dat"), Is.EqualTo(NameCase.Dat));
Assert.That(NameCase.FromJsonString("acc"), Is.EqualTo(NameCase.Acc));
Assert.That(NameCase.FromJsonString("ins"), Is.EqualTo(NameCase.Ins));
Assert.That(NameCase.FromJsonString("abl"), Is.EqualTo(NameCase.Abl));
}
[Test]
public void NewsObjectTypesTest()
{
// get test
Assert.That(NewsObjectTypes.Wall.ToString(), Is.EqualTo("wall"));
Assert.That(NewsObjectTypes.Tag.ToString(), Is.EqualTo("tag"));
Assert.That(NewsObjectTypes.ProfilePhoto.ToString(), Is.EqualTo("profilephoto"));
Assert.That(NewsObjectTypes.Video.ToString(), Is.EqualTo("video"));
Assert.That(NewsObjectTypes.Photo.ToString(), Is.EqualTo("photo"));
Assert.That(NewsObjectTypes.Audio.ToString(), Is.EqualTo("audio"));
// parse test
Assert.That(NewsObjectTypes.FromJsonString("wall"), Is.EqualTo(NewsObjectTypes.Wall));
Assert.That(NewsObjectTypes.FromJsonString("tag"), Is.EqualTo(NewsObjectTypes.Tag));
Assert.That(NewsObjectTypes.FromJsonString("profilephoto")
, Is.EqualTo(NewsObjectTypes.ProfilePhoto));
Assert.That(NewsObjectTypes.FromJsonString("video"), Is.EqualTo(NewsObjectTypes.Video));
Assert.That(NewsObjectTypes.FromJsonString("photo"), Is.EqualTo(NewsObjectTypes.Photo));
Assert.That(NewsObjectTypes.FromJsonString("audio"), Is.EqualTo(NewsObjectTypes.Audio));
}
[Test]
public void NewsTypesTest()
{
// get test
Assert.That(NewsTypes.Post.ToString(), Is.EqualTo("post"));
Assert.That(NewsTypes.Photo.ToString(), Is.EqualTo("photo"));
Assert.That(NewsTypes.PhotoTag.ToString(), Is.EqualTo("photo_tag"));
Assert.That(NewsTypes.WallPhoto.ToString(), Is.EqualTo("wall_photo"));
Assert.That(NewsTypes.Friend.ToString(), Is.EqualTo("friend"));
Assert.That(NewsTypes.Note.ToString(), Is.EqualTo("note"));
// parse test
Assert.That(NewsTypes.FromJsonString("post"), Is.EqualTo(NewsTypes.Post));
Assert.That(NewsTypes.FromJsonString("photo"), Is.EqualTo(NewsTypes.Photo));
Assert.That(NewsTypes.FromJsonString("photo_tag"), Is.EqualTo(NewsTypes.PhotoTag));
Assert.That(NewsTypes.FromJsonString("wall_photo"), Is.EqualTo(NewsTypes.WallPhoto));
Assert.That(NewsTypes.FromJsonString("friend"), Is.EqualTo(NewsTypes.Friend));
Assert.That(NewsTypes.FromJsonString("note"), Is.EqualTo(NewsTypes.Note));
}
[Test]
public void OccupationTypeTest()
{
// get test
Assert.That(OccupationType.Work.ToString(), Is.EqualTo("work"));
Assert.That(OccupationType.School.ToString(), Is.EqualTo("school"));
Assert.That(OccupationType.University.ToString(), Is.EqualTo("university"));
// parse test
Assert.That(OccupationType.FromJsonString("work"), Is.EqualTo(OccupationType.Work));
Assert.That(OccupationType.FromJsonString("school"), Is.EqualTo(OccupationType.School));
Assert.That(OccupationType.FromJsonString("university")
, Is.EqualTo(OccupationType.University));
}
[Test]
public void PhotoAlbumTypeTest()
{
// get test
Assert.That(PhotoAlbumType.Wall.ToString(), Is.EqualTo("wall"));
Assert.That(PhotoAlbumType.Profile.ToString(), Is.EqualTo("profile"));
Assert.That(PhotoAlbumType.Saved.ToString(), Is.EqualTo("saved"));
// parse test
Assert.That(PhotoAlbumType.FromJsonString("wall"), Is.EqualTo(PhotoAlbumType.Wall));
Assert.That(PhotoAlbumType.FromJsonString("profile")
, Is.EqualTo(PhotoAlbumType.Profile));
Assert.That(PhotoAlbumType.FromJsonString("saved"), Is.EqualTo(PhotoAlbumType.Saved));
}
[Test]
public void PhotoFeedTypeTest()
{
// get test
Assert.That(PhotoFeedType.Photo.ToString(), Is.EqualTo("photo"));
Assert.That(PhotoFeedType.PhotoTag.ToString(), Is.EqualTo("photo_tag"));
// parse test
Assert.That(PhotoFeedType.FromJsonString("photo"), Is.EqualTo(PhotoFeedType.Photo));
Assert.That(PhotoFeedType.FromJsonString("photo_tag")
, Is.EqualTo(PhotoFeedType.PhotoTag));
}
[Test]
public void PhotoSearchRadiusTest()
{
// get test
Assert.That(PhotoSearchRadius.Ten.ToString(), Is.EqualTo("10"));
Assert.That(PhotoSearchRadius.OneHundred.ToString(), Is.EqualTo("100"));
Assert.That(PhotoSearchRadius.Eighty.ToString(), Is.EqualTo("800"));
Assert.That(PhotoSearchRadius.SixThousand.ToString(), Is.EqualTo("6000"));
Assert.That(PhotoSearchRadius.FiftyThousand.ToString(), Is.EqualTo("50000"));
// parse test
Assert.That(PhotoSearchRadius.FromJsonString("10"), Is.EqualTo(PhotoSearchRadius.Ten));
Assert.That(PhotoSearchRadius.FromJsonString("100")
, Is.EqualTo(PhotoSearchRadius.OneHundred));
Assert.That(PhotoSearchRadius.FromJsonString("800")
, Is.EqualTo(PhotoSearchRadius.Eighty));
Assert.That(PhotoSearchRadius.FromJsonString("6000")
, Is.EqualTo(PhotoSearchRadius.SixThousand));
Assert.That(PhotoSearchRadius.FromJsonString("50000")
, Is.EqualTo(PhotoSearchRadius.FiftyThousand));
}
[Test]
public void PhotoSizeTypeTest()
{
// get test
Assert.That(PhotoSizeType.S.ToString(), Is.EqualTo("s"));
Assert.That(PhotoSizeType.M.ToString(), Is.EqualTo("m"));
Assert.That(PhotoSizeType.X.ToString(), Is.EqualTo("x"));
Assert.That(PhotoSizeType.O.ToString(), Is.EqualTo("o"));
Assert.That(PhotoSizeType.P.ToString(), Is.EqualTo("p"));
Assert.That(PhotoSizeType.Q.ToString(), Is.EqualTo("q"));
Assert.That(PhotoSizeType.R.ToString(), Is.EqualTo("r"));
Assert.That(PhotoSizeType.Y.ToString(), Is.EqualTo("y"));
Assert.That(PhotoSizeType.Z.ToString(), Is.EqualTo("z"));
Assert.That(PhotoSizeType.W.ToString(), Is.EqualTo("w"));
// parse test
Assert.That(PhotoSizeType.FromJsonString("s"), Is.EqualTo(PhotoSizeType.S));
Assert.That(PhotoSizeType.FromJsonString("m"), Is.EqualTo(PhotoSizeType.M));
Assert.That(PhotoSizeType.FromJsonString("x"), Is.EqualTo(PhotoSizeType.X));
Assert.That(PhotoSizeType.FromJsonString("o"), Is.EqualTo(PhotoSizeType.O));
Assert.That(PhotoSizeType.FromJsonString("p"), Is.EqualTo(PhotoSizeType.P));
Assert.That(PhotoSizeType.FromJsonString("q"), Is.EqualTo(PhotoSizeType.Q));
Assert.That(PhotoSizeType.FromJsonString("r"), Is.EqualTo(PhotoSizeType.R));
Assert.That(PhotoSizeType.FromJsonString("y"), Is.EqualTo(PhotoSizeType.Y));
Assert.That(PhotoSizeType.FromJsonString("z"), Is.EqualTo(PhotoSizeType.Z));
Assert.That(PhotoSizeType.FromJsonString("w"), Is.EqualTo(PhotoSizeType.W));
}
[Test]
public void PlatformTest()
{
// get test
Assert.That(Platform.Android.ToString(), Is.EqualTo("android"));
Assert.That(Platform.IPhone.ToString(), Is.EqualTo("iphone"));
Assert.That(Platform.WindowsPhone.ToString(), Is.EqualTo("wphone"));
// parse test
Assert.That(Platform.FromJsonString("android"), Is.EqualTo(Platform.Android));
Assert.That(Platform.FromJsonString("iphone"), Is.EqualTo(Platform.IPhone));
Assert.That(Platform.FromJsonString("wphone"), Is.EqualTo(Platform.WindowsPhone));
}
[Test]
public void PostSourceTypeTest()
{
// get test
Assert.That(PostSourceType.Vk.ToString(), Is.EqualTo("vk"));
Assert.That(PostSourceType.Widget.ToString(), Is.EqualTo("widget"));
Assert.That(PostSourceType.Api.ToString(), Is.EqualTo("api"));
Assert.That(PostSourceType.Rss.ToString(), Is.EqualTo("rss"));
Assert.That(PostSourceType.Sms.ToString(), Is.EqualTo("sms"));
// parse test
Assert.That(PostSourceType.FromJsonString("vk"), Is.EqualTo(PostSourceType.Vk));
Assert.That(PostSourceType.FromJsonString("widget"), Is.EqualTo(PostSourceType.Widget));
Assert.That(PostSourceType.FromJsonString("api"), Is.EqualTo(PostSourceType.Api));
Assert.That(PostSourceType.FromJsonString("rss"), Is.EqualTo(PostSourceType.Rss));
Assert.That(PostSourceType.FromJsonString("sms"), Is.EqualTo(PostSourceType.Sms));
}
[Test]
public void PostTypeOrderTest()
{
// get test
Assert.That(PostTypeOrder.Post.ToString(), Is.EqualTo("post"));
Assert.That(PostTypeOrder.Copy.ToString(), Is.EqualTo("copy"));
// parse test
Assert.That(PostTypeOrder.FromJsonString("post"), Is.EqualTo(PostTypeOrder.Post));
Assert.That(PostTypeOrder.FromJsonString("copy"), Is.EqualTo(PostTypeOrder.Copy));
}
[Test]
public void PostTypeTest()
{
// get test
Assert.That(PostType.Post.ToString(), Is.EqualTo("post"));
Assert.That(PostType.Copy.ToString(), Is.EqualTo("copy"));
Assert.That(PostType.Reply.ToString(), Is.EqualTo("reply"));
Assert.That(PostType.Postpone.ToString(), Is.EqualTo("postpone"));
Assert.That(PostType.Suggest.ToString(), Is.EqualTo("suggest"));
// parse test
Assert.That(PostType.FromJsonString("post"), Is.EqualTo(PostType.Post));
Assert.That(PostType.FromJsonString("copy"), Is.EqualTo(PostType.Copy));
Assert.That(PostType.FromJsonString("reply"), Is.EqualTo(PostType.Reply));
Assert.That(PostType.FromJsonString("postpone"), Is.EqualTo(PostType.Postpone));
Assert.That(PostType.FromJsonString("suggest"), Is.EqualTo(PostType.Suggest));
}
[Test]
public void PrivacyTest()
{
// get test
Assert.That(Privacy.All.ToString(), Is.EqualTo("all"));
Assert.That(Privacy.Friends.ToString(), Is.EqualTo("friends"));
Assert.That(Privacy.FriendsOfFriends.ToString(), Is.EqualTo("friends_of_friends"));
Assert.That(Privacy.FriendsOfFriendsOnly.ToString(), Is.EqualTo("friends_of_friends_only"));
Assert.That(Privacy.Nobody.ToString(), Is.EqualTo("nobody"));
Assert.That(Privacy.OnlyMe.ToString(), Is.EqualTo("only_me"));
// parse test
Assert.That(Privacy.FromJsonString("all"), Is.EqualTo(Privacy.All));
Assert.That(Privacy.FromJsonString("friends"), Is.EqualTo(Privacy.Friends));
Assert.That(Privacy.FromJsonString("friends_of_friends")
, Is.EqualTo(Privacy.FriendsOfFriends));
Assert.That(Privacy.FromJsonString("friends_of_friends_only")
, Is.EqualTo(Privacy.FriendsOfFriendsOnly));
Assert.That(Privacy.FromJsonString("nobody"), Is.EqualTo(Privacy.Nobody));
Assert.That(Privacy.FromJsonString("only_me"), Is.EqualTo(Privacy.OnlyMe));
}
[Test]
public void RelativeTypeTest()
{
// get test
Assert.That(RelativeType.Sibling.ToString(), Is.EqualTo("sibling"));
Assert.That(RelativeType.Parent.ToString(), Is.EqualTo("parent"));
Assert.That(RelativeType.Child.ToString(), Is.EqualTo("child"));
Assert.That(RelativeType.Grandparent.ToString(), Is.EqualTo("grandparent"));
Assert.That(RelativeType.Grandchild.ToString(), Is.EqualTo("grandchild"));
// parse test
Assert.That(RelativeType.FromJsonString("sibling"), Is.EqualTo(RelativeType.Sibling));
Assert.That(RelativeType.FromJsonString("parent"), Is.EqualTo(RelativeType.Parent));
Assert.That(RelativeType.FromJsonString("child"), Is.EqualTo(RelativeType.Child));
Assert.That(RelativeType.FromJsonString("grandparent")
, Is.EqualTo(RelativeType.Grandparent));
Assert.That(RelativeType.FromJsonString("grandchild")
, Is.EqualTo(RelativeType.Grandchild));
}
[Test]
public void ReportTypeTest()
{
// get test
Assert.That(ReportType.Porn.ToString(), Is.EqualTo("porn"));
Assert.That(ReportType.Spam.ToString(), Is.EqualTo("spam"));
Assert.That(ReportType.Insult.ToString(), Is.EqualTo("insult"));
Assert.That(ReportType.Advertisment.ToString(), Is.EqualTo("advertisment"));
// parse test
Assert.That(ReportType.FromJsonString("porn"), Is.EqualTo(ReportType.Porn));
Assert.That(ReportType.FromJsonString("spam"), Is.EqualTo(ReportType.Spam));
Assert.That(ReportType.FromJsonString("insult"), Is.EqualTo(ReportType.Insult));
Assert.That(ReportType.FromJsonString("advertisment")
, Is.EqualTo(ReportType.Advertisment));
}
[Test]
public void ServicesTest()
{
// get test
Assert.That(Services.Email.ToString(), Is.EqualTo("email"));
Assert.That(Services.Phone.ToString(), Is.EqualTo("phone"));
Assert.That(Services.Twitter.ToString(), Is.EqualTo("twitter"));
Assert.That(Services.Facebook.ToString(), Is.EqualTo("facebook"));
Assert.That(Services.Odnoklassniki.ToString(), Is.EqualTo("odnoklassniki"));
Assert.That(Services.Instagram.ToString(), Is.EqualTo("instagram"));
Assert.That(Services.Google.ToString(), Is.EqualTo("google"));
// parse test
Assert.That(Services.FromJsonString("email"), Is.EqualTo(Services.Email));
Assert.That(Services.FromJsonString("phone"), Is.EqualTo(Services.Phone));
Assert.That(Services.FromJsonString("twitter"), Is.EqualTo(Services.Twitter));
Assert.That(Services.FromJsonString("facebook"), Is.EqualTo(Services.Facebook));
Assert.That(Services.FromJsonString("odnoklassniki")
, Is.EqualTo(Services.Odnoklassniki));
Assert.That(Services.FromJsonString("instagram"), Is.EqualTo(Services.Instagram));
Assert.That(Services.FromJsonString("google"), Is.EqualTo(Services.Google));
}
[Test]
public void UserSectionTest()
{
// get test
Assert.That(UserSection.Friends.ToString(), Is.EqualTo("friends"));
Assert.That(UserSection.Subscriptions.ToString(), Is.EqualTo("subscriptions"));
// parse test
Assert.That(UserSection.FromJsonString("friends"), Is.EqualTo(UserSection.Friends));
Assert.That(UserSection.FromJsonString("subscriptions")
, Is.EqualTo(UserSection.Subscriptions));
}
[Test]
public void VideoCatalogItemTypeTest()
{
// get test
Assert.That(VideoCatalogItemType.Video.ToString(), Is.EqualTo("video"));
Assert.That(VideoCatalogItemType.Album.ToString(), Is.EqualTo("album"));
// parse test
Assert.That(VideoCatalogItemType.FromJsonString("video")
, Is.EqualTo(VideoCatalogItemType.Video));
Assert.That(VideoCatalogItemType.FromJsonString("album")
, Is.EqualTo(VideoCatalogItemType.Album));
}
[Test]
public void VideoCatalogTypeTest()
{
// get test
Assert.That(VideoCatalogType.Channel.ToString(), Is.EqualTo("channel"));
Assert.That(VideoCatalogType.Category.ToString(), Is.EqualTo("category"));
// parse test
Assert.That(VideoCatalogType.FromJsonString("channel")
, Is.EqualTo(VideoCatalogType.Channel));
Assert.That(VideoCatalogType.FromJsonString("category")
, Is.EqualTo(VideoCatalogType.Category));
}
[Test]
public void WallFilterTest()
{
// get test
Assert.That(WallFilter.Owner.ToString(), Is.EqualTo("owner"));
Assert.That(WallFilter.Others.ToString(), Is.EqualTo("others"));
Assert.That(WallFilter.All.ToString(), Is.EqualTo("all"));
Assert.That(WallFilter.Suggests.ToString(), Is.EqualTo("suggests"));
Assert.That(WallFilter.Postponed.ToString(), Is.EqualTo("postponed"));
// parse test
Assert.That(WallFilter.FromJsonString("owner"), Is.EqualTo(WallFilter.Owner));
Assert.That(WallFilter.FromJsonString("others"), Is.EqualTo(WallFilter.Others));
Assert.That(WallFilter.FromJsonString("all"), Is.EqualTo(WallFilter.All));
Assert.That(WallFilter.FromJsonString("suggests"), Is.EqualTo(WallFilter.Suggests));
Assert.That(WallFilter.FromJsonString("postponed"), Is.EqualTo(WallFilter.Postponed));
}
[Test]
public void KeyboardButtonColorTest()
{
// get test
Assert.That(KeyboardButtonColor.Default.ToString(), Is.EqualTo("default"));
Assert.That(KeyboardButtonColor.Negative.ToString(), Is.EqualTo("negative"));
Assert.That(KeyboardButtonColor.Positive.ToString(), Is.EqualTo("positive"));
Assert.That(KeyboardButtonColor.Primary.ToString(), Is.EqualTo("primary"));
// parse test
Assert.That(KeyboardButtonColor.FromJsonString("default"), Is.EqualTo(KeyboardButtonColor.Default));
Assert.That(KeyboardButtonColor.FromJsonString("negative"), Is.EqualTo(KeyboardButtonColor.Negative));
Assert.That(KeyboardButtonColor.FromJsonString("positive"), Is.EqualTo(KeyboardButtonColor.Positive));
Assert.That(KeyboardButtonColor.FromJsonString("primary"), Is.EqualTo(KeyboardButtonColor.Primary));
}
[Test]
public void KeyboardButtonActionTypeTest()
{
// get test
Assert.That(KeyboardButtonActionType.Text.ToString(), Is.EqualTo("text"));
Assert.That(KeyboardButtonActionType.Location.ToString(), Is.EqualTo("location"));
Assert.That(KeyboardButtonActionType.OpenLink.ToString(), Is.EqualTo("open_link"));
Assert.That(KeyboardButtonActionType.VkApp.ToString(), Is.EqualTo("open_app"));
Assert.That(KeyboardButtonActionType.VkPay.ToString(), Is.EqualTo("vkpay"));
Assert.That(KeyboardButtonActionType.Callback.ToString(), Is.EqualTo("callback"));
// parse test
Assert.That(KeyboardButtonActionType.FromJsonString("text"), Is.EqualTo(KeyboardButtonActionType.Text));
Assert.That(KeyboardButtonActionType.FromJsonString("location"), Is.EqualTo(KeyboardButtonActionType.Location));
Assert.That(KeyboardButtonActionType.FromJsonString("open_link"), Is.EqualTo(KeyboardButtonActionType.OpenLink));
Assert.That(KeyboardButtonActionType.FromJsonString("open_app"), Is.EqualTo(KeyboardButtonActionType.VkApp));
Assert.That(KeyboardButtonActionType.FromJsonString("vkpay"), Is.EqualTo(KeyboardButtonActionType.VkPay));
Assert.That(KeyboardButtonActionType.FromJsonString("callback"), Is.EqualTo(KeyboardButtonActionType.Callback));
}
[Test]
public void StoryObjectStateTest()
{
// get test
Assert.That(StoryObjectState.Hidden.ToString(), Is.EqualTo("hidden"));
Assert.That(StoryObjectState.On.ToString(), Is.EqualTo("on"));
Assert.That(StoryObjectState.Off.ToString(), Is.EqualTo("off"));
// parse test
Assert.That(StoryObjectState.FromJsonString("hidden"), Is.EqualTo(StoryObjectState.Hidden));
Assert.That(StoryObjectState.FromJsonString("on"), Is.EqualTo(StoryObjectState.On));
Assert.That(StoryObjectState.FromJsonString("off"), Is.EqualTo(StoryObjectState.Off));
}
[Test]
public void StoryLinkTextTest()
{
// get test
Assert.That(StoryLinkText.Book.ToString(), Is.EqualTo("book"));
Assert.That(StoryLinkText.Buy.ToString(), Is.EqualTo("buy"));
Assert.That(StoryLinkText.Contact.ToString(), Is.EqualTo("contact"));
Assert.That(StoryLinkText.Enroll.ToString(), Is.EqualTo("enroll"));
Assert.That(StoryLinkText.Fill.ToString(), Is.EqualTo("fill"));
Assert.That(StoryLinkText.GoTo.ToString(), Is.EqualTo("go_to"));
Assert.That(StoryLinkText.Install.ToString(), Is.EqualTo("install"));
Assert.That(StoryLinkText.LearnMore.ToString(), Is.EqualTo("learn_more"));
Assert.That(StoryLinkText.More.ToString(), Is.EqualTo("more"));
Assert.That(StoryLinkText.Open.ToString(), Is.EqualTo("open"));
Assert.That(StoryLinkText.Order.ToString(), Is.EqualTo("order"));
Assert.That(StoryLinkText.Play.ToString(), Is.EqualTo("play"));
Assert.That(StoryLinkText.Read.ToString(), Is.EqualTo("read"));
Assert.That(StoryLinkText.Signup.ToString(), Is.EqualTo("signup"));
Assert.That(StoryLinkText.View.ToString(), Is.EqualTo("view"));
Assert.That(StoryLinkText.Vote.ToString(), Is.EqualTo("vote"));
Assert.That(StoryLinkText.Watch.ToString(), Is.EqualTo("watch"));
Assert.That(StoryLinkText.Write.ToString(), Is.EqualTo("write"));
// parse test
Assert.That(StoryLinkText.FromJsonString("book"), Is.EqualTo(StoryLinkText.Book));
Assert.That(StoryLinkText.FromJsonString("buy"), Is.EqualTo(StoryLinkText.Buy));
Assert.That(StoryLinkText.FromJsonString("contact"), Is.EqualTo(StoryLinkText.Contact));
Assert.That(StoryLinkText.FromJsonString("enroll"), Is.EqualTo(StoryLinkText.Enroll));
Assert.That(StoryLinkText.FromJsonString("fill"), Is.EqualTo(StoryLinkText.Fill));
Assert.That(StoryLinkText.FromJsonString("go_to"), Is.EqualTo(StoryLinkText.GoTo));
Assert.That(StoryLinkText.FromJsonString("install"), Is.EqualTo(StoryLinkText.Install));
Assert.That(StoryLinkText.FromJsonString("learn_more"), Is.EqualTo(StoryLinkText.LearnMore));
Assert.That(StoryLinkText.FromJsonString("more"), Is.EqualTo(StoryLinkText.More));
Assert.That(StoryLinkText.FromJsonString("open"), Is.EqualTo(StoryLinkText.Open));
Assert.That(StoryLinkText.FromJsonString("order"), Is.EqualTo(StoryLinkText.Order));
Assert.That(StoryLinkText.FromJsonString("play"), Is.EqualTo(StoryLinkText.Play));
Assert.That(StoryLinkText.FromJsonString("read"), Is.EqualTo(StoryLinkText.Read));
Assert.That(StoryLinkText.FromJsonString("signup"), Is.EqualTo(StoryLinkText.Signup));
Assert.That(StoryLinkText.FromJsonString("view"), Is.EqualTo(StoryLinkText.View));
Assert.That(StoryLinkText.FromJsonString("vote"), Is.EqualTo(StoryLinkText.Vote));
Assert.That(StoryLinkText.FromJsonString("watch"), Is.EqualTo(StoryLinkText.Watch));
Assert.That(StoryLinkText.FromJsonString("write"), Is.EqualTo(StoryLinkText.Write));
}
[Test]
public void MarketItemButtonTitleTest()
{
// get test
Assert.That(MarketItemButtonTitle.Buy.ToString(), Is.EqualTo("Купить"));
Assert.That(MarketItemButtonTitle.BuyATicket.ToString(), Is.EqualTo("Купить билет"));
Assert.That(MarketItemButtonTitle.GoToTheStore.ToString(), Is.EqualTo("Перейти в магазин"));
// parse test
Assert.That(MarketItemButtonTitle.FromJsonString("Купить"), Is.EqualTo(MarketItemButtonTitle.Buy));
Assert.That(MarketItemButtonTitle.FromJsonString("Купить билет"), Is.EqualTo(MarketItemButtonTitle.BuyATicket));
Assert.That(MarketItemButtonTitle.FromJsonString("Перейти в магазин"), Is.EqualTo(MarketItemButtonTitle.GoToTheStore));
}
[Test]
public void AppWidgetTypeTest()
{
// get test
Assert.That(AppWidgetType.Donation.ToString(), Is.EqualTo("donation"));
Assert.That(AppWidgetType.List.ToString(), Is.EqualTo("list"));
Assert.That(AppWidgetType.Match.ToString(), Is.EqualTo("match"));
Assert.That(AppWidgetType.Matches.ToString(), Is.EqualTo("matches"));
Assert.That(AppWidgetType.Table.ToString(), Is.EqualTo("table"));
Assert.That(AppWidgetType.Text.ToString(), Is.EqualTo("text"));
Assert.That(AppWidgetType.Tiles.ToString(), Is.EqualTo("tiles"));
Assert.That(AppWidgetType.CompactList.ToString(), Is.EqualTo("compact_list"));
Assert.That(AppWidgetType.CoverList.ToString(), Is.EqualTo("cover_list"));
// parse test
Assert.That(AppWidgetType.FromJsonString("donation"), Is.EqualTo(AppWidgetType.Donation));
Assert.That(AppWidgetType.FromJsonString("list"), Is.EqualTo(AppWidgetType.List));
Assert.That(AppWidgetType.FromJsonString("match"), Is.EqualTo(AppWidgetType.Match));
Assert.That(AppWidgetType.FromJsonString("matches"), Is.EqualTo(AppWidgetType.Matches));
Assert.That(AppWidgetType.FromJsonString("table"), Is.EqualTo(AppWidgetType.Table));
Assert.That(AppWidgetType.FromJsonString("text"), Is.EqualTo(AppWidgetType.Text));
Assert.That(AppWidgetType.FromJsonString("tiles"), Is.EqualTo(AppWidgetType.Tiles));
Assert.That(AppWidgetType.FromJsonString("compact_list"), Is.EqualTo(AppWidgetType.CompactList));
Assert.That(AppWidgetType.FromJsonString("cover_list"), Is.EqualTo(AppWidgetType.CoverList));
}
[Test]
public void TranscriptStatesTest()
{
// get test
Assert.That(TranscriptStates.Done.ToString(), Is.EqualTo("done"));
Assert.That(TranscriptStates.InProgress.ToString(), Is.EqualTo("in_progress"));
// parse test
Assert.That(TranscriptStates.FromJsonString("done"), Is.EqualTo(TranscriptStates.Done));
Assert.That(TranscriptStates.FromJsonString("in_progress"), Is.EqualTo(TranscriptStates.InProgress));
}
[Test]
public void MessageEventTypeTest()
{
// get test
Assert.That(MessageEventType.OpenApp.ToString(), Is.EqualTo("open_app"));
Assert.That(MessageEventType.OpenLink.ToString(), Is.EqualTo("open_link"));
Assert.That(MessageEventType.SnowSnackbar.ToString(), Is.EqualTo("show_snackbar"));
// parse test
Assert.That(MessageEventType.FromJsonString("open_app"), Is.EqualTo(MessageEventType.OpenApp));
Assert.That(MessageEventType.FromJsonString("open_link"), Is.EqualTo(MessageEventType.OpenLink));
Assert.That(MessageEventType.FromJsonString("show_snackbar"), Is.EqualTo(MessageEventType.SnowSnackbar));
}
}
} | {
"pile_set_name": "Github"
} |
# Translation of Odoo Server.
# This file contains the translation of the following modules:
# * pos_restaurant
#
# Translators:
# jonas jensen <[email protected]>, 2019
# Per Rasmussen <[email protected]>, 2019
# Morten Schou <[email protected]>, 2019
# Jesper Carstensen <[email protected]>, 2019
# Ejner Sønniksen <[email protected]>, 2019
# Martin Trigaux, 2019
# Pernille Kristensen <[email protected]>, 2019
# Sanne Kristensen <[email protected]>, 2019
# lhmflexerp <[email protected]>, 2019
# JonathanStein <[email protected]>, 2020
# Mads Søndergaard, 2020
#
msgid ""
msgstr ""
"Project-Id-Version: Odoo Server 13.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-10-07 07:11+0000\n"
"PO-Revision-Date: 2019-08-26 09:13+0000\n"
"Last-Translator: Mads Søndergaard, 2020\n"
"Language-Team: Danish (https://www.transifex.com/odoo/teams/41243/da/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: \n"
"Language: da\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#. module: pos_restaurant
#: model:ir.model.fields.selection,name:pos_restaurant.selection__restaurant_printer__printer_type__iot
msgid " Use a printer connected to the IoT Box"
msgstr "Brug en printer forbundet til IoT boksen"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "$ 3.12"
msgstr "$ 3.12"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "$ 4.40"
msgstr "$ 4.40"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "$ 4.50"
msgstr "$ 4.50"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "$ 8.50"
msgstr "$ 8.50"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.pos_config_view_form_inherit_restaurant
msgid ""
"<span class=\"fa fa-lg fa-cutlery\" title=\"For bars and restaurants\" "
"role=\"img\" aria-label=\"For bars and restaurants\"/>"
msgstr ""
"<span class=\"fa fa-lg fa-cutlery\" title=\"For barer og restauranter\" "
"role=\"img\" aria-label=\"For barer og restauranter\"/> "
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "<span class=\"pos-change_amount\">$ 0.86</span>"
msgstr "<span class=\"pos-change_amount\">$ 0.86</span>"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "<span class=\"pos-change_title\">Change</span>"
msgstr "<span class=\"pos-change_title\">Byttepenge</span>"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "<span class=\"total-amount-formatting\">TOTAL</span>"
msgstr "<span class=\"total-amount-formatting\">TOTAL</span>"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "<span id=\"total-amount\" class=\"pos_total-amount\">$ 469.14</span>"
msgstr "<span id=\"total-amount\" class=\"pos_total-amount\">$ 469.14</span>"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "<span>$ 470.00</span>"
msgstr "<span>$ 470.00</span>"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "<span>Cash (USD):</span>"
msgstr "<span>Kontant (USD):</span>"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.view_restaurant_floor_kanban
msgid "<strong>Floor Name: </strong>"
msgstr "<strong>Navn på område: </strong>"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.view_restaurant_floor_kanban
msgid "<strong>Point of Sale: </strong>"
msgstr "<strong>Kasse: </strong>"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_floor__background_image
msgid ""
"A background image used to display a floor layout in the point of sale "
"interface"
msgstr ""
"Et baggrundsbillede som anvendes til at vise layoutet på et restaurantområde"
" kassens brugerflade"
#. module: pos_restaurant
#: model_terms:ir.actions.act_window,help:pos_restaurant.action_restaurant_floor_form
msgid ""
"A restaurant floor represents the place where customers are served, this is where you can\n"
" define and position the tables."
msgstr ""
"Et restaurantområde repræsenterer et sted hvor kunder betjenes, det er her du kan\n"
" opsætte og placere bordene."
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__active
msgid "Active"
msgstr "Aktiv"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Add"
msgstr "Tilføj"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/js/notes.js:0
#, python-format
msgid "Add Note"
msgstr "Tilføj notat"
#. module: pos_restaurant
#: model_terms:ir.actions.act_window,help:pos_restaurant.action_restaurant_floor_form
msgid "Add a new restaurant floor"
msgstr "Tilføj en ny restaurant etage"
#. module: pos_restaurant
#: model_terms:ir.actions.act_window,help:pos_restaurant.action_restaurant_printer_form
msgid "Add a new restaurant order printer"
msgstr "Tilføj en ny resturant bestillings printer"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Add button"
msgstr "Tilføj knap"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.pos_config_view_form_inherit_restaurant
msgid "Add notes to orderlines"
msgstr "Tilføj noter til ordrelinjer"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_pos_config__iface_orderline_notes
msgid "Allow custom notes on Orderlines."
msgstr "Tillad tilpassede noter på Ordrelinjer."
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.pos_config_view_form_inherit_restaurant
msgid "Allow to print bill before payment"
msgstr "Tillad print af regning før betaling"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_pos_config__iface_printbill
msgid "Allows to print the Bill before payment."
msgstr "Tillader printning af regning før betaling."
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_table__name
msgid "An internal identification of a table"
msgstr "En intern identifikation af et bord"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_printer__name
msgid "An internal identification of the printer"
msgstr "En intern identifikation af printeren"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_floor__name
msgid "An internal identification of the restaurant floor"
msgstr "En interne identifikation på restaurantområdet"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.view_restaurant_table_form
msgid "Appearance"
msgstr "Udseende"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/js/floors.js:0
#, python-format
msgid "Are you sure ?"
msgstr "Er du sikker?"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/printbill.xml:0
#: code:addons/pos_restaurant/static/src/xml/splitbill.xml:0
#, python-format
msgid "Back"
msgstr "Tilbage"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Back to floor"
msgstr "Tilbage til etage"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__background_color
msgid "Background Color"
msgstr "Baggrundsfarve"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__background_image
msgid "Background Image"
msgstr "Baggrundsbillede"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_bacon
#: model:product.template,name:pos_restaurant.pos_food_bacon_product_template
msgid "Bacon Burger"
msgstr "Bacon Burger"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/printbill.xml:0
#, python-format
msgid "Bill"
msgstr "Faktura"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/printbill.xml:0
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_config__iface_printbill
#, python-format
msgid "Bill Printing"
msgstr "Udskrivning af regning"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/splitbill.xml:0
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_config__iface_splitbill
#, python-format
msgid "Bill Splitting"
msgstr "Deling af regning"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Blue"
msgstr "Blå"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/multiprint.xml:0
#, python-format
msgid "CANCELLED"
msgstr "ANNULLERET"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/js/floors.js:0
#, python-format
msgid "Changes could not be saved"
msgstr "Ændringerne blev ikke gemt"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_cheeseburger
#: model:product.template,name:pos_restaurant.pos_food_cheeseburger_product_template
msgid "Cheese Burger"
msgstr "Cheese Burger"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_chicken
#: model:product.template,name:pos_restaurant.pos_food_chicken_product_template
msgid "Chicken Curry Sandwich"
msgstr "Kylling Karry Sandwich"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Close"
msgstr "Luk"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_club
#: model:product.template,name:pos_restaurant.pos_food_club_product_template
msgid "Club Sandwich"
msgstr "Club Sandwich"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.coke
#: model:product.template,name:pos_restaurant.coke_product_template
msgid "Coca-Cola"
msgstr "Coca-Cola"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__color
msgid "Color"
msgstr "Farve"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__create_uid
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer__create_uid
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__create_uid
msgid "Created by"
msgstr "Oprettet af"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__create_date
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer__create_date
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__create_date
msgid "Created on"
msgstr "Oprettet den"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Delete"
msgstr "Slet"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "Desk Organizer"
msgstr "Skrivebord organisator "
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__display_name
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer__display_name
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__display_name
msgid "Display Name"
msgstr "Vis navn"
#. module: pos_restaurant
#: model:pos.category,name:pos_restaurant.drinks
msgid "Drinks"
msgstr "Drinks"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Duplicate"
msgstr "Duplikér"
#. module: pos_restaurant
#: model_terms:ir.actions.act_window,help:pos_restaurant.action_restaurant_printer_form
msgid ""
"Each Order Printer has an IP Address that defines the IoT Box/Hardware\n"
" Proxy where the printer can be found, and a list of product categories.\n"
" An Order Printer will only print updates for products belonging to one of\n"
" its categories."
msgstr ""
"Hver bestililngs printer har en IP adresse som definerer IoT Boks/Hardware\n"
" Proxy hvor printeren kan findes, og en liste af produkt kategorier\n"
" En bestillings printer vil kun printe opdateringer for produkter der tilhører en af\n"
" dens kategorier."
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Edit"
msgstr "Rediger"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_pos_config__iface_splitbill
msgid "Enables Bill Splitting in the Point of Sale."
msgstr "Aktivere deling af regning ved Point of Sale."
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__floor_id
msgid "Floor"
msgstr "Etage"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__name
msgid "Floor Name"
msgstr "Etage navn"
#. module: pos_restaurant
#: model:ir.actions.act_window,name:pos_restaurant.action_restaurant_floor_form
#: model:ir.ui.menu,name:pos_restaurant.menu_restaurant_floor_all
msgid "Floor Plans"
msgstr "Grundplan"
#. module: pos_restaurant
#: code:addons/pos_restaurant/models/pos_restaurant.py:0
#, python-format
msgid "Floor: %s - PoS Config: %s \n"
msgstr "Etage: %s - PoS Konfiguration: %s\n"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.pos_config_view_form_inherit_restaurant
msgid "Floors"
msgstr "Restaurant etager"
#. module: pos_restaurant
#: model:pos.category,name:pos_restaurant.food
msgid "Food"
msgstr "Mad"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_funghi
#: model:product.template,name:pos_restaurant.pos_food_funghi_product_template
msgid "Funghi"
msgstr "Svampe"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Green"
msgstr "Grøn"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Grey"
msgstr "Grå"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_order__customer_count
#, python-format
msgid "Guests"
msgstr "Gæster"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/js/floors.js:0
#, python-format
msgid "Guests ?"
msgstr "Gæster?"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Guests:"
msgstr "Gæster:"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__height
msgid "Height"
msgstr "Højde"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__position_h
msgid "Horizontal Position"
msgstr "Horisontal position"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__id
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer__id
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__id
msgid "ID"
msgstr "ID"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_table__active
msgid ""
"If false, the table is deactivated and will not be available in the point of"
" sale"
msgstr ""
"Hvis falsk, deaktiveres bordet og vil ikke være tilgængelig i point of sale"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_config__module_pos_restaurant
msgid "Is a Bar/Restaurant"
msgstr "Er en bar/restaurant"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor____last_update
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer____last_update
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table____last_update
msgid "Last Modified on"
msgstr "Sidst ændret den"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__write_uid
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer__write_uid
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__write_uid
msgid "Last Updated by"
msgstr "Sidst opdateret af"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__write_date
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer__write_date
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__write_date
msgid "Last Updated on"
msgstr "Sidst opdateret den"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "Led Lamp"
msgstr "LED lampe"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Light grey"
msgstr "Lysegrå"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_maki
#: model:product.template,name:pos_restaurant.pos_food_maki_product_template
msgid "Lunch Maki 18pc"
msgstr "Frokost Maki-ruller 18stk"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_salmon
#: model:product.template,name:pos_restaurant.pos_food_salmon_product_template
msgid "Lunch Salmon 20pc"
msgstr "Frokost Laks 20stk"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_temaki
#: model:product.template,name:pos_restaurant.pos_food_temaki_product_template
msgid "Lunch Temaki mix 3pc"
msgstr "Frokost Temaki mix 3stk"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.pos_config_view_form_inherit_restaurant
msgid "Manage table orders"
msgstr "Administrer bord bestillinger"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_margherita
#: model:product.template,name:pos_restaurant.pos_food_margherita_product_template
msgid "Margherita"
msgstr "Marghertia"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.minute_maid
#: model:product.template,name:pos_restaurant.minute_maid_product_template
msgid "Minute Maid"
msgstr "Minute Maid"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "Monitor Stand"
msgstr "Skærmfod"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_mozza
#: model:product.template,name:pos_restaurant.pos_food_mozza_product_template
msgid "Mozzarella Sandwich"
msgstr "Mozzarella Sandwich"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/multiprint.xml:0
#, python-format
msgid "NEW"
msgstr "NY"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/multiprint.xml:0
#: code:addons/pos_restaurant/static/src/xml/multiprint.xml:0
#, python-format
msgid "NOTE"
msgstr "NOTAT"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/notes.xml:0
#: code:addons/pos_restaurant/static/src/xml/notes.xml:0
#, python-format
msgid "Note"
msgstr "Notat"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_order_line__note
msgid "Note added by the waiter."
msgstr "Notat tilføjet af tjener."
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/js/printbill.js:0
#, python-format
msgid "Nothing to Print"
msgstr "Intet at udskrive"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/js/floors.js:0
#, python-format
msgid "Number of Seats ?"
msgstr "Antal pladser?"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "Odoo Logo"
msgstr "Odoo logo"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/printbill.xml:0
#, python-format
msgid "Ok"
msgstr "OK"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Orange"
msgstr "Orange"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/multiprint.xml:0
#, python-format
msgid "Order"
msgstr "Ordre"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_config__is_order_printer
msgid "Order Printer"
msgstr "Bestillings printer"
#. module: pos_restaurant
#: model:ir.actions.act_window,name:pos_restaurant.action_restaurant_printer_form
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_config__printer_ids
#: model:ir.ui.menu,name:pos_restaurant.menu_restaurant_printer_all
msgid "Order Printers"
msgstr "Ordrer udskrivninger"
#. module: pos_restaurant
#: model_terms:ir.actions.act_window,help:pos_restaurant.action_restaurant_printer_form
msgid ""
"Order Printers are used by restaurants and bars to print the\n"
" order updates in the kitchen/bar when the waiter updates the order."
msgstr ""
"Bestillings printere bruges af restauranter og barer til at printe\n"
" bestillings opdateringer i køkkenet/baren, når en tjener opdatere bestillingen."
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_config__iface_orderline_notes
msgid "Orderline Notes"
msgstr "Ordrelinjenoter"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.view_restaurant_printer_form
msgid "POS Printer"
msgstr "POS printer"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/printbill.xml:0
#, python-format
msgid "PRO FORMA"
msgstr "PRO FORMA"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_4formaggi
#: model:product.template,name:pos_restaurant.pos_food_4formaggi_product_template
msgid "Pasta 4 formaggi "
msgstr "Pasta m/ 4 slags ost"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_bolo
#: model:product.template,name:pos_restaurant.pos_food_bolo_product_template
msgid "Pasta Bolognese"
msgstr "Pasta bolognese"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/splitbill.xml:0
#, python-format
msgid "Payment"
msgstr "Betaling"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__pos_config_id
msgid "Point of Sale"
msgstr "POS"
#. module: pos_restaurant
#: model:ir.model,name:pos_restaurant.model_pos_config
msgid "Point of Sale Configuration"
msgstr "POS konfiguration"
#. module: pos_restaurant
#: model:ir.model,name:pos_restaurant.model_pos_order_line
msgid "Point of Sale Order Lines"
msgstr "Point of Sale linjer"
#. module: pos_restaurant
#: model:ir.model,name:pos_restaurant.model_pos_order
msgid "Point of Sale Orders"
msgstr "POS ordrer"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "Price"
msgstr "Pris"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/printbill.xml:0
#, python-format
msgid "Print"
msgstr "Udskriv"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.pos_config_view_form_inherit_restaurant
msgid "Print orders at the kitchen, at the bar, etc."
msgstr "Print ordrer i køkkenet, i baren osv."
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer__product_categories_ids
msgid "Printed Product Categories"
msgstr "Udskrevne produkt kategorier"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer__name
msgid "Printer Name"
msgstr "Printernavn"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer__printer_type
msgid "Printer Type"
msgstr "Printer type"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.pos_config_view_form_inherit_restaurant
msgid "Printers"
msgstr "Printere"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_printer__proxy_ip
msgid "Proxy IP Address"
msgstr "Proxy IP Adresse"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Purple"
msgstr "Lilla"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "Quantity"
msgstr "Antal"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Red"
msgstr "Rød"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/js/floors.js:0
#, python-format
msgid "Removing a table cannot be undone"
msgstr "Ved flytning af bord kan man ikke fortryde"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Rename"
msgstr "Omdøb"
#. module: pos_restaurant
#: model:ir.model,name:pos_restaurant.model_restaurant_floor
#: model_terms:ir.ui.view,arch_db:pos_restaurant.view_restaurant_floor_form
msgid "Restaurant Floor"
msgstr "Restaurant etager"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_config__floor_ids
#: model_terms:ir.ui.view,arch_db:pos_restaurant.view_restaurant_floor_tree
msgid "Restaurant Floors"
msgstr "Restaurant etager"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.view_restaurant_printer
msgid "Restaurant Order Printers"
msgstr "Restaurant ordreprintere"
#. module: pos_restaurant
#: model:ir.model,name:pos_restaurant.model_restaurant_printer
msgid "Restaurant Printer"
msgstr "Restaurant printer"
#. module: pos_restaurant
#: model:ir.model,name:pos_restaurant.model_restaurant_table
#: model_terms:ir.ui.view,arch_db:pos_restaurant.view_restaurant_table_form
msgid "Restaurant Table"
msgstr "Restaurant bord"
#. module: pos_restaurant
#: model:ir.model.fields.selection,name:pos_restaurant.selection__restaurant_table__shape__round
msgid "Round"
msgstr "Rund"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Round Shape"
msgstr "Rund form"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_chirashi
#: model:product.template,name:pos_restaurant.pos_food_chirashi_product_template
msgid "Salmon and Avocado"
msgstr "Laks og avocado"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__seats
#, python-format
msgid "Seats"
msgstr "Sæder"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__sequence
msgid "Sequence"
msgstr "Sekvens"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__shape
msgid "Shape"
msgstr "Form"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_order_line__mp_skip
msgid "Skip line when sending ticket to kitchen printers."
msgstr "Spring linje over når bestilling sendes til køkken printere."
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_tuna
#: model:product.template,name:pos_restaurant.pos_food_tuna_product_template
msgid "Spicy Tuna Sandwich"
msgstr "Stærk tun sandwich"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/splitbill.xml:0
#, python-format
msgid "Split"
msgstr "Del"
#. module: pos_restaurant
#: model_terms:ir.ui.view,arch_db:pos_restaurant.pos_config_view_form_inherit_restaurant
msgid "Split total or order lines"
msgstr "Opdel total eller ordrelinjer"
#. module: pos_restaurant
#: model:ir.model.fields.selection,name:pos_restaurant.selection__restaurant_table__shape__square
msgid "Square"
msgstr "Firkantet"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Square Shape"
msgstr "Firkantet form"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_order__table_id
msgid "Table"
msgstr "Tabel"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_pos_config__is_table_management
msgid "Table Management"
msgstr "Bord administration"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__name
msgid "Table Name"
msgstr "Bordnavn"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/js/floors.js:0
#, python-format
msgid "Table Name ?"
msgstr "Bordnavn?"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_floor__table_ids
#: model_terms:ir.ui.view,arch_db:pos_restaurant.view_restaurant_floor_form
msgid "Tables"
msgstr "Borde"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_printer__proxy_ip
msgid "The IP Address or hostname of the Printer's hardware proxy"
msgstr "IP adresse eller værtsnavn for printerens hardware proxy"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_pos_order__customer_count
msgid "The amount of customers that have been served by this order."
msgstr "Antal kunder som er blevet betjent på denne ordre."
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_floor__background_color
msgid ""
"The background color of the floor layout, (must be specified in a html-"
"compatible format)"
msgstr ""
"Baggrundsfarven på layoutet på restaurantområdet (skal være angivet i en "
"html-kompatibel format)"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_table__seats
msgid "The default number of customer served at this table."
msgstr "Standardantallet af kunder betjent ved dette bord."
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_floor__table_ids
msgid "The list of tables in this floor"
msgstr "Listen af borde på denne etage "
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_pos_config__floor_ids
msgid "The restaurant floors served by this point of sale."
msgstr "Restaurantområderne som betjenes i dennes kasse."
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_pos_order__table_id
msgid "The table where this order was served"
msgstr "Bordet hvor denne ordre blev serveret"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_table__color
msgid ""
"The table's color, expressed as a valid 'background' CSS property value"
msgstr "Bordets farve, udtrykt som en gyldig CSS 'baggrunds' egenskabs værdi"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_table__height
msgid "The table's height in pixels"
msgstr "Bordets højde i pixels"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_table__position_h
msgid ""
"The table's horizontal position from the left side to the table's center, in"
" pixels"
msgstr ""
"Bordets horisontale position fra venstre side til bordets midte, i pixels"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_table__position_v
msgid ""
"The table's vertical position from the top to the table's center, in pixels"
msgstr "Bordet vertikale position fra toppen til bordets midte, i pixels"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_table__width
msgid "The table's width in pixels"
msgstr "Bordets bredde i pixels"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/js/printbill.js:0
#, python-format
msgid "There are no order lines"
msgstr "Der er ingen ordrelinjer"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "This floor has no tables yet, use the"
msgstr "Denne etage har ikke nogle borde endnu, brug"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Tint"
msgstr "Farv"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Transfer"
msgstr "Overfør"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Turquoise"
msgstr "Tyrkis"
#. module: pos_restaurant
#: model:product.product,uom_name:pos_restaurant.coke
#: model:product.product,uom_name:pos_restaurant.minute_maid
#: model:product.product,uom_name:pos_restaurant.pos_food_4formaggi
#: model:product.product,uom_name:pos_restaurant.pos_food_bacon
#: model:product.product,uom_name:pos_restaurant.pos_food_bolo
#: model:product.product,uom_name:pos_restaurant.pos_food_cheeseburger
#: model:product.product,uom_name:pos_restaurant.pos_food_chicken
#: model:product.product,uom_name:pos_restaurant.pos_food_chirashi
#: model:product.product,uom_name:pos_restaurant.pos_food_club
#: model:product.product,uom_name:pos_restaurant.pos_food_funghi
#: model:product.product,uom_name:pos_restaurant.pos_food_maki
#: model:product.product,uom_name:pos_restaurant.pos_food_margherita
#: model:product.product,uom_name:pos_restaurant.pos_food_mozza
#: model:product.product,uom_name:pos_restaurant.pos_food_salmon
#: model:product.product,uom_name:pos_restaurant.pos_food_temaki
#: model:product.product,uom_name:pos_restaurant.pos_food_tuna
#: model:product.product,uom_name:pos_restaurant.pos_food_vege
#: model:product.product,uom_name:pos_restaurant.water
#: model:product.template,uom_name:pos_restaurant.coke_product_template
#: model:product.template,uom_name:pos_restaurant.minute_maid_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_4formaggi_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_bacon_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_bolo_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_cheeseburger_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_chicken_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_chirashi_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_club_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_funghi_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_maki_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_margherita_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_mozza_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_salmon_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_temaki_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_tuna_product_template
#: model:product.template,uom_name:pos_restaurant.pos_food_vege_product_template
#: model:product.template,uom_name:pos_restaurant.water_product_template
msgid "Units"
msgstr "Enheder"
#. module: pos_restaurant
#: model:ir.model.fields,help:pos_restaurant.field_restaurant_floor__sequence
msgid "Used to sort Floors"
msgstr "Bruges til at organisere etager"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.pos_food_vege
#: model:product.template,name:pos_restaurant.pos_food_vege_product_template
msgid "Vegetarian"
msgstr "Vegetarisk"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__position_v
msgid "Vertical Position"
msgstr "Vertical position"
#. module: pos_restaurant
#: model:product.product,name:pos_restaurant.water
#: model:product.template,name:pos_restaurant.water_product_template
msgid "Water"
msgstr "Vand"
#. module: pos_restaurant
#: model_terms:pos.config,customer_facing_display_html:pos_restaurant.pos_config_restaurant
msgid "Whiteboard Pen"
msgstr "Table pen"
#. module: pos_restaurant
#: model:ir.model.fields,field_description:pos_restaurant.field_restaurant_table__width
msgid "Width"
msgstr "Bredde"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/splitbill.xml:0
#, python-format
msgid "With a"
msgstr "Med en"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "Yellow"
msgstr "Gul"
#. module: pos_restaurant
#: code:addons/pos_restaurant/models/pos_restaurant.py:0
#, python-format
msgid ""
"You cannot remove a floor that is used in a PoS session, close the "
"session(s) first: \n"
msgstr ""
"Du kan ikke fjerne en etage der bruges i en PoS session, luk session(erne) "
"først: \n"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/js/floors.js:0
#, python-format
msgid ""
"You must be connected to the internet to save your changes.\n"
"\n"
"Changes made to previously synced orders will get lost at the next sync.\n"
"Orders that where not synced before will be synced next time you open and close the same table."
msgstr ""
"Du skal være forbundet til internettet for at gemme dine ændringer.\n"
"\n"
"Ændringer foretaget på tidligere synkroniserede ordre vil gå tabt ved næste synkronisering.\n"
"Ordre der ikke var synkroniseret før, vil blive synkroniseret næste gang du åbner og lukker samme bord."
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/splitbill.xml:0
#, python-format
msgid "at"
msgstr "på"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "at table"
msgstr "Ved bordet"
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/floors.xml:0
#, python-format
msgid "button in the editing toolbar to create new tables."
msgstr "knap i redigerings værktøjslinjen til at oprette nye borde."
#. module: pos_restaurant
#. openerp-web
#: code:addons/pos_restaurant/static/src/xml/splitbill.xml:0
#, python-format
msgid "discount"
msgstr "rabat"
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <PhotoLibrary/PLSlideshowPlugin.h>
#import <PhotoLibrary/PLImageLoadingQueueDelegate-Protocol.h>
@class NSString, PLCachedImage, PLCroppedImageView, PLImageCache, PLImageLoadingQueue, PLImageSource, PLManagedAsset;
@interface PLPictureFramePlugin : PLSlideshowPlugin <PLImageLoadingQueueDelegate>
{
PLImageCache *_imageCache;
PLImageLoadingQueue *_imageLoadingQueue;
PLImageSource *_imageSource;
struct __CFArray *_imageIndexes;
unsigned long long _currentIndex;
PLManagedAsset *_requestedImage;
PLCachedImage *_nextImage;
PLCroppedImageView *_currentImageView;
PLCroppedImageView *_nextImageView;
unsigned int _didLoadFirstImage:1;
unsigned int _slideshowTimerDidFire:1;
unsigned int _slideshowTimerIsScheduled:1;
unsigned int _paused:1;
}
- (void)_slideshowTimerFired;
- (void)_crossFadeAnimationDidStop:(id)arg1 finished:(id)arg2 context:(void *)arg3;
- (void)_transitionToNextImage;
- (void)_didLoadImage:(id)arg1;
- (void)_displayFirstImage;
- (void)imageLoadingQueue:(id)arg1 didLoadImage:(id)arg2 forAsset:(id)arg3 fromSource:(id)arg4;
- (void)_requestNextImageSynchronously:(_Bool)arg1;
- (id)_nextImage;
- (long long)_albumImageIndexForSlideIndex:(long long)arg1;
- (void)_scheduleSlideshowTimer;
- (void)stopSlideshow;
- (void)resumeSlideshow;
- (void)pauseSlideshow;
- (void)slideshowViewDidDisappear;
- (void)slideshowViewDidAppear;
- (void)slideshowViewWillAppear;
- (id)newSlideshowView;
- (struct CGRect)_contentBounds;
- (void)setAlbumAssets:(id)arg1;
- (void)dealloc;
- (id)init;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| {
"pile_set_name": "Github"
} |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace Nop.Plugin.Api.DTOs.ProductManufacturerMappings
{
public class ProductManufacturerMappingsRootObject : ISerializableObject
{
public ProductManufacturerMappingsRootObject()
{
ProductManufacturerMappingsDtos = new List<ProductManufacturerMappingsDto>();
}
[JsonProperty("product_manufacturer_mappings")]
public IList<ProductManufacturerMappingsDto> ProductManufacturerMappingsDtos { get; set; }
public string GetPrimaryPropertyName()
{
return "product_manufacturer_mappings";
}
public Type GetPrimaryPropertyType()
{
return typeof (ProductManufacturerMappingsDto);
}
}
} | {
"pile_set_name": "Github"
} |
fileFormatVersion: 2
guid: dd89cf5b9246416f84610a006f916af7
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:
| {
"pile_set_name": "Github"
} |
# md5 from https://pypi.python.org/pypi/u-msgpack-python/json, sha256 locally computed
md5 f5adfb3e19910d8a41e331d3b03aa7c6 u-msgpack-python-2.2.tar.gz
sha256 cdd5a88f2313856a6a9f481f652dab9edd5731059badbb0111280f27249930d7 u-msgpack-python-2.2.tar.gz
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/dcn_popup_closed_pressed" />
<item android:drawable="@drawable/dcn_popup_closed_normal" />
</selector> | {
"pile_set_name": "Github"
} |
@import: head
let-inline ctx \glueneg = inline-glue 0pt 0pt (0pt -' 100pt) in
document (|
title = {Glue Test};
author = {Takashi SUWA};
|) '<
+frame <
+p {
\glueneg;The quick brown fox jumps over the\glueneg;lazy dog.
}
>
>
| {
"pile_set_name": "Github"
} |
<template>
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-xl-3 col-md-6">
<stats-card>
<div slot="header" class="icon-warning">
<i class="nc-icon nc-chart text-warning"></i>
</div>
<div slot="content">
<p class="card-category">Capacity</p>
<h4 class="card-title">105GB</h4>
</div>
<div slot="footer">
<i class="fa fa-refresh"></i>Updated now
</div>
</stats-card>
</div>
<div class="col-xl-3 col-md-6">
<stats-card>
<div slot="header" class="icon-success">
<i class="nc-icon nc-light-3 text-success"></i>
</div>
<div slot="content">
<p class="card-category">Revenue</p>
<h4 class="card-title">$1,345</h4>
</div>
<div slot="footer">
<i class="fa fa-calendar-o"></i>Last day
</div>
</stats-card>
</div>
<div class="col-xl-3 col-md-6">
<stats-card>
<div slot="header" class="icon-danger">
<i class="nc-icon nc-vector text-danger"></i>
</div>
<div slot="content">
<p class="card-category">Errors</p>
<h4 class="card-title">23</h4>
</div>
<div slot="footer">
<i class="fa fa-clock-o"></i>Last day
</div>
</stats-card>
</div>
<div class="col-xl-3 col-md-6">
<stats-card>
<div slot="header" class="icon-info">
<i class="nc-icon nc-favourite-28 text-primary"></i>
</div>
<div slot="content">
<p class="card-category">Followers</p>
<h4 class="card-title">+45</h4>
</div>
<div slot="footer">
<i class="fa fa-refresh"></i>Updated now
</div>
</stats-card>
</div>
</div>
<div class="row">
<div class="col-md-8">
<chart-card :chart-data="lineChart.data"
:chart-options="lineChart.options"
:responsive-options="lineChart.responsiveOptions">
<template slot="header">
<h4 class="card-title">Users Behavior</h4>
<p class="card-category">24 Hours performance</p>
</template>
<template slot="footer">
<div class="legend">
<i class="fa fa-circle text-info"></i> Open
<i class="fa fa-circle text-danger"></i> Click
<i class="fa fa-circle text-warning"></i> Click Second Time
</div>
<hr>
<div class="stats">
<i class="fa fa-history"></i> Updated 3 minutes ago
</div>
</template>
</chart-card>
</div>
<div class="col-md-4">
<chart-card :chart-data="pieChart.data" chart-type="Pie">
<template slot="header">
<h4 class="card-title">Email Statistics</h4>
<p class="card-category">Last Campaign Performance</p>
</template>
<template slot="footer">
<div class="legend">
<i class="fa fa-circle text-info"></i> Open
<i class="fa fa-circle text-danger"></i> Bounce
<i class="fa fa-circle text-warning"></i> Unsubscribe
</div>
<hr>
<div class="stats">
<i class="fa fa-clock-o"></i> Campaign sent 2 days ago
</div>
</template>
</chart-card>
</div>
</div>
<div class="row">
<div class="col-md-6">
<chart-card
:chart-data="barChart.data"
:chart-options="barChart.options"
:chart-responsive-options="barChart.responsiveOptions"
chart-type="Bar">
<template slot="header">
<h4 class="card-title">2014 Sales</h4>
<p class="card-category">All products including Taxes</p>
</template>
<template slot="footer">
<div class="legend">
<i class="fa fa-circle text-info"></i> Tesla Model S
<i class="fa fa-circle text-danger"></i> BMW 5 Series
</div>
<hr>
<div class="stats">
<i class="fa fa-check"></i> Data information certified
</div>
</template>
</chart-card>
</div>
<div class="col-md-6">
<card>
<template slot="header">
<h5 class="title">Tasks</h5>
<p class="category">Backend development</p>
</template>
<l-table :data="tableData.data"
:columns="tableData.columns">
<template slot="columns"></template>
<template slot-scope="{row}">
<td>
<base-checkbox v-model="row.checked"></base-checkbox>
</td>
<td>{{row.title}}</td>
<td class="td-actions text-right">
<button type="button" class="btn-simple btn btn-xs btn-info" v-tooltip.top-center="editTooltip">
<i class="fa fa-edit"></i>
</button>
<button type="button" class="btn-simple btn btn-xs btn-danger" v-tooltip.top-center="deleteTooltip">
<i class="fa fa-times"></i>
</button>
</td>
</template>
</l-table>
<div class="footer">
<hr>
<div class="stats">
<i class="fa fa-history"></i> Updated 3 minutes ago
</div>
</div>
</card>
</div>
</div>
</div>
</div>
</template>
<script>
import ChartCard from 'src/components/Cards/ChartCard.vue'
import StatsCard from 'src/components/Cards/StatsCard.vue'
import LTable from 'src/components/Table.vue'
export default {
components: {
LTable,
ChartCard,
StatsCard
},
data () {
return {
editTooltip: 'Edit Task',
deleteTooltip: 'Remove',
pieChart: {
data: {
labels: ['40%', '20%', '40%'],
series: [40, 20, 40]
}
},
lineChart: {
data: {
labels: ['9:00AM', '12:00AM', '3:00PM', '6:00PM', '9:00PM', '12:00PM', '3:00AM', '6:00AM'],
series: [
[287, 385, 490, 492, 554, 586, 698, 695],
[67, 152, 143, 240, 287, 335, 435, 437],
[23, 113, 67, 108, 190, 239, 307, 308]
]
},
options: {
low: 0,
high: 800,
showArea: false,
height: '245px',
axisX: {
showGrid: false
},
lineSmooth: true,
showLine: true,
showPoint: true,
fullWidth: true,
chartPadding: {
right: 50
}
},
responsiveOptions: [
['screen and (max-width: 640px)', {
axisX: {
labelInterpolationFnc (value) {
return value[0]
}
}
}]
]
},
barChart: {
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
series: [
[542, 443, 320, 780, 553, 453, 326, 434, 568, 610, 756, 895],
[412, 243, 280, 580, 453, 353, 300, 364, 368, 410, 636, 695]
]
},
options: {
seriesBarDistance: 10,
axisX: {
showGrid: false
},
height: '245px'
},
responsiveOptions: [
['screen and (max-width: 640px)', {
seriesBarDistance: 5,
axisX: {
labelInterpolationFnc (value) {
return value[0]
}
}
}]
]
},
tableData: {
data: [
{title: 'Sign contract for "What are conference organizers afraid of?"', checked: false},
{title: 'Lines From Great Russian Literature? Or E-mails From My Boss?', checked: true},
{
title: 'Flooded: One year later, assessing what was lost and what was found when a ravaging rain swept through metro Detroit',
checked: true
},
{title: 'Create 4 Invisible User Experiences you Never Knew About', checked: false},
{title: 'Read "Following makes Medium better"', checked: false},
{title: 'Unfollow 5 enemies from twitter', checked: false}
]
}
}
}
}
</script>
<style>
</style>
| {
"pile_set_name": "Github"
} |
// UpdateAction.h
#ifndef __UPDATE_ACTION_H
#define __UPDATE_ACTION_H
namespace NUpdateArchive {
namespace NPairState
{
const int kNumValues = 7;
enum EEnum
{
kNotMasked = 0,
kOnlyInArchive,
kOnlyOnDisk,
kNewInArchive,
kOldInArchive,
kSameFiles,
kUnknowNewerFiles
};
}
namespace NPairAction
{
enum EEnum
{
kIgnore = 0,
kCopy,
kCompress,
kCompressAsAnti
};
}
struct CActionSet
{
NPairAction::EEnum StateActions[NPairState::kNumValues];
bool NeedScanning() const
{
int i;
for (i = 0; i < NPairState::kNumValues; i++)
if (StateActions[i] == NPairAction::kCompress)
return true;
for (i = 1; i < NPairState::kNumValues; i++)
if (StateActions[i] != NPairAction::kIgnore)
return true;
return false;
}
};
extern const CActionSet kAddActionSet;
extern const CActionSet kUpdateActionSet;
extern const CActionSet kFreshActionSet;
extern const CActionSet kSynchronizeActionSet;
extern const CActionSet kDeleteActionSet;
};
#endif
| {
"pile_set_name": "Github"
} |
///////////////////////////////////////////////////////////////////////////////
// Name: src/osx/core/evtloop_cf.cpp
// Purpose: wxEventLoop implementation common to both Carbon and Cocoa
// Author: Vadim Zeitlin
// Created: 2009-10-18
// Copyright: (c) 2009 Vadim Zeitlin <[email protected]>
// (c) 2013 Rob Bresalier
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/evtloop.h"
#ifndef WX_PRECOMP
#include "wx/log.h"
#include "wx/app.h"
#endif
#include "wx/evtloopsrc.h"
#include "wx/scopedptr.h"
#include "wx/osx/private.h"
#include "wx/osx/core/cfref.h"
#include "wx/thread.h"
#if wxUSE_GUI
#include "wx/nonownedwnd.h"
#endif
#include <CoreFoundation/CFSocket.h>
// ============================================================================
// wxCFEventLoopSource and wxCFEventLoop implementation
// ============================================================================
#if wxUSE_EVENTLOOP_SOURCE
void wxCFEventLoopSource::InitSourceSocket(CFSocketRef cfSocket)
{
wxASSERT_MSG( !m_cfSocket, "shouldn't be called more than once" );
m_cfSocket = cfSocket;
}
wxCFEventLoopSource::~wxCFEventLoopSource()
{
if ( m_cfSocket )
{
CFSocketInvalidate(m_cfSocket);
CFRelease(m_cfSocket);
}
}
#endif // wxUSE_EVENTLOOP_SOURCE
void wxCFEventLoop::OSXCommonModeObserverCallBack(CFRunLoopObserverRef observer, int activity, void *info)
{
wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
if ( eventloop && eventloop->IsRunning() )
eventloop->CommonModeObserverCallBack(observer, activity);
}
void wxCFEventLoop::OSXDefaultModeObserverCallBack(CFRunLoopObserverRef observer, int activity, void *info)
{
wxCFEventLoop * eventloop = static_cast<wxCFEventLoop *>(info);
if ( eventloop && eventloop->IsRunning() )
eventloop->DefaultModeObserverCallBack(observer, activity);
}
void wxCFEventLoop::CommonModeObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer), int activity)
{
if ( activity & kCFRunLoopBeforeTimers )
{
// process pending wx events first as they correspond to low-level events
// which happened before, i.e. typically pending events were queued by a
// previous call to Dispatch() and if we didn't process them now the next
// call to it might enqueue them again (as happens with e.g. socket events
// which would be generated as long as there is input available on socket
// and this input is only removed from it when pending event handlers are
// executed)
if ( wxTheApp && ShouldProcessIdleEvents() )
wxTheApp->ProcessPendingEvents();
}
if ( activity & kCFRunLoopBeforeWaiting )
{
if ( ShouldProcessIdleEvents() && ProcessIdle() )
{
WakeUp();
}
else
{
#if wxUSE_THREADS
wxMutexGuiLeaveOrEnter();
#endif
}
}
}
void
wxCFEventLoop::DefaultModeObserverCallBack(CFRunLoopObserverRef WXUNUSED(observer),
int WXUNUSED(activity))
{
/*
if ( activity & kCFRunLoopBeforeTimers )
{
}
if ( activity & kCFRunLoopBeforeWaiting )
{
}
*/
}
wxCFEventLoop::wxCFEventLoop()
{
m_shouldExit = false;
m_processIdleEvents = true;
#if wxUSE_UIACTIONSIMULATOR
m_shouldWaitForEvent = false;
#endif
m_runLoop = CFGetCurrentRunLoop();
CFRunLoopObserverContext ctxt;
bzero( &ctxt, sizeof(ctxt) );
ctxt.info = this;
m_commonModeRunLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
(CFRunLoopObserverCallBack) wxCFEventLoop::OSXCommonModeObserverCallBack, &ctxt );
CFRunLoopAddObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
m_defaultModeRunLoopObserver = CFRunLoopObserverCreate( kCFAllocatorDefault, kCFRunLoopBeforeTimers | kCFRunLoopBeforeWaiting , true /* repeats */, 0,
(CFRunLoopObserverCallBack) wxCFEventLoop::OSXDefaultModeObserverCallBack, &ctxt );
CFRunLoopAddObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
}
wxCFEventLoop::~wxCFEventLoop()
{
CFRunLoopRemoveObserver(m_runLoop, m_commonModeRunLoopObserver, kCFRunLoopCommonModes);
CFRunLoopRemoveObserver(m_runLoop, m_defaultModeRunLoopObserver, kCFRunLoopDefaultMode);
CFRelease(m_defaultModeRunLoopObserver);
CFRelease(m_commonModeRunLoopObserver);
}
CFRunLoopRef wxCFEventLoop::CFGetCurrentRunLoop() const
{
return CFRunLoopGetCurrent();
}
void wxCFEventLoop::WakeUp()
{
CFRunLoopWakeUp(m_runLoop);
}
#if wxUSE_BASE
void wxMacWakeUp()
{
wxEventLoopBase * const loop = wxEventLoopBase::GetActive();
if ( loop )
loop->WakeUp();
}
#endif
void wxCFEventLoop::DoYieldFor(long eventsToProcess)
{
// process all pending events:
while ( DoProcessEvents() == 1 )
;
wxEventLoopBase::DoYieldFor(eventsToProcess);
}
// implement/override base class pure virtual
bool wxCFEventLoop::Pending() const
{
return true;
}
int wxCFEventLoop::DoProcessEvents()
{
#if wxUSE_UIACTIONSIMULATOR
if ( m_shouldWaitForEvent )
{
int handled = DispatchTimeout( 1000 );
wxASSERT_MSG( handled == 1, "No Event Available");
m_shouldWaitForEvent = false;
return handled;
}
else
#endif
return DispatchTimeout( IsYielding() ? 0 : 1000 );
}
bool wxCFEventLoop::Dispatch()
{
return DoProcessEvents() != 0;
}
int wxCFEventLoop::DispatchTimeout(unsigned long timeout)
{
if ( !wxTheApp )
return 0;
int status = DoDispatchTimeout(timeout);
switch( status )
{
case 0:
break;
case -1:
if ( m_shouldExit )
return 0;
break;
case 1:
break;
}
return status;
}
int wxCFEventLoop::DoDispatchTimeout(unsigned long timeout)
{
SInt32 status = CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout / 1000.0 , true);
switch( status )
{
case kCFRunLoopRunFinished:
wxFAIL_MSG( "incorrect run loop state" );
break;
case kCFRunLoopRunStopped:
return 0;
break;
case kCFRunLoopRunTimedOut:
return -1;
break;
case kCFRunLoopRunHandledSource:
default:
break;
}
return 1;
}
void wxCFEventLoop::OSXDoRun()
{
for ( ;; )
{
OnNextIteration();
// generate and process idle events for as long as we don't
// have anything else to do
DoProcessEvents();
// if the "should exit" flag is set, the loop should terminate
// but not before processing any remaining messages so while
// Pending() returns true, do process them
if ( m_shouldExit )
{
while ( DoProcessEvents() == 1 )
;
break;
}
}
}
void wxCFEventLoop::OSXDoStop()
{
CFRunLoopStop(CFGetCurrentRunLoop());
}
// enters a loop calling OnNextIteration(), Pending() and Dispatch() and
// terminating when Exit() is called
int wxCFEventLoop::DoRun()
{
// we must ensure that OnExit() is called even if an exception is thrown
// from inside ProcessEvents() but we must call it from Exit() in normal
// situations because it is supposed to be called synchronously,
// wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
// something similar here)
#if wxUSE_EXCEPTIONS
for ( ;; )
{
try
{
#endif // wxUSE_EXCEPTIONS
OSXDoRun();
#if wxUSE_EXCEPTIONS
// exit the outer loop as well
break;
}
catch ( ... )
{
try
{
if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
{
OnExit();
break;
}
//else: continue running the event loop
}
catch ( ... )
{
// OnException() throwed, possibly rethrowing the same
// exception again: very good, but we still need OnExit() to
// be called
OnExit();
throw;
}
}
}
#endif // wxUSE_EXCEPTIONS
return m_exitcode;
}
// sets the "should exit" flag and wakes up the loop so that it terminates
// soon
void wxCFEventLoop::ScheduleExit(int rc)
{
m_exitcode = rc;
m_shouldExit = true;
OSXDoStop();
}
wxCFEventLoopPauseIdleEvents::wxCFEventLoopPauseIdleEvents()
{
wxCFEventLoop* cfl = dynamic_cast<wxCFEventLoop*>(wxEventLoopBase::GetActive());
if ( cfl )
{
m_formerState = cfl->ShouldProcessIdleEvents();
cfl->SetProcessIdleEvents(false);
}
else
m_formerState = true;
}
wxCFEventLoopPauseIdleEvents::~wxCFEventLoopPauseIdleEvents()
{
wxCFEventLoop* cfl = dynamic_cast<wxCFEventLoop*>(wxEventLoopBase::GetActive());
if ( cfl )
cfl->SetProcessIdleEvents(m_formerState);
}
// TODO Move to thread_osx.cpp
#if wxUSE_THREADS
// ----------------------------------------------------------------------------
// GUI Serialization copied from MSW implementation
// ----------------------------------------------------------------------------
// if it's false, some secondary thread is holding the GUI lock
static bool gs_bGuiOwnedByMainThread = true;
// critical section which controls access to all GUI functions: any secondary
// thread (i.e. except the main one) must enter this crit section before doing
// any GUI calls
static wxCriticalSection *gs_critsectGui = NULL;
// critical section which protects gs_nWaitingForGui variable
static wxCriticalSection *gs_critsectWaitingForGui = NULL;
// number of threads waiting for GUI in wxMutexGuiEnter()
static size_t gs_nWaitingForGui = 0;
void wxOSXThreadModuleOnInit()
{
gs_critsectWaitingForGui = new wxCriticalSection();
gs_critsectGui = new wxCriticalSection();
gs_critsectGui->Enter();
}
void wxOSXThreadModuleOnExit()
{
if ( gs_critsectGui )
{
if ( !wxGuiOwnedByMainThread() )
{
gs_critsectGui->Enter();
gs_bGuiOwnedByMainThread = true;
}
gs_critsectGui->Leave();
wxDELETE(gs_critsectGui);
}
wxDELETE(gs_critsectWaitingForGui);
}
// wake up the main thread
void WXDLLIMPEXP_BASE wxWakeUpMainThread()
{
wxMacWakeUp();
}
void wxMutexGuiEnterImpl()
{
// this would dead lock everything...
wxASSERT_MSG( !wxThread::IsMain(),
wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
// the order in which we enter the critical sections here is crucial!!
// set the flag telling to the main thread that we want to do some GUI
{
wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
gs_nWaitingForGui++;
}
wxWakeUpMainThread();
// now we may block here because the main thread will soon let us in
// (during the next iteration of OnIdle())
gs_critsectGui->Enter();
}
void wxMutexGuiLeaveImpl()
{
wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
if ( wxThread::IsMain() )
{
gs_bGuiOwnedByMainThread = false;
}
else
{
// decrement the number of threads waiting for GUI access now
wxASSERT_MSG( gs_nWaitingForGui > 0,
wxT("calling wxMutexGuiLeave() without entering it first?") );
gs_nWaitingForGui--;
wxWakeUpMainThread();
}
gs_critsectGui->Leave();
}
void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter()
{
wxASSERT_MSG( wxThread::IsMain(),
wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
if ( !gs_critsectWaitingForGui )
return;
wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
if ( gs_nWaitingForGui == 0 )
{
// no threads are waiting for GUI - so we may acquire the lock without
// any danger (but only if we don't already have it)
if ( !wxGuiOwnedByMainThread() )
{
gs_critsectGui->Enter();
gs_bGuiOwnedByMainThread = true;
}
//else: already have it, nothing to do
}
else
{
// some threads are waiting, release the GUI lock if we have it
if ( wxGuiOwnedByMainThread() )
wxMutexGuiLeave();
//else: some other worker thread is doing GUI
}
}
bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread()
{
return gs_bGuiOwnedByMainThread;
}
#endif
| {
"pile_set_name": "Github"
} |
/**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.recyclical.handle
import android.os.Looper.getMainLooper
import android.os.Looper.myLooper
import android.view.View
import androidx.annotation.VisibleForTesting
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.afollestad.recyclical.datasource.DataSource
import com.afollestad.recyclical.internal.DefinitionAdapter
import com.afollestad.recyclical.itemdefinition.ItemGraph
/** @author Aidan Follestad (@afollestad) */
class RealRecyclicalHandle internal constructor(
internal val emptyView: View?,
private val adapter: DefinitionAdapter,
val dataSource: DataSource<*>,
@VisibleForTesting internal val itemGraph: ItemGraph
) : RecyclicalHandle {
override fun showOrHideEmptyView(show: Boolean) {
check(myLooper() == getMainLooper()) {
"DataSource interaction must be done on the main (UI) thread."
}
emptyView?.visibility = if (show) View.VISIBLE else View.GONE
}
override fun getAdapter(): Adapter<*> = adapter
override fun invalidateList(block: Adapter<*>.() -> Unit) {
check(myLooper() == getMainLooper()) {
"DataSource interaction must be done on the main (UI) thread."
}
getAdapter().block()
showOrHideEmptyView(dataSource.isEmpty())
}
override fun itemGraph(): ItemGraph = itemGraph
internal fun attachDataSource() {
dataSource.attach(this)
adapter.attach(this)
}
internal fun detachDataSource() {
dataSource.detach()
adapter.detach()
}
}
| {
"pile_set_name": "Github"
} |
[NO_PID]: ECPGdebug: set to 1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ECPGconnect: opening database regress1 on <DEFAULT> port <DEFAULT>
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 19: query: create table My_Table ( Item1 int , Item2 text ); with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 19: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 19: OK: CREATE TABLE
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 21: query: insert into My_Table values ( 1 , 'text1' ); with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 21: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 21: OK: INSERT 0 1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 22: query: insert into My_Table values ( 2 , 'text2' ); with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 22: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 22: OK: INSERT 0 1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 23: query: insert into My_Table values ( 3 , 'text3' ); with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 23: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 23: OK: INSERT 0 1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 24: query: insert into My_Table values ( 4 , 'text4' ); with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 24: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 24: OK: INSERT 0 1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 28: query: declare C cursor for select * from My_Table; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 28: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 28: OK: DECLARE CURSOR
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: query: fetch 1 in C; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: correctly got 1 tuples with 2 fields
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 32: RESULT: 1 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 32: RESULT: text1 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: query: fetch 1 in C; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: correctly got 1 tuples with 2 fields
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 32: RESULT: 2 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 32: RESULT: text2 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: query: fetch 1 in C; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: correctly got 1 tuples with 2 fields
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 32: RESULT: 3 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 32: RESULT: text3 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: query: fetch 1 in C; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: correctly got 1 tuples with 2 fields
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 32: RESULT: 4 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 32: RESULT: text4 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: query: fetch 1 in C; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 32: correctly got 0 tuples with 2 fields
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: raising sqlcode 100 on line 32: no data found on line 32
[NO_PID]: sqlca: code: 100, state: 02000
[NO_PID]: ecpg_execute on line 37: query: move backward 2 in C; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 37: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 37: OK: MOVE 2
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 39: query: fetch 1 in C; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 39: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 39: correctly got 1 tuples with 2 fields
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 39: RESULT: 4 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 39: RESULT: text4 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 44: query: declare D cursor for select * from My_Table where Item1 = $1; with 1 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 44: using PQexecParams
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: free_params on line 44: parameter 1 = 1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 44: OK: DECLARE CURSOR
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 48: query: fetch 1 in D; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 48: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 48: correctly got 1 tuples with 2 fields
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 48: RESULT: 1 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_get_data on line 48: RESULT: text1 offset: -1; array: no
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 48: query: fetch 1 in D; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 48: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 48: correctly got 0 tuples with 2 fields
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: raising sqlcode 100 on line 48: no data found on line 48
[NO_PID]: sqlca: code: 100, state: 02000
[NO_PID]: ecpg_execute on line 51: query: close D; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 51: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 51: OK: CLOSE CURSOR
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 53: query: drop table My_Table; with 0 parameter(s) on connection regress1
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_execute on line 53: using PQexec
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: ecpg_check_PQresult on line 53: bad response - ERROR: cannot drop "my_table" because it is being used by active queries in this session
[NO_PID]: sqlca: code: 0, state: 00000
[NO_PID]: raising sqlstate 55006 (sqlcode -400): cannot drop "my_table" because it is being used by active queries in this session on line 53
[NO_PID]: sqlca: code: -400, state: 55006
SQL error: cannot drop "my_table" because it is being used by active queries in this session on line 53
[NO_PID]: ecpg_finish: connection regress1 closed
[NO_PID]: sqlca: code: 0, state: 00000
| {
"pile_set_name": "Github"
} |
/* src/backend/utils/mb/Unicode/win866_to_utf8.map */
/* This file is generated by src/backend/utils/mb/Unicode/UCS_to_most.pl */
static const uint32 win866_to_unicode_tree_table[256];
static const pg_mb_radix_tree win866_to_unicode_tree =
{
NULL, /* 16-bit table not used */
win866_to_unicode_tree_table,
0x0080, /* offset of table for 1-byte inputs */
0x80, /* b1_lower */
0xff, /* b1_upper */
0x0000, /* offset of table for 2-byte inputs */
0x00, /* b2_1_lower */
0x00, /* b2_1_upper */
0x00, /* b2_2_lower */
0x00, /* b2_2_upper */
0x0000, /* offset of table for 3-byte inputs */
0x00, /* b3_1_lower */
0x00, /* b3_1_upper */
0x00, /* b3_2_lower */
0x00, /* b3_2_upper */
0x00, /* b3_3_lower */
0x00, /* b3_3_upper */
0x0000, /* offset of table for 3-byte inputs */
0x00, /* b4_1_lower */
0x00, /* b4_1_upper */
0x00, /* b4_2_lower */
0x00, /* b4_2_upper */
0x00, /* b4_3_lower */
0x00, /* b4_3_upper */
0x00, /* b4_4_lower */
0x00 /* b4_4_upper */
};
static const uint32 win866_to_unicode_tree_table[256] =
{
/*** Dummy map, for invalid values - offset 0x00000 ***/
/* 00 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 04 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 08 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 0c */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 10 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 14 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 18 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 1c */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 20 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 24 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 28 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 2c */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 30 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 34 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 38 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 3c */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 40 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 44 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 48 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 4c */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 50 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 54 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 58 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 5c */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 60 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 64 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 68 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 6c */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 70 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 74 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 78 */ 0x000000, 0x000000, 0x000000, 0x000000,
/* 7c */ 0x000000, 0x000000, 0x000000, 0x000000,
/*** Single byte table, leaf: xx - offset 0x00080 ***/
/* 80 */ 0x00d090, 0x00d091, 0x00d092, 0x00d093,
/* 84 */ 0x00d094, 0x00d095, 0x00d096, 0x00d097,
/* 88 */ 0x00d098, 0x00d099, 0x00d09a, 0x00d09b,
/* 8c */ 0x00d09c, 0x00d09d, 0x00d09e, 0x00d09f,
/* 90 */ 0x00d0a0, 0x00d0a1, 0x00d0a2, 0x00d0a3,
/* 94 */ 0x00d0a4, 0x00d0a5, 0x00d0a6, 0x00d0a7,
/* 98 */ 0x00d0a8, 0x00d0a9, 0x00d0aa, 0x00d0ab,
/* 9c */ 0x00d0ac, 0x00d0ad, 0x00d0ae, 0x00d0af,
/* a0 */ 0x00d0b0, 0x00d0b1, 0x00d0b2, 0x00d0b3,
/* a4 */ 0x00d0b4, 0x00d0b5, 0x00d0b6, 0x00d0b7,
/* a8 */ 0x00d0b8, 0x00d0b9, 0x00d0ba, 0x00d0bb,
/* ac */ 0x00d0bc, 0x00d0bd, 0x00d0be, 0x00d0bf,
/* b0 */ 0xe29691, 0xe29692, 0xe29693, 0xe29482,
/* b4 */ 0xe294a4, 0xe295a1, 0xe295a2, 0xe29596,
/* b8 */ 0xe29595, 0xe295a3, 0xe29591, 0xe29597,
/* bc */ 0xe2959d, 0xe2959c, 0xe2959b, 0xe29490,
/* c0 */ 0xe29494, 0xe294b4, 0xe294ac, 0xe2949c,
/* c4 */ 0xe29480, 0xe294bc, 0xe2959e, 0xe2959f,
/* c8 */ 0xe2959a, 0xe29594, 0xe295a9, 0xe295a6,
/* cc */ 0xe295a0, 0xe29590, 0xe295ac, 0xe295a7,
/* d0 */ 0xe295a8, 0xe295a4, 0xe295a5, 0xe29599,
/* d4 */ 0xe29598, 0xe29592, 0xe29593, 0xe295ab,
/* d8 */ 0xe295aa, 0xe29498, 0xe2948c, 0xe29688,
/* dc */ 0xe29684, 0xe2968c, 0xe29690, 0xe29680,
/* e0 */ 0x00d180, 0x00d181, 0x00d182, 0x00d183,
/* e4 */ 0x00d184, 0x00d185, 0x00d186, 0x00d187,
/* e8 */ 0x00d188, 0x00d189, 0x00d18a, 0x00d18b,
/* ec */ 0x00d18c, 0x00d18d, 0x00d18e, 0x00d18f,
/* f0 */ 0x00d081, 0x00d191, 0x00d084, 0x00d194,
/* f4 */ 0x00d087, 0x00d197, 0x00d08e, 0x00d19e,
/* f8 */ 0x00c2b0, 0xe28899, 0x00c2b7, 0xe2889a,
/* fc */ 0xe28496, 0x00c2a4, 0xe296a0, 0x00c2a0
};
| {
"pile_set_name": "Github"
} |
<?php
namespace Drupal\Core\Cache\Context;
use Drupal\Core\Cache\CacheableMetadata;
/**
* Defines the IsSuperUserCacheContext service, for "super user or not" caching.
*
* Cache context ID: 'user.is_super_user'.
*/
class IsSuperUserCacheContext extends UserCacheContextBase implements CacheContextInterface {
/**
* {@inheritdoc}
*/
public static function getLabel() {
return t('Is super user');
}
/**
* {@inheritdoc}
*/
public function getContext() {
return ((int) $this->user->id()) === 1 ? '1' : '0';
}
/**
* {@inheritdoc}
*/
public function getCacheableMetadata() {
return new CacheableMetadata();
}
}
| {
"pile_set_name": "Github"
} |
/*
* Models.h
* AuthService
*
* Copyright 2011 QuickBlox team. All rights reserved.
*
*/
#import "Session/QBASession.h"
| {
"pile_set_name": "Github"
} |
module.exports = {
entry: {
index: './src/index.js',
indexVue: './src/vue/index.vue.js'
},
output: {
path: __dirname,
filename: '[name].js'
}
}
| {
"pile_set_name": "Github"
} |
.featured-domain-suggestion--is-placeholder {
min-height: 222px;
.domain-registration-suggestion__title,
.domain-registration-suggestion__progress-bar,
.domain-registration-suggestion__match-reasons,
.domain-suggestion__action {
animation: loading-fade 1.6s ease-in-out infinite;
background-color: var( --color-neutral-0 );
color: transparent;
}
.domain-registration-suggestion__title {
height: 22px;
padding: 0;
width: 60%;
}
.domain-registration-suggestion__title {
height: 45px;
}
.domain-product-price {
height: 18px;
}
.domain-registration-suggestion__progress-bar {
height: 22px;
}
.domain-registration-suggestion__match-reasons {
height: 52px;
}
.domain-suggestion__action {
height: 40px;
}
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<PropertyGroup>
<ProjectGuid>{30D10654-A5F5-4AC5-A370-E6DD4D0FAC50}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<OutputType>Library</OutputType>
<RootNamespace>ICSharpCode.NRefactory.ConsistencyCheck</RootNamespace>
<AssemblyName>NRConsistencyCheckAddIn</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
<NoStdLib>False</NoStdLib>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Platform)' == 'x86' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<RegisterForComInterop>False</RegisterForComInterop>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<BaseAddress>4194304</BaseAddress>
<FileAlignment>4096</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<OutputPath>bin\Debug\</OutputPath>
<DebugSymbols>true</DebugSymbols>
<DebugType>Full</DebugType>
<Optimize>False</Optimize>
<CheckForOverflowUnderflow>True</CheckForOverflowUnderflow>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<StartAction>Program</StartAction>
<StartProgram>..\..\..\bin\SharpDevelop.exe</StartProgram>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<OutputPath>bin\Release\</OutputPath>
<DebugSymbols>False</DebugSymbols>
<DebugType>None</DebugType>
<Optimize>True</Optimize>
<CheckForOverflowUnderflow>False</CheckForOverflowUnderflow>
<DefineConstants>TRACE</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Reference Include="ICSharpCode.AvalonEdit">
<HintPath>..\..\..\bin\ICSharpCode.AvalonEdit.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="ICSharpCode.Core">
<HintPath>..\..\..\bin\ICSharpCode.Core.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="ICSharpCode.NRefactory">
<HintPath>..\..\..\bin\ICSharpCode.NRefactory.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="ICSharpCode.NRefactory.CSharp">
<HintPath>..\..\..\bin\ICSharpCode.NRefactory.CSharp.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="ICSharpCode.SharpDevelop">
<HintPath>..\..\..\bin\ICSharpCode.SharpDevelop.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="PresentationCore">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="PresentationFramework">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
</ItemGroup>
<ItemGroup>
<None Include="NRConsistencyCheckAddIn.addin">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\Libraries\NRefactory\ICSharpCode.NRefactory.ConsistencyCheck\FindReferencesConsistencyCheck.cs">
<Link>FindReferencesConsistencyCheck.cs</Link>
</Compile>
<Compile Include="..\..\Libraries\NRefactory\ICSharpCode.NRefactory.ConsistencyCheck\RandomizedOrderResolverTest.cs">
<Link>RandomizedOrderResolverTest.cs</Link>
</Compile>
<Compile Include="..\..\Libraries\NRefactory\ICSharpCode.NRefactory.ConsistencyCheck\ResolverTest.cs">
<Link>ResolverTest.cs</Link>
</Compile>
<Compile Include="..\..\Libraries\NRefactory\ICSharpCode.NRefactory.ConsistencyCheck\TypeSystemTests.cs">
<Link>TypeSystemTests.cs</Link>
</Compile>
<Compile Include="..\..\Libraries\NRefactory\ICSharpCode.NRefactory.ConsistencyCheck\VisitorBenchmark.cs">
<Link>VisitorBenchmark.cs</Link>
</Compile>
<Compile Include="Commands.cs" />
<Compile Include="Configuration\AssemblyInfo.cs" />
<Compile Include="Adapter.cs" />
</ItemGroup>
<PropertyGroup>
<StartArguments>/addindir:"$(MsBuildProjectDirectory)\$(OutputPath)"</StartArguments>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.Targets" />
</Project> | {
"pile_set_name": "Github"
} |
# Welcome to the Mixed Reality Toolkit

The Mixed Reality Toolkit's primary focus is to make it extremely easy to get started creating Mixed Reality applications and to accelerate deployment to multiple platforms from the same Unity project.
## Build Status
| Modules | Azure Pipelines | OpenUpm |
|---|---|---|
|XRTK-Core|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=44&branchName=master)|[](https://openupm.com/packages/com.xrtk.core/)|
|[SDK](https://github.com/XRTK/SDK)|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=50&branchName=master)|[](https://openupm.com/packages/com.xrtk.sdk/)|
|[ARCore](https://github.com/XRTK/ARCore)|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=56&branchName=master)|[](https://openupm.com/packages/com.xrtk.arcore/)|
|[Etee](https://github.com/XRTK/Etee)|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=54&branchName=master)|[](https://openupm.com/packages/com.xrtk.etee/)|
|[Lenovo](https://github.com/XRTK/Lenovo)|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=53&branchName=master)|[](https://openupm.com/packages/com.xrtk.lenovo/)|
|[Lumin](https://github.com/XRTK/Lumin)|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=47&branchName=master)|[](https://openupm.com/packages/com.xrtk.lumin/)|
|[Nreal](https://github.com/XRTK/Nreal)|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=52&branchName=master)|[](https://openupm.com/packages/com.xrtk.nreal/)|
|[Oculus](https://github.com/XRTK/Oculus)|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=48&branchName=master)|[](https://openupm.com/packages/com.xrtk.oculus/)|
|[SteamVR](https://github.com/XRTK/SteamVR)|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=55&branchName=master)|[](https://openupm.com/packages/com.xrtk.steamvr/)|
|[Ultraleap](https://github.com/XRTK/Ultraleap)|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=51&branchName=master)|[](https://openupm.com/packages/com.xrtk.ultraleap/)|
|[Windows Mixed Reality](https://github.com/XRTK/WindowsMixedReality)|[](https://dev.azure.com/xrtk/Mixed%20Reality%20Toolkit/_build/latest?definitionId=49&branchName=master)|[](https://openupm.com/packages/com.xrtk.wmr/)|
## [Getting Started](articles/00-GettingStarted.md)
- [Installing](articles/00-GettingStarted.md#adding-the-mixed-reality-toolkit-to-your-project)
- [Configuring](articles/00-GettingStarted.md#configure-your-base-scene)
- [Building](articles/00-GettingStarted.md#build-and-play)
- [Contributing](CONTRIBUTING.md)
## Overview
Developing Mixed Reality Applications in Unity is hard, and we know there are many [developers](./CONTRIBUTORS.md) who are frustrated with the current state of both game and general application development within the Mixed Reality ecosystem: a quickly developing market that encompasses the whole spectrum from Mobile Augmented Reality to high-end Virtual Reality.
To improve this situation, the Mixed Reality Toolkit's vision is simple, to provide a complete cross-platform solution for AR/XR/VR development that supports three different developer skill levels:
- **Beginner** No Coding Required: Perfect for artists, Hackathons, and Quick Prototyping.
- **Intermediate** Customizable: The framework is flexible enough so coders can customize what they need to cover edge cases with ease.
- **Advanced** Extensible: The framework is easy to extend and modify to add additional custom services to meet specific criteria and needs.
Our philosophy is to enable developers to focus on building content and structure and not have to worry about the underlying complexities for supporting multiple platforms in order to build it everywhere and on each device as required. In short, built it once and ship it everywhere with as little effort as possible.
We’d like to invite all the major hardware vendors to help guide their platform-specific implementations, from Microsoft’s Windows Mixed Reality and Magic Leap’s Lumin OS to Google’s ARCore and Apple’s ARKit. Including any upcoming Mixed Reality capable devices that would like to be included for adoption.
## Chat with the community
We recently moved our main conversations regarding Mixed Reality Toolkit over to Discord, which allows us to do a lot more (and the chat/streaming there is awesome), but we keep a Mixed Reality Toolkit presence on Slack too, in order to retain links to our friends on there.
[](https://discord.gg/rJMSc8Z)
### [Come join us on Discord!](https://discord.gg/rJMSc8Z)
## Sponsors
The XRTK is an MIT-licensed open source project with its ongoing development made possible entirely by the support of these awesome sponsors and backers.
|Sponsors||
|---|---|
|<a href="https://www.vimaec.com/">](/images/Sponsors/vim_logo.jpg)</a>|VIM provides a universal format for fast BIM access for large and complex projects in the AEC industry.|
We use the donations for continuous active development by core team members, web hosting, and licensing costs for build tools and infrastructure.
## Supported Platforms
By default, we support OpenVR on all platforms that support the standard, as well as Native SDK implementations for various vendors. This list is in no particular order.
All platforms are supported using their native plugins.
> Want to add a platform? Check out our new [Template Generator](articles/03-template-generator.md#platform-template-generation)!
- [x] Windows Standalone
- [x] Linux Standalone
- [x] OSX Standalone
- [x] [Windows Mixed Reality](https://github.com/XRTK/WindowsMixedReality)
- [x] Windows Mixed Reality HMDs
- [x] HoloLens 1 & 2
- [x] [Lumin](https://github.com/XRTK/Lumin)
- [x] Magic Leap One
- [x] [Oculus](https://github.com/XRTK/Oculus)
- [x] Rift
- [x] Quest
- [ ] Go
- [x] Android
- [ ] [ARCore](https://github.com/XRTK/ARCore)
- [ ] iOS
- [ ] ARKit
- [ ] [Etee](https://github.com/XRTK/Etee)
- [ ] [Ultraleap](https://github.com/XRTK/Ultraleap)
- [ ] North Star
- [ ] Varjo
- [ ] [Lenovo](https://github.com/XRTK/Lenovo)
- [ ] A6
- [ ] [Nreal](https://github.com/XRTK/Nreal)
- [ ] [SteamVR (OpenVR)](https://github.com/XRTK/SteamVR)
- [ ] Index
- [ ] HTC Vive
- [ ] OpenXR
- [ ] WebAssembly (requires threading support)
- [ ] WebXR
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2005 Openedhand Ltd.
*
* Author: Richard Purdie <[email protected]>
*
* Based on WM8753.h
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#ifndef _WM8750_H
#define _WM8750_H
/* WM8750 register space */
#define WM8750_LINVOL 0x00
#define WM8750_RINVOL 0x01
#define WM8750_LOUT1V 0x02
#define WM8750_ROUT1V 0x03
#define WM8750_ADCDAC 0x05
#define WM8750_IFACE 0x07
#define WM8750_SRATE 0x08
#define WM8750_LDAC 0x0a
#define WM8750_RDAC 0x0b
#define WM8750_BASS 0x0c
#define WM8750_TREBLE 0x0d
#define WM8750_RESET 0x0f
#define WM8750_3D 0x10
#define WM8750_ALC1 0x11
#define WM8750_ALC2 0x12
#define WM8750_ALC3 0x13
#define WM8750_NGATE 0x14
#define WM8750_LADC 0x15
#define WM8750_RADC 0x16
#define WM8750_ADCTL1 0x17
#define WM8750_ADCTL2 0x18
#define WM8750_PWR1 0x19
#define WM8750_PWR2 0x1a
#define WM8750_ADCTL3 0x1b
#define WM8750_ADCIN 0x1f
#define WM8750_LADCIN 0x20
#define WM8750_RADCIN 0x21
#define WM8750_LOUTM1 0x22
#define WM8750_LOUTM2 0x23
#define WM8750_ROUTM1 0x24
#define WM8750_ROUTM2 0x25
#define WM8750_MOUTM1 0x26
#define WM8750_MOUTM2 0x27
#define WM8750_LOUT2V 0x28
#define WM8750_ROUT2V 0x29
#define WM8750_MOUTV 0x2a
#define WM8750_CACHE_REGNUM 0x2a
#define WM8750_SYSCLK 0
struct wm8750_setup_data {
int spi;
int i2c_bus;
unsigned short i2c_address;
};
extern struct snd_soc_dai wm8750_dai;
extern struct snd_soc_codec_device soc_codec_dev_wm8750;
#endif
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html>
<head>
<title>Dokumentacja API</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap.min.css'/>
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/prettify.css'/>
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/bundled/bootstrap-responsive.min.css'/>
<link type='text/css' rel='stylesheet' href='../../../apidoc/stylesheets/application.css'/>
<!-- IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div id='container'>
<ul class='breadcrumb'>
<li>
<a href='../../../apidoc/v2.pl.html'>Foreman v2</a>
<span class='divider'>/</span>
</li>
<li>
<a href='../../../apidoc/v2/auth_source_ldaps.pl.html'>
Auth source ldaps
</a>
<span class='divider'>/</span>
</li>
<li class='active'>update</li>
<li class='pull-right'>
[ <a href="../../../apidoc/v2/auth_source_ldaps/update.pt_BR.html">pt_BR</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.de.html">de</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.it.html">it</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.sv_SE.html">sv_SE</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.zh_CN.html">zh_CN</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.en_GB.html">en_GB</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.cs_CZ.html">cs_CZ</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.fr.html">fr</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.ru.html">ru</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.ja.html">ja</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.es.html">es</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.ko.html">ko</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.ca.html">ca</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.gl.html">gl</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.en.html">en</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.zh_TW.html">zh_TW</a> | <a href="../../../apidoc/v2/auth_source_ldaps/update.nl_NL.html">nl_NL</a> | <b><a href="../../../apidoc/v2/auth_source_ldaps/update.pl.html">pl</a></b> ]
</li>
</ul>
<div class='page-header'>
<h1>
PUT /api/auth_source_ldaps/:id
<br>
<small>Aktualizuj źródło autentyfikacji serwera LDAP</small>
</h1>
</div>
<div>
<h2>Przykłady</h2>
<pre class="prettyprint">PUT /api/auth_source_ldaps/980190962-ldap-server
{
"auth_source_ldap": {
"name": "ldap2",
"host": "ldap2",
"server_type": "posix"
}
}
200
{
"host": "ldap2",
"port": 123,
"account": null,
"base_dn": "dn=x,dn=y",
"ldap_filter": null,
"attr_login": "uid",
"attr_firstname": "givenName",
"attr_lastname": "sn",
"attr_mail": "mail",
"attr_photo": null,
"onthefly_register": true,
"usergroup_sync": true,
"tls": true,
"server_type": "posix",
"groups_base": null,
"use_netgroups": false,
"created_at": "2019-02-20 13:35:01 UTC",
"updated_at": "2019-02-20 13:35:05 UTC",
"id": 980190962,
"type": "AuthSourceLdap",
"name": "ldap2",
"external_usergroups": [],
"locations": [
{
"id": 255093256,
"name": "Location 1",
"title": "Location 1",
"description": null
}
],
"organizations": [
{
"id": 447626438,
"name": "Organization 1",
"title": "Organization 1",
"description": null
}
]
}</pre>
<h2>Parametry</h2>
<table class='table'>
<thead>
<tr>
<th>Nazwa parametru</th>
<th>Opis</th>
</tr>
</thead>
<tbody>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>location_id </strong><br>
<small>
opcjonalny
</small>
</td>
<td>
<p>Zakres w zależności od lokalizacji</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>organization_id </strong><br>
<small>
opcjonalny
</small>
</td>
<td>
<p>Zakres w zależności od organizacji</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Integer</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>id </strong><br>
<small>
wymagany
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(255,255,255);'>
<td>
<strong>auth_source_ldap </strong><br>
<small>
wymagany
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a Hash</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[name] </strong><br>
<small>
opcjonalny
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[host] </strong><br>
<small>
opcjonalny
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[port] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>domyślnie 389</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a number.</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[account] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[base_dn] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[account_password] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>“wymagane jeśli onthefly_register ma wartość "true\</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[attr_login] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>“wymagane jeśli onthefly_register ma wartość "true\</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[attr_firstname] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>“wymagane jeśli onthefly_register ma wartość "true\</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[attr_lastname] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>“wymagane jeśli onthefly_register ma wartość "true\</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[attr_mail] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>“wymagane jeśli onthefly_register ma wartość "true\</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[attr_photo] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[onthefly_register] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be one of: <code>true</code>, <code>false</code>, <code>1</code>, <code>0</code>.</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[usergroup_sync] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>synchronizacja zewnętrznej grupy użytkowników przy logowaniu</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be one of: <code>true</code>, <code>false</code>, <code>1</code>, <code>0</code>.</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[tls] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be one of: <code>true</code>, <code>false</code>, <code>1</code>, <code>0</code>.</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[groups_base] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>Grupy oparte na DN</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[use_netgroups] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>use NIS netgroups instead of posix groups, applicable only when server_type is posix or free_ipa</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be one of: <code>true</code>, <code>false</code>, <code>1</code>, <code>0</code>.</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[server_type] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>Typ serwera LDAP</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be one of: <code>free_ipa</code>, <code>active_directory</code>, <code>posix</code>.</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[ldap_filter] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>Filtr LDAP</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be a String</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[location_ids] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>ZMIEŃ lokalizacje o podanym id</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be an array of any type</p>
</li>
</ul>
</td>
</tr>
<tr style='background-color:rgb(250,250,250);'>
<td>
<strong>auth_source_ldap[organization_ids] </strong><br>
<small>
opcjonalny
, nil dopuszczalny
</small>
</td>
<td>
<p>ZMIEŃ organizacje o podanym id</p>
<p><strong>Validations:</strong></p>
<ul>
<li>
<p>Must be an array of any type</p>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<hr>
<footer></footer>
</div>
<script type='text/javascript' src='../../../apidoc/javascripts/bundled/jquery.js'></script>
<script type='text/javascript' src='../../../apidoc/javascripts/bundled/bootstrap-collapse.js'></script>
<script type='text/javascript' src='../../../apidoc/javascripts/bundled/prettify.js'></script>
<script type='text/javascript' src='../../../apidoc/javascripts/apipie.js'></script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
Admin
=====
Please refer to the [CONTRIBUTING.md](../../CONTRIBUTING.md) before adding or updating any material
| {
"pile_set_name": "Github"
} |
require "mixlib/log/logger"
require "pp" unless defined?(PP)
MonoLogger = Mixlib::Log::Logger
| {
"pile_set_name": "Github"
} |
name: application-layer
runtime: nodejs
description: Application layer for the aws-stackreference-architecture
template:
config:
aws:region:
description: The AWS region to deploy into.
default: us-west-2
networkingStack:
description: "(Required) The reference to the networking stack on which the database will be deployed
(in the form <organization_or_user>/<projectName>/<stackName> e.g. myUsername/multicloud/dev)"
databaseStack:
description: "(Required) The reference to the database so that the Application Instance can get the correct credentials
and database information for application startup (in the form <organization_or_user>/<projectName>/<stackName>
e.g. myUsername/multicloud/dev)"
| {
"pile_set_name": "Github"
} |
import {
compile,
execute,
getCompiler,
normalizeErrors,
readAsset,
} from './helpers';
describe('"mimetype" option', () => {
it('should work with unspecified value', async () => {
const compiler = getCompiler('simple.js');
const stats = await compile(compiler);
expect(
execute(readAsset('main.bundle.js', compiler, stats))
).toMatchSnapshot('result');
expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
'warnings'
);
expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
});
it('should work with "Boolean" true', async () => {
const compiler = getCompiler('simple-html.js', {
mimetype: true,
});
const stats = await compile(compiler);
expect(
execute(readAsset('main.bundle.js', compiler, stats))
).toMatchSnapshot('result');
expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
'warnings'
);
expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
});
it('should work with "Boolean" false', async () => {
const compiler = getCompiler('simple-html.js', {
mimetype: false,
});
const stats = await compile(compiler);
expect(
execute(readAsset('main.bundle.js', compiler, stats))
).toMatchSnapshot('result');
expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
'warnings'
);
expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
});
it('should work with "String" value', async () => {
const compiler = getCompiler('simple.js', {
mimetype: 'image/x-custom',
});
const stats = await compile(compiler);
expect(
execute(readAsset('main.bundle.js', compiler, stats))
).toMatchSnapshot('result');
expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
'warnings'
);
expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
});
it('should work with "String" value equal to unknown/unknown', async () => {
const compiler = getCompiler('simple.js', {
mimetype: 'unknown/unknown',
});
const stats = await compile(compiler);
expect(
execute(readAsset('main.bundle.js', compiler, stats))
).toMatchSnapshot('result');
expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
'warnings'
);
expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
});
it('should work for unknown mimetype', async () => {
const compiler = getCompiler('simple-unknown.js');
const stats = await compile(compiler);
expect(
execute(readAsset('main.bundle.js', compiler, stats))
).toMatchSnapshot('result');
expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
'warnings'
);
expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
});
it('should work for unknown mimetype when value is true', async () => {
const compiler = getCompiler('simple-unknown.js', {
mimetype: true,
});
const stats = await compile(compiler);
expect(
execute(readAsset('main.bundle.js', compiler, stats))
).toMatchSnapshot('result');
expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
'warnings'
);
expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
});
it('should work for unknown mimetype when value is false and encoding is false', async () => {
const compiler = getCompiler('simple-unknown.js', {
mimetype: false,
encoding: false,
});
const stats = await compile(compiler);
expect(
execute(readAsset('main.bundle.js', compiler, stats))
).toMatchSnapshot('result');
expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
'warnings'
);
expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
});
it('should work for unknown mimetype when value is true and encoding is true', async () => {
const compiler = getCompiler('simple-unknown.js', {
mimetype: true,
encoding: true,
});
const stats = await compile(compiler);
expect(
execute(readAsset('main.bundle.js', compiler, stats))
).toMatchSnapshot('result');
expect(Object.keys(stats.compilation.assets)).toMatchSnapshot('assets');
expect(normalizeErrors(stats.compilation.warnings)).toMatchSnapshot(
'warnings'
);
expect(normalizeErrors(stats.compilation.errors)).toMatchSnapshot('errors');
});
});
| {
"pile_set_name": "Github"
} |
{
"Data": {
"customer": {
"foo": "Freddy Freeman_Q3VzdG9tZXIKZDE="
}
},
"Errors": null,
"Extensions": null,
"ContextData": null
}
| {
"pile_set_name": "Github"
} |
/*
Source File : PDFWriterDriver.cpp
Copyright 2013 Gal Kahana HummusJS
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 "PDFWriterDriver.h"
#include "PDFPageDriver.h"
#include "ByteReaderWithPositionDriver.h"
#include "PageContentContextDriver.h"
#include "FormXObjectDriver.h"
#include "UsedFontDriver.h"
#include "ImageXObjectDriver.h"
#include "ObjectsContextDriver.h"
#include "DocumentContextExtenderAdapter.h"
#include "DocumentCopyingContextDriver.h"
#include "InputFile.h"
#include "PDFParser.h"
#include "PDFDateDriver.h"
#include "PDFTextStringDriver.h"
#include "PDFParser.h"
#include "PDFPageInput.h"
#include "PDFRectangle.h"
#include "TIFFImageHandler.h"
#include "IOBasicTypes.h"
#include "PDFDocumentCopyingContext.h"
#include "PDFFormXObject.h"
#include "PDFReaderDriver.h"
#include "InputFileDriver.h"
#include "OutputFileDriver.h"
#include "DocumentContextDriver.h"
#include "ObjectByteReaderWithPosition.h"
#include "DictionaryContextDriver.h"
#include "ResourcesDictionaryDriver.h"
#include "ConstructorsHolder.h"
using namespace v8;
PDFWriterDriver::PDFWriterDriver()
{
mWriteStreamProxy = NULL;
mReadStreamProxy = NULL;
mStartedWithStream = false;
mIsCatalogUpdateRequired = false;
}
PDFWriterDriver::~PDFWriterDriver()
{
delete mWriteStreamProxy;
delete mReadStreamProxy;
}
DEF_SUBORDINATE_INIT(PDFWriterDriver::Init)
{
CREATE_ISOLATE_CONTEXT;
Local<FunctionTemplate> t = NEW_FUNCTION_TEMPLATE_EXTERNAL(New);
t->SetClassName(NEW_STRING("PDFWriter"));
t->InstanceTemplate()->SetInternalFieldCount(1);
SET_PROTOTYPE_METHOD(t, "end", End);
SET_PROTOTYPE_METHOD(t, "createPage", CreatePage);
SET_PROTOTYPE_METHOD(t, "writePage", WritePage);
SET_PROTOTYPE_METHOD(t, "writePageAndReturnID", WritePageAndReturnID);
SET_PROTOTYPE_METHOD(t, "startPageContentContext", StartPageContentContext);
SET_PROTOTYPE_METHOD(t, "pausePageContentContext", PausePageContentContext);
SET_PROTOTYPE_METHOD(t, "createFormXObject", CreateFormXObject);
SET_PROTOTYPE_METHOD(t, "endFormXObject", EndFormXObject);
SET_PROTOTYPE_METHOD(t, "createFormXObjectFromJPG", CreateformXObjectFromJPG);
SET_PROTOTYPE_METHOD(t, "getFontForFile", GetFontForFile);
SET_PROTOTYPE_METHOD(t, "attachURLLinktoCurrentPage", AttachURLLinktoCurrentPage);
SET_PROTOTYPE_METHOD(t, "shutdown", Shutdown);
SET_PROTOTYPE_METHOD(t, "createFormXObjectFromTIFF", CreateFormXObjectFromTIFF);
SET_PROTOTYPE_METHOD(t, "createImageXObjectFromJPG", CreateImageXObjectFromJPG);
SET_PROTOTYPE_METHOD(t, "createFormXObjectFromPNG", CreateFormXObjectFromPNG);
SET_PROTOTYPE_METHOD(t, "retrieveJPGImageInformation", RetrieveJPGImageInformation);
SET_PROTOTYPE_METHOD(t, "getObjectsContext", GetObjectsContext);
SET_PROTOTYPE_METHOD(t, "getDocumentContext", GetDocumentContext);
SET_PROTOTYPE_METHOD(t, "appendPDFPagesFromPDF", AppendPDFPagesFromPDF);
SET_PROTOTYPE_METHOD(t, "mergePDFPagesToPage", MergePDFPagesToPage);
SET_PROTOTYPE_METHOD(t, "createPDFCopyingContext", CreatePDFCopyingContext);
SET_PROTOTYPE_METHOD(t, "createFormXObjectsFromPDF", CreateFormXObjectsFromPDF);
SET_PROTOTYPE_METHOD(t, "createPDFCopyingContextForModifiedFile", CreatePDFCopyingContextForModifiedFile);
SET_PROTOTYPE_METHOD(t, "createPDFTextString", CreatePDFTextString);
SET_PROTOTYPE_METHOD(t, "createPDFDate", CreatePDFDate);
SET_PROTOTYPE_METHOD(t, "getImageDimensions", GetImageDimensions);
SET_PROTOTYPE_METHOD(t, "getImagePagesCount", GetImagePagesCount);
SET_PROTOTYPE_METHOD(t, "getImageType", GetImageType);
SET_PROTOTYPE_METHOD(t, "getModifiedFileParser", GetModifiedFileParser);
SET_PROTOTYPE_METHOD(t, "getModifiedInputFile", GetModifiedInputFile);
SET_PROTOTYPE_METHOD(t, "getOutputFile", GetOutputFile);
SET_PROTOTYPE_METHOD(t, "registerAnnotationReferenceForNextPageWrite", RegisterAnnotationReferenceForNextPageWrite);
SET_PROTOTYPE_METHOD(t, "requireCatalogUpdate", RequireCatalogUpdate);
SET_CONSTRUCTOR_EXPORT("PDFWriter", t);
// save in factory
EXPOSE_EXTERNAL_FOR_INIT(ConstructorsHolder, holder)
SET_CONSTRUCTOR(holder->PDFWriter_constructor, t);
}
METHOD_RETURN_TYPE PDFWriterDriver::New(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
EXPOSE_EXTERNAL_ARGS(ConstructorsHolder, externalHolder)
PDFWriterDriver* pdfWriter = new PDFWriterDriver();
pdfWriter->holder = externalHolder;
pdfWriter->Wrap(args.This());
SET_FUNCTION_RETURN_VALUE(args.This())
}
METHOD_RETURN_TYPE PDFWriterDriver::End(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
EStatusCode status;
if(pdfWriter->mStartedWithStream)
status = pdfWriter->mPDFWriter.EndPDFForStream();
else
status = pdfWriter->mPDFWriter.EndPDF();
// now remove event listener
pdfWriter->mPDFWriter.GetDocumentContext().AddDocumentContextExtender(pdfWriter);
if(status != PDFHummus::eSuccess)
{
THROW_EXCEPTION("Unable to end PDF");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
if(pdfWriter->mWriteStreamProxy)
{
delete pdfWriter->mWriteStreamProxy;
pdfWriter->mWriteStreamProxy = NULL;
}
if(pdfWriter->mReadStreamProxy)
{
delete pdfWriter->mReadStreamProxy;
pdfWriter->mReadStreamProxy = NULL;
}
SET_FUNCTION_RETURN_VALUE(args.This())
}
METHOD_RETURN_TYPE PDFWriterDriver::CreatePage(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
SET_FUNCTION_RETURN_VALUE(pdfWriter->holder->GetNewPDFPage(args))
}
METHOD_RETURN_TYPE PDFWriterDriver::WritePage(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
WritePageAndReturnID(args);
SET_FUNCTION_RETURN_VALUE(args.This())
}
METHOD_RETURN_TYPE PDFWriterDriver::WritePageAndReturnID(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
if (args.Length() != 1 || !pdfWriter->holder->IsPDFPageInstance(args[0])) {
THROW_EXCEPTION("Wrong arguments, provide a page as the single parameter");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFPageDriver* pageDriver = ObjectWrap::Unwrap<PDFPageDriver>(args[0]->TO_OBJECT());
if(!pageDriver)
{
THROW_EXCEPTION("Wrong arguments, provide a page as the single parameter");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
if(pageDriver->ContentContext &&
(pdfWriter->mPDFWriter.EndPageContentContext(pageDriver->ContentContext) != PDFHummus::eSuccess))
{
THROW_EXCEPTION("Unable to finalize page context");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
pageDriver->ContentContext = NULL;
EStatusCodeAndObjectIDType result = pdfWriter->mPDFWriter.WritePageAndReturnPageID(pageDriver->GetPage());
if(result.first != PDFHummus::eSuccess)
{
THROW_EXCEPTION("Unable to write page");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
SET_FUNCTION_RETURN_VALUE(NEW_NUMBER(result.second))
}
METHOD_RETURN_TYPE PDFWriterDriver::StartPageContentContext(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
if (args.Length() != 1 || !pdfWriter->holder->IsPDFPageInstance(args[0])) {
THROW_EXCEPTION("Wrong arguments, provide a page as the single parameter");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFPageDriver* pageDriver = ObjectWrap::Unwrap<PDFPageDriver>(args[0]->TO_OBJECT());
if(!pageDriver)
{
THROW_EXCEPTION("Wrong arguments, provide a page as the single parameter");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewPageContentContext(args);
PageContentContextDriver* contentContextDriver = ObjectWrap::Unwrap<PageContentContextDriver>(newInstance->TO_OBJECT());
contentContextDriver->ContentContext = pdfWriter->mPDFWriter.StartPageContentContext(pageDriver->GetPage());
contentContextDriver->SetResourcesDictionary(&(pageDriver->GetPage()->GetResourcesDictionary()));
// save it also at page driver, so we can end the context when the page is written
pageDriver->ContentContext = contentContextDriver->ContentContext;
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::PausePageContentContext(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
if (args.Length() != 1 || !pdfWriter->holder->IsPageContentContextInstance(args[0])) {
THROW_EXCEPTION("Wrong arguments, provide a page context as the single parameter");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PageContentContextDriver* pageContextDriver = ObjectWrap::Unwrap<PageContentContextDriver>(args[0]->TO_OBJECT());
if(!pageContextDriver)
{
THROW_EXCEPTION("Wrong arguments, provide a page context as the single parameter");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
if(!pageContextDriver->ContentContext)
{
THROW_EXCEPTION("paused context not initialized, please create one using pdfWriter.startPageContentContext");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
pdfWriter->mPDFWriter.PausePageContentContext(pageContextDriver->ContentContext);
SET_FUNCTION_RETURN_VALUE(args.This())
}
METHOD_RETURN_TYPE PDFWriterDriver::CreateFormXObject(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if((args.Length() != 4 && args.Length() != 5) || !args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsNumber() || !args[3]->IsNumber()
|| (args.Length() == 5 && !args[4]->IsNumber()))
{
THROW_EXCEPTION("wrong arguments, pass 4 coordinates of the form rectangle and an optional 5th agument which is the forward reference ID");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
Local<Value> newInstance = pdfWriter->holder->GetNewFormXObject(args);
FormXObjectDriver* formXObjectDriver = ObjectWrap::Unwrap<FormXObjectDriver>(newInstance->TO_OBJECT());
formXObjectDriver->FormXObject =
args.Length() == 5 ?
pdfWriter->mPDFWriter.StartFormXObject(
PDFRectangle(TO_NUMBER(args[0])->Value(),
TO_NUMBER(args[1])->Value(),
TO_NUMBER(args[2])->Value(),
TO_NUMBER(args[3])->Value()),
(ObjectIDType)TO_NUMBER(args[4])->Value()):
pdfWriter->mPDFWriter.StartFormXObject(
PDFRectangle(TO_NUMBER(args[0])->Value(),
TO_NUMBER(args[1])->Value(),
TO_NUMBER(args[2])->Value(),
TO_NUMBER(args[3])->Value()));
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::EndFormXObject(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
if (args.Length() != 1 || !pdfWriter->holder->IsFormXObjectInstance(args[0])) {
THROW_EXCEPTION("Wrong arguments, provide a form as the single parameter");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
FormXObjectDriver* formContextDriver = ObjectWrap::Unwrap<FormXObjectDriver>(args[0]->TO_OBJECT());
if(!formContextDriver)
{
THROW_EXCEPTION("Wrong arguments, provide a form as the single parameter");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
pdfWriter->mPDFWriter.EndFormXObject(formContextDriver->FormXObject);
SET_FUNCTION_RETURN_VALUE(args.This())
}
METHOD_RETURN_TYPE PDFWriterDriver::CreateformXObjectFromJPG(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if((args.Length() != 1 && args.Length() != 2 ) || (!args[0]->IsString() && !args[0]->IsObject()) || (args.Length() == 2 && !args[1]->IsNumber()))
{
THROW_EXCEPTION("wrong arguments, pass 1 argument that is the path to the image or an image stream. Optionally pass an object ID for a forward reference image");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFFormXObject* formXObject;
if(args[0]->IsObject())
{
ObjectByteReaderWithPosition proxy(args[0]->TO_OBJECT());
formXObject =
args.Length() == 2 ?
pdfWriter->mPDFWriter.CreateFormXObjectFromJPGStream(&proxy,(ObjectIDType)TO_INT32(args[1])->Value()):
pdfWriter->mPDFWriter.CreateFormXObjectFromJPGStream(&proxy);
}
else
{
formXObject =
args.Length() == 2 ?
pdfWriter->mPDFWriter.CreateFormXObjectFromJPGFile(*UTF_8_VALUE(args[0]->TO_STRING()),(ObjectIDType)TO_INT32(args[1])->Value()):
pdfWriter->mPDFWriter.CreateFormXObjectFromJPGFile(*UTF_8_VALUE(args[0]->TO_STRING()));
}
if(!formXObject)
{
THROW_EXCEPTION("unable to create form xobject. verify that the target is an existing jpg file/stream");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewFormXObject(args);
ObjectWrap::Unwrap<FormXObjectDriver>(newInstance->TO_OBJECT())->FormXObject = formXObject;
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::RetrieveJPGImageInformation(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if(args.Length() != 1 ||
!args[0]->IsString())
{
THROW_EXCEPTION("wrong arguments, pass 1 argument that is the path to the image");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
BoolAndJPEGImageInformation info = pdfWriter->mPDFWriter.GetDocumentContext().GetJPEGImageHandler().RetrieveImageInformation(*UTF_8_VALUE(args[0]->TO_STRING()));
if(!info.first)
{
THROW_EXCEPTION("unable to retrieve image information");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Object> result = NEW_OBJECT;
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("samplesWidth"), NEW_INTEGER((int)info.second.SamplesWidth));
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("samplesHeight"), NEW_INTEGER((int)info.second.SamplesHeight));
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("colorComponentsCount"), NEW_INTEGER(info.second.ColorComponentsCount));
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("JFIFInformationExists"), NEW_BOOLEAN(info.second.JFIFInformationExists));
if(info.second.JFIFInformationExists)
{
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("JFIFUnit"), NEW_INTEGER(info.second.JFIFUnit));
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("JFIFXDensity"), NEW_NUMBER(info.second.JFIFXDensity));
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("JFIFYDensity"), NEW_NUMBER(info.second.JFIFYDensity));
}
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("ExifInformationExists"), NEW_BOOLEAN(info.second.ExifInformationExists));
if(info.second.ExifInformationExists)
{
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("ExifUnit"), NEW_INTEGER(info.second.ExifUnit));
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("ExifXDensity"), NEW_NUMBER(info.second.ExifXDensity));
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("ExifYDensity"), NEW_NUMBER(info.second.ExifYDensity));
}
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("PhotoshopInformationExists"), NEW_BOOLEAN(info.second.PhotoshopInformationExists));
if(info.second.PhotoshopInformationExists)
{
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("PhotoshopXDensity"), NEW_NUMBER(info.second.PhotoshopXDensity));
result->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("PhotoshopYDensity"), NEW_NUMBER(info.second.PhotoshopYDensity));
}
SET_FUNCTION_RETURN_VALUE(result)
}
METHOD_RETURN_TYPE PDFWriterDriver::CreateFormXObjectFromPNG(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if((args.Length() != 1 && args.Length() != 2 ) || (!args[0]->IsString() && !args[0]->IsObject()) || (args.Length() == 2 && !args[1]->IsNumber()))
{
THROW_EXCEPTION("wrong arguments, pass 1 argument that is the path to the image or an image stream. Optionally pass an object ID for a forward reference image");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFFormXObject* formXObject;
if(args[0]->IsObject())
{
ObjectByteReaderWithPosition proxy(args[0]->TO_OBJECT());
formXObject =
args.Length() == 2 ?
pdfWriter->mPDFWriter.CreateFormXObjectFromPNGStream(&proxy,(ObjectIDType)TO_INT32(args[1])->Value()):
pdfWriter->mPDFWriter.CreateFormXObjectFromPNGStream(&proxy);
}
else
{
formXObject =
args.Length() == 2 ?
pdfWriter->mPDFWriter.CreateFormXObjectFromPNGFile(*UTF_8_VALUE(args[0]->TO_STRING()),(ObjectIDType)TO_INT32(args[1])->Value()):
pdfWriter->mPDFWriter.CreateFormXObjectFromPNGFile(*UTF_8_VALUE(args[0]->TO_STRING()));
}
if(!formXObject)
{
THROW_EXCEPTION("unable to create form xobject. verify that the target is an existing png file/stream");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewFormXObject(args);
ObjectWrap::Unwrap<FormXObjectDriver>(newInstance->TO_OBJECT())->FormXObject = formXObject;
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::GetFontForFile(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if(args.Length() < 1 ||
!args[0]->IsString() ||
(args.Length() == 2 && !args[1]->IsString() && !args[1]->IsNumber()) ||
(args.Length() == 3 && !args[1]->IsString() && !args[2]->IsNumber()))
{
THROW_EXCEPTION("wrong arguments, pass 1 argument that is the path to the font file, with option to a 2nd parameter for another path in case of type 1 font. another optional argument may follow with font index in case of font packages (TTC, DFont)");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFUsedFont* usedFont;
if(args.Length() == 3)
{
usedFont = pdfWriter->mPDFWriter.GetFontForFile(*UTF_8_VALUE(args[0]->TO_STRING()),
*UTF_8_VALUE(args[1]->TO_STRING()),
TO_UINT32(args[0])->Value());
}
else if(args.Length() == 2)
{
if(args[1]->IsString())
usedFont = pdfWriter->mPDFWriter.GetFontForFile(*UTF_8_VALUE(args[0]->TO_STRING()),
*UTF_8_VALUE(args[1]->TO_STRING()));
else
usedFont = pdfWriter->mPDFWriter.GetFontForFile(*UTF_8_VALUE(args[0]->TO_STRING()),
TO_UINT32(args[1])->Value());
}
else // length is 1
{
usedFont = pdfWriter->mPDFWriter.GetFontForFile(*UTF_8_VALUE(args[0]->TO_STRING()));
}
if(!usedFont)
{
THROW_EXCEPTION("unable to create font object. verify that the target is an existing and supported font type (ttf,otf,type1,dfont,ttc)");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewUsedFont(args);
ObjectWrap::Unwrap<UsedFontDriver>(newInstance->TO_OBJECT())->UsedFont = usedFont;
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::AttachURLLinktoCurrentPage(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if(args.Length() != 5 ||
!args[0]->IsString() ||
!args[1]->IsNumber() ||
!args[2]->IsNumber() ||
!args[3]->IsNumber() ||
!args[4]->IsNumber())
{
THROW_EXCEPTION("wrong arguments, pass a url, and 4 numbers (left,bottom,right,top) for the rectangle valid for clicking");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
EStatusCode status = pdfWriter->mPDFWriter.AttachURLLinktoCurrentPage(*UTF_8_VALUE(args[0]->TO_STRING()),
PDFRectangle(TO_NUMBER(args[1])->Value(),
TO_NUMBER(args[2])->Value(),
TO_NUMBER(args[3])->Value(),
TO_NUMBER(args[4])->Value()));
if(status != eSuccess)
{
THROW_EXCEPTION("unable to attach link to current page. will happen if the input URL may not be encoded to ascii7");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
SET_FUNCTION_RETURN_VALUE(args.This())
}
METHOD_RETURN_TYPE PDFWriterDriver::Shutdown(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if(args.Length() != 1 ||
!args[0]->IsString())
{
THROW_EXCEPTION("wrong arguments, pass a path to save the state file to");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
EStatusCode status = pdfWriter->mPDFWriter.Shutdown(*UTF_8_VALUE(args[0]->TO_STRING()));
if(status != eSuccess)
{
THROW_EXCEPTION("unable to save state file. verify that path is not occupied");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
SET_FUNCTION_RETURN_VALUE(args.This())
}
PDFHummus::EStatusCode PDFWriterDriver::StartPDF(const std::string& inOutputFilePath,
EPDFVersion inPDFVersion,
const LogConfiguration& inLogConfiguration,
const PDFCreationSettings& inCreationSettings)
{
mStartedWithStream = false;
return setupListenerIfOK(mPDFWriter.StartPDF(inOutputFilePath,inPDFVersion,inLogConfiguration,inCreationSettings));
}
PDFHummus::EStatusCode PDFWriterDriver::StartPDF(Local<Object> inWriteStream,
EPDFVersion inPDFVersion,
const LogConfiguration& inLogConfiguration,
const PDFCreationSettings& inCreationSettings)
{
mWriteStreamProxy = new ObjectByteWriterWithPosition(inWriteStream);
mStartedWithStream = true;
return setupListenerIfOK(mPDFWriter.StartPDFForStream(mWriteStreamProxy,inPDFVersion,inLogConfiguration,inCreationSettings));
}
PDFHummus::EStatusCode PDFWriterDriver::ContinuePDF(const std::string& inOutputFilePath,
const std::string& inStateFilePath,
const std::string& inOptionalOtherOutputFile,
const LogConfiguration& inLogConfiguration)
{
mStartedWithStream = false;
return setupListenerIfOK(mPDFWriter.ContinuePDF(inOutputFilePath,inStateFilePath,inOptionalOtherOutputFile,inLogConfiguration));
}
PDFHummus::EStatusCode PDFWriterDriver::ContinuePDF(Local<Object> inOutputStream,
const std::string& inStateFilePath,
Local<Object> inModifiedSourceStream,
const LogConfiguration& inLogConfiguration)
{
mStartedWithStream = true;
mWriteStreamProxy = new ObjectByteWriterWithPosition(inOutputStream);
if(!inModifiedSourceStream.IsEmpty())
mReadStreamProxy = new ObjectByteReaderWithPosition(inModifiedSourceStream);
return setupListenerIfOK(mPDFWriter.ContinuePDFForStream(mWriteStreamProxy,inStateFilePath,inModifiedSourceStream.IsEmpty() ? NULL : mReadStreamProxy,inLogConfiguration));
}
PDFHummus::EStatusCode PDFWriterDriver::ModifyPDF(const std::string& inSourceFile,
EPDFVersion inPDFVersion,
const std::string& inOptionalOtherOutputFile,
const LogConfiguration& inLogConfiguration,
const PDFCreationSettings& inCreationSettings)
{
// two phase, cause i don't want to bother the users with the level BS.
// first, parse the source file, get the level. then modify with this level
mStartedWithStream = false;
return setupListenerIfOK(mPDFWriter.ModifyPDF(inSourceFile,inPDFVersion,inOptionalOtherOutputFile,inLogConfiguration,inCreationSettings));
}
PDFHummus::EStatusCode PDFWriterDriver::ModifyPDF(Local<Object> inSourceStream,
Local<Object> inDestinationStream,
EPDFVersion inPDFVersion,
const LogConfiguration& inLogConfiguration,
const PDFCreationSettings& inCreationSettings)
{
mStartedWithStream = true;
mWriteStreamProxy = new ObjectByteWriterWithPosition(inDestinationStream);
mReadStreamProxy = new ObjectByteReaderWithPosition(inSourceStream);
// use minimal leve ePDFVersion10 to use the modified file level (cause i don't care
return setupListenerIfOK(mPDFWriter.ModifyPDFForStream(mReadStreamProxy,mWriteStreamProxy,false,inPDFVersion,inLogConfiguration,inCreationSettings));
}
METHOD_RETURN_TYPE PDFWriterDriver::CreateFormXObjectFromTIFF(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if((args.Length() != 1 && args.Length() != 2) || (!args[0]->IsString() && !args[0]->IsObject()) || (args.Length() == 2 && !args[1]->IsObject() && !args[1]->IsNumber()))
{
THROW_EXCEPTION("wrong arguments, pass 1 argument that is the path to the image, and optionally an options object or object ID");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
TIFFUsageParameters tiffUsageParameters = TIFFUsageParameters::DefaultTIFFUsageParameters();
ObjectIDType objectID = 0;
if(args.Length() == 2)
{
if(args[1]->IsObject())
{
Local<Object> anObject = args[1]->TO_OBJECT();
// page index parameters
if(anObject->Has(GET_CURRENT_CONTEXT, NEW_STRING("pageIndex")).FromJust() && anObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("pageIndex")).ToLocalChecked()->IsNumber())
tiffUsageParameters.PageIndex = (unsigned int)TO_NUMBER(anObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("pageIndex")).ToLocalChecked())->Value();
if(anObject->Has(GET_CURRENT_CONTEXT, NEW_STRING("bwTreatment")).FromJust() && anObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("bwTreatment")).ToLocalChecked()->IsObject())
{
// special black and white treatment
Local<Object> bwObject = anObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("bwTreatment")).ToLocalChecked()->TO_OBJECT();
if(bwObject->Has(GET_CURRENT_CONTEXT, NEW_STRING("asImageMask")).FromJust() && bwObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("asImageMask")).ToLocalChecked()->IsBoolean())
tiffUsageParameters.BWTreatment.AsImageMask = bwObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("asImageMask")).ToLocalChecked()->TO_BOOLEAN()->Value();
if(bwObject->Has(GET_CURRENT_CONTEXT, NEW_STRING("oneColor")).FromJust() && bwObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("oneColor")).ToLocalChecked()->IsArray())
tiffUsageParameters.BWTreatment.OneColor = colorFromArray(bwObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("oneColor")).ToLocalChecked());
}
if(anObject->Has(GET_CURRENT_CONTEXT, NEW_STRING("grayscaleTreatment")).FromJust() && anObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("grayscaleTreatment")).ToLocalChecked()->IsObject())
{
// special black and white treatment
Local<Object> colormapObject = anObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("grayscaleTreatment")).ToLocalChecked()->TO_OBJECT();
if(colormapObject->Has(GET_CURRENT_CONTEXT, NEW_STRING("asColorMap")).FromJust() && colormapObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("asColorMap")).ToLocalChecked()->IsBoolean())
tiffUsageParameters.GrayscaleTreatment.AsColorMap = colormapObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("asColorMap")).ToLocalChecked()->TO_BOOLEAN()->Value();
if(colormapObject->Has(GET_CURRENT_CONTEXT, NEW_STRING("oneColor")).FromJust() && colormapObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("oneColor")).ToLocalChecked()->IsArray())
tiffUsageParameters.GrayscaleTreatment.OneColor = colorFromArray(colormapObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("oneColor")).ToLocalChecked());
if(colormapObject->Has(GET_CURRENT_CONTEXT, NEW_STRING("zeroColor")).FromJust() && colormapObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("zeroColor")).ToLocalChecked()->IsArray())
tiffUsageParameters.GrayscaleTreatment.ZeroColor = colorFromArray(colormapObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("zeroColor")).ToLocalChecked());
}
}
else // number
{
objectID = TO_INT32(args[1])->Value();
}
}
PDFFormXObject* formXObject;
if(args[0]->IsObject())
{
ObjectByteReaderWithPosition proxy(args[0]->TO_OBJECT());
formXObject =
objectID == 0 ?
pdfWriter->mPDFWriter.CreateFormXObjectFromTIFFStream(&proxy,tiffUsageParameters):
pdfWriter->mPDFWriter.CreateFormXObjectFromTIFFStream(&proxy,objectID,tiffUsageParameters);
}
else
{
formXObject =
objectID == 0 ?
pdfWriter->mPDFWriter.CreateFormXObjectFromTIFFFile(*UTF_8_VALUE(args[0]->TO_STRING()),tiffUsageParameters):
pdfWriter->mPDFWriter.CreateFormXObjectFromTIFFFile(*UTF_8_VALUE(args[0]->TO_STRING()),objectID,tiffUsageParameters);
}
if(!formXObject)
{
THROW_EXCEPTION("unable to create form xobject. verify that the target is an existing tiff file");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewFormXObject(args);
ObjectWrap::Unwrap<FormXObjectDriver>(newInstance->TO_OBJECT())->FormXObject = formXObject;
SET_FUNCTION_RETURN_VALUE(newInstance)
}
CMYKRGBColor PDFWriterDriver::colorFromArray(v8::Local<v8::Value> inArray)
{
CREATE_ISOLATE_CONTEXT;
if(inArray->TO_OBJECT()->Get(GET_CURRENT_CONTEXT, NEW_STRING("length")).ToLocalChecked()->TO_UINT32Value() == 4)
{
// cmyk color
return CMYKRGBColor((unsigned char)TO_NUMBER(inArray->TO_OBJECT()->Get(GET_CURRENT_CONTEXT, 0).ToLocalChecked())->Value(),
(unsigned char)TO_NUMBER(inArray->TO_OBJECT()->Get(GET_CURRENT_CONTEXT, 1).ToLocalChecked())->Value(),
(unsigned char)TO_NUMBER(inArray->TO_OBJECT()->Get(GET_CURRENT_CONTEXT, 2).ToLocalChecked())->Value(),
(unsigned char)TO_NUMBER(inArray->TO_OBJECT()->Get(GET_CURRENT_CONTEXT, 3).ToLocalChecked())->Value());
}
else if(inArray->TO_OBJECT()->Get(GET_CURRENT_CONTEXT, v8::NEW_STRING("length")).ToLocalChecked()->TO_UINT32Value() == 3)
{
// rgb color
return CMYKRGBColor((unsigned char)TO_NUMBER(inArray->TO_OBJECT()->Get(GET_CURRENT_CONTEXT, 0).ToLocalChecked())->Value(),
(unsigned char)TO_NUMBER(inArray->TO_OBJECT()->Get(GET_CURRENT_CONTEXT, 1).ToLocalChecked())->Value(),
(unsigned char)TO_NUMBER(inArray->TO_OBJECT()->Get(GET_CURRENT_CONTEXT, 2).ToLocalChecked())->Value());
}
else
{
THROW_EXCEPTION("wrong input for color values. should be array of either 3 or 4 colors");
return CMYKRGBColor::CMYKBlack();
}
}
METHOD_RETURN_TYPE PDFWriterDriver::CreateImageXObjectFromJPG(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if((args.Length() != 1 && args.Length() != 2) || (!args[0]->IsString() && !args[0]->IsObject()) || (args.Length() == 2 && !args[1]->IsNumber()))
{
THROW_EXCEPTION("wrong arguments, pass 1 argument that is the path to the image. pass another optional argument of a forward reference object ID");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFImageXObject* imageXObject;
if(args[0]->IsObject())
{
ObjectByteReaderWithPosition proxy(args[0]->TO_OBJECT());
imageXObject =
args.Length() == 2 ?
pdfWriter->mPDFWriter.CreateImageXObjectFromJPGStream(&proxy,(ObjectIDType)TO_INT32(args[1])->Value()) :
pdfWriter->mPDFWriter.CreateImageXObjectFromJPGStream(&proxy);
}
else
{
imageXObject =
args.Length() == 2 ?
pdfWriter->mPDFWriter.CreateImageXObjectFromJPGFile(*UTF_8_VALUE(args[0]->TO_STRING()),(ObjectIDType)TO_INT32(args[1])->Value()) :
pdfWriter->mPDFWriter.CreateImageXObjectFromJPGFile(*UTF_8_VALUE(args[0]->TO_STRING()));
}
if(!imageXObject)
{
THROW_EXCEPTION("unable to create image xobject. verify that the target is an existing jpg file");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewImageXObject(args);
ObjectWrap::Unwrap<ImageXObjectDriver>(newInstance->TO_OBJECT())->ImageXObject = imageXObject;
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::GetObjectsContext(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
Local<Value> newInstance = pdfWriter->holder->GetNewObjectsContext(args);
ObjectsContextDriver* objectsContextDriver = ObjectWrap::Unwrap<ObjectsContextDriver>(newInstance->TO_OBJECT());
objectsContextDriver->ObjectsContextInstance = &(pdfWriter->mPDFWriter.GetObjectsContext());
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::GetDocumentContext(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
Local<Value> newInstance = pdfWriter->holder->GetNewDocumentContext(args);
DocumentContextDriver* documentContextDriver = ObjectWrap::Unwrap<DocumentContextDriver>(newInstance->TO_OBJECT());
documentContextDriver->DocumentContextInstance = &(pdfWriter->mPDFWriter.GetDocumentContext());
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::AppendPDFPagesFromPDF(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if( (args.Length() < 1 && args.Length() > 2) ||
(!args[0]->IsString() && !args[0]->IsObject()) ||
(args.Length() >= 2 && !args[1]->IsObject())
)
{
THROW_EXCEPTION("wrong arguments, pass a path for file to append pages from or a stream object, optionally an options object");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFPageRange pageRange;
PDFParsingOptions parsingOptions;
if(args.Length() >= 2) {
Local<Object> options = args[1]->TO_OBJECT();
if(options->Has(GET_CURRENT_CONTEXT, NEW_STRING("password")).FromJust() && options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->IsString())
{
parsingOptions.Password = *UTF_8_VALUE(options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->TO_STRING());
}
pageRange = ObjectToPageRange(options);
}
EStatusCodeAndObjectIDTypeList result;
if(args[0]->IsObject())
{
ObjectByteReaderWithPosition proxy(args[0]->TO_OBJECT());
result = pdfWriter->mPDFWriter.AppendPDFPagesFromPDF(
&proxy,
pageRange,
ObjectIDTypeList(),
parsingOptions);
}
else
{
result = pdfWriter->mPDFWriter.AppendPDFPagesFromPDF(
*UTF_8_VALUE(args[0]->TO_STRING()),
pageRange,
ObjectIDTypeList(),
parsingOptions);
}
if(result.first != eSuccess)
{
THROW_EXCEPTION("unable to append page, make sure it's fine");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Array> resultPageIDs = NEW_ARRAY((unsigned int)result.second.size());
unsigned int index = 0;
ObjectIDTypeList::iterator it = result.second.begin();
for(; it != result.second.end();++it)
resultPageIDs->Set(GET_CURRENT_CONTEXT, NEW_NUMBER(index++),NEW_NUMBER(*it));
SET_FUNCTION_RETURN_VALUE(resultPageIDs)
}
PDFPageRange PDFWriterDriver::ObjectToPageRange(Local<Object> inObject)
{
CREATE_ISOLATE_CONTEXT;
PDFPageRange pageRange;
if(inObject->Has(GET_CURRENT_CONTEXT, NEW_STRING("type")).FromJust() && inObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("type")).ToLocalChecked()->IsNumber())
{
pageRange.mType = (PDFPageRange::ERangeType)(TO_UINT32(inObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("type")).ToLocalChecked())->Value());
}
if(inObject->Has(GET_CURRENT_CONTEXT, NEW_STRING("specificRanges")).FromJust() && inObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("specificRanges")).ToLocalChecked()->IsArray())
{
Local<Object> anArray = inObject->Get(GET_CURRENT_CONTEXT, NEW_STRING("specificRanges")).ToLocalChecked()->TO_OBJECT();
unsigned int length = TO_UINT32(anArray->Get(GET_CURRENT_CONTEXT, NEW_STRING("length")).ToLocalChecked())->Value();
for(unsigned int i=0; i < length; ++i)
{
if(!anArray->Get(GET_CURRENT_CONTEXT, i).ToLocalChecked()->IsArray() ||
TO_UINT32(anArray->Get(GET_CURRENT_CONTEXT, i).ToLocalChecked()->TO_OBJECT()->Get(GET_CURRENT_CONTEXT, NEW_STRING("length")).ToLocalChecked())->Value() != 2)
{
THROW_EXCEPTION("wrong argument for specificRanges. it should be an array of arrays. each subarray should be of the length of 2, signifying begining page and ending page numbers");
break;
}
Local<Object> item = anArray->Get(GET_CURRENT_CONTEXT, i).ToLocalChecked()->TO_OBJECT();
if(!item->Get(GET_CURRENT_CONTEXT, 0).ToLocalChecked()->IsNumber() || !item->Get(GET_CURRENT_CONTEXT, 1).ToLocalChecked()->IsNumber())
{
THROW_EXCEPTION("wrong argument for specificRanges. it should be an array of arrays. each subarray should be of the length of 2, signifying begining page and ending page numbers");
break;
}
pageRange.mSpecificRanges.push_back(ULongAndULong(
TO_UINT32(item->Get(GET_CURRENT_CONTEXT, 0).ToLocalChecked())->Value(),
TO_UINT32(item->Get(GET_CURRENT_CONTEXT, 1).ToLocalChecked())->Value()));
}
}
return pageRange;
}
class MergeInterpageCallbackCaller : public DocumentContextExtenderAdapter
{
public:
EStatusCode OnAfterMergePageFromPage(
PDFPage* inTargetPage,
PDFDictionary* inPageObjectDictionary,
ObjectsContext* inPDFWriterObjectContext,
DocumentContext* inPDFWriterDocumentContext,
PDFDocumentHandler* inPDFDocumentHandler)
{
if(!callback.IsEmpty())
{
const unsigned argc = 0;
callback->Call(GET_CURRENT_CONTEXT, GET_CURRENT_CONTEXT->Global(), argc, NULL).ToLocalChecked();
}
return PDFHummus::eSuccess;
}
bool IsValid(){return !callback.IsEmpty();}
Local<Function> callback;
};
METHOD_RETURN_TYPE PDFWriterDriver::MergePDFPagesToPage(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
/*
parameters are:
target page
file path to pdf to merge pages from OR stream of pdf to merge pages from
optional 1: options object
optional 2: callback function to call after each page merge
*/
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
if(args.Length() < 2)
{
THROW_EXCEPTION("Too few arguments. Pass a page object, a path to pages source file or an IByteReaderWithPosition, and two optional: configuration object and callback function that will be called between pages merging");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
if(!pdfWriter->holder->IsPDFPageInstance(args[0]))
{
THROW_EXCEPTION("Invalid arguments. First argument must be a page object");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
if(!args[1]->IsString() &&
!args[1]->IsObject())
{
THROW_EXCEPTION("Invalid arguments. Second argument must be either an input stream or a path to a pages source file.");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFPageDriver* page = ObjectWrap::Unwrap<PDFPageDriver>(args[0]->TO_OBJECT());
PDFPageRange pageRange;
PDFParsingOptions parsingOptions;
// get page range
if(args.Length() > 2 && args[2]->IsObject()) {
Local<Object> options = args[2]->TO_OBJECT();
if(options->Has(GET_CURRENT_CONTEXT, NEW_STRING("password")).FromJust() && options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->IsString())
{
parsingOptions.Password = *UTF_8_VALUE(options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->TO_STRING());
}
pageRange = ObjectToPageRange(options);
}
else if(args.Length() > 3 && args[3]->IsObject()) {
Local<Object> options = args[3]->TO_OBJECT();
if(options->Has(GET_CURRENT_CONTEXT, NEW_STRING("password")).FromJust() && options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->IsString())
{
parsingOptions.Password = *UTF_8_VALUE(options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->TO_STRING());
}
pageRange = ObjectToPageRange(options);
}
// now see if there's a need for activating the callback. will do that using the document extensibility option of the lib
MergeInterpageCallbackCaller caller;
if((args.Length() > 2 && args[2]->IsFunction()) ||
(args.Length() > 3 && args[3]->IsFunction()))
caller.callback = Local<Function>::Cast(args[2]->IsFunction() ? args[2] : args[3]);
if(caller.IsValid())
pdfWriter->mPDFWriter.GetDocumentContext().AddDocumentContextExtender(&caller);
EStatusCode status;
if(args[1]->IsString())
{
status = pdfWriter->mPDFWriter.MergePDFPagesToPage(page->GetPage(),
*UTF_8_VALUE(args[1]->TO_STRING()),
pageRange,
ObjectIDTypeList(),
parsingOptions);
}
else
{
ObjectByteReaderWithPosition proxy(args[1]->TO_OBJECT());
status = pdfWriter->mPDFWriter.MergePDFPagesToPage(page->GetPage(),
&proxy,
pageRange,
ObjectIDTypeList(),
parsingOptions);
}
if(caller.IsValid())
pdfWriter->mPDFWriter.GetDocumentContext().RemoveDocumentContextExtender(&caller);
if(status != eSuccess)
{
THROW_EXCEPTION("unable to append to page, make sure source file exists");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
SET_FUNCTION_RETURN_VALUE(args.This())
}
METHOD_RETURN_TYPE PDFWriterDriver::CreatePDFCopyingContext(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if( (args.Length() < 1 && args.Length() > 2) ||
(!args[0]->IsString() && !args[0]->IsObject()) ||
(args.Length() >= 2 && !args[1]->IsObject())
)
{
THROW_EXCEPTION("wrong arguments, pass a path to a PDF file to create copying context for or a stream object, and then an optional options object");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFDocumentCopyingContext* copyingContext;
ObjectByteReaderWithPosition* proxy = NULL;
PDFParsingOptions parsingOptions;
if(args.Length() >= 2) {
Local<Object> options = args[1]->TO_OBJECT();
if(options->Has(GET_CURRENT_CONTEXT, NEW_STRING("password")).FromJust() && options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->IsString())
{
parsingOptions.Password = *UTF_8_VALUE(options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->TO_STRING());
}
}
if(args[0]->IsObject())
{
if(pdfWriter->holder->IsPDFReaderInstance(args[0]))
{
// parser based copying context [note that here parsingOptions doesn't matter as the parser creation already took it into account]
PDFParser* theParser = ObjectWrap::Unwrap<PDFReaderDriver>(args[0]->TO_OBJECT())->GetParser();
copyingContext = pdfWriter->mPDFWriter.GetDocumentContext().CreatePDFCopyingContext(theParser);
}
else
{
// stream based copying context
proxy = new ObjectByteReaderWithPosition(args[0]->TO_OBJECT());
copyingContext = pdfWriter->mPDFWriter.CreatePDFCopyingContext(proxy,parsingOptions);
}
}
else
{
// file path based copying context
copyingContext = pdfWriter->mPDFWriter.CreatePDFCopyingContext(*UTF_8_VALUE(args[0]->TO_STRING()),parsingOptions);
}
if(!copyingContext)
{
THROW_EXCEPTION("unable to create copying context. verify that the target is an existing PDF file");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewDocumentCopyingContext(args);
ObjectWrap::Unwrap<DocumentCopyingContextDriver>(newInstance->TO_OBJECT())->CopyingContext = copyingContext;
ObjectWrap::Unwrap<DocumentCopyingContextDriver>(newInstance->TO_OBJECT())->ReadStreamProxy = proxy;
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::CreateFormXObjectsFromPDF(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if(args.Length() < 1 ||
args.Length() > 5 ||
!args[0]->IsString() ||
(args.Length() >= 2 && (!args[1]->IsNumber() && !args[1]->IsArray())) ||
(args.Length() >= 3 && !args[2]->IsObject()) ||
(args.Length() >= 4 && !args[3]->IsArray()) ||
(args.Length() == 5 && !args[4]->IsArray())
)
{
THROW_EXCEPTION("wrong arguments, pass a path to the file, and optionals - a box enumerator or actual 4 numbers box, a range object, a matrix for the form, array of object ids to copy in addition");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFPageRange pageRange;
PDFParsingOptions parsingOptions;
if(args.Length() >= 3) {
Local<Object> options = args[2]->TO_OBJECT();
if(options->Has(GET_CURRENT_CONTEXT, NEW_STRING("password")).FromJust() && options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->IsString())
{
parsingOptions.Password = *UTF_8_VALUE(options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->TO_STRING());
}
pageRange = ObjectToPageRange(options);
}
EStatusCodeAndObjectIDTypeList result;
double matrixBuffer[6];
double* transformationMatrix = NULL;
if(args.Length() >= 4)
{
Local<Object> matrixArray = args[3]->TO_OBJECT();
if(matrixArray->Get(GET_CURRENT_CONTEXT, v8::NEW_STRING("length")).ToLocalChecked()->TO_UINT32Value() != 6)
{
THROW_EXCEPTION("matrix array should be 6 numbers long");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
for(int i=0;i<6;++i)
matrixBuffer[i] = TO_NUMBER(matrixArray->Get(GET_CURRENT_CONTEXT, i).ToLocalChecked())->Value();
transformationMatrix = matrixBuffer;
}
ObjectIDTypeList extraObjectsList;
if(args.Length() >= 5)
{
Local<Object> objectsIDsArray = args[4]->TO_OBJECT();
unsigned int arrayLength = objectsIDsArray->Get(GET_CURRENT_CONTEXT, v8::NEW_STRING("length")).ToLocalChecked()->TO_UINT32Value();
for(unsigned int i=0;i<arrayLength;++i)
extraObjectsList.push_back((ObjectIDType)(TO_UINT32(objectsIDsArray->Get(GET_CURRENT_CONTEXT, i).ToLocalChecked())->Value()));
}
if(args[1]->IsArray())
{
Local<Object> boxArray = args[1]->TO_OBJECT();
if(boxArray->Get(GET_CURRENT_CONTEXT, v8::NEW_STRING("length")).ToLocalChecked()->TO_UINT32Value() != 4)
{
THROW_EXCEPTION("box dimensions array should be 4 numbers long");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFRectangle box(TO_NUMBER(boxArray->Get(GET_CURRENT_CONTEXT, 0).ToLocalChecked())->Value(),
TO_NUMBER(boxArray->Get(GET_CURRENT_CONTEXT, 1).ToLocalChecked())->Value(),
TO_NUMBER(boxArray->Get(GET_CURRENT_CONTEXT, 2).ToLocalChecked())->Value(),
TO_NUMBER(boxArray->Get(GET_CURRENT_CONTEXT, 3).ToLocalChecked())->Value());
result = pdfWriter->mPDFWriter.CreateFormXObjectsFromPDF(
*UTF_8_VALUE(args[0]->TO_STRING()),
pageRange,
box,
transformationMatrix,
extraObjectsList,
parsingOptions);
}
else
{
result = pdfWriter->mPDFWriter.CreateFormXObjectsFromPDF(
*UTF_8_VALUE(args[0]->TO_STRING()),
pageRange,
(EPDFPageBox)TO_UINT32(args[1])->Value(),
transformationMatrix,
extraObjectsList,
parsingOptions);
}
if(result.first != eSuccess)
{
THROW_EXCEPTION("unable to create forms from file. make sure the file exists, and that the input page range is valid (well, if you provided one..m'k?");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Array> resultFormIDs = NEW_ARRAY((unsigned int)result.second.size());
unsigned int index = 0;
ObjectIDTypeList::iterator it = result.second.begin();
for(; it != result.second.end();++it)
resultFormIDs->Set(GET_CURRENT_CONTEXT, NEW_NUMBER(index++),NEW_NUMBER(*it));
SET_FUNCTION_RETURN_VALUE(resultFormIDs)
}
METHOD_RETURN_TYPE PDFWriterDriver::CreatePDFCopyingContextForModifiedFile(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFDocumentCopyingContext* copyingContext = pdfWriter->mPDFWriter.CreatePDFCopyingContextForModifiedFile();
if(!copyingContext)
{
THROW_EXCEPTION("unable to create copying context for modified file...possibly a file is not being modified by this writer...");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewDocumentCopyingContext(args);
ObjectWrap::Unwrap<DocumentCopyingContextDriver>(newInstance->TO_OBJECT())->CopyingContext = copyingContext;
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::CreatePDFTextString(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
SET_FUNCTION_RETURN_VALUE(pdfWriter->holder->GetNewPDFTextString(args))
}
METHOD_RETURN_TYPE PDFWriterDriver::CreatePDFDate(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
SET_FUNCTION_RETURN_VALUE(pdfWriter->holder->GetNewPDFDate(args))
}
PDFWriter* PDFWriterDriver::GetWriter()
{
return &mPDFWriter;
}
METHOD_RETURN_TYPE PDFWriterDriver::GetImageDimensions(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if(args.Length() < 1 || args.Length() > 3 ||
(!args[0]->IsString() && !args[0]->IsObject()) ||
(args.Length()>=2 && !args[1]->IsNumber()) ||
(args.Length() >= 3 && !args[2]->IsObject())
)
{
THROW_EXCEPTION("wrong arguments, pass 1 to 3 arguments. a path to an image or a stream object, an optional image index (for multi-image files), and an options object");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFParsingOptions parsingOptions;
if(args.Length() >= 3) {
Local<Object> options = args[2]->TO_OBJECT();
if(options->Has(GET_CURRENT_CONTEXT, NEW_STRING("password")).FromJust() && options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->IsString())
{
parsingOptions.Password = *UTF_8_VALUE(options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->TO_STRING());
}
}
DoubleAndDoublePair dimensions;
if(args[0]->IsObject())
{
ObjectByteReaderWithPosition proxy(args[0]->TO_OBJECT());
dimensions = pdfWriter->mPDFWriter.GetImageDimensions(&proxy,
args.Length() >= 2 ? TO_UINT32(args[1])->Value() : 0,
parsingOptions);
}
else
{
dimensions = pdfWriter->mPDFWriter.GetImageDimensions(*UTF_8_VALUE(args[0]->TO_STRING()),
args.Length() >= 2 ? TO_UINT32(args[1])->Value() : 0,
parsingOptions);
}
Local<Object> newObject = NEW_OBJECT;
newObject->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("width"),NEW_NUMBER(dimensions.first));
newObject->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("height"),NEW_NUMBER(dimensions.second));
SET_FUNCTION_RETURN_VALUE(newObject)
};
METHOD_RETURN_TYPE PDFWriterDriver::GetImagePagesCount(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if(args.Length() < 1 || args.Length() > 2 ||
!args[0]->IsString() ||
(args.Length() >= 2 && !args[1]->IsObject())
)
{
THROW_EXCEPTION("wrong arguments, pass 1 argument and an optional one. a path to an image, and an options object");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFParsingOptions parsingOptions;
if(args.Length() >= 2) {
Local<Object> options = args[1]->TO_OBJECT();
if(options->Has(GET_CURRENT_CONTEXT, NEW_STRING("password")).FromJust() && options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->IsString())
{
parsingOptions.Password = *UTF_8_VALUE(options->Get(GET_CURRENT_CONTEXT, NEW_STRING("password")).ToLocalChecked()->TO_STRING());
}
}
unsigned long result = pdfWriter->mPDFWriter.GetImagePagesCount(*UTF_8_VALUE(args[0]->TO_STRING()),parsingOptions);
SET_FUNCTION_RETURN_VALUE(NEW_NUMBER(result))
}
METHOD_RETURN_TYPE PDFWriterDriver::GetImageType(const ARGS_TYPE& args) {
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if (args.Length() != 1 ||
!args[0]->IsString())
{
THROW_EXCEPTION("wrong arguments, pass 1 argument. a path to an image");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFHummus::EHummusImageType imageType = pdfWriter->mPDFWriter.GetImageType(*UTF_8_VALUE(args[0]->TO_STRING()),0);
switch(imageType)
{
case PDFHummus::ePDF:
{
SET_FUNCTION_RETURN_VALUE(NEW_STRING("PDF"))
break;
}
case PDFHummus::eJPG:
{
SET_FUNCTION_RETURN_VALUE(NEW_STRING("JPEG"))
break;
}
case PDFHummus::eTIFF:
{
SET_FUNCTION_RETURN_VALUE(NEW_STRING("TIFF"))
break;
}
case PDFHummus::ePNG:
{
SET_FUNCTION_RETURN_VALUE(NEW_STRING("PNG"))
break;
}
default:
{
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
}
}
METHOD_RETURN_TYPE PDFWriterDriver::GetModifiedFileParser(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
PDFParser* parser = &(pdfWriter->mPDFWriter.GetModifiedFileParser());
if(!parser->GetTrailer()) // checking for the trailer should be a good indication to whether this parser is relevant
{
THROW_EXCEPTION("unable to create modified parser...possibly a file is not being modified by this writer...");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewPDFReader(args);
ObjectWrap::Unwrap<PDFReaderDriver>(newInstance->TO_OBJECT())->SetFromOwnedParser(parser);
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::GetModifiedInputFile(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
InputFile* inputFile = &(pdfWriter->mPDFWriter.GetModifiedInputFile());
if(!inputFile->GetInputStream())
{
THROW_EXCEPTION("unable to create modified input file...possibly a file is not being modified by this writer...");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewInputFile(args);
ObjectWrap::Unwrap<InputFileDriver>(newInstance->TO_OBJECT())->SetFromOwnedFile(inputFile);
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::GetOutputFile(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
OutputFile* outputFile = &(pdfWriter->mPDFWriter.GetOutputFile());
if(!outputFile->GetOutputStream())
{
THROW_EXCEPTION("unable to get output file. probably pdf writing hasn't started, or the output is not to a file");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
Local<Value> newInstance = pdfWriter->holder->GetNewOutputFile(args);
ObjectWrap::Unwrap<OutputFileDriver>(newInstance->TO_OBJECT())->SetFromOwnedFile(outputFile);
SET_FUNCTION_RETURN_VALUE(newInstance)
}
METHOD_RETURN_TYPE PDFWriterDriver::RegisterAnnotationReferenceForNextPageWrite(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
if(args.Length() != 1 ||
!args[0]->IsNumber())
{
THROW_EXCEPTION("wrong arguments, pass an object ID for an annotation to register");
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
pdfWriter->mPDFWriter.GetDocumentContext().RegisterAnnotationReferenceForNextPageWrite(TO_UINT32(args[0])->Value());
SET_FUNCTION_RETURN_VALUE(args.This())
}
METHOD_RETURN_TYPE PDFWriterDriver::RequireCatalogUpdate(const ARGS_TYPE& args)
{
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
PDFWriterDriver* pdfWriter = ObjectWrap::Unwrap<PDFWriterDriver>(args.This());
pdfWriter->mIsCatalogUpdateRequired = true;
SET_FUNCTION_RETURN_VALUE(UNDEFINED)
}
/*
From now on, extensions event triggers.
got the following events for now:
OnPageWrite: {
page:PDFPage,
pageDictionaryContext:DictionaryContext
}
OnResourcesWrite {
resources: ResourcesDictionary
pageResourcesDictionaryContext: DictionaryContext
}
OnResourceDictionaryWrite {
resourceDictionaryName: string
resourceDictionary: DictionaryContext
}
OnCatalogWrite {
catalogDictionaryContext: DictionaryContext
}
*/
PDFHummus::EStatusCode PDFWriterDriver::OnPageWrite(
PDFPage* inPage,
DictionaryContext* inPageDictionaryContext,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext) {
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
Local<Object> params = NEW_OBJECT;
params->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("page"),this->holder->GetInstanceFor(inPage));
params->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("pageDictionaryContext"), this->holder->GetInstanceFor(inPageDictionaryContext));
return triggerEvent("OnPageWrite",params);
}
PDFHummus::EStatusCode PDFWriterDriver::OnResourcesWrite(
ResourcesDictionary* inResources,
DictionaryContext* inPageResourcesDictionaryContext,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext) {
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
Local<Object> params = NEW_OBJECT;
params->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("resources"),this->holder->GetInstanceFor(inResources));
params->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("pageResourcesDictionaryContext"),this->holder->GetInstanceFor(inPageResourcesDictionaryContext));
return triggerEvent("OnResourcesWrite",params);
}
PDFHummus::EStatusCode PDFWriterDriver::OnResourceDictionaryWrite(
DictionaryContext* inResourceDictionary,
const std::string& inResourceDictionaryName,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext) {
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
Local<Object> params = NEW_OBJECT;
params->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("resourceDictionaryName"),NEW_STRING(inResourceDictionaryName.c_str()));
params->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("resourceDictionary"),this->holder->GetInstanceFor(inResourceDictionary));
return triggerEvent("OnResourceDictionaryWrite",params);
}
PDFHummus::EStatusCode PDFWriterDriver::OnFormXObjectWrite(
ObjectIDType inFormXObjectID,
ObjectIDType inFormXObjectResourcesDictionaryID,
DictionaryContext* inFormDictionaryContext,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext) {
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::OnJPEGImageXObjectWrite(
ObjectIDType inImageXObjectID,
DictionaryContext* inImageDictionaryContext,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext,
JPEGImageHandler* inJPGImageHandler) {
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::OnTIFFImageXObjectWrite(
ObjectIDType inImageXObjectID,
DictionaryContext* inImageDictionaryContext,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext,
TIFFImageHandler* inTIFFImageHandler) {
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::triggerEvent(const std::string& inEventName, v8::Local<v8::Object> inParams) {
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
Local<Value> value = THIS_HANDLE->Get(GET_CURRENT_CONTEXT, NEW_STRING("triggerDocumentExtensionEvent")).ToLocalChecked();
if(value->IsUndefined())
return PDFHummus::eFailure;
Local<Function> func = Local<Function>::Cast(value);
Local<Value> args[2];
args[0] = NEW_STRING(inEventName.c_str());
args[1] = inParams;
func->Call(GET_CURRENT_CONTEXT, THIS_HANDLE, 2, args).ToLocalChecked();
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::OnCatalogWrite(
CatalogInformation* inCatalogInformation,
DictionaryContext* inCatalogDictionaryContext,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext) {
CREATE_ISOLATE_CONTEXT;
CREATE_ESCAPABLE_SCOPE;
Local<Object> params = NEW_OBJECT;
// this is the only important one
params->Set(GET_CURRENT_CONTEXT, NEW_SYMBOL("catalogDictionaryContext"),this->holder->GetInstanceFor(inCatalogDictionaryContext));
return triggerEvent("OnCatalogWrite",params);
}
PDFHummus::EStatusCode PDFWriterDriver::OnPDFParsingComplete(
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext,
PDFDocumentHandler* inPDFDocumentHandler) {
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::OnBeforeCreateXObjectFromPage(
PDFDictionary* inPageObjectDictionary,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext,
PDFDocumentHandler* inPDFDocumentHandler) {
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::OnAfterCreateXObjectFromPage(
PDFFormXObject* iPageObjectResultXObject,
PDFDictionary* inPageObjectDictionary,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext,
PDFDocumentHandler* inPDFDocumentHandler) {
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::OnBeforeCreatePageFromPage(
PDFDictionary* inPageObjectDictionary,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext,
PDFDocumentHandler* inPDFDocumentHandler) {
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::OnAfterCreatePageFromPage(
PDFPage* iPageObjectResultPage,
PDFDictionary* inPageObjectDictionary,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext,
PDFDocumentHandler* inPDFDocumentHandler) {
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::OnBeforeMergePageFromPage(
PDFPage* inTargetPage,
PDFDictionary* inPageObjectDictionary,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext,
PDFDocumentHandler* inPDFDocumentHandler) {
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::OnAfterMergePageFromPage(
PDFPage* inTargetPage,
PDFDictionary* inPageObjectDictionary,
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext,
PDFDocumentHandler* inPDFDocumentHandler) {
return PDFHummus::eSuccess;
}
PDFHummus::EStatusCode PDFWriterDriver::OnPDFCopyingComplete(
ObjectsContext* inPDFWriterObjectContext,
PDFHummus::DocumentContext* inDocumentContext,
PDFDocumentHandler* inPDFDocumentHandler) {
return PDFHummus::eSuccess;
}
bool PDFWriterDriver::IsCatalogUpdateRequiredForModifiedFile(PDFParser* inModifiderFileParser) {
return mIsCatalogUpdateRequired;
}
PDFHummus::EStatusCode PDFWriterDriver::setupListenerIfOK(PDFHummus::EStatusCode inCode) {
if(inCode == PDFHummus::eSuccess)
mPDFWriter.GetDocumentContext().AddDocumentContextExtender(this);
return inCode;
}
| {
"pile_set_name": "Github"
} |
#!/bin/bash
#
# Starts a leader node
#
here=$(dirname "$0")
# shellcheck source=multinode-demo/common.sh
source "$here"/common.sh
# shellcheck source=scripts/oom-score-adj.sh
source "$here"/../scripts/oom-score-adj.sh
if [[ -d "$SNAP" ]]; then
# Exit if mode is not yet configured
# (typically the case after the Snap is first installed)
[[ -n "$(snapctl get mode)" ]] || exit 0
fi
[[ -f "$BUFFETT_CONFIG_DIR"/leader.json ]] || {
echo "$BUFFETT_CONFIG_DIR/leader.json not found, create it by running:"
echo
echo " ${here}/setup.sh"
exit 1
}
if [[ -n "$BUFFETT_CUDA" ]]; then
program="$buffett_fullnode_cuda"
else
program="$buffett_fullnode"
fi
tune_networking
trap 'kill "$pid" && wait "$pid"' INT TERM
buffett-fullnode \
--identity "$BUFFETT_CONFIG_DIR"/leader.json \
--ledger "$BUFFETT_CONFIG_DIR"/ledger \
> >($leader_logger) 2>&1 &
pid=$!
oom_score_adj "$pid" 1000
wait "$pid"
| {
"pile_set_name": "Github"
} |
# -*- mode: autoconf -*-
#
# gtk-doc.m4 - configure macro to check for gtk-doc
# Copyright (C) 2003 James Henstridge
# 2007-2017 Stefan Sauer
#
# 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/>.
#
# As a special exception, the above copyright owner gives unlimited
# permission to copy, distribute and modify the configure scripts that
# are the output of Autoconf when processing the Macro. You need not
# follow the terms of the GNU General Public License when using or
# distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
# serial 2
dnl Usage:
dnl GTK_DOC_CHECK([minimum-gtk-doc-version])
AC_DEFUN([GTK_DOC_CHECK],
[
AC_REQUIRE([PKG_PROG_PKG_CONFIG])
AC_BEFORE([AC_PROG_LIBTOOL],[$0])dnl setup libtool first
AC_BEFORE([AM_PROG_LIBTOOL],[$0])dnl setup libtool first
ifelse([$1],[],[gtk_doc_requires="gtk-doc"],[gtk_doc_requires="gtk-doc >= $1"])
AC_MSG_CHECKING([for gtk-doc])
PKG_CHECK_EXISTS([$gtk_doc_requires],[have_gtk_doc=yes],[have_gtk_doc=no])
AC_MSG_RESULT($have_gtk_doc)
if test "$have_gtk_doc" = "no"; then
AC_MSG_WARN([
You will not be able to create source packages with 'make dist'
because $gtk_doc_requires is not found.])
fi
dnl check for tools we added during development
dnl Use AC_CHECK_PROG to avoid the check target using an absolute path that
dnl may not be writable by the user. Currently, automake requires that the
dnl test name must end in '.test'.
dnl https://bugzilla.gnome.org/show_bug.cgi?id=701638
AC_CHECK_PROG([GTKDOC_CHECK],[gtkdoc-check],[gtkdoc-check.test])
AC_PATH_PROG([GTKDOC_CHECK_PATH],[gtkdoc-check])
AC_PATH_PROGS([GTKDOC_REBASE],[gtkdoc-rebase],[true])
AC_PATH_PROG([GTKDOC_MKPDF],[gtkdoc-mkpdf])
dnl for overriding the documentation installation directory
AC_ARG_WITH([html-dir],
AS_HELP_STRING([--with-html-dir=PATH], [path to installed docs]),,
[with_html_dir='${datadir}/gtk-doc/html'])
HTML_DIR="$with_html_dir"
AC_SUBST([HTML_DIR])
dnl enable/disable documentation building
AC_ARG_ENABLE([gtk-doc],
AS_HELP_STRING([--enable-gtk-doc],
[use gtk-doc to build documentation [[default=no]]]),,
[enable_gtk_doc=no])
AC_MSG_CHECKING([whether to build gtk-doc documentation])
AC_MSG_RESULT($enable_gtk_doc)
if test "x$enable_gtk_doc" = "xyes" && test "$have_gtk_doc" = "no"; then
AC_MSG_ERROR([
You must have $gtk_doc_requires installed to build documentation for
$PACKAGE_NAME. Please install gtk-doc or disable building the
documentation by adding '--disable-gtk-doc' to '[$]0'.])
fi
dnl don't check for glib if we build glib
if test "x$PACKAGE_NAME" != "xglib"; then
dnl don't fail if someone does not have glib
PKG_CHECK_MODULES(GTKDOC_DEPS, glib-2.0 >= 2.10.0 gobject-2.0 >= 2.10.0,,[:])
fi
dnl enable/disable output formats
AC_ARG_ENABLE([gtk-doc-html],
AS_HELP_STRING([--enable-gtk-doc-html],
[build documentation in html format [[default=yes]]]),,
[enable_gtk_doc_html=yes])
AC_ARG_ENABLE([gtk-doc-pdf],
AS_HELP_STRING([--enable-gtk-doc-pdf],
[build documentation in pdf format [[default=no]]]),,
[enable_gtk_doc_pdf=no])
if test -z "$GTKDOC_MKPDF"; then
enable_gtk_doc_pdf=no
fi
if test -z "$AM_DEFAULT_VERBOSITY"; then
AM_DEFAULT_VERBOSITY=1
fi
AC_SUBST([AM_DEFAULT_VERBOSITY])
AM_CONDITIONAL([HAVE_GTK_DOC], [test x$have_gtk_doc = xyes])
AM_CONDITIONAL([ENABLE_GTK_DOC], [test x$enable_gtk_doc = xyes])
AM_CONDITIONAL([GTK_DOC_BUILD_HTML], [test x$enable_gtk_doc_html = xyes])
AM_CONDITIONAL([GTK_DOC_BUILD_PDF], [test x$enable_gtk_doc_pdf = xyes])
AM_CONDITIONAL([GTK_DOC_USE_LIBTOOL], [test -n "$LIBTOOL"])
AM_CONDITIONAL([GTK_DOC_USE_REBASE], [test -n "$GTKDOC_REBASE"])
])
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
<article>
<title>Graph Tutorial 1</title>
<para>The GeoTools project strives to support as many geographical data
formats and opperations as possible.</para>
<para>The geotools2 graph package defines the concept of a graph (or
network) made up of geotools2 Features. The graph module strives to provide
a convient flexable and performant API for graph construction and query.</para>
<para>In additional to generic Graph support, Networks based on LineStrings
and Directed Networks have been implementations.</para>
<sect1>
<title>Graphing Terms</title>
<para>The Graph module makes use of concepts and (classes) from the
geotools2 core:<itemizedlist><listitem><para>Feature - atomic unit of
geographic information</para></listitem><listitem><para>FeatureType -
keeps track of what attributes each Feature can hold</para></listitem><listitem><para>FeatureID
- a unique id associated with each Feature (must start with a non-numeric
character)</para></listitem></itemizedlist>In addition to the Feature API
from core, the graph module makes use of relationships. Usually
relationships are based on spatial comparisions between features.</para>
<para>Example Relationships</para>
<itemizedlist>
<listitem>
<para>Graph constructed from LineStrings based on "shared end
points"</para>
</listitem>
<listitem>
<para>Graph constructed from Polygons based on "touches"</para>
</listitem>
</itemizedlist>
</sect1>
<sect1>
<title>Creating and using a Graph</title>
<para>Graph creations is handled using a Graph Builder. For those
familliar with the Builder Pattern (GOF Design Patterns) this will look
familliar.</para>
<para>Example of building a Line network:<programlisting>LineGraphBuilder lgb = new LineGraphBuilder();
FeatureSource fs = (FeatureSource)layers.get(typeName);
FeatureResults fr = fs.getFeatures();
FeatureCollection fc = fr.collection();
FeatureIterator f = fc.features();
while(f.hasNext()){
Feature ft = f.next();
if(envelope.contains(ft.getBounds()))
lgb.add(ft);
}
// lgb is loaded
Graph g = lgb.build();
</programlisting></para>
<para>To make use of your graph we will use a GraphVisitor (this is the
usual GOF Visitor pattern):</para>
<para>Example of making use of the network:<programlisting>class OrphanVisitor implements GraphVisitor{
private int count = 0;
public int getCount(){return count;}
public int visit(GraphComponent element){
if(element.getAdjacentElements().size()==0)
count++;
results.error(element.getFeature(),"Orphaned");
return GraphTraversal.CONTINUE;
}
}
OrphanVisitor ov = new OrphanVisitor();
SimpleGraphWalker sgv = new SimpleGraphWalker(ov);
BasicGraphTraversal bgt = new BasicGraphTraversal(g,sgv);
bgt.walkNodes();
if(ov.getCount()==0)
return true;
else
return false;</programlisting></para>
</sect1>
</article> | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef B2_CONTACT_SOLVER_H
#define B2_CONTACT_SOLVER_H
#include <Common/b2Math.h>
#include <Collision/b2Collision.h>
#include <Dynamics/b2TimeStep.h>
class b2Contact;
class b2Body;
class b2StackAllocator;
struct b2ContactPositionConstraint;
struct b2VelocityConstraintPoint
{
b2Vec2 rA;
b2Vec2 rB;
float32 normalImpulse;
float32 tangentImpulse;
float32 normalMass;
float32 tangentMass;
float32 velocityBias;
};
struct b2ContactVelocityConstraint
{
b2VelocityConstraintPoint points[b2_maxManifoldPoints];
b2Vec2 normal;
b2Mat22 normalMass;
b2Mat22 K;
int32 indexA;
int32 indexB;
float32 invMassA, invMassB;
float32 invIA, invIB;
float32 friction;
float32 restitution;
float32 tangentSpeed;
int32 pointCount;
int32 contactIndex;
};
struct b2ContactSolverDef
{
b2TimeStep step;
b2Contact** contacts;
int32 count;
b2Position* positions;
b2Velocity* velocities;
b2StackAllocator* allocator;
};
class b2ContactSolver
{
public:
b2ContactSolver(b2ContactSolverDef* def);
~b2ContactSolver();
void InitializeVelocityConstraints();
void WarmStart();
void SolveVelocityConstraints();
void StoreImpulses();
bool SolvePositionConstraints();
bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB);
b2TimeStep m_step;
b2Position* m_positions;
b2Velocity* m_velocities;
b2StackAllocator* m_allocator;
b2ContactPositionConstraint* m_positionConstraints;
b2ContactVelocityConstraint* m_velocityConstraints;
b2Contact** m_contacts;
int m_count;
};
#endif
| {
"pile_set_name": "Github"
} |
FROM buildpack-deps:stretch-curl
MAINTAINER Manfred Touron <[email protected]> (https://github.com/moul)
# Install deps
RUN set -x; echo "Starting image build for Debian Stretch" \
&& dpkg --add-architecture arm64 \
&& dpkg --add-architecture armel \
&& dpkg --add-architecture armhf \
&& dpkg --add-architecture i386 \
&& dpkg --add-architecture mips \
&& dpkg --add-architecture mipsel \
&& dpkg --add-architecture powerpc \
&& dpkg --add-architecture ppc64el \
&& apt-get update \
&& apt-get install -y -q \
autoconf \
automake \
autotools-dev \
bc \
binfmt-support \
binutils-multiarch \
binutils-multiarch-dev \
build-essential \
clang \
crossbuild-essential-arm64 \
crossbuild-essential-armel \
crossbuild-essential-armhf \
crossbuild-essential-mipsel \
crossbuild-essential-ppc64el \
curl \
devscripts \
gdb \
git-core \
libtool \
llvm \
mercurial \
multistrap \
patch \
software-properties-common \
subversion \
wget \
xz-utils \
cmake \
qemu-user-static \
libxml2-dev \
lzma-dev \
openssl \
libssl-dev \
&& apt-get clean
# FIXME: install gcc-multilib
# FIXME: add mips and powerpc architectures
# Install Windows cross-tools
RUN apt-get install -y mingw-w64 \
&& apt-get clean
# Install OSx cross-tools
#Build arguments
ARG osxcross_repo="tpoechtrager/osxcross"
ARG osxcross_revision="542acc2ef6c21aeb3f109c03748b1015a71fed63"
ARG darwin_sdk_version="10.10"
ARG darwin_osx_version_min="10.6"
ARG darwin_version="14"
ARG darwin_sdk_url="https://www.dropbox.com/s/yfbesd249w10lpc/MacOSX${darwin_sdk_version}.sdk.tar.xz"
# ENV available in docker image
ENV OSXCROSS_REPO="${osxcross_repo}" \
OSXCROSS_REVISION="${osxcross_revision}" \
DARWIN_SDK_VERSION="${darwin_sdk_version}" \
DARWIN_VERSION="${darwin_version}" \
DARWIN_OSX_VERSION_MIN="${darwin_osx_version_min}" \
DARWIN_SDK_URL="${darwin_sdk_url}"
RUN mkdir -p "/tmp/osxcross" \
&& cd "/tmp/osxcross" \
&& curl -sLo osxcross.tar.gz "https://codeload.github.com/${OSXCROSS_REPO}/tar.gz/${OSXCROSS_REVISION}" \
&& tar --strip=1 -xzf osxcross.tar.gz \
&& rm -f osxcross.tar.gz \
&& curl -sLo tarballs/MacOSX${DARWIN_SDK_VERSION}.sdk.tar.xz \
"${DARWIN_SDK_URL}" \
&& yes "" | SDK_VERSION="${DARWIN_SDK_VERSION}" OSX_VERSION_MIN="${DARWIN_OSX_VERSION_MIN}" ./build.sh \
&& mv target /usr/osxcross \
&& mv tools /usr/osxcross/ \
&& ln -sf ../tools/osxcross-macports /usr/osxcross/bin/omp \
&& ln -sf ../tools/osxcross-macports /usr/osxcross/bin/osxcross-macports \
&& ln -sf ../tools/osxcross-macports /usr/osxcross/bin/osxcross-mp \
&& rm -rf /tmp/osxcross \
&& rm -rf "/usr/osxcross/SDK/MacOSX${DARWIN_SDK_VERSION}.sdk/usr/share/man"
# Create symlinks for triples and set default CROSS_TRIPLE
ENV LINUX_TRIPLES=arm-linux-gnueabi,arm-linux-gnueabihf,aarch64-linux-gnu,mipsel-linux-gnu,powerpc64le-linux-gnu \
DARWIN_TRIPLES=x86_64h-apple-darwin${DARWIN_VERSION},x86_64-apple-darwin${DARWIN_VERSION},i386-apple-darwin${DARWIN_VERSION} \
WINDOWS_TRIPLES=i686-w64-mingw32,x86_64-w64-mingw32 \
CROSS_TRIPLE=x86_64-linux-gnu
COPY ./assets/osxcross-wrapper /usr/bin/osxcross-wrapper
RUN mkdir -p /usr/x86_64-linux-gnu; \
for triple in $(echo ${LINUX_TRIPLES} | tr "," " "); do \
for bin in /usr/bin/$triple-*; do \
if [ ! -f /usr/$triple/bin/$(basename $bin | sed "s/$triple-//") ]; then \
ln -s $bin /usr/$triple/bin/$(basename $bin | sed "s/$triple-//"); \
fi; \
done; \
for bin in /usr/bin/$triple-*; do \
if [ ! -f /usr/$triple/bin/cc ]; then \
ln -s gcc /usr/$triple/bin/cc; \
fi; \
done; \
done && \
for triple in $(echo ${DARWIN_TRIPLES} | tr "," " "); do \
mkdir -p /usr/$triple/bin; \
for bin in /usr/osxcross/bin/$triple-*; do \
ln /usr/bin/osxcross-wrapper /usr/$triple/bin/$(basename $bin | sed "s/$triple-//"); \
done && \
rm -f /usr/$triple/bin/clang*; \
ln -s cc /usr/$triple/bin/gcc; \
ln -s /usr/osxcross/SDK/MacOSX${DARWIN_SDK_VERSION}.sdk/usr /usr/x86_64-linux-gnu/$triple; \
done; \
for triple in $(echo ${WINDOWS_TRIPLES} | tr "," " "); do \
mkdir -p /usr/$triple/bin; \
for bin in /etc/alternatives/$triple-* /usr/bin/$triple-*; do \
if [ ! -f /usr/$triple/bin/$(basename $bin | sed "s/$triple-//") ]; then \
ln -s $bin /usr/$triple/bin/$(basename $bin | sed "s/$triple-//"); \
fi; \
done; \
ln -s gcc /usr/$triple/bin/cc; \
ln -s /usr/$triple /usr/x86_64-linux-gnu/$triple; \
done
# we need to use default clang binary to avoid a bug in osxcross that recursively call himself
# with more and more parameters
ENV LD_LIBRARY_PATH /usr/osxcross/lib:$LD_LIBRARY_PATH
# Image metadata
ENTRYPOINT ["/usr/bin/crossbuild"]
CMD ["/bin/bash"]
WORKDIR /workdir
COPY ./assets/crossbuild /usr/bin/crossbuild
| {
"pile_set_name": "Github"
} |
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard.
//
#import "TBaseEncryptionPasswordViewController.h"
@class TTextField;
@interface TDecryptionPasswordViewController : TBaseEncryptionPasswordViewController
{
TTextField *_mainTextFld;
TTextField *_instructionsFld;
}
- (void)okButtonPressed:(id)arg1;
- (void)setVolumeNode:(const struct TFENode *)arg1;
- (void)viewLoaded;
@end
| {
"pile_set_name": "Github"
} |
#include "D:\AutoIt\Include\WinAPI.au3"
$Width = _WinAPI_GetSystemMetrics(78)
$High = _WinAPI_GetSystemMetrics(79)
select
case StringLower($CmdLine[1]) = "mouse"
$x = int($CmdLine[2])
$y = int($CmdLine[3])
$click = 0
if $CmdLine[0] > 3 then $click = int($CmdLine[4])
if $x < 0 then $x = $Width/2
if $y < 0 then $y = $High/2
if $click < 1 then
MouseMove($x, $y, 0)
else
MouseClick("left", $x, $y, $click, 0)
endif
case StringLower($CmdLine[1]) = "key"
if $CmdLine[0] > 2 then AutoItSetOption("SendKeyDelay", int($CmdLine[3]))
Send($CmdLine[2])
endselect | {
"pile_set_name": "Github"
} |
__all__ = ['energies']
| {
"pile_set_name": "Github"
} |
-- EMACS settings: -*- tab-width: 2; indent-tabs-mode: t -*-
-- vim: tabstop=2:shiftwidth=2:noexpandtab
-- kate: tab-width 2; replace-tabs off; indent-width 2;
-- =============================================================================
-- Authors: Patrick Lehmann
--
-- Entity: A generic buffer module for the PoC.Stream protocol.
--
-- Description:
-- -------------------------------------
-- .. TODO:: No documentation available.
--
-- License:
-- =============================================================================
-- Copyright 2007-2015 Technische Universitaet Dresden - Germany
-- Chair of VLSI-Design, Diagnostics and Architecture
--
-- 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.
-- =============================================================================
library IEEE;
use IEEE.STD_LOGIC_1164.all;
use IEEE.NUMERIC_STD.all;
library PoC;
use PoC.config.all;
use PoC.utils.all;
use PoC.vectors.all;
entity stream_DeMux is
generic (
PORTS : positive := 2;
DATA_BITS : positive := 8;
META_BITS : natural := 8;
META_REV_BITS : natural := 2
);
port (
Clock : in std_logic;
Reset : in std_logic;
-- Control interface
DeMuxControl : in std_logic_vector(PORTS - 1 downto 0);
-- IN Port
In_Valid : in std_logic;
In_Data : in std_logic_vector(DATA_BITS - 1 downto 0);
In_Meta : in std_logic_vector(META_BITS - 1 downto 0);
In_Meta_rev : out std_logic_vector(META_REV_BITS - 1 downto 0);
In_SOF : in std_logic;
In_EOF : in std_logic;
In_Ack : out std_logic;
-- OUT Ports
Out_Valid : out std_logic_vector(PORTS - 1 downto 0);
Out_Data : out T_SLM(PORTS - 1 downto 0, DATA_BITS - 1 downto 0);
Out_Meta : out T_SLM(PORTS - 1 downto 0, META_BITS - 1 downto 0);
Out_Meta_rev : in T_SLM(PORTS - 1 downto 0, META_REV_BITS - 1 downto 0);
Out_SOF : out std_logic_vector(PORTS - 1 downto 0);
Out_EOF : out std_logic_vector(PORTS - 1 downto 0);
Out_Ack : in std_logic_vector(PORTS - 1 downto 0)
);
end entity;
architecture rtl of stream_DeMux is
attribute KEEP : boolean;
attribute FSM_ENCODING : string;
subtype T_CHANNEL_INDEX is natural range 0 to PORTS - 1;
type T_STATE is (ST_IDLE, ST_DATAFLOW, ST_DISCARD_FRAME);
signal State : T_STATE := ST_IDLE;
signal NextState : T_STATE;
signal Is_SOF : std_logic;
signal Is_EOF : std_logic;
signal In_Ack_i : std_logic;
signal Out_Valid_i : std_logic;
signal DiscardFrame : std_logic;
signal ChannelPointer_rst : std_logic;
signal ChannelPointer_en : std_logic;
signal ChannelPointer : std_logic_vector(PORTS - 1 downto 0);
signal ChannelPointer_d : std_logic_vector(PORTS - 1 downto 0) := (others => '0');
signal ChannelPointer_bin : unsigned(log2ceilnz(PORTS) - 1 downto 0);
signal idx : T_CHANNEL_INDEX;
signal Out_Data_i : T_SLM(PORTS - 1 downto 0, DATA_BITS - 1 downto 0) := (others => (others => 'Z')); -- necessary default assignment 'Z' to get correct simulation results (iSIM, vSIM, ghdl/gtkwave)
signal Out_Meta_i : T_SLM(PORTS - 1 downto 0, META_BITS - 1 downto 0) := (others => (others => 'Z')); -- necessary default assignment 'Z' to get correct simulation results (iSIM, vSIM, ghdl/gtkwave)
begin
In_Ack_i <= slv_or(Out_Ack and ChannelPointer);
DiscardFrame <= slv_nor(DeMuxControl);
Is_SOF <= In_Valid and In_SOF;
Is_EOF <= In_Valid and In_EOF;
process(Clock)
begin
if rising_edge(Clock) then
if (Reset = '1') then
State <= ST_IDLE;
else
State <= NextState;
end if;
end if;
end process;
process(State, In_Ack_i, In_Valid, Is_SOF, Is_EOF, DiscardFrame, DeMuxControl, ChannelPointer_d)
begin
NextState <= State;
ChannelPointer_rst <= Is_EOF;
ChannelPointer_en <= '0';
ChannelPointer <= ChannelPointer_d;
In_Ack <= '0';
Out_Valid_i <= '0';
case State is
when ST_IDLE =>
ChannelPointer <= DeMuxControl;
if (Is_SOF = '1') then
if (DiscardFrame = '0') then
ChannelPointer_en <= '1';
In_Ack <= In_Ack_i;
Out_Valid_i <= '1';
NextState <= ST_DATAFLOW;
else
In_Ack <= '1';
NextState <= ST_DISCARD_FRAME;
end if;
end if;
when ST_DATAFLOW =>
In_Ack <= In_Ack_i;
Out_Valid_i <= In_Valid;
ChannelPointer <= ChannelPointer_d;
if (Is_EOF = '1') then
NextState <= ST_IDLE;
end if;
when ST_DISCARD_FRAME =>
In_Ack <= '1';
if (Is_EOF = '1') then
NextState <= ST_IDLE;
end if;
end case;
end process;
process(Clock)
begin
if rising_edge(Clock) then
if ((Reset or ChannelPointer_rst) = '1') then
ChannelPointer_d <= (others => '0');
elsif (ChannelPointer_en = '1') then
ChannelPointer_d <= DeMuxControl;
end if;
end if;
end process;
ChannelPointer_bin <= onehot2bin(ChannelPointer_d);
idx <= to_integer(ChannelPointer_bin);
In_Meta_rev <= get_row(Out_Meta_rev, idx);
genOutput : for i in 0 to PORTS - 1 generate
Out_Valid(i) <= Out_Valid_i and ChannelPointer(i);
assign_row(Out_Data_i, In_Data, i);
assign_row(Out_Meta_i, In_Meta, i);
Out_SOF(i) <= In_SOF;
Out_EOF(i) <= In_EOF;
end generate;
Out_Data <= Out_Data_i;
Out_Meta <= Out_Meta_i;
end architecture;
| {
"pile_set_name": "Github"
} |
#%RAML 1.0
title: Api
types:
MyType: |
{
"$schema":"http://json-schema.org/draft-04/schema",
"type":"object",
"properties":{
"child":{"$ref": "scheme.json#"}
},
"required": [ "child" ]
}
/resource:
get:
body:
application/json:
type: MyType
example:
child:
name1: somename
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_39) on Wed Mar 11 11:15:18 CST 2015 -->
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
com.sina.weibo.sdk.api.share 类分层结构
</TITLE>
<META NAME="date" CONTENT="2015-03-11">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.sina.weibo.sdk.api.share 类分层结构";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<HR>
<CENTER>
<H2>
软件包 com.sina.weibo.sdk.api.share 的分层结构
</H2>
</CENTER>
<DL>
<DT><B>软件包分层结构:</B><DD><A HREF="../../../../../../overview-tree.html">所有软件包</A></DL>
<HR>
<H2>
类分层结构
</H2>
<UL>
<LI TYPE="circle">java.lang.Object<UL>
<LI TYPE="circle">com.sina.weibo.sdk.api.share.<A HREF="../../../../../../com/sina/weibo/sdk/api/share/WeiboShareSDK.html" title="com.sina.weibo.sdk.api.share 中的类"><B>WeiboShareSDK</B></A></UL>
</UL>
<H2>
接口分层结构
</H2>
<UL>
<LI TYPE="circle">com.sina.weibo.sdk.api.share.<A HREF="../../../../../../com/sina/weibo/sdk/api/share/IWeiboShareAPI.html" title="com.sina.weibo.sdk.api.share 中的接口"><B>IWeiboShareAPI</B></A></UL>
<HR>
<HR>
</BODY>
</HTML>
| {
"pile_set_name": "Github"
} |
@namespace AntDesign
@inherits AntDomComponentBase
<CascadingValue Value=this>
<div class="@ClassMapper.Class">@Label</div>
@ChildContent
</CascadingValue>
| {
"pile_set_name": "Github"
} |
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"declarationDir": "./dist",
"outDir": "./dist"
},
"include": ["src", "src/**/*.json", "statics/**/*.json", "./package.json", "lib"],
"exclude": ["node_modules", "**/*.spec.*"]
}
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env wish
#==============================================================================
# Demonstrates the interactive tablelist cell editing with the aid of some
# widgets from the Iwidgets package and of the Tk core checkbutton and
# menubutton widgets.
#
# Copyright (c) 2004-2015 Csaba Nemethi (E-mail: [email protected])
#==============================================================================
package require tablelist_tile 5.14
package require Iwidgets
wm title . "Serial Line Configuration"
#
# Add some entries to the Tk option database
#
set dir [file dirname [info script]]
source [file join $dir option_tile.tcl]
option add *Tablelist*Checkbutton.background white
option add *Tablelist*Checkbutton.activeBackground white
option add *Tablelist*textBackground white
option add *Tablelist*Entry.disabledBackground white
option add *Tablelist*Entry.disabledForeground black
option add *Tablelist*Dateentry*Label.background white
option add *Tablelist*Timeentry*Label.background white
#
# Register some widgets from the Iwidgets package for interactive cell editing
#
tablelist::addIncrEntryfield
tablelist::addIncrSpinint
tablelist::addIncrCombobox
tablelist::addIncrDateTimeWidget dateentry -seconds
tablelist::addIncrDateTimeWidget timeentry -seconds
#
# Create the images "checkedImg" and "uncheckedImg", as well as 16 images of
# names like "img#FF0000", displaying colors identified by names like "red"
#
source [file join $dir images.tcl]
#
# Improve the window's appearance by using a tile
# frame as a container for the other widgets
#
set f [ttk::frame .f]
#
# Create a tablelist widget with editable columns (except the first one)
#
set tbl $f.tbl
tablelist::tablelist $tbl \
-columns {0 "No." right
0 "Available" center
0 "Name" left
0 "Baud Rate" right
0 "Data Bits" center
0 "Parity" left
0 "Stop Bits" center
0 "Handshake" left
0 "Activation Date" center
0 "Activation Time" center
0 "Cable Color" center} \
-editstartcommand editStartCmd -editendcommand editEndCmd \
-height 0 -width 0
if {[$tbl cget -selectborderwidth] == 0} {
$tbl configure -spacing 1
}
$tbl columnconfigure 0 -sortmode integer
$tbl columnconfigure 1 -name available -editable yes -editwindow checkbutton \
-formatcommand emptyStr
$tbl columnconfigure 2 -name lineName -editable yes -editwindow entryfield \
-sortmode dictionary
$tbl columnconfigure 3 -name baudRate -editable yes -editwindow combobox \
-sortmode integer
$tbl columnconfigure 4 -name dataBits -editable yes -editwindow spinint
$tbl columnconfigure 5 -name parity -editable yes -editwindow combobox
$tbl columnconfigure 6 -name stopBits -editable yes -editwindow combobox
$tbl columnconfigure 7 -name handshake -editable yes -editwindow combobox
$tbl columnconfigure 8 -name actDate -editable yes -editwindow dateentry \
-formatcommand formatDate -sortmode integer
$tbl columnconfigure 9 -name actTime -editable yes -editwindow timeentry \
-formatcommand formatTime -sortmode integer
$tbl columnconfigure 10 -name color -editable yes -editwindow menubutton \
-formatcommand emptyStr
proc emptyStr val { return "" }
proc formatDate val { return [clock format $val -format "%Y-%m-%d"] }
proc formatTime val { return [clock format $val -format "%H:%M:%S"] }
#
# Populate the tablelist widget; set the activation
# date & time to 10 minutes past the current clock value
#
set clock [expr {[clock seconds] + 600}]
for {set i 0; set n 1} {$i < 16} {set i $n; incr n} {
$tbl insert end [list $n [expr {$i < 8}] "Line $n" 9600 8 None 1 XON/XOFF \
$clock $clock [lindex $colorNames $i]]
set availImg [expr {($i < 8) ? "checkedImg" : "uncheckedImg"}]
$tbl cellconfigure end,available -image $availImg
$tbl cellconfigure end,color -image img[lindex $colorValues $i]
}
set btn [ttk::button $f.btn -text "Close" -command exit]
#
# Manage the widgets
#
pack $btn -side bottom -pady 10
pack $tbl -side top -expand yes -fill both
pack $f -expand yes -fill both
#------------------------------------------------------------------------------
# editStartCmd
#
# Applies some configuration options to the edit window; if the latter is a
# combobox, the procedure populates it.
#------------------------------------------------------------------------------
proc editStartCmd {tbl row col text} {
set w [$tbl editwinpath]
switch [$tbl columncget $col -name] {
lineName {
#
# Set an upper limit of 20 for the number of characters
#
$w configure -pasting no -fixed 20
}
baudRate {
#
# Populate the combobox and allow no more
# than 6 digits in its entry component
#
$w insert list end 50 75 110 300 1200 2400 4800 9600 19200 38400 \
57600 115200 230400 460800 921600
$w configure -pasting no -fixed 6 -validate numeric
}
dataBits {
#
# Configure the spinint widget
#
$w configure -range {5 8} -wrap no -pasting no -fixed 1 \
-validate {regexp {^[5-8]$} %c}
}
parity {
#
# Populate the combobox and make it non-editable
#
$w insert list end None Even Odd Mark Space
$w configure -editable no -listheight 120
}
stopBits {
#
# Populate the combobox and make it non-editable
#
$w insert list end 1 1.5 2
$w configure -editable no -listheight 90
}
handshake {
#
# Populate the combobox and make it non-editable
#
$w insert list end XON/XOFF RTS/CTS None
$w configure -editable no -listheight 90
}
actDate {
#
# Set the date format "%Y-%m-%d"
#
$w configure -int yes
}
actTime {
#
# Set the time format "%H:%M:%S"
#
$w configure -format military
}
color {
#
# Populate the menu and make sure the menubutton will display the
# color name rather than $text, which is "", due to -formatcommand
#
set menu [$w cget -menu]
foreach name $::colorNames {
$menu add radiobutton -compound left \
-image img$::colors($name) -label $name
}
$menu entryconfigure 8 -columnbreak 1
return [$tbl cellcget $row,$col -text]
}
}
return $text
}
#------------------------------------------------------------------------------
# editEndCmd
#
# Performs a final validation of the text contained in the edit window and gets
# the cell's internal contents.
#------------------------------------------------------------------------------
proc editEndCmd {tbl row col text} {
switch [$tbl columncget $col -name] {
available {
#
# Update the image contained in the cell
#
set img [expr {$text ? "checkedImg" : "uncheckedImg"}]
$tbl cellconfigure $row,$col -image $img
}
baudRate {
#
# Check whether the baud rate is an integer in the range 50..921600
#
if {![regexp {^[0-9]+$} $text] || $text < 50 || $text > 921600} {
bell
tk_messageBox -title "Error" -icon error -message \
"The baud rate must be an integer in the range 50..921600"
$tbl rejectinput
}
}
dataBits {
#
# Check whether the # of data bits is an integer in the range 5..8
#
if {![regexp {^[5-8]$} $text]} {
bell
tk_messageBox -title "Error" -icon error -message \
"The # of data bits must be an integer in the range 5..8"
$tbl rejectinput
}
}
actDate {
#
# Check whether the activation clock value is later than the
# current one; if this is the case then make sure the cells
# "actDate" and "actTime" will have the same internal value
#
set actTime [$tbl cellcget $row,actTime -text]
set actClock [clock scan [formatTime $actTime] -base $text]
if {$actClock <= [clock seconds]} {
bell
tk_messageBox -title "Error" -icon error -message \
"The activation date & time must be in the future"
$tbl rejectinput
} else {
$tbl cellconfigure $row,actTime -text $actClock
return $actClock
}
}
actTime {
#
# Check whether the activation clock value is later than the
# current one; if this is the case then make sure the cells
# "actDate" and "actTime" will have the same internal value
#
set actDate [$tbl cellcget $row,actDate -text]
set actClock [clock scan [formatTime $text] -base $actDate]
if {$actClock <= [clock seconds]} {
bell
tk_messageBox -title "Error" -icon error -message \
"The activation date & time must be in the future"
$tbl rejectinput
} else {
$tbl cellconfigure $row,actDate -text $actClock
return $actClock
}
}
color {
#
# Update the image contained in the cell
#
$tbl cellconfigure $row,$col -image img$::colors($text)
}
}
return $text
}
| {
"pile_set_name": "Github"
} |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CsQuery.Utility;
using CsQuery.ExtensionMethods;
using CsQuery.ExtensionMethods.Internal;
using CsQuery.Engine;
using CsQuery.Implementation;
namespace CsQuery
{
public partial class CQ
{
#region public methods
/// <summary>
/// Get the immediately preceding sibling of each element in the set of matched elements,
/// optionally filtered by a selector.
/// </summary>
///
/// <param name="selector">
/// A string containing a selector expression to match elements against.
/// </param>
///
/// <returns>
/// A new CQ object
/// </returns>
///
/// <url>
/// http://api.jquery.com/prev/
/// </url>
public CQ Prev(string selector = null)
{
return nextPrevImpl(selector, false);
}
/// <summary>
/// Get the immediately following sibling of each element in the set of matched elements. If a
/// selector is provided, it retrieves the next sibling only if it matches that selector.
/// </summary>
///
/// <param name="selector">
/// A string containing a selector expression to match elements against.
/// </param>
///
/// <returns>
/// A new CQ object.
/// </returns>
///
/// <url>
/// http://api.jquery.com/next/
/// </url>
public CQ Next(string selector = null)
{
return nextPrevImpl(selector, true);
}
/// <summary>
/// Get all following siblings of each element in the set of matched elements, optionally
/// filtered by a selector.
/// </summary>
///
/// <param name="filter">
/// A selector that must match each element returned.
/// </param>
///
/// <returns>
/// A new CQ object
/// </returns>
///
/// <url>
/// http://api.jquery.com/nextAll/
/// </url>
public CQ NextAll(string filter = null)
{
return nextPrevAllImpl(filter, true);
}
/// <summary>
/// Get all following siblings of each element up to but not including the element matched by the
/// selector, optionally filtered by a selector.
/// </summary>
///
/// <param name="selector">
/// A selector that must match each element returned.
/// </param>
/// <param name="filter">
/// A selector use to filter each result
/// </param>
///
/// <returns>
/// A new CQ object
/// </returns>
///
/// <url>
/// http://api.jquery.com/nextUntil/
/// </url>
public CQ NextUntil(string selector = null, string filter = null)
{
return nextPrevUntilImpl(selector, filter, true);
}
/// <summary>
/// Get all preceding siblings of each element in the set of matched elements, optionally
/// filtered by a selector.
/// </summary>
///
/// <param name="filter">
/// A selector that must match each element returned.
/// </param>
///
/// <returns>
/// A new CQ object
/// </returns>
///
/// <url>
/// http://api.jquery.com/prevAll/
/// </url>
public CQ PrevAll(string filter = null)
{
return nextPrevAllImpl(filter, false);
}
/// <summary>
/// Get all preceding siblings of each element up to but not including the element matched by the
/// selector, optionally filtered by a selector.
/// </summary>
///
/// <param name="selector">
/// A selector that must match each element returned.
/// </param>
/// <param name="filter">
/// A selector use to filter each result.
/// </param>
///
/// <returns>
/// A new CQ object.
/// </returns>
///
/// <url>
/// http://api.jquery.com/prevUntil/
/// </url>
public CQ PrevUntil(string selector = null, string filter = null)
{
return nextPrevUntilImpl(selector, filter, false);
}
#endregion
#region private methods
private CQ nextPrevImpl(string selector, bool next)
{
IEnumerable<IDomElement> siblings;
SelectionSetOrder order;
if (next) {
siblings = Elements.Select(item=>item.NextElementSibling).Where(item=>item != null);
order = SelectionSetOrder.Ascending;
} else {
siblings = Elements.Select(item => item.PreviousElementSibling).Where(item => item != null);
order = SelectionSetOrder.Descending ;
}
return FilterIfSelector(selector,siblings,order);
}
private CQ nextPrevAllImpl(string filter, bool next)
{
return FilterIfSelector(filter, MapRangeToNewCQ(Elements, (input) =>
{
return nextPrevAllImpl(input, next);
}), next ? SelectionSetOrder.Ascending : SelectionSetOrder.Descending);
}
private CQ nextPrevUntilImpl(string selector, string filter, bool next)
{
if (string.IsNullOrEmpty(selector))
{
return next ? NextAll(filter) : PrevAll(filter);
}
HashSet<IDomElement> untilEls = new HashSet<IDomElement>(Select(selector).Elements);
return FilterIfSelector(filter, MapRangeToNewCQ(Elements, (input) =>
{
return nextPrevUntilFilterImpl(input, untilEls, next);
}), next ? SelectionSetOrder.Ascending : SelectionSetOrder.Descending);
}
private IEnumerable<IDomObject> nextPrevAllImpl(IDomObject input, bool next)
{
IDomObject item = next ? input.NextElementSibling : input.PreviousElementSibling;
while (item != null)
{
yield return item;
item = next ? item.NextElementSibling : item.PreviousElementSibling;
}
}
private IEnumerable<IDomObject> nextPrevUntilFilterImpl(IDomObject input, HashSet<IDomElement> untilEls, bool next)
{
foreach (IDomElement el in nextPrevAllImpl(input, next))
{
if (untilEls.Contains(el))
{
break;
}
yield return el;
}
}
#endregion
}
}
| {
"pile_set_name": "Github"
} |
namespace WebApi
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Modules;
using Modules.Common;
using Modules.Common.FeatureFlags;
using Modules.Common.Swagger;
using Prometheus;
/// <summary>
/// Startup.
/// </summary>
public sealed class Startup
{
/// <summary>
/// Startup constructor.
/// </summary>
public Startup(IConfiguration configuration) => this.Configuration = configuration;
private IConfiguration Configuration { get; }
/// <summary>
/// Configure dependencies from application.
/// </summary>
public void ConfigureServices(IServiceCollection services)
{
services
.AddFeatureFlags(this.Configuration) // should be the first one.
.AddInvalidRequestLogging()
.AddCurrencyExchange(this.Configuration)
.AddSQLServer(this.Configuration)
.AddHealthChecks(this.Configuration)
.AddAuthentication(this.Configuration)
.AddVersioning()
.AddSwagger()
.AddUseCases()
.AddCustomControllers()
.AddCustomCors()
.AddProxy()
.AddCustomDataProtection();
}
/// <summary>
/// Configure http request pipeline.
/// </summary>
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env,
IApiVersionDescriptionProvider provider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/api/V1/CustomError")
.UseHsts();
}
app
.UseProxy(this.Configuration)
.UseHealthChecks()
.UseCustomCors()
.UseCustomHttpMetrics()
.UseRouting()
.UseVersionedSwagger(provider, this.Configuration, env)
.UseAuthentication()
.UseAuthorization()
.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapMetrics();
});
}
}
}
| {
"pile_set_name": "Github"
} |
// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/lockd/host.c
*
* Management for NLM peer hosts. The nlm_host struct is shared
* between client and server implementation. The only reason to
* do so is to reduce code bloat.
*
* Copyright (C) 1996, Olaf Kirch <[email protected]>
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/sunrpc/clnt.h>
#include <linux/sunrpc/addr.h>
#include <linux/sunrpc/svc.h>
#include <linux/lockd/lockd.h>
#include <linux/mutex.h>
#include <linux/sunrpc/svc_xprt.h>
#include <net/ipv6.h>
#include "netns.h"
#define NLMDBG_FACILITY NLMDBG_HOSTCACHE
#define NLM_HOST_NRHASH 32
#define NLM_HOST_REBIND (60 * HZ)
#define NLM_HOST_EXPIRE (300 * HZ)
#define NLM_HOST_COLLECT (120 * HZ)
static struct hlist_head nlm_server_hosts[NLM_HOST_NRHASH];
static struct hlist_head nlm_client_hosts[NLM_HOST_NRHASH];
#define for_each_host(host, chain, table) \
for ((chain) = (table); \
(chain) < (table) + NLM_HOST_NRHASH; ++(chain)) \
hlist_for_each_entry((host), (chain), h_hash)
#define for_each_host_safe(host, next, chain, table) \
for ((chain) = (table); \
(chain) < (table) + NLM_HOST_NRHASH; ++(chain)) \
hlist_for_each_entry_safe((host), (next), \
(chain), h_hash)
static unsigned long nrhosts;
static DEFINE_MUTEX(nlm_host_mutex);
static void nlm_gc_hosts(struct net *net);
struct nlm_lookup_host_info {
const int server; /* search for server|client */
const struct sockaddr *sap; /* address to search for */
const size_t salen; /* it's length */
const unsigned short protocol; /* transport to search for*/
const u32 version; /* NLM version to search for */
const char *hostname; /* remote's hostname */
const size_t hostname_len; /* it's length */
const int noresvport; /* use non-priv port */
struct net *net; /* network namespace to bind */
};
/*
* Hash function must work well on big- and little-endian platforms
*/
static unsigned int __nlm_hash32(const __be32 n)
{
unsigned int hash = (__force u32)n ^ ((__force u32)n >> 16);
return hash ^ (hash >> 8);
}
static unsigned int __nlm_hash_addr4(const struct sockaddr *sap)
{
const struct sockaddr_in *sin = (struct sockaddr_in *)sap;
return __nlm_hash32(sin->sin_addr.s_addr);
}
static unsigned int __nlm_hash_addr6(const struct sockaddr *sap)
{
const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sap;
const struct in6_addr addr = sin6->sin6_addr;
return __nlm_hash32(addr.s6_addr32[0]) ^
__nlm_hash32(addr.s6_addr32[1]) ^
__nlm_hash32(addr.s6_addr32[2]) ^
__nlm_hash32(addr.s6_addr32[3]);
}
static unsigned int nlm_hash_address(const struct sockaddr *sap)
{
unsigned int hash;
switch (sap->sa_family) {
case AF_INET:
hash = __nlm_hash_addr4(sap);
break;
case AF_INET6:
hash = __nlm_hash_addr6(sap);
break;
default:
hash = 0;
}
return hash & (NLM_HOST_NRHASH - 1);
}
/*
* Allocate and initialize an nlm_host. Common to both client and server.
*/
static struct nlm_host *nlm_alloc_host(struct nlm_lookup_host_info *ni,
struct nsm_handle *nsm)
{
struct nlm_host *host = NULL;
unsigned long now = jiffies;
if (nsm != NULL)
refcount_inc(&nsm->sm_count);
else {
host = NULL;
nsm = nsm_get_handle(ni->net, ni->sap, ni->salen,
ni->hostname, ni->hostname_len);
if (unlikely(nsm == NULL)) {
dprintk("lockd: %s failed; no nsm handle\n",
__func__);
goto out;
}
}
host = kmalloc(sizeof(*host), GFP_KERNEL);
if (unlikely(host == NULL)) {
dprintk("lockd: %s failed; no memory\n", __func__);
nsm_release(nsm);
goto out;
}
memcpy(nlm_addr(host), ni->sap, ni->salen);
host->h_addrlen = ni->salen;
rpc_set_port(nlm_addr(host), 0);
host->h_srcaddrlen = 0;
host->h_rpcclnt = NULL;
host->h_name = nsm->sm_name;
host->h_version = ni->version;
host->h_proto = ni->protocol;
host->h_reclaiming = 0;
host->h_server = ni->server;
host->h_noresvport = ni->noresvport;
host->h_inuse = 0;
init_waitqueue_head(&host->h_gracewait);
init_rwsem(&host->h_rwsem);
host->h_state = 0;
host->h_nsmstate = 0;
host->h_pidcount = 0;
refcount_set(&host->h_count, 1);
mutex_init(&host->h_mutex);
host->h_nextrebind = now + NLM_HOST_REBIND;
host->h_expires = now + NLM_HOST_EXPIRE;
INIT_LIST_HEAD(&host->h_lockowners);
spin_lock_init(&host->h_lock);
INIT_LIST_HEAD(&host->h_granted);
INIT_LIST_HEAD(&host->h_reclaim);
host->h_nsmhandle = nsm;
host->h_addrbuf = nsm->sm_addrbuf;
host->net = ni->net;
strlcpy(host->nodename, utsname()->nodename, sizeof(host->nodename));
out:
return host;
}
/*
* Destroy an nlm_host and free associated resources
*
* Caller must hold nlm_host_mutex.
*/
static void nlm_destroy_host_locked(struct nlm_host *host)
{
struct rpc_clnt *clnt;
struct lockd_net *ln = net_generic(host->net, lockd_net_id);
dprintk("lockd: destroy host %s\n", host->h_name);
hlist_del_init(&host->h_hash);
nsm_unmonitor(host);
nsm_release(host->h_nsmhandle);
clnt = host->h_rpcclnt;
if (clnt != NULL)
rpc_shutdown_client(clnt);
kfree(host);
ln->nrhosts--;
nrhosts--;
}
/**
* nlmclnt_lookup_host - Find an NLM host handle matching a remote server
* @sap: network address of server
* @salen: length of server address
* @protocol: transport protocol to use
* @version: NLM protocol version
* @hostname: '\0'-terminated hostname of server
* @noresvport: 1 if non-privileged port should be used
*
* Returns an nlm_host structure that matches the passed-in
* [server address, transport protocol, NLM version, server hostname].
* If one doesn't already exist in the host cache, a new handle is
* created and returned.
*/
struct nlm_host *nlmclnt_lookup_host(const struct sockaddr *sap,
const size_t salen,
const unsigned short protocol,
const u32 version,
const char *hostname,
int noresvport,
struct net *net)
{
struct nlm_lookup_host_info ni = {
.server = 0,
.sap = sap,
.salen = salen,
.protocol = protocol,
.version = version,
.hostname = hostname,
.hostname_len = strlen(hostname),
.noresvport = noresvport,
.net = net,
};
struct hlist_head *chain;
struct nlm_host *host;
struct nsm_handle *nsm = NULL;
struct lockd_net *ln = net_generic(net, lockd_net_id);
dprintk("lockd: %s(host='%s', vers=%u, proto=%s)\n", __func__,
(hostname ? hostname : "<none>"), version,
(protocol == IPPROTO_UDP ? "udp" : "tcp"));
mutex_lock(&nlm_host_mutex);
chain = &nlm_client_hosts[nlm_hash_address(sap)];
hlist_for_each_entry(host, chain, h_hash) {
if (host->net != net)
continue;
if (!rpc_cmp_addr(nlm_addr(host), sap))
continue;
/* Same address. Share an NSM handle if we already have one */
if (nsm == NULL)
nsm = host->h_nsmhandle;
if (host->h_proto != protocol)
continue;
if (host->h_version != version)
continue;
nlm_get_host(host);
dprintk("lockd: %s found host %s (%s)\n", __func__,
host->h_name, host->h_addrbuf);
goto out;
}
host = nlm_alloc_host(&ni, nsm);
if (unlikely(host == NULL))
goto out;
hlist_add_head(&host->h_hash, chain);
ln->nrhosts++;
nrhosts++;
dprintk("lockd: %s created host %s (%s)\n", __func__,
host->h_name, host->h_addrbuf);
out:
mutex_unlock(&nlm_host_mutex);
return host;
}
/**
* nlmclnt_release_host - release client nlm_host
* @host: nlm_host to release
*
*/
void nlmclnt_release_host(struct nlm_host *host)
{
if (host == NULL)
return;
dprintk("lockd: release client host %s\n", host->h_name);
WARN_ON_ONCE(host->h_server);
if (refcount_dec_and_mutex_lock(&host->h_count, &nlm_host_mutex)) {
WARN_ON_ONCE(!list_empty(&host->h_lockowners));
WARN_ON_ONCE(!list_empty(&host->h_granted));
WARN_ON_ONCE(!list_empty(&host->h_reclaim));
nlm_destroy_host_locked(host);
mutex_unlock(&nlm_host_mutex);
}
}
/**
* nlmsvc_lookup_host - Find an NLM host handle matching a remote client
* @rqstp: incoming NLM request
* @hostname: name of client host
* @hostname_len: length of client hostname
*
* Returns an nlm_host structure that matches the [client address,
* transport protocol, NLM version, client hostname] of the passed-in
* NLM request. If one doesn't already exist in the host cache, a
* new handle is created and returned.
*
* Before possibly creating a new nlm_host, construct a sockaddr
* for a specific source address in case the local system has
* multiple network addresses. The family of the address in
* rq_daddr is guaranteed to be the same as the family of the
* address in rq_addr, so it's safe to use the same family for
* the source address.
*/
struct nlm_host *nlmsvc_lookup_host(const struct svc_rqst *rqstp,
const char *hostname,
const size_t hostname_len)
{
struct hlist_head *chain;
struct nlm_host *host = NULL;
struct nsm_handle *nsm = NULL;
struct sockaddr *src_sap = svc_daddr(rqstp);
size_t src_len = rqstp->rq_daddrlen;
struct net *net = SVC_NET(rqstp);
struct nlm_lookup_host_info ni = {
.server = 1,
.sap = svc_addr(rqstp),
.salen = rqstp->rq_addrlen,
.protocol = rqstp->rq_prot,
.version = rqstp->rq_vers,
.hostname = hostname,
.hostname_len = hostname_len,
.net = net,
};
struct lockd_net *ln = net_generic(net, lockd_net_id);
dprintk("lockd: %s(host='%.*s', vers=%u, proto=%s)\n", __func__,
(int)hostname_len, hostname, rqstp->rq_vers,
(rqstp->rq_prot == IPPROTO_UDP ? "udp" : "tcp"));
mutex_lock(&nlm_host_mutex);
if (time_after_eq(jiffies, ln->next_gc))
nlm_gc_hosts(net);
chain = &nlm_server_hosts[nlm_hash_address(ni.sap)];
hlist_for_each_entry(host, chain, h_hash) {
if (host->net != net)
continue;
if (!rpc_cmp_addr(nlm_addr(host), ni.sap))
continue;
/* Same address. Share an NSM handle if we already have one */
if (nsm == NULL)
nsm = host->h_nsmhandle;
if (host->h_proto != ni.protocol)
continue;
if (host->h_version != ni.version)
continue;
if (!rpc_cmp_addr(nlm_srcaddr(host), src_sap))
continue;
/* Move to head of hash chain. */
hlist_del(&host->h_hash);
hlist_add_head(&host->h_hash, chain);
nlm_get_host(host);
dprintk("lockd: %s found host %s (%s)\n",
__func__, host->h_name, host->h_addrbuf);
goto out;
}
host = nlm_alloc_host(&ni, nsm);
if (unlikely(host == NULL))
goto out;
memcpy(nlm_srcaddr(host), src_sap, src_len);
host->h_srcaddrlen = src_len;
hlist_add_head(&host->h_hash, chain);
ln->nrhosts++;
nrhosts++;
refcount_inc(&host->h_count);
dprintk("lockd: %s created host %s (%s)\n",
__func__, host->h_name, host->h_addrbuf);
out:
mutex_unlock(&nlm_host_mutex);
return host;
}
/**
* nlmsvc_release_host - release server nlm_host
* @host: nlm_host to release
*
* Host is destroyed later in nlm_gc_host().
*/
void nlmsvc_release_host(struct nlm_host *host)
{
if (host == NULL)
return;
dprintk("lockd: release server host %s\n", host->h_name);
WARN_ON_ONCE(!host->h_server);
refcount_dec(&host->h_count);
}
/*
* Create the NLM RPC client for an NLM peer
*/
struct rpc_clnt *
nlm_bind_host(struct nlm_host *host)
{
struct rpc_clnt *clnt;
dprintk("lockd: nlm_bind_host %s (%s)\n",
host->h_name, host->h_addrbuf);
/* Lock host handle */
mutex_lock(&host->h_mutex);
/* If we've already created an RPC client, check whether
* RPC rebind is required
*/
if ((clnt = host->h_rpcclnt) != NULL) {
if (time_after_eq(jiffies, host->h_nextrebind)) {
rpc_force_rebind(clnt);
host->h_nextrebind = jiffies + NLM_HOST_REBIND;
dprintk("lockd: next rebind in %lu jiffies\n",
host->h_nextrebind - jiffies);
}
} else {
unsigned long increment = nlmsvc_timeout;
struct rpc_timeout timeparms = {
.to_initval = increment,
.to_increment = increment,
.to_maxval = increment * 6UL,
.to_retries = 5U,
};
struct rpc_create_args args = {
.net = host->net,
.protocol = host->h_proto,
.address = nlm_addr(host),
.addrsize = host->h_addrlen,
.timeout = &timeparms,
.servername = host->h_name,
.program = &nlm_program,
.version = host->h_version,
.authflavor = RPC_AUTH_UNIX,
.flags = (RPC_CLNT_CREATE_NOPING |
RPC_CLNT_CREATE_AUTOBIND),
};
/*
* lockd retries server side blocks automatically so we want
* those to be soft RPC calls. Client side calls need to be
* hard RPC tasks.
*/
if (!host->h_server)
args.flags |= RPC_CLNT_CREATE_HARDRTRY;
if (host->h_noresvport)
args.flags |= RPC_CLNT_CREATE_NONPRIVPORT;
if (host->h_srcaddrlen)
args.saddress = nlm_srcaddr(host);
clnt = rpc_create(&args);
if (!IS_ERR(clnt))
host->h_rpcclnt = clnt;
else {
printk("lockd: couldn't create RPC handle for %s\n", host->h_name);
clnt = NULL;
}
}
mutex_unlock(&host->h_mutex);
return clnt;
}
/*
* Force a portmap lookup of the remote lockd port
*/
void
nlm_rebind_host(struct nlm_host *host)
{
dprintk("lockd: rebind host %s\n", host->h_name);
if (host->h_rpcclnt && time_after_eq(jiffies, host->h_nextrebind)) {
rpc_force_rebind(host->h_rpcclnt);
host->h_nextrebind = jiffies + NLM_HOST_REBIND;
}
}
/*
* Increment NLM host count
*/
struct nlm_host * nlm_get_host(struct nlm_host *host)
{
if (host) {
dprintk("lockd: get host %s\n", host->h_name);
refcount_inc(&host->h_count);
host->h_expires = jiffies + NLM_HOST_EXPIRE;
}
return host;
}
static struct nlm_host *next_host_state(struct hlist_head *cache,
struct nsm_handle *nsm,
const struct nlm_reboot *info)
{
struct nlm_host *host;
struct hlist_head *chain;
mutex_lock(&nlm_host_mutex);
for_each_host(host, chain, cache) {
if (host->h_nsmhandle == nsm
&& host->h_nsmstate != info->state) {
host->h_nsmstate = info->state;
host->h_state++;
nlm_get_host(host);
mutex_unlock(&nlm_host_mutex);
return host;
}
}
mutex_unlock(&nlm_host_mutex);
return NULL;
}
/**
* nlm_host_rebooted - Release all resources held by rebooted host
* @net: network namespace
* @info: pointer to decoded results of NLM_SM_NOTIFY call
*
* We were notified that the specified host has rebooted. Release
* all resources held by that peer.
*/
void nlm_host_rebooted(const struct net *net, const struct nlm_reboot *info)
{
struct nsm_handle *nsm;
struct nlm_host *host;
nsm = nsm_reboot_lookup(net, info);
if (unlikely(nsm == NULL))
return;
/* Mark all hosts tied to this NSM state as having rebooted.
* We run the loop repeatedly, because we drop the host table
* lock for this.
* To avoid processing a host several times, we match the nsmstate.
*/
while ((host = next_host_state(nlm_server_hosts, nsm, info)) != NULL) {
nlmsvc_free_host_resources(host);
nlmsvc_release_host(host);
}
while ((host = next_host_state(nlm_client_hosts, nsm, info)) != NULL) {
nlmclnt_recovery(host);
nlmclnt_release_host(host);
}
nsm_release(nsm);
}
static void nlm_complain_hosts(struct net *net)
{
struct hlist_head *chain;
struct nlm_host *host;
if (net) {
struct lockd_net *ln = net_generic(net, lockd_net_id);
if (ln->nrhosts == 0)
return;
pr_warn("lockd: couldn't shutdown host module for net %x!\n",
net->ns.inum);
dprintk("lockd: %lu hosts left in net %x:\n", ln->nrhosts,
net->ns.inum);
} else {
if (nrhosts == 0)
return;
printk(KERN_WARNING "lockd: couldn't shutdown host module!\n");
dprintk("lockd: %lu hosts left:\n", nrhosts);
}
for_each_host(host, chain, nlm_server_hosts) {
if (net && host->net != net)
continue;
dprintk(" %s (cnt %d use %d exp %ld net %x)\n",
host->h_name, refcount_read(&host->h_count),
host->h_inuse, host->h_expires, host->net->ns.inum);
}
}
void
nlm_shutdown_hosts_net(struct net *net)
{
struct hlist_head *chain;
struct nlm_host *host;
mutex_lock(&nlm_host_mutex);
/* First, make all hosts eligible for gc */
dprintk("lockd: nuking all hosts in net %x...\n",
net ? net->ns.inum : 0);
for_each_host(host, chain, nlm_server_hosts) {
if (net && host->net != net)
continue;
host->h_expires = jiffies - 1;
if (host->h_rpcclnt) {
rpc_shutdown_client(host->h_rpcclnt);
host->h_rpcclnt = NULL;
}
}
/* Then, perform a garbage collection pass */
nlm_gc_hosts(net);
nlm_complain_hosts(net);
mutex_unlock(&nlm_host_mutex);
}
/*
* Shut down the hosts module.
* Note that this routine is called only at server shutdown time.
*/
void
nlm_shutdown_hosts(void)
{
dprintk("lockd: shutting down host module\n");
nlm_shutdown_hosts_net(NULL);
}
/*
* Garbage collect any unused NLM hosts.
* This GC combines reference counting for async operations with
* mark & sweep for resources held by remote clients.
*/
static void
nlm_gc_hosts(struct net *net)
{
struct hlist_head *chain;
struct hlist_node *next;
struct nlm_host *host;
dprintk("lockd: host garbage collection for net %x\n",
net ? net->ns.inum : 0);
for_each_host(host, chain, nlm_server_hosts) {
if (net && host->net != net)
continue;
host->h_inuse = 0;
}
/* Mark all hosts that hold locks, blocks or shares */
nlmsvc_mark_resources(net);
for_each_host_safe(host, next, chain, nlm_server_hosts) {
if (net && host->net != net)
continue;
if (host->h_inuse || time_before(jiffies, host->h_expires)) {
dprintk("nlm_gc_hosts skipping %s "
"(cnt %d use %d exp %ld net %x)\n",
host->h_name, refcount_read(&host->h_count),
host->h_inuse, host->h_expires,
host->net->ns.inum);
continue;
}
if (refcount_dec_if_one(&host->h_count))
nlm_destroy_host_locked(host);
}
if (net) {
struct lockd_net *ln = net_generic(net, lockd_net_id);
ln->next_gc = jiffies + NLM_HOST_COLLECT;
}
}
| {
"pile_set_name": "Github"
} |
(* ==== INITIAL BASIS : STRINGS ====
*
* Copyright 2013 Ravenbrook Limited <http://www.ravenbrook.com/>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY 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
* HOLDER 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.
*
* Description
* -----------
* This is part of the extended Initial Basis.
*
* Revision Log
* ------------
* $Log: __string.sml,v $
* Revision 1.17 1999/02/17 14:40:57 mitchell
* [Bug #190507]
* Modify to satisfy CM constraints.
*
* Revision 1.16 1999/02/02 15:58:20 mitchell
* [Bug #190500]
* Remove redundant require statements
*
* Revision 1.15 1997/08/08 14:31:01 brucem
* [Bug #30086]
* Add map and mapi.
*
* Revision 1.14 1997/03/06 16:45:54 jont
* [Bug #1938]
* Get rid of unsafe stuff from PreBasis where possible
*
* Revision 1.13 1996/12/17 16:52:29 matthew
* Using PreChar instead of Char
*
* Revision 1.12 1996/10/03 14:23:06 io
* [Bug #1614]
* remove some redundant requires
*
* Revision 1.11 1996/10/01 13:11:27 io
* [Bug #1626]
* remove option type for Char.toCString
*
* Revision 1.10 1996/07/26 10:24:56 daveb
* Added comment describing optimisation used in extract.
*
* Revision 1.9 1996/07/25 14:31:06 daveb
* [Bug #1497]
* Extract now does bound checking for the empty string.
*
* Revision 1.8 1996/07/09 12:13:31 andreww
* rewriting to make use of expanded toplevel.
*
* Revision 1.7 1996/07/02 15:19:53 io
* modify isPrint, fix fromCString accum bug
*
* Revision 1.6 1996/06/24 20:07:13 io
* unconstrain Char so that scanc can be seen by other basis routines
*
* Revision 1.5 1996/06/04 17:53:50 io
* stringcvt->string_cvt
*
* Revision 1.4 1996/05/23 20:38:11 io
* from|toCString
*
* Revision 1.3 1996/05/16 16:58:55 io
* fix from, to String
*
* Revision 1.2 1996/05/16 14:54:11 io
* remove warnings
*
* Revision 1.1 1996/05/16 09:39:54 io
* new unit
*
* Revision 1.2 1996/05/13 17:50:56 io
* fix explode and complete toString
*
* Revision 1.1 1996/05/10 16:18:45 io
* new unit
*
*)
require "__pre_basis";
require "string";
require "__pre_char";
structure String : STRING =
struct
val maxSize = PreBasis.maxSize
val char_sub = chr o MLWorks.String.ordof
(* miscellaneous *)
val unsafe_concatenate : string * string -> string =
MLWorks.Internal.Runtime.environment "string concatenate"
(* end of miscellaneous *)
structure Char = PreChar
type char = Char.char
type string = string
val size = size
fun sub (s, i) =
let val size = size s in
if i < 0 orelse i >= size then
raise Subscript
else
char_sub(s, i)
end
(* Top level functions *)
val substring: string * int * int -> string = substring
val concat: string list -> string = concat
val str: char -> string = str
val explode: string -> char list = explode
val implode: char list -> string = implode
(* basis concat is aka old style implode *)
fun compare (x:string,y) =
if x<y then LESS else if x>y then GREATER else EQUAL
fun collate (comp: (char * char) -> order) ((s1,s2):string * string)
: order =
let val s1l = explode s1
val s2l = explode s2
fun aux ([],[]) = EQUAL
| aux ([], _) = LESS
| aux (_, []) = GREATER
| aux (x::xs, y::ys) =
case comp (x,y) of
EQUAL => aux (xs, ys)
| arg => arg
in
aux (s1l, s2l)
end
fun fields (isDelimiter:char -> bool) (s:string) : string list =
let
val size = size s
fun aux (i, j, acc) =
let val size' = i+j in
if (size' = size) then (MLWorks.String.substring (s, i, j) :: acc)
else if isDelimiter (char_sub(s, size')) then
aux (size'+1, 0, MLWorks.String.substring(s, i, j)::acc)
else aux (i, j+1, acc)
end
in
rev(aux (0, 0, []))
end
fun tokens (p:char -> bool) "" = []
| tokens p s =
let
val size = size s
fun mySubstring (s, i, j, acc) =
if j = 0 then acc else MLWorks.String.substring (s, i, j) :: acc
fun skip i =
if i = size then i else if p (char_sub(s, i)) then skip (i+1) else i
fun aux (i, j, acc) =
let
val size' = i+j
in
if (size' = size) then mySubstring (s, i, j, acc)
else if p (char_sub (s, size')) then
aux (skip size', 0, mySubstring(s, i, j, acc))
else
aux (i, j+1, acc)
end
in
rev(aux (0, 0, []))
end
fun isPrefix (s:string) (t:string) =
let
val size_s = size s
in
if size_s > size t then false
else
let fun aux i =
if i < size_s then
char_sub(s,i) = char_sub (t, i) andalso
aux (i+1)
else
true
in
aux 0
end
end
(* The bounds checking here uses unsigned comparisons as an optimisation.
E.g. if size_s' > i' then we know both that size_s > i and i > 0
(this relies on the fact that size_s > 0, which it must be). *)
fun extract (s, i, NONE) =
let
val size_s = size s
val size_s' = MLWorks.Internal.Value.cast size_s : word
val i' = MLWorks.Internal.Value.cast i : word
in
if size_s' < i' then
raise Subscript
else
MLWorks.String.substring (s, i, size_s - i)
end
| extract (s, i, SOME n) =
let
val size_s = size s
val size_s' = MLWorks.Internal.Value.cast size_s : word
val i' = MLWorks.Internal.Value.cast i : word
val n' = MLWorks.Internal.Value.cast n : word
in
if size_s' < i' orelse MLWorks.Internal.Value.cast (size_s - i) < n'
then
raise Subscript
else
MLWorks.String.substring (s, i, n)
end
fun map f s =
let
val l = size s
val newS = MLWorks.Internal.Value.alloc_string (l+1)
val i = ref 0
val _ =
while (!i<l) do(
MLWorks.Internal.Value.unsafe_string_update
(newS, !i,
ord (f (chr(MLWorks.Internal.Value.unsafe_string_sub (s,!i)))));
i := !i + 1 )
val _ = MLWorks.Internal.Value.unsafe_string_update (newS, l, 0)
in
newS
end
fun check_slice (s, i, SOME j) =
if i < 0 orelse j < 0 orelse i + j > size s
then raise Subscript
else j
| check_slice (s, i, NONE) =
let
val l = size s
in
if i < 0 orelse i > l
then raise Subscript
else l - i
end
fun mapi f (st, s, l) =
let
val l' = check_slice (st, s, l)
val newS = MLWorks.Internal.Value.alloc_string (l' + 1)
val i = ref 0
val _ =
while (!i<l') do (
MLWorks.Internal.Value.unsafe_string_update
(newS, !i,
ord (f (!i + s,
chr(MLWorks.Internal.Value.unsafe_string_sub(st, !i+s )
)
)
)
) ;
i := !i + 1)
val _ = MLWorks.Internal.Value.unsafe_string_update (newS, l', 0)
in
newS
end
fun translate _ "" = ""
| translate (p:char -> string) (s:string) : string =
let
val size = size s
fun aux (i, acc) =
if i < size then
aux (i+1, (p (char_sub (s, i)))::acc)
else
concat (rev acc)
in
aux (0, [])
end
fun toString s = translate Char.toString s
fun fromString s =
let
val sz = size s
fun getc i =
if i < sz then
SOME (char_sub(s, i), i+1)
else
NONE
fun aux (i, acc) =
if i < sz then
case Char.scan getc i of
SOME (c, i) =>
aux (i, c::acc)
| NONE => acc
else
acc
in
case aux (0, []) of
[] => NONE
| xs => SOME (PreBasis.revImplode xs)
end
fun fromCString "" = NONE
| fromCString s =
let
val sz = size s
fun getc i =
if i < sz then
SOME (char_sub(s, i), i+1)
else
NONE
fun scan (i, acc) =
if i < sz then
case PreChar.scanc getc i of
SOME (c, i) =>
scan (i, c::acc)
| NONE => acc
else
acc
in
case scan (0, []) of
[] => NONE
| xs => SOME (PreBasis.revImplode xs)
end
fun toCString s =
translate Char.toCString s
fun op^(s1, s2) =
if size s1 + size s2 > maxSize then raise Size
else unsafe_concatenate (s1, s2)
val op< : string * string -> bool = op<
val op<= : string * string -> bool = op<=
val op> : string * string -> bool = op>
val op>= : string * string -> bool = op>=
end
| {
"pile_set_name": "Github"
} |
function anonHeaderS = defineAnonHeader()
%
% function anonHeaderS = defineAnonHeader()
%
% Defines the anonymous "header" data structure. The fields containing PHI have
% been left out by default. In order to leave out additional fields, remove
% them from the list below.
%
% The following three operations are allowed per field of the input data structure:
% 1. Keep the value as is: listed as 'keep' in the list below.
% 2. Allow only the specific values: permitted values listed within a cell array.
% If no match is found, a default anonymous string will be inserted.
% 3. Insert dummy date: listed as 'date' in the list below. Date will be
% replaced by a dummy value of 11/11/1111.
%
% APA, 1/11/2018
anonHeaderS = struct( ...
'writer', {{'CERR DICOM Import'}}, ...
'timeSaved', 'keep', ...
'lastSavedInVer', 'keep', ...
'CERRImportVersion', 'keep', ...
'anonymizedID', 'keep' ...
);
| {
"pile_set_name": "Github"
} |
[
"assert",
"buffer",
"child_process",
"cluster",
"console",
"constants",
"crypto",
"dgram",
"dns",
"domain",
"events",
"fs",
"http",
"https",
"module",
"net",
"os",
"path",
"process",
"punycode",
"querystring",
"readline",
"repl",
"stream",
"string_decoder",
"timers",
"tls",
"tty",
"url",
"util",
"v8",
"vm",
"zlib"
]
| {
"pile_set_name": "Github"
} |
#include "test-neon.h"
#include "run-tests.h"
static MunitSuite suites[] = {
#define SIMDE_TEST_DECLARE_SUITE(name) \
{ NULL, NULL, NULL, 1, MUNIT_SUITE_OPTION_NONE }, \
{ NULL, NULL, NULL, 1, MUNIT_SUITE_OPTION_NONE }, \
{ NULL, NULL, NULL, 1, MUNIT_SUITE_OPTION_NONE }, \
{ NULL, NULL, NULL, 1, MUNIT_SUITE_OPTION_NONE },
#include "declare-suites.h"
#undef SIMDE_TEST_DECLARE_SUITE
{ NULL, NULL, NULL, 0, MUNIT_SUITE_OPTION_NONE }
};
static MunitSuite suite = { "/neon", NULL, suites, 1, MUNIT_SUITE_OPTION_NONE };
MunitSuite*
simde_tests_arm_neon_get_suite(void) {
int i = 0;
#define SIMDE_TEST_DECLARE_SUITE(name) \
suites[i++] = *HEDLEY_CONCAT3(simde_test_arm_neon_get_suite_, name, _native_c)(); \
suites[i++] = *HEDLEY_CONCAT3(simde_test_arm_neon_get_suite_, name, _native_cpp)(); \
suites[i++] = *HEDLEY_CONCAT3(simde_test_arm_neon_get_suite_, name, _emul_c)(); \
suites[i++] = *HEDLEY_CONCAT3(simde_test_arm_neon_get_suite_, name, _emul_cpp)();
#include "declare-suites.h"
#undef SIMDE_TEST_DECLARE_SUITE
return &suite;
}
| {
"pile_set_name": "Github"
} |
// This file is automatically generated.
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace Steam4NET
{
public enum ELobbyComparison : int
{
k_ELobbyComparisonEqualToOrLessThan = -2,
k_ELobbyComparisonLessThan = -1,
k_ELobbyComparisonEqual = 0,
k_ELobbyComparisonGreaterThan = 1,
k_ELobbyComparisonEqualToOrGreaterThan = 2,
k_ELobbyComparisonNotEqual = 3,
};
public enum ELobbyDistanceFilter : int
{
k_ELobbyDistanceFilterClose = 0,
k_ELobbyDistanceFilterDefault = 1,
k_ELobbyDistanceFilterFar = 2,
k_ELobbyDistanceFilterWorldwide = 3,
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(501)]
public struct FavoritesListChangedOld_t
{
public const int k_iCallback = 501;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(502)]
public struct FavoritesListChanged_t
{
public const int k_iCallback = 502;
public UInt32 m_nIP;
public UInt32 m_nQueryPort;
public UInt32 m_nConnPort;
public UInt32 m_nAppID;
public UInt32 m_nFlags;
[MarshalAs(UnmanagedType.I1)]
public bool m_bAdd;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(503)]
public struct LobbyInvite_t
{
public const int k_iCallback = 503;
public SteamID_t m_ulSteamIDUser;
public SteamID_t m_ulSteamIDLobby;
public GameID_t m_ulGameID;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(504)]
public struct LobbyEnter_t
{
public const int k_iCallback = 504;
public SteamID_t m_ulSteamIDLobby;
public EChatPermission m_rgfChatPermissions;
[MarshalAs(UnmanagedType.I1)]
public bool m_bLocked;
public EChatRoomEnterResponse m_EChatRoomEnterResponse;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(505)]
public struct LobbyDataUpdate_t
{
public const int k_iCallback = 505;
public SteamID_t m_ulSteamIDLobby;
public SteamID_t m_ulSteamIDMember;
public Byte m_bSuccess;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(506)]
public struct LobbyChatUpdate_t
{
public const int k_iCallback = 506;
public SteamID_t m_ulSteamIDLobby;
public SteamID_t m_ulSteamIDUserChanged;
public SteamID_t m_ulSteamIDMakingChange;
public EChatMemberStateChange m_rgfChatMemberStateChange;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(507)]
public struct LobbyChatMsg_t
{
public const int k_iCallback = 507;
public UInt64 m_ulSteamIDLobby;
public UInt64 m_ulSteamIDUser;
public Byte m_eChatEntryType;
public UInt32 m_iChatID;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(508)]
public struct LobbyAdminChange_t
{
public const int k_iCallback = 508;
public SteamID_t m_ulSteamIDLobby;
public SteamID_t m_ulSteamIDNewAdmin;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(509)]
public struct LobbyGameCreated_t
{
public const int k_iCallback = 509;
public SteamID_t m_ulSteamIDLobby;
public SteamID_t m_ulSteamIDGameServer;
public UInt32 m_unIP;
public UInt16 m_usPort;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(510)]
public struct LobbyMatchList_t
{
public const int k_iCallback = 510;
public UInt32 m_nLobbiesMatching;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(511)]
public struct LobbyClosing_t
{
public const int k_iCallback = 511;
public SteamID_t m_ulSteamIDLobby;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(512)]
public struct LobbyKicked_t
{
public const int k_iCallback = 512;
public UInt64 m_ulSteamIDLobby;
public UInt64 m_ulSteamIDAdmin;
public Byte m_bKickedDueToDisconnect;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(513)]
public struct LobbyCreated_t
{
public const int k_iCallback = 513;
public EResult m_eResult;
public UInt64 m_ulSteamIDLobby;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
[InteropHelp.CallbackIdentity(514)]
public struct RequestFriendsLobbiesResponse_t
{
public const int k_iCallback = 514;
public UInt64 m_ulSteamIDFriend;
public UInt64 m_ulSteamIDLobby;
public Int32 m_cResultIndex;
public Int32 m_cResultsTotal;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
public struct GMSQueryResult_t
{
public UInt32 uServerIP;
public UInt32 uServerPort;
public Int32 nAuthPlayers;
};
[StructLayout(LayoutKind.Sequential,Pack=8)]
public struct PingSample_t
{
public Int32 m_iPadding;
};
}
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.