text:
<?php

namespace Symfony\Component\HttpFoundation\Session\Storage;

use Symfony\Component\HttpFoundation\Session\SessionBagInterface;

/**
 * Metadata container.
 *
 * Adds metadata to the session.
 *
 * @author Drak <drak@zikula.org>
 */
class MetadataBag implements SessionBagInterface
{
    public const CREATED = 'c';
    public const UPDATED = 'u';
    public const LIFETIME = 'l';

    private string $name = '__metadata';
    private string $storageKey;

    /**
     * @var array
     */
    protected $meta = [self::CREATED => 0, self::UPDATED => 0, self::LIFETIME => 0];

    /**
     * Unix timestamp.
     */
    private int $lastUsed;

    private int $updateThreshold;

    /**
     * @param string $storageKey      The key used to store bag in the session
     * @param int    $updateThreshold The time to wait between two UPDATED updates
     */
    public function __construct(string $storageKey = '_sf2_meta', int $updateThreshold = 0)
    {
        $this->storageKey = $storageKey;
        $this->updateThreshold = $updateThreshold;
    }

    /**
     * {@inheritdoc}
     */
    public function initialize(array &$array)
    {
        $this->meta = &$array;

        if (isset($array[self::CREATED])) {
            $this->lastUsed = $this->meta[self::UPDATED];

            $timeStamp = time();
            if ($timeStamp - $array[self::UPDATED] >= $this->updateThreshold) {
                $this->meta[self::UPDATED] = $timeStamp;
            }
        } else {
            $this->stampCreated();
        }
    }

    /**
     * Gets the lifetime that the session cookie was set with.
     */
    public function getLifetime(): int
    {
        return $this->meta[self::LIFETIME];
    }

    /**
     * Stamps a new session's metadata.
     *
     * @param int $lifetime Sets the cookie lifetime for the session cookie. A null value
     *                      will leave the system settings unchanged, 0 sets the cookie
     *                      to expire with browser session. Time is in seconds, and is
     *                      not a Unix timestamp.
     */
    public function stampNew(int $lifetime = null)
    {
        $this->stampCreated($lifetime);
    }

    /**
     * {@inheritdoc}
     */
    public function getStorageKey(): string
    {
        return $this->storageKey;
    }

    /**
     * Gets the created timestamp metadata.
     *
     * @return int Unix timestamp
     */
    public function getCreated(): int
    {
        return $this->meta[self::CREATED];
    }

    /**
     * Gets the last used metadata.
     *
     * @return int Unix timestamp
     */
    public function getLastUsed(): int
    {
        return $this->lastUsed;
    }

    /**
     * {@inheritdoc}
     */
    public function clear(): mixed
    {
        // nothing to do
        return null;
    }

    /**
     * {@inheritdoc}
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * Sets name.
     */
    public function setName(string $name)
    {
        $this->name = $name;
    }

    private function stampCreated(int $lifetime = null): void
    {
        $timeStamp = time();
        $this->meta[self::CREATED] = $this->meta[self::UPDATED] = $this->lastUsed = $timeStamp;
        $this->meta[self::LIFETIME] = $lifetime ?? (int) \ini_get('session.cookie_lifetime');
    }
}


text:
namespace base {
class TickClock;
}  // namespace base

namespace media {
class AudioBus;
}  // namespace media

namespace audio {

// An AudioInputStream that provides the result of looping-back and
// mixing-together all current and future audio output streams in the same
// group. The loopback re-mixes the audio, if necessary, so that the resulting
// data stream's format matches the required AudioParameters.
//
// This is organized in three main components: 1) The LoopbackStream itself acts
// as a "shell" that manages mojo bindings and creates/controls the other
// components. 2) One or more SnooperNodes that buffer input data for each
// source OutputStream and format-convert it. 3) A "flow network" that runs via
// a different task runner, to take all the audio collected in the SnooperNodes
// and mix it into a single data stream.
class LoopbackStream : public media::mojom::AudioInputStream,
                       public LoopbackCoordinator::Observer {
 public:
  using CreatedCallback =
      base::OnceCallback<void(media::mojom::ReadOnlyAudioDataPipePtr)>;
  using BindingLostCallback = base::OnceCallback<void(LoopbackStream*)>;

  LoopbackStream(
      CreatedCallback created_callback,
      BindingLostCallback binding_lost_callback,
      scoped_refptr<base::SequencedTaskRunner> flow_task_runner,
      mojo::PendingReceiver<media::mojom::AudioInputStream> receiver,
      mojo::PendingRemote<media::mojom::AudioInputStreamClient> client,
      mojo::PendingRemote<media::mojom::AudioInputStreamObserver> observer,
      const media::AudioParameters& params,
      uint32_t shared_memory_count,
      LoopbackCoordinator* coordinator,
      const base::UnguessableToken& group_id);

  ~LoopbackStream() final;

  bool is_recording() const { return network_ && network_->is_started(); }

  // media::mojom::AudioInputStream implementation.
  void Record() final;
  void SetVolume(double volume) final;

  // LoopbackCoordinator::Observer implementation. When a member joins
  // a group, a SnooperNode is created for it, and a loopback flow from
  // LoopbackGroupMember → SnooperNode → FlowNetwork is built-up.
  void OnMemberJoinedGroup(LoopbackGroupMember* member) final;
  void OnMemberLeftGroup(LoopbackGroupMember* member) final;

  // Overrides for unit testing. These must be called before Record().
  void set_clock_for_testing(const base::TickClock* clock) {
    network_->set_clock_for_testing(clock);
  }
  void set_sync_writer_for_testing(
      std::unique_ptr<InputController::SyncWriter> writer) {
    network_->set_writer_for_testing(std::move(writer));
  }

  // Generally, a volume of 1.0 should be the maximum possible. However, there
  // are cases where requests to amplify are made by specifying values higher
  // than 1.0.
  static constexpr double kMaxVolume = 2.0;

 private:
  // Drives all audio flows, re-mixing the audio from multiple SnooperNodes into
  // a single audio stream. This class mainly operates on a separate task runner
  // from LoopbackStream and can only be destroyed by scheduling it to occur on
  // that same task runner.
  class FlowNetwork {
   public:
    FlowNetwork(scoped_refptr<base::SequencedTaskRunner> flow_task_runner,
                const media::AudioParameters& output_params,
                std::unique_ptr<InputSyncWriter> writer);

    // These must be called to override the Clock/SyncWriter before Start().
    void set_clock_for_testing(const base::TickClock* clock) { clock_ = clock; }
    void set_writer_for_testing(
        std::unique_ptr<InputController::SyncWriter> writer) {
      writer_ = std::move(writer);
    }

    bool is_started() const {
      DCHECK_CALLED_ON_VALID_SEQUENCE(control_sequence_);
      return !!timer_;
    }

    const media::AudioParameters& output_params() const {
      return output_params_;
    }

    // Add/Remove an input into this flow network. These may be called at any
    // time, before or after Start(). All inputs must be removed before the
    // FlowNetwork is scheduled for destruction.
    void AddInput(SnooperNode* node);
    void RemoveInput(SnooperNode* node);

    // This may be called at any time, before or after Start(), to change the
    // volume setting.
    void SetVolume(double volume);

    // Start generating audio data. This must only be called once, and there is
    // no "stop" until destruction time.
    void Start();

   private:
    // Since this class guarantees its destructor will be called via the flow
    // task runner, and destruction is carried out only by base::DeleteHelper,
    // make the destructor is private.
    friend class base::DeleteHelper<FlowNetwork>;
    ~FlowNetwork();

    // Called periodically via the audio flow task runner to drive all the audio
    // flows from the SnooperNodes, mix them together, and output to the
    // AudioDataPipe. Each call schedules the next one until the |run_state_|
    // becomes stopped.
    void GenerateMoreAudio();

    const base::TickClock* clock_;

    // Task runner that calls GenerateMoreAudio() to drive all the audio data
    // flows.
    const scoped_refptr<base::SequencedTaskRunner> flow_task_runner_;

    // The audio parameters of the output.
    const media::AudioParameters output_params_;

    // Destination for the output of this FlowNetwork.
    std::unique_ptr<InputController::SyncWriter> writer_;

    // Ensures thread-safe access to changing the |inputs_| and |volume_| while
    // running.
    base::Lock lock_;

    // The input nodes.
    std::vector<SnooperNode*> inputs_;  // Guarded by |lock_|.

    // Current stream volume. The audio output from this FlowNetwork is scaled
    // by this amount during mixing.
    double volume_ = 1.0;  // Guarded by |lock_|.

    // This is set once Start() is called, and lives until this FlowNetwork is
    // destroyed. It is used to schedule cancelable tasks run by the
    // |flow_task_runner_|.
    base::Optional<base::OneShotTimer> timer_;

    // These are used to compute when the |timer_| fires and calls
    // GenerateMoreAudio(). They ensure that each timer task is scheduled to
    // fire with a delay that accounted for how much time was spent processing.
    base::TimeTicks first_generate_time_;
    int64_t frames_elapsed_ = 0;
    base::TimeTicks next_generate_time_;

    // The amount of time in the past from which to capture the audio. The audio
    // recorded from each SnooperNode input is being generated with a target
    // playout time in the near future (usually 1 to 20 ms). To avoid underflow,
    // audio is always fetched from a safe position in the recent past.
    //
    // This is updated to match the SnooperNode whose recording is most delayed.
    base::TimeDelta capture_delay_;

    // Used to transfer the audio from each SnooperNode and mix them into a
    // single audio signal. |transfer_bus_| is only allocated when first needed,
    // but |mix_bus_| is allocated in the constructor because it is always
    // needed.
    std::unique_ptr<media::AudioBus> transfer_bus_;
    const std::unique_ptr<media::AudioBus> mix_bus_;

    SEQUENCE_CHECKER(control_sequence_);

    DISALLOW_COPY_AND_ASSIGN(FlowNetwork);
  };

  // Reports a fatal error to the client, and then runs the BindingLostCallback.
  void OnError();

  // Run when any of |receiver_|, |client_|, or |observer_| are closed. This
  // callback is generally used to automatically terminate this LoopbackStream.
  BindingLostCallback binding_lost_callback_;

  // Mojo bindings. If any of these is closed, the LoopbackStream will call
  // OnError(), which will run the |binding_lost_callback_|.
  mojo::Receiver<media::mojom::AudioInputStream> receiver_;
  mojo::Remote<media::mojom::AudioInputStreamClient> client_;
  mojo::Remote<media::mojom::AudioInputStreamObserver> observer_;

  // Used for identifying group members and snooping on their audio data flow.
  LoopbackCoordinator* const coordinator_;
  const base::UnguessableToken group_id_;

  // The snoopers associated with each group member. This is not a flat_map
  // because SnooperNodes cannot move around in memory while in operation.
  std::map<LoopbackGroupMember*, SnooperNode> snoopers_;

  // The flow network that generates the single loopback result stream. It is
  // owned by LoopbackStream, but it's destruction must be carried out by the
  // flow task runner. This is never null, unless the system cannot support
  // loopback (see constructor definition comments).
  std::unique_ptr<FlowNetwork, base::OnTaskRunnerDeleter> network_;

  SEQUENCE_CHECKER(sequence_checker_);

  base::WeakPtrFactory<LoopbackStream> weak_factory_{this};

  DISALLOW_COPY_AND_ASSIGN(LoopbackStream);
};

}  // namespace audio

#endif  // SERVICES_AUDIO_LOOPBACK_STREAM_H_

redpajama_set_name: RedPajamaGithub


text:
package org.openkilda.persistence.ferma.repositories;

import org.openkilda.model.FlowPath;
import org.openkilda.model.PathId;
import org.openkilda.model.TransitVlan;
import org.openkilda.model.TransitVlan.TransitVlanData;
import org.openkilda.persistence.exceptions.PersistenceException;
import org.openkilda.persistence.ferma.FramedGraphFactory;
import org.openkilda.persistence.ferma.frames.KildaBaseVertexFrame;
import org.openkilda.persistence.ferma.frames.TransitVlanFrame;
import org.openkilda.persistence.ferma.frames.converters.PathIdConverter;
import org.openkilda.persistence.repositories.TransitVlanRepository;
import org.openkilda.persistence.tx.TransactionManager;

import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;

import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Ferma (Tinkerpop) implementation of {@link TransitVlanRepository}.
 */
public class FermaTransitVlanRepository extends FermaGenericRepository<TransitVlan, TransitVlanData, TransitVlanFrame>
        implements TransitVlanRepository {
    public FermaTransitVlanRepository(FramedGraphFactory<?> graphFactory, TransactionManager transactionManager) {
        super(graphFactory, transactionManager);
    }

    @Override
    public Collection<TransitVlan> findAll() {
        return framedGraph().traverse(g -> g.V()
                .hasLabel(TransitVlanFrame.FRAME_LABEL))
                .toListExplicit(TransitVlanFrame.class).stream()
                .map(TransitVlan::new)
                .collect(Collectors.toList());
    }

    /**
     * Lookup for {@link FlowPath} object by pathId (or opposite pathId) value.
     *
     * <p>It make lookup by pathId first and if there is no result it make lookup by {@code oppositePathId}. Such
     * weird logic allow to support both kind of flows(first kind - each path have it's own transit vlan, second
     * kind - only one path have transit vlan, but both of them use it).
     */
    @Override
    public Collection<TransitVlan> findByPathId(PathId pathId, PathId oppositePathId) {
        List<? extends TransitVlanFrame> frames =
                framedGraph().traverse(g -> g.V()
                        .hasLabel(TransitVlanFrame.FRAME_LABEL)
                        .has(TransitVlanFrame.PATH_ID_PROPERTY, PathIdConverter.INSTANCE.toGraphProperty(pathId)))
                        .toListExplicit(TransitVlanFrame.class);
        if (frames.isEmpty() && oppositePathId != null) {
            frames = framedGraph().traverse(g -> g.V()
                    .hasLabel(TransitVlanFrame.FRAME_LABEL)
                    .has(TransitVlanFrame.PATH_ID_PROPERTY, PathIdConverter.INSTANCE.toGraphProperty(oppositePathId)))
                    .toListExplicit(TransitVlanFrame.class);
        }
        return frames.stream()
                .map(TransitVlan::new)
                .collect(Collectors.toList());
    }

    @Override
    public Optional<TransitVlan> findByPathId(PathId pathId) {
        List<? extends TransitVlanFrame> transitVlanFrames = framedGraph().traverse(g -> g.V()
                .hasLabel(TransitVlanFrame.FRAME_LABEL)
                .has(TransitVlanFrame.PATH_ID_PROPERTY, PathIdConverter.INSTANCE.toGraphProperty(pathId)))
                .toListExplicit(TransitVlanFrame.class);
        return transitVlanFrames.isEmpty() ? Optional.empty() : Optional.of(transitVlanFrames.get(0))
                .map(TransitVlan::new);
    }

    @Override
    public boolean exists(int vlan) {
        try (GraphTraversal<?, ?> traversal = framedGraph().traverse(g -> g.V()
                .hasLabel(TransitVlanFrame.FRAME_LABEL)
                .has(TransitVlanFrame.VLAN_PROPERTY, vlan))
                .getRawTraversal()) {
            return traversal.hasNext();
        } catch (Exception e) {
            throw new PersistenceException("Failed to traverse", e);
        }
    }

    @Override
    public Optional<TransitVlan> findByVlan(int vlan) {
        List<? extends TransitVlanFrame> transitVlanFrames = framedGraph().traverse(g -> g.V()
                .hasLabel(TransitVlanFrame.FRAME_LABEL)
                .has(TransitVlanFrame.VLAN_PROPERTY, vlan))
                .toListExplicit(TransitVlanFrame.class);
        return transitVlanFrames.isEmpty() ? Optional.empty() : Optional.of(transitVlanFrames.get(0))
                .map(TransitVlan::new);
    }

    @Override
    public Optional<Integer> findFirstUnassignedVlan(int lowestTransitVlan, int highestTransitVlan) {
        try (GraphTraversal<?, ?> traversal = framedGraph().traverse(g -> g.V()
                .hasLabel(TransitVlanFrame.FRAME_LABEL)
                .has(TransitVlanFrame.VLAN_PROPERTY, P.gte(lowestTransitVlan))
                .has(TransitVlanFrame.VLAN_PROPERTY, P.lt(highestTransitVlan))
                .values(TransitVlanFrame.VLAN_PROPERTY)
                .order().math("_ + 1").as("a")
                .where(__.not(__.V().hasLabel(TransitVlanFrame.FRAME_LABEL)
                        .values(TransitVlanFrame.VLAN_PROPERTY)
                        .where(P.eq("a"))))
                .select("a")
                .limit(1))
                .getRawTraversal()) {
            if (traversal.hasNext()) {
                return traversal.tryNext()
                        .map(l -> ((Double) l).intValue());
            }
        } catch (Exception e) {
            throw new PersistenceException("Failed to traverse", e);
        }

        try (GraphTraversal<?, ?> traversal = framedGraph().traverse(g -> g.V()
                .hasLabel(TransitVlanFrame.FRAME_LABEL)
                .has(TransitVlanFrame.VLAN_PROPERTY, lowestTransitVlan))
                .getRawTraversal()) {
            if (!traversal.hasNext()) {
                return Optional.of(lowestTransitVlan);
            }
        } catch (Exception e) {
            throw new PersistenceException("Failed to traverse", e);
        }

        return Optional.empty();
    }

    @Override
    protected TransitVlanFrame doAdd(TransitVlanData data) {
        TransitVlanFrame frame = KildaBaseVertexFrame.addNewFramedVertex(framedGraph(),
                TransitVlanFrame.FRAME_LABEL, TransitVlanFrame.class);
        TransitVlan.TransitVlanCloner.INSTANCE.copy(data, frame);
        return frame;
    }

    @Override
    protected void doRemove(TransitVlanFrame frame) {
        frame.remove();
    }

    @Override
    protected TransitVlanData doDetach(TransitVlan entity, TransitVlanFrame frame) {
        return TransitVlan.TransitVlanCloner.INSTANCE.copy(frame);
    }
}


text:
package io.joynr.examples.jee;

import joynr.vehicle.RadioSync;

public interface RadioService extends RadioSync {

    void fireWeakSignal();

    String printMetrics();

}


text:
/** @jsx jsx */
// Apply a mark across a range containing text with other marks and a void
import { Editor, Transforms } from 'slate'
import { jsx } from '../../..'

export const run = editor => {
  Editor.addMark(editor, 'bold', true)
}
export const input = (
  <editor>
    <block>
      <text>
        <anchor />
        word{' '}
      </text>
      <text italic>italic words </text>
      <inline void>
        <text />
      </inline>
      <text underline>
        {' '}
        underlined words
        <focus />
      </text>
    </block>
  </editor>
)
export const output = (
  <editor>
    <block>
      <text bold>
        <anchor />
        word{' '}
      </text>
      <text italic bold>
        italic words{' '}
      </text>
      <inline void>
        <text />
      </inline>
      <text underline bold>
        {' '}
        underlined words
        <focus />
      </text>
    </block>
  </editor>
)


text:
angular.module('D', [])
  .controller('dController', function ($scope) {
    $scope.foo = 'foo';
  });

/* global ngDescribe, it */
ngDescribe({
  name: 'step by step test controller',
  modules: 'D',
  inject: ['$controller', '$rootScope'],
  tests: function (deps) {
    it('has $controller function', function () {
      la(check.fn(deps.$controller));
    });

    it('can create new controller', function () {
      var scope = deps.$rootScope.$new();
      la(check.object(scope), 'created new scope');
      var ctrl = deps.$controller('dController', {
        $scope: scope
      });
      la(check.object(ctrl), 'got back controller instance', ctrl);
      la(scope.foo === 'foo', 'scope has been updated');
    });
  }
});

ngDescribe({
  name: 'single shot controller test',
  modules: 'D',
  inject: ['$controller', '$rootScope'],
  controllers: 'dController',
  tests: function (deps) {
    it('has dController scope', function () {
      la(check.has(deps, 'dController'));
    });

    it('is an object', function () {
      la(check.object(deps.dController));
    });

    it('has correct properties', function () {
      la(deps.dController.foo === 'foo');
    });
  }
});

ngDescribe({
  name: 'auto $controller and $rootScope injection',
  modules: 'D',
  controllers: 'dController',
  tests: function (deps) {
    it('has dController scope', function () {
      la(check.has(deps, 'dController'));
    });

    it('is an object', function () {
      la(check.object(deps.dController));
    });

    it('has correct properties', function () {
      la(deps.dController.foo === 'foo');
    });
  }
});

angular.module('S', [])
  .controller('sample', function ($timeout, $scope) {
    $scope.foo = 'foo';

    $scope.update = function () {
      $timeout(function () {
        $scope.foo = 'bar';
      }, 1000);
    };
  });
ngDescribe({
  name: 'timeout in controller',
  modules: 'S',
  inject: ['$timeout'],
  controllers: 'sample',
  tests: function (deps) {
    it('has initial values', function () {
      la(deps.sample.foo === 'foo');
    });

    it('updates after timeout', function () {
      deps.sample.update();
      deps.$timeout.flush();
      la(deps.sample.foo === 'bar');
    });
  }
});


text:
/** @module delite/on */
define(function () {
	/**
	 * Call specified function when event occurs.
	 * @param {Element} [node] - Element to attach handler to.
	 * @param {string} type - Name of event (ex: "click").
	 * @param {Function} callback - Callback function.
	 * @returns {Object} Handle with `remove()` method to cancel the listener.
	 */
	var on = function (node, type, callback) {
		var capture = false;

		// Shim support for focusin/focusout where necessary.
		// Don't shim on IE since IE supports focusin/focusout natively, and conversely
		// focus and blur events have a problem that relatedTarget isn't set.
		var captures = "onfocusin" in node ? {} : { focusin: "focus", focusout: "blur" };
		if (type in captures) {
			type = captures[type];
			capture = true;
		}

		// Shim support for Event.key, and fix some wrong/outdated Event.key values
		if (/^key(down|press|up)$/.test(type)) {
			var origFunc = callback;
			callback = function (event) {
				var key = event.key || event.keyIdentifier || String.fromCharCode(event.charCode);

				var fixedKey = {
					// mappings for event.keyIdentifier differences from event.key for special keys
					"U+0020": "Spacebar",
					"U+0008": "Backspace",
					"U+0009": "Tab",
					"U+001B": "Escape",

					// fix for FF 34
					" ": "Spacebar",

					// fix for old key names, see https://www.w3.org/Bugs/Public/show_bug.cgi?id=22084
					"Apps": "ContextMenu",
					"Left": "ArrowLeft",
					"Down": "ArrowDown",
					"Right": "ArrowRight",
					"Up": "ArrowUp",
					"Del": "Delete",
					"Esc": "Escape",

					// fix for Android 4.2
					"U+00007F": "Backspace"
				}[key] || key.replace(/^U\+0*(.*)$/, function (all, hexString) {
					// fix event.keyIdentifier for normal printable characters, ex: "U+0041" --> "A" or "a"
					var code = parseInt(hexString, 16);
					if (code >= 65 && code <= 90 && !event.shiftKey) {
						code += 32;	// uppercase --> lowercase
					}
					return String.fromCharCode(code);
				});

				if (event.key !== fixedKey) {
					// A simple "event.key = fixedKey" doesn't work on FF31 (for " " --> "Spacebar" conversion).
					// And Object.defineProperty(event, "key", {value: fixedKey}); (for "Down" --> "ArrowDown")
					// doesn't work on IE.
					Object.defineProperty(event, "key", {get: function () { return fixedKey; }});
				}

				origFunc(event);
			};
		}

		node.addEventListener(type, callback, capture);

		return {
			remove: function () {
				node.removeEventListener(type, callback, capture);
			}
		};
	};

	/**
	 * Emits a synthetic event of specified type, based on eventObj.
	 * @param {Element} node - Element to emit event on.
	 * @param {string} type - Name of event.
	 * @param {Object} [eventObj] - Properties to mix in to emitted event.  Can also contain
	 * `bubbles` and `cancelable` properties to control how the event is emitted.
	 * @returns {boolean} True if the event was *not* canceled, false if it was canceled.
	 * @example
	 * myWidget.emit("query-success", {});
	 * @protected
	 */
	on.emit = function (node, type, eventObj) {
		eventObj = eventObj || {};
		var bubbles = "bubbles" in eventObj ? eventObj.bubbles : true;
		var cancelable = "cancelable" in eventObj ? eventObj.cancelable : true;

		// Note: can't use jQuery.trigger() because it doesn't work with addEventListener(),
		// see http://bugs.jquery.com/ticket/11047.
		var nativeEvent = node.ownerDocument.createEvent("HTMLEvents");
		nativeEvent.initEvent(type, bubbles, cancelable);
		for (var i in eventObj) {
			if (!(i in nativeEvent)) {
				nativeEvent[i] = eventObj[i];
			}
		}

		return node.dispatchEvent(nativeEvent);
	};

	return on;
});


text:
{% load i18n %}

    {% for field in action_form %}{{ field.label }} {{ field }}{% endfor %}
    <button type="submit" class="button" title="{% trans "Run the selected action" %}" name="index" value="{{ action_index|default:0 }}">{% trans "Go" %}</button>
{% if cl.formset and cl.result_count %}<input type="submit" name="_save" class="default" value="{% trans 'Save' %}"/>{% endif %}


text:
import {regex} from './regex'

let
    class2type = {},
    toString   = Object.prototype.toString;

/**
 * 类型判断
 *
 * @param {string}  type    url tel mobilePhone email account IdCard ip...参考regex 模块导出对象的属性
 * @param {string|number}  string
 * @example
 *
 *
 * ```javascript
 * isType('email','user@163.com')   //=>true
 * ```
 * @returns {boolean}
 */
export function isType(type, string) {
    if (isString(string)||isNumber(string)) {
        if (regex[type] && type !== 'default') {
            string = String(string);
            return regex[type].test(string)
        } else {
            throw Error(`unknown type ${type}`);
        }
    } else {
        throw Error('type should be string or number');
    }
}

/**
 * 判断值是否为function
 *
 * @returns {boolean}
 */
export function isFunction(value) {
    return typeof value === "function"
}

/**
 * 判断值是否为undefined
 *
 * @returns {boolean}
 */
export function isUndefined(value) {
    return typeof value === 'undefined'
}

/**
 * 判断值是否为window
 *
 * @returns {boolean}
 */
export function isWindow(value) {
    return whatIs(value)=== "window"
}

/**
 * 判断值是否为string
 *
 * @returns {boolean}
 */
export function isString(value) {
    return typeof  value === 'string'
}

/**
 * 判断值是否为number
 *
 * @returns {boolean}
 */
export function isNumber(value) {
    return typeof  value === 'number'
}

/**
 * 判断值是否为object(注意:此方法使用Object.prototype.toString.call(value)进行判断)
 *
 * @returns {boolean}
 */
export function isObject(value) {
   return whatIs(value)==='object'
}

/**
 * 判断值是否为广义的object(注意:此方法使用typeof进行判断)
 *
 * @returns {boolean}
 */
export function isGeneralizedObject(value) {
   return typeof value === 'object' && value !== null
}

/**
 * 判断值是否为Date
 *
 * @returns {boolean}
 */
export function isDate(value) {
    return  whatIs(value)=== "date";
}

/**
 * 判断值是否为Plain Object
 *
 * @returns {boolean}
 */
export function isPlainObject(value) {
    return isObject(value) && Object.getPrototypeOf(value) === Object.prototype
}

/**
 * 判断值是否类似array
 *
 * @returns {boolean}
 */
export function isLikeArray(value) {
    return isGeneralizedObject(value) && isNumber(value.length)
}

/**
 * 判断值是否为Array
 * @function isArray
 * @returns {boolean}
 */
export  let isArray = Array.isArray ||
    function (value) {
        return toString.call(value) === '[object Array]'
    };

/**
 * 判断值是否为boolean
 *
 * @returns {boolean}
 */
export function isBoolean(value) {
    return typeof value === 'boolean'
}

/**
 * 判断值的类型
 *@example
 *```javascript
 *whatIs(new Date())//=>'date'
 * whatIs(null)//=>'null'
 *
 *```
 * @returns {string}
 */
export function whatIs(value) {
    return /(?:(\S*)])/.exec( toString.call(value) )[1].toLowerCase()
}

/**
 * 判断值是否为dom对象
 * @function isDOM
 *@example
 *```javascript
 *isDOM(document.querySelector('div'))
 *
 *
 *```
 * @returns {boolean}
 */
export const isDOM=(function(){
    return ( typeof HTMLElement === 'function' ) ?
        function(obj){
            return obj instanceof HTMLElement;
        } :
        function(obj){
            return obj && typeof obj === 'object' && obj.nodeType === 1 && isString( obj.nodeName) ;
        }
})();


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>objconfig.processor package — ObjConfig 1.2.0 documentation</title>

    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="objconfig.reader package" href="objconfig.reader.html" />
    <link rel="prev" title="objconfig.exception package" href="objconfig.exception.html" />

Navigation

          index

          modules |

          next |

          previous |

ObjConfig 1.2.0 documentation »

objconfig »

objconfig package »

objconfig.processor package¶

Submodules¶

objconfig.processor.processorinterface module¶

This is a port of zend-config to Python

Some idioms of PHP are still employed, but where possible I have Pythonized it

Following is the header as given in zend-config:

class objconfig.processor.processorinterface.ProcessorInterface[source]¶

Bases: object

The following is an 'interface' (abstraction) to be implemented
by all configuration processors

process(value)[source]¶

Following is the header as given in zend-config:

/**
 * Process the whole Config structure and recursively parse all its values.
 *
 * @param  Config $value
 * @return Config
 */

processValue(value)[source]¶

Following is the header as given in zend-config:

/**
 * Process a single value
 *
 * @param  mixed $value
 * @return mixed
 */

objconfig.processor.token module¶

This is a port of zend-config to Python

Some idioms of PHP are still employed, but where possible I have Pythonized it

Following is the header as given in zend-config:

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the
 *            canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc.
 *            (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

class objconfig.processor.token.Token(tokens=None, prefix=", suffix=")[source]¶

Bases: objconfig.processor.processorinterface.ProcessorInterface

Following is the class documentation as given in zend-config:

No class documentation was given.

addToken(token, value)[source]¶

Following is the class documentation as given in zend-config:

/**
 * Add new token.
 *
 * @param  string $token
 * @param  mixed $value
 * @return Token
 * @throws Exception\InvalidArgumentException
 */

buildMap()[source]¶

Following is the class documentation as given in zend-config:

/**
 * Build replacement map
 *
 * @return array
 */

doProcess(value, replacements)[source]¶

CHANGELOG:
objconfig v1.1: edit value in place rather than return copy - 3/2/2017

Following is the class documentation as given in zend-config:

/**
 * Applies replacement map to the given value by modifying the value itself
 *
 * @param mixed $value
 * @param array $replacements
 *
 * @return mixed
 *
 * @throws Exception\InvalidArgumentException if the provided value is a read-only {@see Config}
 */

getPrefix()[source]¶

Following is the class documentation as given in zend-config:

/**
 * @return string
 */

getSuffix()[source]¶

Following is the class documentation as given in zend-config:

/**
 * @return string
 */

getTokens()[source]¶

Following is the class documentation as given in zend-config:

/**
 * Get current token registry.
 *
 * @return array
 */

process(config)[source]¶

Following is the class documentation as given in zend-config:

/**
 * Process
 *
 * @param  Config $config
 * @return Config
 * @throws Exception\InvalidArgumentException
 */

processValue(value)[source]¶

Following is the class documentation as given in zend-config:

/**
 * Process a single value
 *
 * @param $value
 * @return mixed
 */

setPrefix(prefix)[source]¶

Following is the class documentation as given in zend-config:

/**
 * @param  string $prefix
 * @return Token
 */

setSuffix(suffix)[source]¶

Following is the class documentation as given in zend-config:

/**
 * @param  string $suffix
 * @return Token
 */

setToken(token, value)[source]¶

Following is the class documentation as given in zend-config:

/**
 * Add new token.
 *
 * @param string $token
 * @param mixed $value
 * @return Token
 */

setTokens(tokens)[source]¶

Following is the class documentation as given in zend-config:

/**
 * Set token registry.
 *
 * @param  array|Config|Traversable  $tokens  Associative array of TOKEN => value
 *                                            to replace it with
 * @return Token
 * @throws Exception\InvalidArgumentException
 */

Module contents¶

Table Of Contents

objconfig.processor package

Submodules

objconfig.processor.processorinterface module

objconfig.processor.token module

Module contents

Previous topic

objconfig.exception package

Next topic

objconfig.reader package

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          modules |

          next |

          previous |

ObjConfig 1.2.0 documentation »

objconfig »

objconfig package »

        © Copyright 2017, Asher Wolfstein.
      Created using Sphinx 1.6.2.


text:
#if NET40_OR_GREATER || TARGETS_NETSTANDARD || TARGETS_NETCOREAPP // PUBLIC_API_CHANGES. TODO: update after fixes in Theraot.Core
using System;
using System.Reflection;

namespace CodeJam.Metadata
{
	///
	/// Metadata reader interface.
	///
	public interface IMetadataReader
	{
		///
		/// Returns custom attributes applied to provided type.
		///
		/// <param name="type">Object type</param>
		/// <param name="inherit">true to search this member's inheritance chain to find the attributes; otherwise, false.</param>
		/// <typeparam name="T">The type of attribute to search for. Only attributes that are assignable to this type are returned.</typeparam>
		/// <returns>Array of custom attributes.</returns>
		T[] GetAttributes<T>(Type type, bool inherit = true) where T : Attribute;

		///
		/// Returns custom attributes applied to provided type member.
		///
		/// <param name="memberInfo">Type member.</param>
		/// <param name="inherit">true to search this member's inheritance chain to find the attributes; otherwise, false.</param>
		/// <typeparam name="T">The type of attribute to search for. Only attributes that are assignable to this member are returned.</typeparam>
		/// <returns>Array of custom attributes.</returns>
		T[] GetAttributes<T>(MemberInfo memberInfo, bool inherit = true) where T : Attribute;
	}
}

#endif


text:
function writeAMICI(this,modelname)
    % writeAMICI writes the symbolic information from an SBMLode object
    % into an AMICI model definition file
    %
    % Parameters:
    %  modelname: target name of the model (_syms.m will be appended to the name )
    %
    % Return values:
    % void

    fprintf('writing file ...\n')
    fid = fopen([modelname '_syms.m'],'w');

    fprintf(fid,['function model = ' modelname '_syms()\n']);
    fprintf(fid,'\n');
    if(strcmp(this.time_symbol,''))
        fprintf(fid,'t = sym(''t'');\n');
    else
        fprintf(fid,[this.time_symbol ' = sym(''t'');\n']);
    end
    fprintf(fid,'\n');
    fprintf(fid,'avogadro = 6.02214179e23;');

%     fprintf(fid,'model.debug = true;\n');
    writeDefinition('STATES','x','state',this,fid)
    writeDefinition('PARAMETERS','p','parameter',this,fid)
    writeDefinition('CONDITIONS','k','condition',this,fid)
    writeDerived('DYNAMICS','xdot','xdot',this,fid)
    writeDerived('INITIALIZATION','x0','initState',this,fid)
    writeDerived('OBSERVABLES','y','observable',this,fid)
    fprintf(fid,'\n');
    fprintf(fid,'\n');
    fprintf(fid,['% EVENTS\n']);
    for ievent = 1:length(this.trigger)
        str_trigger = char(this.trigger(ievent));
        str_bolus = strjoin(arrayfun(@char,this.bolus(:,ievent),'UniformOutput',false),',');
        fprintf(fid,['model.event(' num2str(ievent) ') = amievent(' ...
            str_trigger ', ...\n' ...
            '[' str_bolus '], ...\n' ...
            '[]);\n']);
    end
    fprintf(fid,'\n');
    fprintf(fid,'end\n');
    fprintf(fid,'\n');
    fprintf(fid,'function r = pow(x,y)\n');
    fprintf(fid,'\n');
    fprintf(fid,'    r = x^y;\n');
    fprintf(fid,'\n');
    fprintf(fid,'end\n');
    fprintf(fid,'\n');
    fprintf(fid,'function r = power(x,y)\n');
    fprintf(fid,'\n');
    fprintf(fid,'    r = x^y;\n');
    fprintf(fid,'\n');
    fprintf(fid,'end\n');
    fprintf(fid,'\n');

    for ifun = 1:length(this.funmath)
        fprintf(fid,['function r = ' this.funarg{ifun} '\n']);
        fprintf(fid,'\n');
        fprintf(fid,['    r = ' this.funmath{ifun} ';\n']);
        fprintf(fid,'\n');
        fprintf(fid,'end\n');
        fprintf(fid,'\n');
    end

    for fun = {'factorial','cei','psi'}
        fprintUnsupportedFunctionError(fun{1},fid)
    end

    fclose(fid);
end

function writeDefinition(header,identifier,field,this,fid)
    fprintf(fid,'\n');
    fprintf(fid,'\n');
    fprintf(fid,['%%%%\n%% ' header '\n']);
    if(length(this.(field))>0)
        fprintf(fid,['syms ' strjoin(cellfun(@char,num2cell(this.(field)),'UniformOutput',false)) '\n']);
    end
    fprintf(fid,['model.sym.' identifier ' = [' strjoin(cellfun(@char,num2cell(this.(field)),'UniformOutput',false),',') '];\n']);
end

function writeDerived(header,identifier,field,this,fid)
    fprintf(fid,'\n');
    fprintf(fid,'\n');
    fprintf(fid,['%%%%\n%% ' header '\n']);
    fprintf(fid,'\n');
    if(strcmp(header,'OBSERVABLES'))
        fprintf(fid,['%% ' strjoin(cellfun(@char,num2cell(this.observable_name),'UniformOutput',false),'\n%% ')  '\n']);
    end
    fprintf(fid,['model.sym.' identifier ' = [' strjoin(cellfun(@char,num2cell(this.(field)),'UniformOutput',false),', ...\n') '];']);
end

function fprintUnsupportedFunctionError(functionName,fid)
    fprintf(fid,['function r = ' functionName '(x)\n']);
    fprintf(fid,'\n');
    fprintf(fid,['    error(''The ' functionName ' function is currently not supported!'');\n']);
    fprintf(fid,'\n');
    fprintf(fid,'end\n');
    fprintf(fid,'\n');
end


text:
package org.apache.beam.sdk.io.aws.sns;

import com.amazonaws.ResponseMetadata;
import com.amazonaws.http.SdkHttpMetadata;
import com.amazonaws.services.sns.model.PublishResult;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.CoderException;
import org.apache.beam.sdk.coders.CustomCoder;
import org.apache.beam.sdk.coders.NullableCoder;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.io.aws.coders.AwsCoders;

/** Coders for SNS {@link PublishResult}. */
@SuppressWarnings({
  "nullness" // TODO(https://github.com/apache/beam/issues/20497)
})
public final class PublishResultCoders {

  private static final Coder<String> MESSAGE_ID_CODER = StringUtf8Coder.of();
  private static final Coder<ResponseMetadata> RESPONSE_METADATA_CODER =
      NullableCoder.of(AwsCoders.responseMetadata());

  private PublishResultCoders() {}

  /**
   * Returns a new PublishResult coder which by default serializes only the messageId.
   *
   * @return the PublishResult coder
   */
  public static Coder<PublishResult> defaultPublishResult() {
    return new PublishResultCoder(null, null);
  }

  /**
   * Returns a new PublishResult coder which serializes the sdkResponseMetadata and sdkHttpMetadata,
   * including the HTTP response headers.
   *
   * @return the PublishResult coder
   */
  public static Coder<PublishResult> fullPublishResult() {
    return new PublishResultCoder(
        RESPONSE_METADATA_CODER, NullableCoder.of(AwsCoders.sdkHttpMetadata()));
  }

  /**
   * Returns a new PublishResult coder which serializes the sdkResponseMetadata and sdkHttpMetadata,
   * but does not include the HTTP response headers.
   *
   * @return the PublishResult coder
   */
  public static Coder<PublishResult> fullPublishResultWithoutHeaders() {
    return new PublishResultCoder(
        RESPONSE_METADATA_CODER, NullableCoder.of(AwsCoders.sdkHttpMetadataWithoutHeaders()));
  }

  static class PublishResultCoder extends CustomCoder<PublishResult> {

    private final Coder<ResponseMetadata> responseMetadataEncoder;
    private final Coder<SdkHttpMetadata> sdkHttpMetadataCoder;

    private PublishResultCoder(
        Coder<ResponseMetadata> responseMetadataEncoder,
        Coder<SdkHttpMetadata> sdkHttpMetadataCoder) {
      this.responseMetadataEncoder = responseMetadataEncoder;
      this.sdkHttpMetadataCoder = sdkHttpMetadataCoder;
    }

    @Override
    public void encode(PublishResult value, OutputStream outStream)
        throws CoderException, IOException {
      MESSAGE_ID_CODER.encode(value.getMessageId(), outStream);
      if (responseMetadataEncoder != null) {
        responseMetadataEncoder.encode(value.getSdkResponseMetadata(), outStream);
      }
      if (sdkHttpMetadataCoder != null) {
        sdkHttpMetadataCoder.encode(value.getSdkHttpMetadata(), outStream);
      }
    }

    @Override
    public PublishResult decode(InputStream inStream) throws CoderException, IOException {
      String messageId = MESSAGE_ID_CODER.decode(inStream);
      PublishResult publishResult = new PublishResult().withMessageId(messageId);
      if (responseMetadataEncoder != null) {
        publishResult.setSdkResponseMetadata(responseMetadataEncoder.decode(inStream));
      }
      if (sdkHttpMetadataCoder != null) {
        publishResult.setSdkHttpMetadata(sdkHttpMetadataCoder.decode(inStream));
      }
      return publishResult;
    }

    @Override
    public void verifyDeterministic() throws NonDeterministicException {
      MESSAGE_ID_CODER.verifyDeterministic();
      if (responseMetadataEncoder != null) {
        responseMetadataEncoder.verifyDeterministic();
      }
      if (sdkHttpMetadataCoder != null) {
        sdkHttpMetadataCoder.verifyDeterministic();
      }
    }
  }
}


text:
define(['angular','services/module-name'], function (angular,moduleName) {
    angular.module(moduleName).factory('Utils', ["$timeout", function ($timeout) {

        var waitForDomRetryCounts = {};

        var data = {

            stickTabHeader: function ($element) {
                var self = this;
                var tabsWrapper = element.find('md-tabs-wrapper');
                self.stickTabHeader($element, tabsWrapper);

            },
            stickTabHeader: function ($element, $tabsWrapper) {
                var header = angular.element('.page-header');
                var headerHeight = header.height();

                var window_top = 0;
                var div_top = $element.find('.sticky-anchor').offset().top;
                if (div_top < headerHeight) {
                    if (div_top < 0) {
                        $tabsWrapper.css('top', Math.abs(div_top) + headerHeight + 'px')
                    }
                    else {
                        $tabsWrapper.css('top', Math.abs(headerHeight - Math.abs(div_top)) + 'px')
                    }
                } else {
                    $tabsWrapper.css('top', '0px')
                }
            },
            maskProfanity: function (str) {
                return str;
            },

            /**
             *
             * @param selector  element selector (i.e. #TableId)
             * @param callbackFn  // the function to execute when the selector element is found in the DOM
             */
            waitForDomElementReady: function (selector, callbackFn) {
                if (waitForDomRetryCounts[selector] == undefined) {
                    waitForDomRetryCounts[selector] = 0;
                }
                var $ele = angular.element(selector);
                if ($ele.length > 0) {
                    delete waitForDomRetryCounts[selector];
                    callbackFn();
                }
                else {

                    waitForDomRetryCounts[selector] += 1;
                    if (waitForDomRetryCounts[selector] <= 50) {
                        $timeout(data.waitForDomElementReady, 5, false, selector, callbackFn);
                    }
                }
            },

            strEndsWith: function (str, suffix) {
                return str.indexOf(suffix, str.length - suffix.length) !== -1;
            },
            endsWith: function (str, suffix) {
                return this.strEndsWith(str, suffix);
            },
            startsWith: function (str, prefix) {
                return str.indexOf(prefix) === 0;
            },
            camelCaseToWords: function (str) {
                return str.match(/^[a-z]+|[A-Z][a-z]*/g).map(function (x) {
                    return x[0].toUpperCase() + x.substr(1).toLowerCase();
                }).join(' ');
            },

            capitalizeFirstLetter: function (string) {
                if (string && string != '') {
                    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
                }
                return '';
            },

            convertDate: function (date) {
                if (date == null) {
                    return "--";
                }
                var local = new Date(date);
                local.setMinutes(local.getMinutes() - local.getTimezoneOffset());
                return local.toISOString().slice(0, 10) + " " + local.toISOString().slice(11, 19);
            },
            dateDifference: function (startDate, endDate) {
                if (startDate == null || endDate == null) {
                    return "N/A";
                }
                else {
                    var msec = endDate - startDate;
                    return this.formatTimeMinSec(msec);
                }
            },

            dateDifferenceMs: function (startDate, endDate) {
                var diff = endDate - startDate;
                return diff;
            },
            formatTimeMinSec: function (timeInMSec) {
                //       return self.TimeDiffString(timeInMSec);
                if (timeInMSec == null) {
                    return "N/A";
                }
                else {
                    if (timeInMSec < 0) {
                        return "0 sec";
                    }
                    var sec_num = timeInMSec / 1000;
                    sec_num = parseInt(sec_num, 10);
                    var hours = Math.floor(sec_num / 3600);
                    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
                    var seconds = sec_num - (hours * 3600) - (minutes * 60);

                    var str = seconds + " sec";
                    if (hours == 0) {
                        if (minutes != 0) {
                            str = minutes + " min " + str;
                        }
                    }
                    else {
                        str = hours + " hrs " + minutes + " min " + str;
                    }
                    return str;
                }

            },

            TimeDiffString: function (timeInMs) {
                var diffString = moment.duration(timeInMs).format('HH:mm:ss');
                if (diffString == '00') {
                    diffString = '0';
                }
                var parts = diffString.split(':');
                var suffixes = ['hr', 'min', 'sec'];
                var len = parts.length;
                var suffixIndex = Math.abs(len - 3);

                var startIndex = parts.length;
                var timeString = '';
                for (var i = 0; i < parts.length; i++) {
                    if (i > 0) {
                        timeString += ' ';
                    }
                    timeString += parts[i] + ' ' + suffixes[suffixIndex];
                    suffixIndex++;
                }
                return timeString;
            },
            DateDiffString: function (date1, date2) {
                var diff = date2.getTime() - date2.getTime();
                return this.TimeDiffString(diff);
            },

            getParameterByName: function (name) {
                var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
                return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
            },
            toBoolean: function (str) {
                if (typeof str == "boolean") {
                    return str;
                }
                else if (typeof str == "string") {
                    return str.toLowerCase() == "true";
                }
                else if (typeof str == "number") {
                    return str == 1;
                }
                return false;
            },

            resolveStatusClass: function (status, exitCode) {

                var statusClass = 'status-info';
                switch (status) {
                    case "STARTED":
                    case "RUNNING":
                    case "COMPLETED":
                        if (exitCode && exitCode == 'FAILED') {
                            statusClass = 'status-errors';
                        }
                        else {
                            statusClass = 'status-healthy';
                        }
                        break;
                    case "FAILED":
                        statusClass = 'status-errors';
                        break;
                    default:
                }
                return statusClass;
            }

        };
        return data;

    }]);
});


text:
pub mod acquire_pessimistic_lock;
pub mod check_data_constraint;
pub mod check_txn_status;
pub mod cleanup;
pub mod commit;
pub mod gc;
pub(crate) mod get_old_value;
pub mod prewrite;
pub mod tests;


text:
namespace blink {

DoublePoint::operator gfx::PointF() const {
  return gfx::PointF(ClampTo<float>(x_), ClampTo<float>(y_));
}

DoublePoint DoublePoint::ExpandedTo(const DoublePoint& other) const {
  return DoublePoint(std::max(x_, other.x_), std::max(y_, other.y_));
}

DoublePoint DoublePoint::ShrunkTo(const DoublePoint& other) const {
  return DoublePoint(std::min(x_, other.x_), std::min(y_, other.y_));
}

std::ostream& operator<<(std::ostream& ostream, const DoublePoint& point) {
  return ostream << point.ToString();
}

String DoublePoint::ToString() const {
  return String::Format("%lg,%lg", X(), Y());
}

}  // namespace blink


text:
<?php namespace frontend\controllers;

use common\models\user\LoginForm;
use common\models\user\User;
use frontend\models\auth\SignupForm;
use frontend\models\auth\SignupStudentForm;
use frontend\models\auth\SignupTeacherForm;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\Controller;

class WelcomeController extends Controller
{
    const REGISTER_STEP1 = 'register_step_1';

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['?']
                    ]
                ],
                'denyCallback' => function () {
                    /* @var \frontend\components\web\User $user */
                    $user = Yii::$app->user;
                    return $this->redirect([$user->homeUrl]);
                }
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'index' => ['get', 'post'],
                    'register' => ['get', 'post'],
                    'register-student' => ['get', 'post'],
                    'register-teacher' => ['get', 'post'],
                    'register-owner' => ['get', 'post']
                ]
            ]
        ];
    }

    public function actionIndex()
    {
        $model = new LoginForm();

        if (isset($_POST['LoginForm'])) {
            if ($model->load(Yii::$app->request->post()) && $model->login()) {
                return $this->redirect([Yii::$app->user->homeUrl]);
            }
        }

        return $this->render('login', [
            'form' => $model
        ]);
    }

    /**
     * Этот метод принимает данные, посланные клиентом
     * на первом шаге регистрации. Если они валидны -
     * происоходит перенаправление на второй шаг регистрации.
     *
     * @return bool|string|\yii\web\Response
     */
    public function actionRegister()
    {
        $model = new SignupForm();
        $app = Yii::$app;

        if ($app->session->has(self::REGISTER_STEP1)) {
            $model->setAttributes($app->session->get(self::REGISTER_STEP1));
            $app->session->remove(self::REGISTER_STEP1);
        }

        if (isset($_POST['SignupForm'])) {
            if ($model->load($app->request->post()) && $model->validate()) {
                $app->session->set(self::REGISTER_STEP1, $_POST['SignupForm']);
                return $this->redirectToStep2($model);
            }
        }

        return $this->render('register', [
            'form' => $model
        ]);
    }

    /**
     * Этот метод принимает данные с формы второго шага
     * регистрации пользователя. Если данные валидны, то он
     * сохраняет пользователя в базу данных, выставляя ему роль "Студент"
     *
     * NOTE:    перед валидацией данных, метод проверяет, что в сессии
     *          хрянятся данные с первого шага, если их там нет -
     *          пользователь будет перенаправлен на него.
     *
     * @return string|\yii\web\Response
     */
    public function actionRegisterStudent()
    {
        $model = new SignupStudentForm();

        if (!$this->checkFirstStep($model)) {
            Yii::$app->session->remove(self::REGISTER_STEP1);
            return $this->redirect(['welcome/register']);
        }

        if (isset($_POST['SignupStudentForm'])) {
            if ($model->load(Yii::$app->request->post()) && ($user = $model->signup())) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->redirect([Yii::$app->user->homeUrl]);
                }
            }
        }
        return $this->render('register_student', [
            'form' => $model
        ]);
    }

    /**
     * Этот метод принимает данные с формы второго шага
     * регистрации пользователя. Если данные валидны, то он
     * сохраняет пользователя в базу данных, выставляя ему роль "Преподаватель"
     *
     * NOTE:    перед валидацией данных, метод проверяет, что в сессии
     *          хрянятся данные с первого шага, если их там нет -
     *          пользователь будет перенаправлен на него.
     *
     * @return string|\yii\web\Response
     */
    public function actionRegisterTeacher()
    {
        $model = new SignupTeacherForm();

        if (!$this->checkFirstStep($model)) {
            Yii::$app->session->remove(self::REGISTER_STEP1);
            return $this->redirect(['welcome/register']);
        }

        if (isset($_POST['SignupTeacherForm'])) {
            if ($model->load(Yii::$app->request->post()) && ($user = $model->signup())) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->redirect([Yii::$app->user->homeUrl]);
                }
            }
        }

        return $this->render('register_teacher', [
            'form' => $model
        ]);
    }

    /**
     * В зависимости от роли пользователя определяет url
     * для второго шага регистрации и перенаправляет туда
     *
     * @param SignupForm $model
     * @return bool|\yii\web\Response
     */
    public function redirectToStep2(SignupForm $model)
    {
        switch ($model->role) {
            case User::COLLEGE_OWNER:
                $route = 'welcome/register-owner'; break;
            case User::STUDENT:
                $route = 'welcome/register-student'; break;
            case User::TEACHER:
                $route = 'welcome/register-teacher'; break;
            default:
                return false;
        }

        return $this->redirect([$route]);
    }

    /**
     * Если в сессии есть данные с первого шага регистрации -
     * возвращает результат их валидации, иначе - возвращает false
     *
     * @param SignupForm $model
     * @return bool
     */
    protected function checkFirstStep(SignupForm $model)
    {
        $primaryData = Yii::$app->session->get(self::REGISTER_STEP1);

        if ($primaryData) {
            $model->setAttributes($primaryData);
            return $model->validate(['email', 'password', 'password_repeat', 'role']);
        }

        return false;
    }

}


text:
layout: post
title: 	"RavenDB Talks"
date: 	2011-12-30 08:00:00
tags: [ravendb, talks]
---
I'd like to invite you to my RavenDB/NoSQL talks:

  * [5th of January at .NET User Group in Łódź](http://www.codeguru.pl/kalendarium/podglad-wydarzenia/raven-db---dokumentowe-bazy-danych,6004) (level 200)
  * 28th of January at SoftDevCon in Kraków (NO Power Point type of presentation)

Feel free to come, listen and discuss!

I hope I'll be speaking at some more events during this year. Now - let's go back digging inside some geeky, cool stuff.


text:
from sqlalchemy.test.testing import eq_
from sqlalchemy import *
from sqlalchemy.databases import firebird
from sqlalchemy.exc import ProgrammingError
from sqlalchemy.sql import table, column
from sqlalchemy.test import *

class DomainReflectionTest(TestBase, AssertsExecutionResults):
    "Test Firebird domains"

    __only_on__ = 'firebird'

    @classmethod
    def setup_class(cls):
        con = testing.db.connect()
        try:
            con.execute('CREATE DOMAIN int_domain AS INTEGER DEFAULT 42 NOT NULL')
            con.execute('CREATE DOMAIN str_domain AS VARCHAR(255)')
            con.execute('CREATE DOMAIN rem_domain AS BLOB SUB_TYPE TEXT')
            con.execute('CREATE DOMAIN img_domain AS BLOB SUB_TYPE BINARY')
        except ProgrammingError, e:
            if not "attempt to store duplicate value" in str(e):
                raise e
        con.execute('''CREATE GENERATOR gen_testtable_id''')
        con.execute('''CREATE TABLE testtable (question int_domain,
                                               answer str_domain DEFAULT 'no answer',
                                               remark rem_domain DEFAULT '',
                                               photo img_domain,
                                               d date,
                                               t time,
                                               dt timestamp,
                                               redundant str_domain DEFAULT NULL)''')
        con.execute('''ALTER TABLE testtable
                       ADD CONSTRAINT testtable_pk PRIMARY KEY (question)''')
        con.execute('''CREATE TRIGGER testtable_autoid FOR testtable
                       ACTIVE BEFORE INSERT AS
                       BEGIN
                         IF (NEW.question IS NULL) THEN
                           NEW.question = gen_id(gen_testtable_id, 1);
                       END''')

    @classmethod
    def teardown_class(cls):
        con = testing.db.connect()
        con.execute('DROP TABLE testtable')
        con.execute('DROP DOMAIN int_domain')
        con.execute('DROP DOMAIN str_domain')
        con.execute('DROP DOMAIN rem_domain')
        con.execute('DROP DOMAIN img_domain')
        con.execute('DROP GENERATOR gen_testtable_id')

    def test_table_is_reflected(self):
        from sqlalchemy.types import Integer, Text, BLOB, String, Date, Time, DateTime
        metadata = MetaData(testing.db)
        table = Table('testtable', metadata, autoload=True)
        eq_(set(table.columns.keys()),
            set(['question', 'answer', 'remark',
                 'photo', 'd', 't', 'dt', 'redundant']),
            "Columns of reflected table didn't equal expected columns")
        eq_(table.c.question.primary_key, True)
        # disabled per http://www.sqlalchemy.org/trac/ticket/1660
        # eq_(table.c.question.sequence.name, 'gen_testtable_id')
        assert isinstance(table.c.question.type, Integer)
        eq_(table.c.question.server_default.arg.text, "42")
        assert isinstance(table.c.answer.type, String)
        assert table.c.answer.type.length == 255
        eq_(table.c.answer.server_default.arg.text, "'no answer'")
        assert isinstance(table.c.remark.type, Text)
        eq_(table.c.remark.server_default.arg.text, "''")
        assert isinstance(table.c.photo.type, BLOB)
        assert table.c.redundant.server_default is None
        # The following assume a Dialect 3 database
        assert isinstance(table.c.d.type, Date)
        assert isinstance(table.c.t.type, Time)
        assert isinstance(table.c.dt.type, DateTime)

class BuggyDomainReflectionTest(TestBase, AssertsExecutionResults):
    "Test Firebird domains, see [ticket:1663] and http://tracker.firebirdsql.org/browse/CORE-356"

    __only_on__ = 'firebird'

    # NB: spacing and newlines are *significant* here!
    # PS: this test is superfluous on recent FB, where the issue 356 is probably fixed...

    AUTOINC_DM = """\
CREATE DOMAIN AUTOINC_DM
AS
NUMERIC(18,0)
"""

    MONEY_DM = """\
CREATE DOMAIN MONEY_DM
AS
NUMERIC(15,2)
DEFAULT 0
CHECK (VALUE BETWEEN -
9999999999999.99 AND +9999999999999.99)
"""

    NOSI_DM = """\
CREATE DOMAIN
NOSI_DM AS
CHAR(1)
DEFAULT 'N'
NOT NULL
CHECK (VALUE IN
('S', 'N'))
"""

    RIT_TESORERIA_CAPITOLO_DM = """\
CREATE DOMAIN RIT_TESORERIA_CAPITOLO_DM
AS
VARCHAR(6)
CHECK ((VALUE IS NULL) OR (VALUE =
UPPER(VALUE)))
"""

    DEF_ERROR_TB = """\
CREATE TABLE DEF_ERROR (
RITENUTAMOV_ID AUTOINC_DM
NOT NULL,
RITENUTA MONEY_DM,
INTERESSI MONEY_DM
DEFAULT
0,
STAMPATO_MODULO NOSI_DM DEFAULT 'S',
TESORERIA_CAPITOLO
RIT_TESORERIA_CAPITOLO_DM)
"""

    DEF_ERROR_NODOM_TB = """\
CREATE TABLE
DEF_ERROR_NODOM (
RITENUTAMOV_ID INTEGER NOT NULL,
RITENUTA NUMERIC(15,2) DEFAULT 0,
INTERESSI NUMERIC(15,2)
DEFAULT
0,
STAMPATO_MODULO CHAR(1) DEFAULT 'S',
TESORERIA_CAPITOLO
CHAR(1))
"""

    DOM_ID = """
CREATE DOMAIN DOM_ID INTEGER NOT NULL
"""

    TABLE_A = """\
CREATE TABLE A (
ID DOM_ID /* INTEGER NOT NULL */ DEFAULT 0 )
"""

    @classmethod
    def setup_class(cls):
        con = testing.db.connect()
        con.execute(cls.AUTOINC_DM)
        con.execute(cls.MONEY_DM)
        con.execute(cls.NOSI_DM)
        con.execute(cls.RIT_TESORERIA_CAPITOLO_DM)
        con.execute(cls.DEF_ERROR_TB)
        con.execute(cls.DEF_ERROR_NODOM_TB)

        con.execute(cls.DOM_ID)
        con.execute(cls.TABLE_A)

    @classmethod
    def teardown_class(cls):
        con = testing.db.connect()
        con.execute('DROP TABLE a')
        con.execute('DROP DOMAIN dom_id')
        con.execute('DROP TABLE def_error_nodom')
        con.execute('DROP TABLE def_error')
        con.execute('DROP DOMAIN rit_tesoreria_capitolo_dm')
        con.execute('DROP DOMAIN nosi_dm')
        con.execute('DROP DOMAIN money_dm')
        con.execute('DROP DOMAIN autoinc_dm')

    def test_tables_are_reflected_same_way(self):
        metadata = MetaData(testing.db)

        table_dom = Table('def_error', metadata, autoload=True)
        table_nodom = Table('def_error_nodom', metadata, autoload=True)

        eq_(table_dom.c.interessi.server_default.arg.text,
            table_nodom.c.interessi.server_default.arg.text)
        eq_(table_dom.c.ritenuta.server_default.arg.text,
            table_nodom.c.ritenuta.server_default.arg.text)
        eq_(table_dom.c.stampato_modulo.server_default.arg.text,
            table_nodom.c.stampato_modulo.server_default.arg.text)

    def test_intermixed_comment(self):
        metadata = MetaData(testing.db)

        table_a = Table('a', metadata, autoload=True)

        eq_(table_a.c.id.server_default.arg.text, "0")

class CompileTest(TestBase, AssertsCompiledSQL):
    __dialect__ = firebird.FBDialect()

    def test_alias(self):
        t = table('sometable', column('col1'), column('col2'))
        s = select([t.alias()])
        self.assert_compile(s, "SELECT sometable_1.col1, sometable_1.col2 FROM sometable AS sometable_1")

        dialect = firebird.FBDialect()
        dialect._version_two = False
        self.assert_compile(s, "SELECT sometable_1.col1, sometable_1.col2 FROM sometable sometable_1",
            dialect = dialect
        )

    def test_function(self):
        self.assert_compile(func.foo(1, 2), "foo(:foo_1, :foo_2)")
        self.assert_compile(func.current_time(), "CURRENT_TIME")
        self.assert_compile(func.foo(), "foo")

        m = MetaData()
        t = Table('sometable', m, Column('col1', Integer), Column('col2', Integer))
        self.assert_compile(select([func.max(t.c.col1)]), "SELECT max(sometable.col1) AS max_1 FROM sometable")

    def test_substring(self):
        self.assert_compile(func.substring('abc', 1, 2), "SUBSTRING(:substring_1 FROM :substring_2 FOR :substring_3)")
        self.assert_compile(func.substring('abc', 1), "SUBSTRING(:substring_1 FROM :substring_2)")

    def test_update_returning(self):
        table1 = table('mytable',
            column('myid', Integer),
            column('name', String(128)),
            column('description', String(128)),
        )

        u = update(table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name)
        self.assert_compile(u, "UPDATE mytable SET name=:name RETURNING mytable.myid, mytable.name")

        u = update(table1, values=dict(name='foo')).returning(table1)
        self.assert_compile(u, "UPDATE mytable SET name=:name "\
            "RETURNING mytable.myid, mytable.name, mytable.description")

        u = update(table1, values=dict(name='foo')).returning(func.length(table1.c.name))
        self.assert_compile(u, "UPDATE mytable SET name=:name RETURNING char_length(mytable.name) AS length_1")

    def test_insert_returning(self):
        table1 = table('mytable',
            column('myid', Integer),
            column('name', String(128)),
            column('description', String(128)),
        )

        i = insert(table1, values=dict(name='foo')).returning(table1.c.myid, table1.c.name)
        self.assert_compile(i, "INSERT INTO mytable (name) VALUES (:name) RETURNING mytable.myid, mytable.name")

        i = insert(table1, values=dict(name='foo')).returning(table1)
        self.assert_compile(i, "INSERT INTO mytable (name) VALUES (:name) "\
            "RETURNING mytable.myid, mytable.name, mytable.description")

        i = insert(table1, values=dict(name='foo')).returning(func.length(table1.c.name))
        self.assert_compile(i, "INSERT INTO mytable (name) VALUES (:name) RETURNING char_length(mytable.name) AS length_1")

class MiscTest(TestBase):
    __only_on__ = 'firebird'

    def test_strlen(self):
        # On FB the length() function is implemented by an external
        # UDF, strlen().  Various SA tests fail because they pass a
        # parameter to it, and that does not work (it always results
        # the maximum string length the UDF was declared to accept).
        # This test checks that at least it works ok in other cases.

        meta = MetaData(testing.db)
        t = Table('t1', meta,
            Column('id', Integer, Sequence('t1idseq'), primary_key=True),
            Column('name', String(10))
        )
        meta.create_all()
        try:
            t.insert(values=dict(name='dante')).execute()
            t.insert(values=dict(name='alighieri')).execute()
            select([func.count(t.c.id)],func.length(t.c.name)==5).execute().first()[0] == 1
        finally:
            meta.drop_all()

    def test_server_version_info(self):
        version = testing.db.dialect.server_version_info
        assert len(version) == 3, "Got strange version info: %s" % repr(version)

    def test_percents_in_text(self):
        for expr, result in (
            (text("select '%' from rdb$database"), '%'),
            (text("select '%%' from rdb$database"), '%%'),
            (text("select '%%%' from rdb$database"), '%%%'),
            (text("select 'hello % world' from rdb$database"), "hello % world")
        ):
            eq_(testing.db.scalar(expr), result)


text:
package org.wso2.carbon.logging.service.util;

import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.net.SyslogAppender;
import org.springframework.util.Log4jConfigurer;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.core.util.SystemFilter;
import org.wso2.carbon.logging.service.LogViewerException;
import org.wso2.carbon.logging.service.appender.CarbonMemoryAppender;
import org.wso2.carbon.logging.service.config.ServiceConfigManager;
import org.wso2.carbon.logging.service.config.SyslogConfigManager;
import org.wso2.carbon.logging.service.config.SyslogConfiguration;
import org.wso2.carbon.logging.service.data.SyslogData;
import org.wso2.carbon.logging.service.internal.DataHolder;
import org.wso2.carbon.logging.service.internal.LoggingServiceComponent;
import org.wso2.carbon.logging.service.registry.RegistryManager;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.Pageable;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.carbon.utils.logging.CircularBuffer;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class LoggingUtil {

    public static final String SYSTEM_LOG_PATTERN = "[%d] %5p - %x %m {%c}%n";
    private static final int MAX_LOG_MESSAGES = 200;
    private static final String CARBON_LOGFILE_APPENDER = "CARBON_LOGFILE";
    private static final Log log = LogFactory.getLog(LoggingUtil.class);
    private static RegistryManager registryManager = new RegistryManager();

    public static boolean isStratosService() throws Exception {
        String serviceName = ServerConfiguration.getInstance().getFirstProperty("ServerKey");
        return ServiceConfigManager.isStratosService(serviceName);
    }

    public static void setSystemLoggingParameters(String logLevel, String logPattern)
            throws Exception {
        registryManager.updateConfigurationProperty(LoggingConstants.SYSTEM_LOG_LEVEL, logLevel);
        registryManager
                .updateConfigurationProperty(LoggingConstants.SYSTEM_LOG_PATTERN, logPattern);
    }

    public static SyslogData getSyslogData() throws Exception {
        return registryManager.getSyslogData();
    }

    private static String[] getAdminServiceNames() {
        ConfigurationContext configurationContext = DataHolder.getInstance()
                .getServerConfigContext();
        Map<String, AxisService> services = configurationContext.getAxisConfiguration()
                .getServices();
        List<String> adminServices = new ArrayList<String>();
        for (Map.Entry<String, AxisService> entry : services.entrySet()) {
            AxisService axisService = entry.getValue();
            if (SystemFilter.isAdminService(axisService)
                    || SystemFilter.isHiddenService(axisService)) {
                adminServices.add(axisService.getName());
            }
        }
        return adminServices.toArray(new String[adminServices.size()]);
    }

    public static int getTenantIdForDomain(String tenantDomain) throws LogViewerException {
        int tenantId;
        TenantManager tenantManager = LoggingServiceComponent.getTenantManager();
        if (tenantDomain == null || tenantDomain.equals("")) {
            tenantId = MultitenantConstants.SUPER_TENANT_ID;
        } else {

            try {
                tenantId = tenantManager.getTenantId(tenantDomain);
            } catch (UserStoreException e) {
                throw new LogViewerException("Cannot find tenant id for the given tenant domain.");
            }
        }
        return tenantId;
    }

    public static boolean isValidTenant(String domain) {
        int tenantId;
        if (domain == null || domain.equals("")) {
            tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        } else {
            try {
                tenantId = LoggingUtil.getTenantIdForDomain(domain);
            } catch (LogViewerException e) {
                return false;
            }
        }

        if (tenantId == org.wso2.carbon.base.MultitenantConstants.INVALID_TENANT_ID) {
            return false;
        }
        return true;
    }

    public static boolean isFileAppenderConfiguredForST() {
        Logger rootLogger = Logger.getRootLogger();
        DailyRollingFileAppender logger = (DailyRollingFileAppender) rootLogger
                .getAppender(CARBON_LOGFILE_APPENDER);
        if (logger != null
                && CarbonContext.getThreadLocalCarbonContext().getTenantId() == org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isAdmingService(String serviceName) {
        String[] adminServices = getAdminServiceNames();
        for (String adminService : adminServices) {
            if (adminService.equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    public static String getSystemLogLevel() throws Exception {
        String systemLogLevel = registryManager
                .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_LEVEL);
        if (systemLogLevel == null) {
            return Logger.getRootLogger().getLevel().toString();
        }
        return systemLogLevel;
    }

    public static String getSystemLogPattern() throws Exception {
        String systemLogPattern = registryManager
                .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_PATTERN);
        if (systemLogPattern == null) {
            return LoggingUtil.SYSTEM_LOG_PATTERN;
        }
        return systemLogPattern;
    }

    public static boolean isValidTenantDomain(String tenantDomain) {
        try {
            getTenantIdForDomain(tenantDomain);
            return true;
        } catch (LogViewerException e) {
            return false;
        }
    }

    public static boolean isManager() {
        if (LoggingConstants.WSO2_STRATOS_MANAGER.equalsIgnoreCase(ServerConfiguration.getInstance()
                .getFirstProperty("ServerKey"))) {
            return true;
        } else {
            return false;
        }
    }

    public static void loadCustomConfiguration() throws Exception {
        // set the appender details

        // we have not provided a facility to add or remove appenders so all the
        // initial appender set should present in the system.
        // and all the initall logger should present in the system
        Set<Appender> appenderSet = new HashSet<Appender>();
        Logger rootLogger = LogManager.getRootLogger();

        // set the root logger level, if the system log level is changed.
        String persistedSystemLoggerLevel = registryManager
                .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_LEVEL);
        boolean systemLogLevelChanged = (persistedSystemLoggerLevel != null);
        if (systemLogLevelChanged) {
            rootLogger.setLevel(Level.toLevel(persistedSystemLoggerLevel));
        }

        String persistedSystemLogPattern = registryManager
                .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_PATTERN);
        boolean systemLogPatternChanged = (persistedSystemLogPattern != null);
        setSystemLoggingParameters(persistedSystemLoggerLevel,
                (systemLogPatternChanged) ? persistedSystemLogPattern : SYSTEM_LOG_PATTERN);

        addAppendersToSet(rootLogger.getAllAppenders(), appenderSet);

        // System log level has been changed, need to update all the loggers and
        // appenders
        if (systemLogLevelChanged) {
            Logger logger;
            Enumeration loggersEnum = LogManager.getCurrentLoggers();
            Level systemLevel = Level.toLevel(persistedSystemLoggerLevel);
            while (loggersEnum.hasMoreElements()) {
                logger = (Logger) loggersEnum.nextElement();
                // we ignore all class level defined loggers
                addAppendersToSet(logger.getAllAppenders(), appenderSet);
                logger.setLevel(systemLevel);
            }

            for (Appender appender : appenderSet) {
                if (appender instanceof AppenderSkeleton) {
                    AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender;
                    appenderSkeleton.setThreshold(systemLevel);
                    appenderSkeleton.activateOptions();
                }
            }
        }

        // Update the logger data according to the data stored in the registry.
        Collection loggerCollection = registryManager.getLoggers();
        if (loggerCollection != null) {
            String[] loggerResourcePaths = loggerCollection.getChildren();
            for (String loggerResourcePath : loggerResourcePaths) {
                String loggerName = loggerResourcePath.substring(LoggingConstants.LOGGERS.length());
                Logger logger = LogManager.getLogger(loggerName);
                Resource loggerResource = registryManager.getLogger(loggerName);
                if (loggerResource != null && logger != null) {
                    logger.setLevel(Level.toLevel(loggerResource
                            .getProperty(LoggingConstants.LoggerProperties.LOG_LEVEL)));
                    logger.setAdditivity(Boolean.parseBoolean(loggerResource
                            .getProperty(LoggingConstants.LoggerProperties.ADDITIVITY)));
                }
            }
        }

        // update the appender data according to data stored in database
        Collection appenderCollection = registryManager.getAppenders();
        if (appenderCollection != null) {
            String[] appenderResourcePaths = appenderCollection.getChildren();
            for (String appenderResourcePath : appenderResourcePaths) {
                String appenderName = appenderResourcePath.substring(LoggingConstants.APPENDERS
                        .length());
                Appender appender = getAppenderFromSet(appenderSet, appenderName);
                Resource appenderResource = registryManager.getAppender(appenderName);
                if (appenderResource != null && appender != null) {
                    if ((appender.getLayout() != null)
                            && (appender.getLayout() instanceof PatternLayout)) {
                        ((PatternLayout) appender.getLayout())
                                .setConversionPattern(appenderResource
                                        .getProperty(LoggingConstants.AppenderProperties.PATTERN));
                    }
                    if (appender instanceof FileAppender) {
                        FileAppender fileAppender = ((FileAppender) appender);

                        // resolves the log file path, if not absolute path, calculate with CARBON_HOME as the base
                        Path logFilePath = Paths.get(appenderResource.getProperty(
                                LoggingConstants.AppenderProperties.LOG_FILE_NAME));
                        if (!logFilePath.isAbsolute()) {
                            logFilePath = Paths.get(System.getProperty(ServerConstants.CARBON_HOME)).resolve(logFilePath);
                        }
                        fileAppender.setFile(logFilePath.normalize().toString());
                        fileAppender.activateOptions();
                    }

                    if (appender instanceof CarbonMemoryAppender) {
                        CarbonMemoryAppender memoryAppender = (CarbonMemoryAppender) appender;
                        memoryAppender.setCircularBuffer(new CircularBuffer(200));
                        memoryAppender.activateOptions();
                    }

                    if (appender instanceof SyslogAppender) {
                        SyslogAppender syslogAppender = (SyslogAppender) appender;
                        syslogAppender.setSyslogHost(appenderResource
                                .getProperty(LoggingConstants.AppenderProperties.SYS_LOG_HOST));
                        syslogAppender.setFacility(appenderResource
                                .getProperty(LoggingConstants.AppenderProperties.FACILITY));
                    }

                    if (appender instanceof AppenderSkeleton) {
                        AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender;
                        appenderSkeleton.setThreshold(Level.toLevel(appenderResource
                                .getProperty(LoggingConstants.AppenderProperties.THRESHOLD)));
                        appenderSkeleton.activateOptions();
                    }
                }
            }
        }
    }

    private static void addAppendersToSet(Enumeration appenders, Set<Appender> appenderSet) {
        while (appenders.hasMoreElements()) {
            Appender appender = (Appender) appenders.nextElement();
            appenderSet.add(appender);
        }
    }

    public static Appender getAppenderFromSet(Set<Appender> appenderSet, String name) {
        for (Appender appender : appenderSet) {
            if ((appender.getName() != null) && (appender.getName().equals(name))) {
                return appender;
            }
        }
        return null;
    }

    public static void updateConfigurationProperty(String key, String value)
            throws RegistryException {
        registryManager.updateConfigurationProperty(key, value);
    }

    public static String getConfigurationProperty(String key) throws RegistryException {
        return registryManager.getConfigurationProperty(key);
    }

    public static void removeAllLoggersAndAppenders() throws Exception {
        registryManager.removeAllRegistryEntries();
    }

    public static boolean isSysLogAppender(String tenantDomain) throws Exception {
        SyslogConfiguration syslogConfig = SyslogConfigManager.loadSyslogConfiguration();
        return syslogConfig.isSyslogOn();
    }

    public static boolean isSyslogConfigured() throws Exception {
        if (registryManager.getSyslogConfig() == null) {
            return false;
        } else {
            return true;
        }
    }

    public static int getLineNumbers(String logFile) throws Exception {
        InputStream logStream;

        try {
            logStream = getLocalInputStream(logFile);
        } catch (IOException e) {
            throw new LogViewerException("Cannot find the specified file location to the log file",
                    e);
        } catch (Exception e) {
            throw new LogViewerException("Cannot find the specified file location to the log file",
                    e);
        }
        try {
            byte[] c = new byte[1024];
            int count = 0;
            int readChars = 0;
            while ((readChars = logStream.read(c)) != -1) {
                for (int i = 0; i < readChars; ++i) {
                    if (c[i] == '\n') {
                        ++count;
                    }
                }
            }
            return count;
        } catch (IOException e) {
            throw new LogViewerException("Cannot read file size from the " + logFile, e);
        } finally {
            try {
                logStream.close();
            } catch (IOException e) {
                throw new LogViewerException("Cannot close the input stream " + logFile, e);
            }
        }
    }

    public static String[] getLogLinesFromFile(String logFile, int maxLogs, int start, int end)
            throws LogViewerException {
        ArrayList<String> logsList = new ArrayList<String>();
        InputStream logStream;
        if (end > maxLogs) {
            end = maxLogs;
        }
        try {
            logStream = getLocalInputStream(logFile);
        } catch (Exception e) {
            throw new LogViewerException("Cannot find the specified file location to the log file",
                    e);
        }
        BufferedReader dataInput = new BufferedReader(new InputStreamReader(logStream));
        int index = 1;
        String line;
        try {
            while ((line = dataInput.readLine()) != null) {
                if (index <= end && index > start) {
                    logsList.add(line);
                }
                index++;
            }
            dataInput.close();
        } catch (IOException e) {
            log.error("Cannot read the log file", e);
            throw new LogViewerException("Cannot read the log file", e);
        }
        return logsList.toArray(new String[logsList.size()]);
    }

    public static void restoreDefaults() throws Exception {
        registryManager.removeAllRegistryEntries();
        LogManager.resetConfiguration();

        try {
            String logFile = CarbonUtils.getCarbonConfigDirPath()
                    + RegistryConstants.PATH_SEPARATOR + "log4j.properties";
            Log4jConfigurer.initLogging(logFile);
        } catch (FileNotFoundException e) {
            String msg = "Cannot restore default logging configuration."
                    + " log4j.properties file not found in the classpath";
            throw new Exception(msg, e);
        }
    }

    private static InputStream getLocalInputStream(String logFile) throws FileNotFoundException, LogViewerException {
        Path logFilePath = Paths.get(CarbonUtils.getCarbonLogsPath(), logFile);

        if (!isPathInsideBaseDirectory(Paths.get(CarbonUtils.getCarbonLogsPath()), logFilePath)) {
            throw new LogViewerException("Specified log file path is outside carbon logs directory.");
        }

        FileAppender carbonLogFileAppender = (FileAppender) Logger.getRootLogger().getAppender(CARBON_LOGFILE_APPENDER);
        String carbonLogFileName = new File(carbonLogFileAppender.getFile()).getName();

        if (!logFilePath.getFileName().toString().startsWith(carbonLogFileName)) {
            throw new LogViewerException("Trying to access logs other than CARBON_LOGFILE appender log file.");
        }

        InputStream is = new BufferedInputStream(new FileInputStream(logFilePath.toString()));
        return is;
    }

    /**
     * This method stream log messages and retrieve 100 log messages per page
     *
     * @param pageNumber The page required. Page number starts with 0.
     * @param sourceList The original list of items
     * @param pageable   The type of Pageable item
     * @return Returned page
     */
    public static <C> List<C> doPaging(int pageNumber, List<C> sourceList, int maxLines,
                                       Pageable pageable) {
        if (pageNumber < 0 || pageNumber == Integer.MAX_VALUE) {
            pageNumber = 0;
        }
        if (sourceList.size() == 0) {
            return sourceList;
        }
        if (pageNumber < 0) {
            throw new RuntimeException("Page number should be a positive integer. "
                    + "Page numbers begin at 0.");
        }
        int itemsPerPageInt = MAX_LOG_MESSAGES; // the default number of item
        // per page
        int numberOfPages = (int) Math.ceil((double) maxLines / itemsPerPageInt);
        if (pageNumber > numberOfPages - 1) {
            pageNumber = numberOfPages - 1;
        }
        List<C> returnList = new ArrayList<C>();
        for (int i = 0; i < sourceList.size(); i++) {
            returnList.add(sourceList.get(i));
        }
        int pages = calculatePageLevel(pageNumber + 1);
        if (pages > numberOfPages) {
            pages = numberOfPages;
        }
        pageable.setNumberOfPages(pages);
        pageable.set(returnList);
        return returnList;
    }

    /*
     * This is an equation to retrieve the visible number of pages ie p1-p5 -> 5
     * p6-p10 -> 10 p11-p15 -> 15
     */
    private static int calculatePageLevel(int x) {
        int p = x / 5;
        int q = x % 5;
        int t = (p + 1) * 5;
        int s = (p * 5) + 1;
        int y = q > 0 ? t : s;
        return y;
    }

    /**
     * Tests if the provided path is inside the base directory path.
     *
     * @param baseDirPath absolute {@link Path} of the base directory in which we want to check whether the given path
     *                    is inside
     * @param path        {@link Path} to be tested
     * @return {@code true} if the given path is inside the base directory path, otherwise {@code false}
     */
    private static boolean isPathInsideBaseDirectory(Path baseDirPath, Path path) {
        Path resolvedPath = baseDirPath.resolve(path).normalize();
        return resolvedPath.startsWith(baseDirPath.normalize());
    }
}


text:
layout: data_model
title: IndicatorBaseType
this_version: 1.1
---

  Heads up! These docs are for STIX 1.1, which is not the latest version (1.2). View the latest!

IndicatorBaseTypeSTIX Common Schema

This type represents the STIX Indicator component. It is extended using the XML Schema Extension feature by the STIX Indicator type itself. Users of this type who wish to express a full indicator using STIX must do so using the xsi:type extension feature. The STIX-defined Indicator type is IndicatorType in the http://stix.mitre.org/Indicator-1 namespace. This type is defined in the indicator.xsd file or at the URL http://stix.mitre.org/XMLSchema/indicator/1.2/indicator.xsd.

Alternatively, uses that require simply specifying an idref as a reference to an indicator defined elsewhere can do so without specifying an xsi:type.

      <form id="nav-version">
        <select>

            <option value="1.2" >STIX 1.2</option>

            <option value="1.1.1" >STIX 1.1.1</option>

            <option value="1.1" selected="selected">STIX 1.1</option>

            <option value="1.0.1" >STIX 1.0.1</option>

            <option value="1.0" >STIX 1.0</option>

        </select>
      </form>

Fields

      Field Name
      Type
      Description

      @idoptional

          QName

Specifies a unique ID for this Indicator.

      @idrefoptional

          QName

Specifies a reference to the ID of an Indicator specified elsewhere.

When idref is specified, the id attribute must not be specified, and any instance of this Indicator should not hold content.

      @timestampoptional

          dateTime

Specifies a timestamp for the definition of a specific version of an Indicator. When used in conjunction with the id, this field is specifying the definition time for the specific version of the Indicator. When used in conjunction with the idref, this field is specifying a reference to a specific version of an Indicator defined elsewhere. This field has no defined semantic meaning if used in the absence of either the id or idref fields.

This field must only be used in conjunction with the idref field.


text:
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { JhiLanguageService } from 'ng-jhipster';
import { JhiLanguageHelper } from 'app/core';

import { GfpSharedModule } from 'app/shared';
import {
    ContaPagamentoComponent,
    ContaPagamentoDetailComponent,
    ContaPagamentoUpdateComponent,
    ContaPagamentoDeletePopupComponent,
    ContaPagamentoDeleteDialogComponent,
    contaPagamentoRoute,
    contaPagamentoPopupRoute
} from './';

const ENTITY_STATES = [...contaPagamentoRoute, ...contaPagamentoPopupRoute];

@NgModule({
    imports: [GfpSharedModule, RouterModule.forChild(ENTITY_STATES)],
    declarations: [
        ContaPagamentoComponent,
        ContaPagamentoDetailComponent,
        ContaPagamentoUpdateComponent,
        ContaPagamentoDeleteDialogComponent,
        ContaPagamentoDeletePopupComponent
    ],
    entryComponents: [
        ContaPagamentoComponent,
        ContaPagamentoUpdateComponent,
        ContaPagamentoDeleteDialogComponent,
        ContaPagamentoDeletePopupComponent
    ],
    providers: [{ provide: JhiLanguageService, useClass: JhiLanguageService }],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class GfpContaPagamentoModule {
    constructor(private languageService: JhiLanguageService, private languageHelper: JhiLanguageHelper) {
        this.languageHelper.language.subscribe((languageKey: string) => {
            if (languageKey !== undefined) {
                this.languageService.changeLanguage(languageKey);
            }
        });
    }
}


text:
import React, { Component } from 'react';
import SwipeableViews from 'react-swipeable-views';

export default class FeaturesSlide3 extends Component {
  render() {

    return (

                Track

                Keep separated track records of how each horse has been exercised and follow their development.

    );
  }
}


text:
\section{Modules}
Here is a list of all modules:\begin{DoxyCompactList}
\item \contentsline{section}{Misc defines}{\pageref{group__TMCLMisc}}{}
\item \contentsline{section}{Status Codes.}{\pageref{group__StatusCodes}}{}
\item \contentsline{section}{TMCL commands.}{\pageref{group__TMCLComm}}{}
\begin{DoxyCompactList}
\item \contentsline{section}{Motion commands.}{\pageref{group__MotionComm}}{}
\item \contentsline{section}{Parameter commands.}{\pageref{group__ParComm}}{}
\item \contentsline{section}{TMCL Control Functions}{\pageref{group__CTLFuncs}}{}
\item \contentsline{section}{TMCL operation type codes.}{\pageref{group__TypeCodes}}{}
\end{DoxyCompactList}
\item \contentsline{section}{Axis Parameters}{\pageref{group__AxisParam}}{}
\begin{DoxyCompactList}
\item \contentsline{section}{Read-\/Write Parameters}{\pageref{group__RWParam}}{}
\item \contentsline{section}{Read-\/Only Parameters}{\pageref{group__ROParam}}{}
\end{DoxyCompactList}
\end{DoxyCompactList}


text:
#ifndef _LIBSYNDICATE_MS_LISTDIR_
#define _LIBSYNDICATE_MS_LISTDIR_

#include "libsyndicate/ms/core.h"
#include "libsyndicate/ms/file.h"
#include "libsyndicate/ms/path.h"
#include "libsyndicate/ms/url.h"
#include "libsyndicate/ms/volume.h"

typedef map< uint64_t, struct md_entry > ms_client_dir_listing;

// listdir context
struct ms_client_listdir_context {

   struct ms_client* client;

   uint64_t volume_id;
   uint64_t parent_id;

   queue<int>* batches;                         // which batches of the index to download next

   set<uint64_t>* children_ids;                 // file ids of downloaded children
   vector<struct md_entry>* children;           // downloaded children

   int listing_error;
   int64_t num_children;
   int64_t capacity;

   bool finished;                              // set to true if we get all the children before we're done

   pthread_mutex_t lock;
};

extern "C" {

int ms_client_listdir( struct ms_client* client, uint64_t parent_id, int64_t num_children, int64_t dir_capacity, struct ms_client_multi_result* results );
int ms_client_diffdir( struct ms_client* client, uint64_t parent_id, int64_t num_children, int64_t least_unknown_generation, struct ms_client_multi_result* results );

}

#endif