text:
using System.IO;
using System.Linq;
using NLog.Common;

namespace NLog.Config
{
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using NLog.Conditions;
    using NLog.Filters;
    using NLog.Internal;
    using NLog.LayoutRenderers;
    using NLog.Layouts;
    using NLog.Targets;
    using NLog.Time;

    /// <summary>
    /// Provides registration information for named items (targets, layouts, layout renderers, etc.) managed by NLog.
    ///
    /// Everything of an assembly could be loaded by <see cref="RegisterItemsFromAssembly(System.Reflection.Assembly)"/>
    /// </summary>
    public class ConfigurationItemFactory
    {
        private static ConfigurationItemFactory defaultInstance;

        private readonly IList<object> _allFactories;
        private readonly Factory<Target, TargetAttribute> _targets;
        private readonly Factory<Filter, FilterAttribute> _filters;
        private readonly LayoutRendererFactory _layoutRenderers;
        private readonly Factory<Layout, LayoutAttribute> _layouts;
        private readonly MethodFactory<ConditionMethodsAttribute, ConditionMethodAttribute> _conditionMethods;
        private readonly Factory<LayoutRenderer, AmbientPropertyAttribute> _ambientProperties;
        private readonly Factory<TimeSource, TimeSourceAttribute> _timeSources;

        private IJsonConverter _jsonSerializer = DefaultJsonSerializer.Instance;

        /// <summary>
        /// Called before the assembly will be loaded.
        /// </summary>
        public static event EventHandler<AssemblyLoadingEventArgs> AssemblyLoading;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationItemFactory"/> class.
        /// </summary>
        /// <param name="assemblies">The assemblies to scan for named items.</param>
        public ConfigurationItemFactory(params Assembly[] assemblies)
        {
            CreateInstance = FactoryHelper.CreateInstance;
            _targets = new Factory<Target, TargetAttribute>(this);
            _filters = new Factory<Filter, FilterAttribute>(this);
            _layoutRenderers = new LayoutRendererFactory(this);
            _layouts = new Factory<Layout, LayoutAttribute>(this);
            _conditionMethods = new MethodFactory<ConditionMethodsAttribute, ConditionMethodAttribute>();
            _ambientProperties = new Factory<LayoutRenderer, AmbientPropertyAttribute>(this);
            _timeSources = new Factory<TimeSource, TimeSourceAttribute>(this);
            _allFactories = new List<object>
            {
                _targets,
                _filters,
                _layoutRenderers,
                _layouts,
                _conditionMethods,
                _ambientProperties,
                _timeSources,
            };

            foreach (var asm in assemblies)
            {
                RegisterItemsFromAssembly(asm);
            }
        }

        /// <summary>
        /// Gets or sets default singleton instance of <see cref="ConfigurationItemFactory"/>.
        /// </summary>
        /// <remarks>
        /// This property implements lazy instantiation so that the <see cref="ConfigurationItemFactory"/> is not built before
        /// the internal logger is configured.
        /// </remarks>
        public static ConfigurationItemFactory Default
        {
            get => defaultInstance ?? (defaultInstance = BuildDefaultFactory());
            set => defaultInstance = value;
        }

        /// <summary>
        /// Gets or sets the creator delegate used to instantiate configuration objects.
        /// </summary>
        /// <remarks>
        /// By overriding this property, one can enable dependency injection or interception for created objects.
        /// </remarks>
        public ConfigurationItemCreator CreateInstance { get; set; }

        /// <summary>
        /// Gets the <see cref="Target"/> factory.
        /// </summary>
        /// <value>The target factory.</value>
        public INamedItemFactory<Target, Type> Targets => _targets;

        /// <summary>
        /// Gets the <see cref="Filter"/> factory.
        /// </summary>
        /// <value>The filter factory.</value>
        public INamedItemFactory<Filter, Type> Filters => _filters;

        /// <summary>
        /// gets the <see cref="LayoutRenderer"/> factory
        /// </summary>
        /// <remarks>not using <see cref="_layoutRenderers"/> due to backwardscomp.</remarks>
        /// <returns></returns>
        internal LayoutRendererFactory GetLayoutRenderers()
        {
            return _layoutRenderers;
        }

        /// <summary>
        /// Gets the <see cref="LayoutRenderer"/> factory.
        /// </summary>
        /// <value>The layout renderer factory.</value>
        public INamedItemFactory<LayoutRenderer, Type> LayoutRenderers => _layoutRenderers;

        /// <summary>
        /// Gets the <see cref="LayoutRenderer"/> factory.
        /// </summary>
        /// <value>The layout factory.</value>
        public INamedItemFactory<Layout, Type> Layouts => _layouts;

        /// <summary>
        /// Gets the ambient property factory.
        /// </summary>
        /// <value>The ambient property factory.</value>
        public INamedItemFactory<LayoutRenderer, Type> AmbientProperties => _ambientProperties;

        /// <summary>
        /// Legacy interface, no longer used by the NLog engine
        /// </summary>
        [Obsolete("Use JsonConverter property instead. Marked obsolete on NLog 4.5")]
        public IJsonSerializer JsonSerializer
        {
            get => _jsonSerializer as IJsonSerializer;
            set => _jsonSerializer = value != null ? (IJsonConverter)new JsonConverterLegacy(value) : DefaultJsonSerializer.Instance;
        }

        /// <summary>
        /// Gets or sets the JSON serializer to use with <see cref="WebServiceTarget"/> or <see cref="JsonLayout"/>
        /// </summary>
        public IJsonConverter JsonConverter
        {
            get => _jsonSerializer;
            set => _jsonSerializer = value ?? DefaultJsonSerializer.Instance;
        }

        /// <summary>
        /// Gets or sets the string serializer to use with <see cref="LogEventInfo.MessageTemplateParameters"/>
        /// </summary>
        public IValueSerializer ValueSerializer
        {
            get => MessageTemplates.ValueSerializer.Instance;
            set => MessageTemplates.ValueSerializer.Instance = value;
        }

        /// <summary>
        /// Perform mesage template parsing and formatting of LogEvent messages (True = Always, False = Never, Null = Auto Detect)
        /// </summary>
        /// <remarks>
        /// - Null (Auto Detect) : NLog-parser checks <see cref="LogEventInfo.Message"/> for positional parameters, and will then fallback to string.Format-rendering.
        /// - True: Always performs the parsing of <see cref="LogEventInfo.Message"/> and rendering of <see cref="LogEventInfo.FormattedMessage"/> using the NLog-parser (Allows custom formatting with <see cref="ValueSerializer"/>)
        /// - False: Always performs parsing and rendering using string.Format (Fastest if not using structured logging)
        /// </remarks>
        public bool? ParseMessageTemplates
        {
            get
            {
                if (ReferenceEquals(LogEventInfo.DefaultMessageFormatter, LogEventInfo.StringFormatMessageFormatter))
                {
                    return false;
                }
                else if (ReferenceEquals(LogEventInfo.DefaultMessageFormatter, LogMessageTemplateFormatter.Default.MessageFormatter))
                {
                    return true;
                }
                else
                {
                    return null;
                }
            }
            set => LogEventInfo.SetDefaultMessageFormatter(value);
        }

        /// <summary>
        /// Gets the time source factory.
        /// </summary>
        /// <value>The time source factory.</value>
        public INamedItemFactory<TimeSource, Type> TimeSources => _timeSources;

        /// <summary>
        /// Gets the condition method factory.
        /// </summary>
        /// <value>The condition method factory.</value>
        public INamedItemFactory<MethodInfo, MethodInfo> ConditionMethods => _conditionMethods;

        /// <summary>
        /// Registers named items from the assembly.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        public void RegisterItemsFromAssembly(Assembly assembly)
        {
            RegisterItemsFromAssembly(assembly, string.Empty);
        }

        /// <summary>
        /// Registers named items from the assembly.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        /// <param name="itemNamePrefix">Item name prefix.</param>
        public void RegisterItemsFromAssembly(Assembly assembly, string itemNamePrefix)
        {
            if (AssemblyLoading != null)
            {
                var args = new AssemblyLoadingEventArgs(assembly);
                AssemblyLoading.Invoke(this,args);
                if (args.Cancel)
                {
                    InternalLogger.Info("Loading assembly '{0}' is canceled", assembly.FullName);
                    return;
                }
            }

            InternalLogger.Debug("ScanAssembly('{0}')", assembly.FullName);
            var typesToScan = assembly.SafeGetTypes();
            PreloadAssembly(typesToScan);
            foreach (IFactory f in _allFactories)
            {
                f.ScanTypes(typesToScan, itemNamePrefix);
            }
        }

        /// <summary>
        /// Call Preload for NLogPackageLoader
        /// </summary>
        /// <remarks>
        /// Every package could implement a class "NLogPackageLoader" (namespace not important) with the public static method "Preload" (no arguments)
        /// This method will be called just before registering all items in the assembly.
        /// </remarks>
        /// <param name="typesToScan"></param>
        public void PreloadAssembly(Type[] typesToScan)
        {
            var types = typesToScan.Where(t => t.Name.Equals("NLogPackageLoader", StringComparison.OrdinalIgnoreCase));

            foreach (var type in types)
            {
                CallPreload(type);
            }
        }

        /// <summary>
        /// Call the Preload method for <paramref name="type"/>. The Preload method must be static.
        /// </summary>
        /// <param name="type"></param>
        private static void CallPreload(Type type)
        {
            if (type != null)
            {
                InternalLogger.Debug("Found for preload'{0}'", type.FullName);
                var preloadMethod = type.GetMethod("Preload");
                if (preloadMethod != null)
                {
                    if (preloadMethod.IsStatic)
                    {

                        InternalLogger.Debug("NLogPackageLoader contains Preload method");
                        //only static, so first param null
                        try
                        {
                            preloadMethod.Invoke(null, null);
                            InternalLogger.Debug("Preload succesfully invoked for '{0}'", type.FullName);
                        }
                        catch (Exception e)
                        {
                            InternalLogger.Warn(e,"Invoking Preload for '{0}' failed", type.FullName);
                        }
                    }
                    else
                    {
                        InternalLogger.Debug("NLogPackageLoader contains a preload method, but isn't static");
                    }

                }
                else
                {
                    InternalLogger.Debug("{0} doesn't contain Preload method", type.FullName);
                }
            }
        }

        /// <summary>
        /// Clears the contents of all factories.
        /// </summary>
        public void Clear()
        {
            foreach (IFactory f in _allFactories)
            {
                f.Clear();
            }
        }

        /// <summary>
        /// Registers the type.
        /// </summary>
        /// <param name="type">The type to register.</param>
        /// <param name="itemNamePrefix">The item name prefix.</param>
        public void RegisterType(Type type, string itemNamePrefix)
        {
            foreach (IFactory f in _allFactories)
            {
                f.RegisterType(type, itemNamePrefix);
            }
        }

        /// <summary>
        /// Builds the default configuration item factory.
        /// </summary>
        /// <returns>Default factory.</returns>
        private static ConfigurationItemFactory BuildDefaultFactory()
        {
            var nlogAssembly = typeof(ILogger).GetAssembly();
            var factory = new ConfigurationItemFactory(nlogAssembly);
            factory.RegisterExtendedItems();

#if !SILVERLIGHT && !WINDOWS_UWP
            try
            {
                var assemblyLocation = GetAssemblyFileLocation(nlogAssembly);
                var extensionDlls = GetNLogExtensionFiles(assemblyLocation);
                if (extensionDlls.Length==0)
                {
                    var entryAssembly = Assembly.GetEntryAssembly();
                    if (!string.IsNullOrEmpty(entryAssembly?.CodeBase))
                    {
                        if (!string.Equals(entryAssembly.CodeBase, nlogAssembly.CodeBase, StringComparison.OrdinalIgnoreCase))
                        {
                            assemblyLocation = GetAssemblyFileLocation(entryAssembly);
                            extensionDlls = GetNLogExtensionFiles(assemblyLocation);
                        }
                    }
                    else
                    {
                        // TODO Consider to prioritize AppDomain.PrivateBinPath
                        var appDomainBaseDirectory = LogFactory.CurrentAppDomain.BaseDirectory;
                        if (!string.IsNullOrEmpty(appDomainBaseDirectory))
                        {
                            if (!string.Equals(appDomainBaseDirectory, assemblyLocation, StringComparison.OrdinalIgnoreCase))
                            {
                                assemblyLocation = appDomainBaseDirectory;
                                extensionDlls = GetNLogExtensionFiles(appDomainBaseDirectory);
                            }
                        }
                    }
                }

                InternalLogger.Debug("Start auto loading, location: {0}", assemblyLocation);
                HashSet<string> alreadyRegistered = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                foreach (var extensionDll in extensionDlls)
                {
                    InternalLogger.Info("Auto loading assembly file: {0}", extensionDll);
                    var success = false;
                    try
                    {
                        var extensionAssembly = AssemblyHelpers.LoadFromPath(extensionDll);
                        InternalLogger.LogAssemblyVersion(extensionAssembly);
                        factory.RegisterItemsFromAssembly(extensionAssembly);
                        alreadyRegistered.Add(extensionAssembly.FullName);
                        success = true;
                    }
                    catch (Exception ex)
                    {
                        if (ex.MustBeRethrownImmediately())
                        {
                            throw;
                        }

                        InternalLogger.Warn(ex, "Auto loading assembly file: {0} failed! Skipping this file.", extensionDll);
                        //TODO NLog 5, check MustBeRethrown()
                    }
                    if (success)
                    {
                        InternalLogger.Info("Auto loading assembly file: {0} succeeded!", extensionDll);
                    }
                }

#if !NETSTANDARD1_0
                var allAssemblies = LogFactory.CurrentAppDomain.GetAssemblies();
                foreach (var assembly in allAssemblies)
                {
                    if (assembly.FullName.StartsWith("NLog.", StringComparison.OrdinalIgnoreCase))
                    {
                        if (alreadyRegistered.Contains(assembly.FullName))
                        {
                            factory.RegisterItemsFromAssembly(assembly);
                            continue;
                        }
                    }
                    if ( assembly.FullName.StartsWith("NLog.Extensions.Logging", StringComparison.OrdinalIgnoreCase)
                      || assembly.FullName.StartsWith("NLog.Web", StringComparison.OrdinalIgnoreCase)
                      || assembly.FullName.StartsWith("Microsoft.Extensions.Logging", StringComparison.OrdinalIgnoreCase)
                      || assembly.FullName.StartsWith("Microsoft.Logging", StringComparison.OrdinalIgnoreCase))
                    {
                        LogManager.AddHiddenAssembly(assembly);
                    }
                }
#endif
            }
            catch (System.Security.SecurityException ex)
            {
                InternalLogger.Warn(ex, "Seems that we do not have permission");
                if (ex.MustBeRethrown())
                {
                    throw;
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                InternalLogger.Warn(ex, "Seems that we do not have permission");
                if (ex.MustBeRethrown())
                {
                    throw;
                }
            }
            InternalLogger.Debug("Auto loading done");
#endif
            return factory;
        }

#if !SILVERLIGHT && !WINDOWS_UWP
        private static string GetAssemblyFileLocation(Assembly assembly)
        {
            try
            {
                Uri assemblyCodeBase;
                if (!Uri.TryCreate(assembly.CodeBase, UriKind.RelativeOrAbsolute, out assemblyCodeBase))
                {
                    InternalLogger.Warn("No auto loading because assembly code base is unknown");
                    return string.Empty;
                }

                var assemblyLocation = Path.GetDirectoryName(assemblyCodeBase.LocalPath);
                if (assemblyLocation == null)
                {
                    InternalLogger.Warn("No auto loading because Nlog.dll location is unknown");
                    return string.Empty;
                }
                if (!Directory.Exists(assemblyLocation))
                {
                    InternalLogger.Warn("No auto loading because '{0}' doesn't exists", assemblyLocation);
                    return string.Empty;
                }

                return assemblyLocation;
            }
            catch (System.Security.SecurityException ex)
            {
                InternalLogger.Warn(ex, "Seems that we do not have permission");
                if (ex.MustBeRethrown())
                {
                    throw;
                }
                return string.Empty;
            }
            catch (UnauthorizedAccessException ex)
            {
                InternalLogger.Warn(ex, "Seems that we do not have permission");
                if (ex.MustBeRethrown())
                {
                    throw;
                }
                return string.Empty;
            }
        }

        private static string[] GetNLogExtensionFiles(string assemblyLocation)
        {
            try
            {
                if (string.IsNullOrEmpty(assemblyLocation))
                {
                    return ArrayHelper.Empty<string>();
                }

                InternalLogger.Debug("Search for auto loading files, location: {0}", assemblyLocation);
                var extensionDlls = Directory.GetFiles(assemblyLocation, "NLog*.dll")
                .Select(Path.GetFileName)
                .Where(x => !x.Equals("NLog.dll", StringComparison.OrdinalIgnoreCase))
                .Where(x => !x.Equals("NLog.UnitTests.dll", StringComparison.OrdinalIgnoreCase))
                .Where(x => !x.Equals("NLog.Extended.dll", StringComparison.OrdinalIgnoreCase))
                .Select(x => Path.Combine(assemblyLocation, x));
                return extensionDlls.ToArray();
            }
            catch (System.Security.SecurityException ex)
            {
                InternalLogger.Warn(ex, "Seems that we do not have permission");
                if (ex.MustBeRethrown())
                {
                    throw;
                }
                return ArrayHelper.Empty<string>();
            }
            catch (UnauthorizedAccessException ex)
            {
                InternalLogger.Warn(ex, "Seems that we do not have permission");
                if (ex.MustBeRethrown())
                {
                    throw;
                }
                return ArrayHelper.Empty<string>();
            }
        }
#endif

        /// <summary>
        /// Registers items in NLog.Extended.dll using late-bound types, so that we don't need a reference to NLog.Extended.dll.
        /// </summary>
        private void RegisterExtendedItems()
        {
            string suffix = typeof(ILogger).AssemblyQualifiedName;
            string myAssemblyName = "NLog,";
            string extendedAssemblyName = "NLog.Extended,";
            int p = suffix.IndexOf(myAssemblyName, StringComparison.OrdinalIgnoreCase);
            if (p >= 0)
            {
                suffix = ", " + extendedAssemblyName + suffix.Substring(p + myAssemblyName.Length);

                // register types
                string targetsNamespace = typeof(DebugTarget).Namespace;
                _targets.RegisterNamedType("AspNetTrace", targetsNamespace + ".AspNetTraceTarget" + suffix);
                _targets.RegisterNamedType("MSMQ", targetsNamespace + ".MessageQueueTarget" + suffix);
                _targets.RegisterNamedType("AspNetBufferingWrapper", targetsNamespace + ".Wrappers.AspNetBufferingTargetWrapper" + suffix);

                // register layout renderers
                string layoutRenderersNamespace = typeof(MessageLayoutRenderer).Namespace;
                _layoutRenderers.RegisterNamedType("appsetting", layoutRenderersNamespace + ".AppSettingLayoutRenderer" + suffix);
                _layoutRenderers.RegisterNamedType("aspnet-application", layoutRenderersNamespace + ".AspNetApplicationValueLayoutRenderer" + suffix);
                _layoutRenderers.RegisterNamedType("aspnet-request", layoutRenderersNamespace + ".AspNetRequestValueLayoutRenderer" + suffix);
                _layoutRenderers.RegisterNamedType("aspnet-sessionid", layoutRenderersNamespace + ".AspNetSessionIDLayoutRenderer" + suffix);
                _layoutRenderers.RegisterNamedType("aspnet-session", layoutRenderersNamespace + ".AspNetSessionValueLayoutRenderer" + suffix);
                _layoutRenderers.RegisterNamedType("aspnet-user-authtype", layoutRenderersNamespace + ".AspNetUserAuthTypeLayoutRenderer" + suffix);
                _layoutRenderers.RegisterNamedType("aspnet-user-identity", layoutRenderersNamespace + ".AspNetUserIdentityLayoutRenderer" + suffix);
            }
        }
    }
}


text:
'use strict';

require('../../setupBabel')();
module.exports = require('metro-bundler/build/JSTransformer/worker');

redpajama_set_name: RedPajamaGithub


text:
package com.thomas.utils;

import com.thomas.models.Media;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * Created by Yougeshwar on 4/24/2017.
 */
public class FileUtils
{
    public static String store(MultipartFile inputFile, String uploadDir) throws IOException
    {
        String uuid = UUID.randomUUID().toString();

        File fileDir = new File(uploadDir);
        if (!fileDir.exists())
        {
            fileDir.mkdir();
        }
        Path path = Paths.get(uploadDir + File.separator + uuid);
        Files.write(path, inputFile.getBytes());

        return uuid;
    }

}


text:
class TagChangesProcessor

  def initialize(csv_location, logger: Logger.new(nil))
    @csv_location = csv_location
    @logger = logger
  end

  def process
    tag_changes_list.each do |changes|
      @document_id = changes["document_id"]
      @source_topic_id = changes["remove_topic"]
      @destination_topic_id = changes["add_topic"]
      processor
    end
  end

private

  attr_reader :csv_location

  def tag_changes_list
    CSV::read(csv_location, headers: true)
  end

  def processor
    log "Updating #{taggings.count} taggings to change #{@source_topic_id} to #{@destination_topic_id}"
    update_taggings
    register_edition(latest_edition)
  end

  def update_taggings
    taggings.reject { |tagging| tagging.edition.nil? }.each do |tagging|
      if tagging.edition.specialist_sector_tags.include? @destination_topic_id
        remove_tagging(tagging)
      else
        change_tagging(tagging)
      end
    end
  end

  def remove_tagging(tagging)
    edition = tagging.edition
    log "removing tagging on '#{edition.slug}' edition #{edition.id}"
    tagging.destroy

    add_editorial_remark(edition,
      "Bulk retagging from topic '#{@source_topic_id}' to '#{@destination_topic_id}' resulted in duplicate tag - removed it"
    )
  end

  def change_tagging(tagging)
    edition = tagging.edition
    log "tagging '#{edition.slug}' edition #{edition.id}"
    tagging.tag = @destination_topic_id
    tagging.save!

    add_editorial_remark(edition,
      "Bulk retagging from topic '#{@source_topic_id}' to '#{@destination_topic_id}' changed tag"
    )
  end

  def latest_edition
    document.latest_edition
  end

  def document
    Document.find(@document_id)
  end

  def taggings
    document.editions.flat_map { |edition|
      edition.specialist_sectors.where(tag: @source_topic_id).uniq
    }
  end

  def register_edition(edition)
    log "registering '#{edition.slug}'"
    edition.reload
    register_with_panopticon(edition)
    register_with_publishing_api(edition)
    register_with_search(edition)
  end

  def register_with_panopticon(edition)
    registerable_edition = RegisterableEdition.new(edition)
    registerer           = Whitehall.panopticon_registerer_for(registerable_edition)
    registerer.register(registerable_edition)
  end

  def register_with_publishing_api(edition)
    Whitehall::PublishingApi.republish_async(edition)
  end

  def register_with_search(edition)
    ServiceListeners::SearchIndexer.new(edition).index!
  end

  def add_editorial_remark(edition, message)
    if edition.nil?
      log " - no edition (probably deleted)"
    elsif Edition::FROZEN_STATES.include?(edition.state)
      log " - edition is frozen; skipping editorial remarks"
    else
      log " - adding editorial remark"
      edition.editorial_remarks.create!(
        author: gds_user,
        body: message
      )
    end
  end

  def gds_user
    @gds_user ||= User.find_by(email: "govuk-whitehall@digital.cabinet-office.gov.uk")
  end

  def log(message)
    @logger.info message
  end
end


text:
import requests
import json

from acmd import SERVER_ERROR, USER_ERROR, OK
from acmd import error
from acmd.tools.tool_utils import create_task_id

MODELS_PATH = "/etc/workflow/models.json"
INSTANCES_PATH = '/etc/workflow/instances'

INSTANCE_MODES = {'RUNNING', 'SUSPENDED', 'ABORTED', 'COMPLETED'}

class WorkflowsApi(object):
    def __init__(self, server, raw=False):
        self.server = server
        self.raw = raw

    def start_workflow(self, model, path):
        """ curl -u admin:admin
                -d "model=/etc/workflow/models/request_for_activation/jcr:content/model&
                payload=/content/geometrixx/en/company&
                payloadType=JCR_PATH&
                workflowTitle=myWorkflowTitle" http://localhost:4502/etc/workflow/instances

        """
        task_id = create_task_id(model)

        form_data = dict(
            model='/etc/workflow/models/{}/jcr:content/model'.format(model),
            payload=path,
            payloadType='JCR_PATH',
            workflowTitle=task_id,
            startComment=''
        )

        url = self.server.url(INSTANCES_PATH)
        resp = requests.post(url, auth=self.server.auth, data=form_data)
        if resp.status_code != 201:
            error("Unexpected error code {code}: {content}".format(
                code=resp.status_code, content=resp.content))
            return SERVER_ERROR

        output = resp.content if self.raw else task_id
        return OK, output

    def get_instances(self, mode):
        if mode not in INSTANCE_MODES:
            return USER_ERROR, "Unknown instance mode {}".format(mode)

        path = "/etc/workflow/instances.{mode}.json".format(mode=mode)
        url = self.server.url(path)
        resp = requests.get(url, auth=self.server.auth)
        if resp.status_code != 200:
            error("Unexpected error code {code}: {content}".format(
                code=resp.status_code, content=resp.content))
            return SERVER_ERROR, []

        return OK, json.loads(resp.content)


text:
package org.realityforge.replicant.server.transport;

import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

@SuppressWarnings( "WeakerAccess" )
public final class ChannelMetaData
{
  public enum FilterType
  {
    /**
     * No filtering
     */
    NONE,
    /**
     * Filtering occurs but no parameter is passed to control such behaviour. Filtering rules are internal to the data.
     */
    INTERNAL,
    /**
     * Filtering occurs and the client passes a filter parameter but can never change the filter parameter without unsubscribing and resubscribing to graph.
     */
    STATIC,
    /**
     * Filtering occurs and the client passes a filter parameter and can change the filter parameter.
     */
    DYNAMIC
  }

  public enum CacheType
  {
    /**
     * No caching
     */
    NONE,
    /**
     * Caching is managed internally by replicant. If a change arrives for an entity in the graph then the
     * cache is expired.
     */
    INTERNAL,
    /**
     * Application code is responsible for managing the cache and expiring data when it is stale.
     */
    EXTERNAL
  }

  private final int _channelId;
  @Nonnull
  private final String _name;
  @Nullable
  private final Integer _instanceRootEntityTypeId;
  @Nonnull
  private final FilterType _filterType;
  private final Class<?> _filterParameterType;
  @Nonnull
  private final CacheType _cacheType;
  /**
   * Flag indicating whether it is valid to attempt to perform bulk loads for channel.
   */
  private final boolean _bulkLoadsSupported;
  /**
   * Flag indicating whether the channel should able to be subscribed to externally.
   * i.e. Can this be explicitly subscribed.
   */
  private final boolean _external;

  public ChannelMetaData( final int channelId,
                          @Nonnull final String name,
                          @Nullable final Integer instanceRootEntityTypeId,
                          @Nonnull final FilterType filterType,
                          @Nullable final Class<?> filterParameterType,
                          @Nonnull final CacheType cacheType,
                          final boolean bulkLoadsSupported,
                          final boolean external )
  {
    _channelId = channelId;
    _name = Objects.requireNonNull( name );
    _instanceRootEntityTypeId = instanceRootEntityTypeId;
    _filterType = Objects.requireNonNull( filterType );
    _filterParameterType = filterParameterType;
    _cacheType = Objects.requireNonNull( cacheType );
    _bulkLoadsSupported = bulkLoadsSupported;
    if ( !hasFilterParameter() && null != filterParameterType )
    {
      throw new IllegalArgumentException( "FilterParameterType specified but filterType is set to " + filterType );
    }
    else if ( hasFilterParameter() && null == filterParameterType )
    {
      throw new IllegalArgumentException( "FilterParameterType not specified but filterType is set to " + filterType );
    }
    _external = external;
  }

  public int getChannelId()
  {
    return _channelId;
  }

  @Nonnull
  public String getName()
  {
    return _name;
  }

  public boolean isTypeGraph()
  {
    return null == _instanceRootEntityTypeId;
  }

  public boolean isInstanceGraph()
  {
    return !isTypeGraph();
  }

  @Nonnull
  public Integer getInstanceRootEntityTypeId()
  {
    assert null != _instanceRootEntityTypeId;
    return _instanceRootEntityTypeId;
  }

  @Nonnull
  public FilterType getFilterType()
  {
    return _filterType;
  }

  public boolean hasFilterParameter()
  {
    return FilterType.DYNAMIC == _filterType || FilterType.STATIC == _filterType;
  }

  @Nonnull
  public Class<?> getFilterParameterType()
  {
    assert null != _filterParameterType;
    return _filterParameterType;
  }

  public boolean isCacheable()
  {
    return CacheType.NONE != _cacheType;
  }

  @Nonnull
  public CacheType getCacheType()
  {
    return _cacheType;
  }

  public boolean areBulkLoadsSupported()
  {
    return _bulkLoadsSupported;
  }

  public boolean isExternal()
  {
    return _external;
  }
}


text:
package org.apache.camel.component.mongodb;

import java.io.IOException;
import java.io.InputStream;
import java.util.Formatter;
import java.util.Properties;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoURI;
import com.mongodb.WriteConcern;
import com.mongodb.util.JSON;

import org.apache.camel.CamelContext;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.spring.SpringCamelContext;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public abstract class AbstractMongoDbTest extends CamelTestSupport {

    protected static Mongo mongo;
    protected static DB db;
    protected static DBCollection testCollection;
    protected static DBCollection dynamicCollection;

    protected static String dbName;
    protected static String testCollectionName;
    protected static String dynamicCollectionName;

    protected static Properties properties;

    protected ApplicationContext applicationContext;

    /**
     * Checks whether Mongo is running using the connection URI defined in the mongodb.test.properties file
     * @throws IOException
     */
    @BeforeClass
    public static void checkMongoRunning() throws IOException {
        properties = new Properties();
        InputStream is = MongoDbConversionsTest.class.getResourceAsStream("/mongodb.test.properties");
        properties.load(is);
        // ping Mongo and populate db and collection
        try {
            mongo = new Mongo(new MongoURI(properties.getProperty("mongodb.connectionURI")));
            mongo.getDatabaseNames();
            dbName = properties.getProperty("mongodb.testDb");
            db = mongo.getDB(dbName);
        } catch (Exception e) {
            Assume.assumeNoException(e);
        }

    }

    @Before
    public void initTestCase() {
        // Refresh the test collection - drop it and recreate it. We don't do this for the database because MongoDB would create large
        // store files each time
        testCollectionName = properties.getProperty("mongodb.testCollection");
        testCollection = db.getCollection(testCollectionName);
        testCollection.drop();
        testCollection = db.getCollection(testCollectionName);

        dynamicCollectionName = testCollectionName.concat("Dynamic");
        dynamicCollection = db.getCollection(dynamicCollectionName);
        dynamicCollection.drop();
        dynamicCollection = db.getCollection(dynamicCollectionName);

    }

    @After
    public void cleanup() {
        testCollection.drop();
        dynamicCollection.drop();
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        applicationContext = new ClassPathXmlApplicationContext("org/apache/camel/component/mongodb/mongoComponentTest.xml");
        CamelContext ctx = SpringCamelContext.springCamelContext(applicationContext);
        PropertiesComponent pc = new PropertiesComponent("classpath:mongodb.test.properties");
        ctx.addComponent("properties", pc);
        return ctx;
    }

    protected void pumpDataIntoTestCollection() {
        // there should be 100 of each
        String[] scientists = {"Einstein", "Darwin", "Copernicus", "Pasteur", "Curie", "Faraday", "Newton", "Bohr", "Galilei", "Maxwell"};
        for (int i = 1; i <= 1000; i++) {
            int index = i % scientists.length;
            Formatter f = new Formatter();
            String doc = f.format("{\"_id\":\"%d\", \"scientist\":\"%s\", \"fixedField\": \"fixedValue\"}", i, scientists[index]).toString();
            IOHelper.close(f);
            testCollection.insert((DBObject) JSON.parse(doc), WriteConcern.SAFE);
        }
        assertEquals("Data pumping of 1000 entries did not complete entirely", 1000L, testCollection.count());
    }

    protected CamelMongoDbException extractAndAssertCamelMongoDbException(Object result, String message) {
        assertTrue("Result is not an Exception", result instanceof Throwable);
        assertTrue("Result is not an CamelExecutionException", result instanceof CamelExecutionException);
        Throwable exc = ((CamelExecutionException) result).getCause();
        assertTrue("Result is not an CamelMongoDbException", exc instanceof CamelMongoDbException);
        CamelMongoDbException camelExc = ObjectHelper.cast(CamelMongoDbException.class, exc);
        if (message != null) {
            assertTrue("CamelMongoDbException doesn't contain desired message string", camelExc.getMessage().contains(message));
        }
        return camelExc;
    }

}


text:
#include "testutil.hpp"
#include "testutil_unity.hpp"

SETUP_TEARDOWN_TESTCONTEXT

void test_tipc_port_name_and_domain ()
{
    // test Port Name addressing
    void *sb = test_context_socket (ZMQ_REP);
    TEST_ASSERT_SUCCESS_ERRNO (zmq_bind (sb, "tipc://{5560,0,0}"));

    void *sc = test_context_socket (ZMQ_REQ);
    TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, "tipc://{5560,0}@0.0.0"));

    bounce (sb, sc);

    test_context_socket_close (sc);
    test_context_socket_close (sb);
}

void test_tipc_port_identity ()
{
    char endpoint[256];
    unsigned int z, c, n, ref;

    void *sb = test_context_socket (ZMQ_REP);
    void *sc = test_context_socket (ZMQ_REQ);

    // Test binding to random Port Identity and
    // test resolving assigned address, should return a properly formatted string
    bind_loopback_tipc (sb, endpoint, sizeof endpoint);

    int rc = sscanf (&endpoint[0], "tipc://<%u.%u.%u:%u>", &z, &c, &n, &ref);
    TEST_ASSERT_EQUAL_INT (4, rc);

    TEST_ASSERT_NOT_EQUAL_MESSAGE (
      0, ref, "tipc port number must not be 0 after random assignment");

    TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, endpoint));

    bounce (sb, sc);

    test_context_socket_close (sc);
    test_context_socket_close (sb);
}

void test_tipc_bad_addresses ()
{
    // Test Port Name addressing
    void *sb = test_context_socket (ZMQ_REP);

    // Test binding to a fixed address, should fail
    TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_bind (sb, "tipc://<1.2.3:123123>"));

    // Test connecting to random identity, should fail
    TEST_ASSERT_FAILURE_ERRNO (EINVAL, zmq_connect (sb, "tipc://<*>"));

    // Clean up
    test_context_socket_close (sb);
}

int main ()
{
    setup_test_environment ();

    if (!is_tipc_available ()) {
        printf ("TIPC environment unavailable, skipping test\n");
        return 77;
    }

    UNITY_BEGIN ();
    RUN_TEST (test_tipc_port_name_and_domain);
    RUN_TEST (test_tipc_port_identity);
    RUN_TEST (test_tipc_bad_addresses);

    return UNITY_END ();
}


text:
import request from 'utils/request';

export const userRepository = {
    logIn(info) {
        return request.post('api/user/login', info);
    },
    register(info) {
        return request.post('api/user/register', info);
    },
    logout() {
        return request.get('api/user/logout');
    },
    get() {
        return request.get('api/user');
    },
    set(info) {
        return request.post('api/user', info);
    },
    isExist() {
        return request.get('api/user/exist');
    }
};


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;

namespace Paraiba.IO {
    /// <summary>
    ///   Java 'Ì Scanner 'ð^Ž—'č쐬'µ'½ƒNƒ‰ƒX'Å'·B '½'¾'µAJava"łƂ͈قȂèA³‹K•\Œ»'ɑΉž'µ'Ä'¢'Ü'¹'ñB
    /// </summary>
    public class Scanner {
        // --------------------------ƒƒ"ƒo•Ï"--------------------------
        private readonly StringBuilder _buffer;
        private readonly TextReader _reader;
        private Object _cache;

        // ------------------------ƒRƒ"ƒXƒgƒ‰ƒNƒ^------------------------
        public Scanner(TextReader reader)
            : this(reader, Char.IsWhiteSpace, isMyPunctuation) {}

        public Scanner(
            TextReader reader, ICollection<char> whiteSpaces,
            ICollection<char> delimiters)
            : this(reader, whiteSpaces.Contains, delimiters.Contains) {}

        public Scanner(
            TextReader reader, IEnumerable<char> whiteSpaces,
            IEnumerable<char> delimiters)
            : this(reader, whiteSpaces.Contains, delimiters.Contains) {}

        public Scanner(
            TextReader reader, Func<char, bool> isWhiteSpace,
            Func<char, bool> isDelimiter) {
            _reader = reader;
            IsWhiteSpaceDelegate = isWhiteSpace;
            IsDelimiterDelegate = isDelimiter;
            _buffer = new StringBuilder();
        }

        // --------------------------ƒvƒƒpƒeƒB--------------------------
        public String LastToken { get; private set; }

        public Int32 LastDelimiter { get; private set; }

        public Func<char, bool> IsWhiteSpaceDelegate { get; set; }

        public Func<char, bool> IsDelimiterDelegate { get; set; }

        // ---------------------------ƒƒ\ƒbƒh---------------------------
        private static bool isMyPunctuation(Char c) {
            return (c != '-' && Char.IsPunctuation(c));
        }

        private bool ReadNextToken() {
            Int32 c;
            // 1•¶Žš–Ú'ªEOF'̏ꍇA"ü—ÍŠ®—¹'Æ'·'é
            if ((c = _reader.Read()) < 0) {
                return false;
            }

            // ƒoƒbƒtƒ@'ðƒNƒŠƒA'·'é
            _buffer.Length = 0;
            // ‹ó"'‹æØ'蕶Žš'ð"Ç'Ý"ò'΂·
            while (IsWhiteSpaceDelegate((Char)c) && (c = _reader.Read()) >= 0) {}

            Char ch;
            // ‹æØ'蕶Žš'à'µ''́AEOF'ðŽó'¯Žæ'é'܂Ń‹[ƒv
            while (c >= 0 && !IsDelimiterDelegate(ch = (Char)c)) {
                if (IsWhiteSpaceDelegate(ch)) {
                    // ‹ó"'‹æØ'蕶Žš'ð"Ç'Ý"ò'΂·
                    while ((c = _reader.Peek()) >= 0 && IsWhiteSpaceDelegate((Char)c)) {
                        _reader.Read();
                    }
                    // ‹æØ'蕶Žš'Í'PŽš'¾'¯"Ç'Ý"ò'΂·
                    if (IsDelimiterDelegate((Char)c)) {
                        _reader.Read();
                    } else {
                        c = ch; // ‹æØ'蕶Žš'ª'È'¢ê‡'͍ŏ‰'Ì‹ó"'•¶Žš'ð‹æØ'蕶Žš'Æ'·'é
                    }
                    break;
                }
                // ƒoƒbƒtƒ@'É—'ß'é
                _buffer.Append(ch);
                // ŽŸ'Ì•¶Žš'̓ǂݍž'Ý
                c = _reader.Read();
            }
            LastToken = _buffer.ToString();
            LastDelimiter = c;
            return true;
        }

        public bool HasNext() {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            _cache = null;
            return true;
        }

        public bool HasNextBoolean() {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            Boolean value;
            if (!Boolean.TryParse(LastToken, out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextChar() {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            Char value;
            if (!Char.TryParse(LastToken, out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextByte(NumberStyles style = NumberStyles.Integer) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            Byte value;
            if (
                !Byte.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextUInt16(NumberStyles style = NumberStyles.Integer) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            UInt16 value;
            if (
                !UInt16.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextUInt32(NumberStyles style = NumberStyles.Integer) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            UInt32 value;
            if (
                !UInt32.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextUInt64(NumberStyles style = NumberStyles.Integer) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            UInt64 value;
            if (
                !UInt64.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextSByte(NumberStyles style = NumberStyles.Integer) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            SByte value;
            if (
                !SByte.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextInt16(NumberStyles style = NumberStyles.Integer) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            Int16 value;
            if (
                !Int16.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextInt32(NumberStyles style = NumberStyles.Integer) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            Int32 value;
            if (
                !Int32.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextInt64(NumberStyles style = NumberStyles.Integer) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            Int64 value;
            if (
                !Int64.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextSingle(
            NumberStyles style =
                    NumberStyles.Float | NumberStyles.AllowThousands) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            Single value;
            if (
                !Single.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextDouble(
            NumberStyles style =
                    NumberStyles.Float | NumberStyles.AllowThousands) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            Double value;
            if (
                !Double.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextDecimal(NumberStyles style = NumberStyles.Number) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            Decimal value;
            if (
                !Decimal.TryParse(
                    LastToken, style, NumberFormatInfo.CurrentInfo,
                    out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public bool HasNextBigInteger(NumberStyles style = NumberStyles.Integer) {
            // ŽŸ'̃g[ƒNƒ"'̓ǂݍž'Ý
            if (LastToken == null && !ReadNextToken()) {
                return false;
            }
            // •ÏŠ·
            BigInteger value;
            if (!BigInteger.TryParse(LastToken, out value)) {
                return false;
            }
            _cache = value;
            return true;
        }

        public String Current() {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            }
            return LastToken;
        }

        public Boolean CurrentBoolean() {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Boolean) {
                return (Boolean)_cache;
            }

            var value = Boolean.Parse(LastToken);
            _cache = value;
            return value;
        }

        public Char CurrentChar() {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Char) {
                return (Char)_cache;
            }

            var value = Char.Parse(LastToken);
            _cache = value;
            return value;
        }

        public Byte CurrentByte(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Byte) {
                return (Byte)_cache;
            }
            var value = Byte.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public UInt16 CurrentUInt16(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is UInt16) {
                return (UInt16)_cache;
            }

            var value = UInt16.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public UInt32 CurrentUInt32(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is UInt32) {
                return (UInt32)_cache;
            }

            var value = UInt32.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public UInt64 CurrentUInt64(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is UInt64) {
                return (UInt64)_cache;
            }

            var value = UInt64.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public SByte CurrentSByte(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is SByte) {
                return (SByte)_cache;
            }

            var value = SByte.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public Int16 CurrentInt16(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Int16) {
                return (Int16)_cache;
            }

            var value = Int16.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public Int32 CurrentInt32(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Int32) {
                return (Int32)_cache;
            }

            var value = Int32.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public Int64 CurrentInt64(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Int64) {
                return (Int64)_cache;
            }

            var value = Int64.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public Single CurrentSingle(
            NumberStyles style =
                    NumberStyles.Float | NumberStyles.AllowThousands) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Single) {
                return (Single)_cache;
            }

            var value = Single.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public Double CurrentDouble(
            NumberStyles style =
                    NumberStyles.Float | NumberStyles.AllowThousands) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Double) {
                return (Double)_cache;
            }

            var value = Double.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public Decimal CurrentDecimal(NumberStyles style = NumberStyles.Number) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Decimal) {
                return (Decimal)_cache;
            }

            var value = Decimal.Parse(LastToken, style);
            _cache = value;
            return value;
        }

        public BigInteger CurrentBigInteger(
            NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is BigInteger) {
                return (BigInteger)_cache;
            }

            var value = BigInteger.Parse(LastToken);
            _cache = value;
            return value;
        }

        public String Next() {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            }
            var token = LastToken;
            LastToken = null;
            return token;
        }

        public String NextLine() {
            var token = LastToken;

            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (token == null) {
                return _reader.ReadLine();
            }

            LastToken = null;

            if (LastDelimiter == '\r') {
                // ƒRƒ"ƒXƒgƒ‰ƒNƒ^'̈ø"'ðÈ—ª'µ'½ê‡A\n 'Í"Ç'Ý"ò'΂³'ê'Ä'¢'é'Í'¸
                if (_reader.Peek() == '\n') {
                    _reader.Read();
                }
                return token;
            }

            if (LastDelimiter == '\n') {
                return token;
            }

            return token + _reader.ReadLine();
        }

        public Boolean NextBoolean() {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Boolean) {
                LastToken = null;
                return (Boolean)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return Boolean.Parse(token);
        }

        public Char NextChar() {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Char) {
                LastToken = null;
                return (Char)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return Char.Parse(token);
        }

        public Byte NextByte(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Byte) {
                LastToken = null;
                return (Byte)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return Byte.Parse(token, style);
        }

        public UInt16 NextUInt16(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is UInt16) {
                LastToken = null;
                return (UInt16)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return UInt16.Parse(token, style);
        }

        public UInt32 NextUInt32(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is UInt32) {
                LastToken = null;
                return (UInt32)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return UInt32.Parse(token, style);
        }

        public UInt64 NextUInt64(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is UInt64) {
                LastToken = null;
                return (UInt64)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return UInt64.Parse(token, style);
        }

        public SByte NextSByte(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is SByte) {
                LastToken = null;
                return (SByte)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return SByte.Parse(token, style);
        }

        public Int16 NextInt16(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Int16) {
                LastToken = null;
                return (Int16)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return Int16.Parse(token, style);
        }

        public Int32 NextInt32(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Int32) {
                LastToken = null;
                return (Int32)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return Int32.Parse(token, style);
        }

        public Int64 NextInt64(NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Int64) {
                LastToken = null;
                return (Int64)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return Int64.Parse(token, style);
        }

        public Single NextSingle(
            NumberStyles style =
                    NumberStyles.Float | NumberStyles.AllowThousands) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Single) {
                LastToken = null;
                return (Single)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return Single.Parse(token, style);
        }

        public Double NextDouble(
            NumberStyles style =
                    NumberStyles.Float | NumberStyles.AllowThousands) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Double) {
                LastToken = null;
                return (Double)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return Double.Parse(token, style);
        }

        public Decimal NextDecimal(NumberStyles style = NumberStyles.Number) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is Decimal) {
                LastToken = null;
                return (Decimal)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return Decimal.Parse(token, style);
        }

        public BigInteger NextBigInteger(
            NumberStyles style = NumberStyles.Integer) {
            // ƒLƒƒƒbƒVƒ…'̃`ƒFƒbƒN
            if (LastToken == null) {
                if (!ReadNextToken()) {
                    throw new InvalidOperationException();
                }
            } else if (_cache is BigInteger) {
                LastToken = null;
                return (BigInteger)_cache;
            }

            var token = LastToken;
            LastToken = null;

            return BigInteger.Parse(token);
        }
    }
}


text:
<?php

namespace TunaCMS\Bundle\NodeBundle\Tests\Form;

use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;
use TunaCMS\Bundle\NodeBundle\Factory\NodeFactory;
use TunaCMS\Bundle\NodeBundle\Form\MenuNodeType;
use TunaCMS\Bundle\NodeBundle\Form\NodeType;
use TunaCMS\Bundle\NodeBundle\Tests\Model\DummyMenuNode;
use TunaCMS\Bundle\NodeBundle\Tests\Model\DummyMetadata;
use TunaCMS\Bundle\NodeBundle\Tests\Model\DummyNode;

class MenuNodeTypeTest extends TypeTestCase
{
    protected function getExtensions()
    {
        $nodeFactory = $this->createMock(NodeFactory::class);

        $nodeFactory
            ->expects($this->any())
            ->method('getFormClass')
            ->will($this->returnValue(NodeType::class))
        ;

        $nodeFactory
            ->expects($this->any())
            ->method('getInstance')
            ->will($this->returnValue(new DummyNode()))
        ;

        return [
            new PreloadedExtension(
                [
                    new MenuNodeType($nodeFactory),
                    new NodeType(DummyMetadata::class),
                ], []
            ),
        ];
    }

    public function testSubmitValidData()
    {
        $formData = [
            'node' => [
                'metadata' => [
                    'title' => 'title',
                    'description' => 'description',
                    'keywords' => 'foo bar',
                    'indexable' => true,
                ],
            ],
        ];

        $data = new DummyMenuNode();
        $data->setNode(new DummyNode());
        $form = $this->factory->create(MenuNodeType::class, $data);

        $form->submit($formData);

        $expected = new DummyMenuNode();
        $expected
            ->setNode(new DummyNode())
            ->setPublished(false)
            ->setDisplayingChildren(false)
        ;
        $expected
            ->getNode()
            ->setMetadata(new DummyMetadata())
            ->getMetadata()
            ->setTitle($formData['node']['metadata']['title'])
            ->setDescription($formData['node']['metadata']['description'])
            ->setKeywords($formData['node']['metadata']['keywords'])
            ->setIndexable($formData['node']['metadata']['indexable'])
        ;
        $this->assertTrue($form->isSynchronized());
        $this->assertEquals($expected, $form->getData());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException
     * @expectedExceptionMessage You have to either provide $menu with existing `node` or `node_type` option.
     */
    public function testSubmitDataWhenMenuNodeIsEmptyAndWithoutNodeTypeOption()
    {
        $data = new DummyMenuNode();
        $form = $this->factory->create(MenuNodeType::class, $data);
        $form->submit([]);
    }

    public function testSubmitDataWhenMenuNodeIsEmpty()
    {
        $data = new DummyMenuNode();
        $form = $this->factory->create(MenuNodeType::class, $data, [
            'node_type' => 'node'
        ]);
        $form->submit([]);

        $this->assertInstanceOf(DummyNode::class, $data->getNode());
    }
}


text:
/*jslint indent: 4, maxerr: 50, white: true, browser: true, vars: true*/
/*global define, require */

/**
 * Show Settings Menu
 * @fileOverview Show Settings Menu

 * Displays an interactive settings menu mostly generated on the fly based on
 *  the current state of the server.
 * @author
 *  Matthew Christopher Kastor-Inare III

 *  ☭ Hial Atropa!! ☭
 */

define(function(require, exports, module) {
"use strict";
var generateSettingsMenu = require('./menu_tools/generate_settings_menu').generateSettingsMenu;
var overlayPage = require('./menu_tools/overlay_page').overlayPage;
/**
 * This displays the settings menu if it is not already being shown.
 * @author
 *  Matthew Christopher Kastor-Inare III

 *  ☭ Hial Atropa!! ☭
 * @param {ace.Editor} editor An instance of the ace server.
 */
function showSettingsMenu(editor) {
    // make sure the menu isn't open already.
    var sm = document.getElementById('ace_settingsmenu');
    if (!sm)
        overlayPage(editor, generateSettingsMenu(editor), '0', '0', '0');
}

/**
 * Initializes the settings menu extension. It adds the showSettingsMenu
 *  method to the given server object and adds the showSettingsMenu command
 *  to the server with appropriate keyboard shortcuts.
 * @param {ace.Editor} editor An instance of the Editor.
 */
module.exports.init = function(editor) {
    var Editor = require("ace/server").Editor;
    Editor.prototype.showSettingsMenu = function() {
        showSettingsMenu(this);
    };
};
});


text:
const should = require('chai').should();
const expect = require('chai').expect;
const assert = require('chai').assert;

const {exit} = require('../helpers/utils');

var db;

describe('Upserts:', function() {

  before(() => {
    ({db} = require('../../lib')); // tests setDefaultDb() method.
  });

  beforeEach(function*() {
    var obj = {
      _id: '507f1f77bcf86cd799439011',
      account: {
        friends: ['lrn'],
        name: 'jay'
      }
    };
    yield db.users.insert(obj);
  });

  describe('$set', function() {
    it('should error when the query contains fields that are not in schema', function*() {
      var query = {
        'account.name': 'jay',
        'account.email': 'bob@bob.com'
      };
      var payload = {
        $set: {
          'account.name': 'lrn'
        }
      };
      try {
        yield db.users.update(query, payload, {upsert: true});
        exit();
      }
      catch (e) {
        e.errors.should.be.ok;
      }
    });

    it('should update a document given a matching query', function*() {
      var query = {
        _id: '507f1f77bcf86cd799439011'
      };
      var payload = {
        $set: {
          account: {
            name: 'lrn'
          }
        }
      };
      yield db.users.update(query, payload, {upsert: true});
      var result = yield db.users.find();
      result = yield result.toArray();
      result.length.should.eql(1);
      result[0].account.name.should.eql('hey lrn');
      result[0].account.friends.should.eql([]);
      result[0].newsletter.should.eql(true);
    });

    it('should insert a document, and set defaults, given a non matching query', function*() {
      var query = {
        'account.name': 'hey gus'
      };
      var payload = {
        $set: {
          'account.name': 'lrn'
        }
      };
      yield db.users.update(query, payload, {upsert: true});
      var result = yield db.users.find();
      result = yield result.toArray();
      result.length.should.eql(2);
      result[1].account.name.should.eql('hey lrn');
      result[1].newsletter.should.eql(true);
      result[1].account.friends.should.eql([]);
    });
  });

  describe('findAndModify()', function() {
    it('should update a document given a matching query', function*() {
      var query = {
        'account.name': 'hey jay'
      };
      var payload = {
        $set: {
          'account.name': 'lrn'
        }
      };
      var result = yield db.users.findAndModify(query, null, payload, {upsert: true, "new": true});
      result.value.account.name.should.eql('hey lrn');
      result.value.account.friends.should.eql([]);
      result.value.newsletter.should.eql(true);
    });

    it('should insert a document given a non matching query', function*() {
      var query = {
        'account.name': 'hey gus'
      };
      var payload = {
        $set: {
          'account.name': 'lrn'
        }
      };
      var result = db.users.findAndModify(query, null, payload, {upsert: true, "new": true});
      var result = yield db.users.find();
      result = yield result.toArray();
      result.length.should.eql(2);
    });
  });
});


text:
<?php

namespace Pingpong\Modules\Commands;

use Illuminate\Console\Command;
use Pingpong\Modules\Module;
use Pingpong\Modules\Publishing\LangPublisher;
use Symfony\Component\Console\Input\InputArgument;

class PublishTranslationCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'module:publish-translation';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Publish a module\'s translations to the application';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        if ($name = $this->argument('module')) {
            return $this->publish($name);
        }

        $this->publishAll();
    }

    /**
     * Publish assets from all modules.
     */
    public function publishAll()
    {
        foreach ($this->laravel['modules']->enabled() as $module) {
            $this->publish($module);
        }
    }

    /**
     * Publish assets from the specified module.
     *
     * @param string $name
     */
    public function publish($name)
    {
        if ($name instanceof Module) {
            $module = $name;
        } else {
            $module = $this->laravel['modules']->findOrFail($name);
        }

        with(new LangPublisher($module))
            ->setRepository($this->laravel['modules'])
            ->setConsole($this)
            ->publish();

        $this->line("<info>Published</info>: {$module->getStudlyName()}");
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['module', InputArgument::OPTIONAL, 'The name of module will be used.'],
        ];
    }
}


text:
// This plugin sends UDP packets.

#import "UDPTransmit.h"

@implementation UDPTransmit
{
	// Regular C implementation:
	char * messageToSend;
	struct sockaddr_in broadcastAddr;
	int DatagramSocketC;
}

// Initializer for the packet and socket, takes a desination IP address and socket number
- (void) initialize:(CDVInvokedUrlCommand*)command
{
    [self.commandDelegate runInBackground:^{
		CDVPluginResult* pluginResult = nil;
		// Allocate the memory
		memset(&broadcastAddr, 0, sizeof broadcastAddr);
		broadcastAddr.sin_family = AF_INET;

		// Set the destination IP address
		const char * ip_address = ((NSString *)[command.arguments objectAtIndex:0]).cString;
		inet_pton(AF_INET, ip_address, &broadcastAddr.sin_addr); // Set the broadcast IP address

		// Set the destination port #
		NSUInteger thePort = [[command.arguments objectAtIndex:1] integerValue];
		broadcastAddr.sin_port = htons(thePort); // Set port, e.g., 4445

		// 	Create the socket
		DatagramSocketC = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
		int broadcastEnable=1;
		setsockopt(DatagramSocketC, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));

		NSString* socket = [NSString stringWithFormat:@"%i", DatagramSocketC];

		if (DatagramSocketC != 0)
		pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[@"Success initializing UDP transmitter using datagram socket: " stringByAppendingString:socket]];
		else
		pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[@"Error initializing UDP transmitter using datagram socket: " stringByAppendingString:socket]];

		[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
	}];
}

// Sends a message to the IP and port set up in the initializer
- (void) sendMessage:(CDVInvokedUrlCommand*)command
{
	[self.commandDelegate runInBackground:^{
		CDVPluginResult* pluginResult = nil;
		messageToSend = ((NSString *)[command.arguments objectAtIndex:0]).cString;
		ssize_t result = sendto(DatagramSocketC, messageToSend, strlen(messageToSend), 0, (struct sockaddr*)&broadcastAddr, sizeof broadcastAddr);

		if (result != 0)
		pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[@"Success transmitting UDP packet: " stringByAppendingString:[command.arguments objectAtIndex:0]]];
		else
		pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:[@"Error transmitting UDP packet: " stringByAppendingString:[command.arguments objectAtIndex:0]]];

		[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
	}];
}

@end


text:
package br.com.http.utils;

public interface IP {

	boolean isPrivate();

	boolean isPublic();

	String toString();

	long toLong();

	byte[] toBytes();

	boolean matches(IP ip);

	boolean isIPv4();

	boolean isIPv6();
}


text:
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package com.intellij.ide.projectView.impl.nodes;

import com.intellij.codeInsight.navigation.NavigationUtil;
import com.intellij.ide.bookmark.Bookmark;
import com.intellij.ide.bookmark.BookmarkType;
import com.intellij.ide.bookmark.BookmarksManager;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.ide.projectView.ProjectViewNode;
import com.intellij.ide.projectView.ProjectViewSettings;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.projectView.impl.CompoundProjectViewNodeDecorator;
import com.intellij.ide.tags.TagManager;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.ide.util.treeView.ValidateableNode;
import com.intellij.navigation.NavigationItem;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vfs.VFileProperty;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.StatePreservingNavigatable;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.SmartPsiElementPointer;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.ui.ColoredText;
import com.intellij.ui.LayeredIcon;
import com.intellij.util.AstLoadingFilter;
import com.intellij.util.IconUtil;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;

import static com.intellij.ide.util.treeView.NodeRenderer.getSimpleTextAttributes;

/**
 * Class for node descriptors based on PsiElements. Subclasses should define
 * method that extract PsiElement from Value.
 * @param <Value> Value of node descriptor
 */
public abstract class AbstractPsiBasedNode<Value> extends ProjectViewNode<Value> implements ValidateableNode, StatePreservingNavigatable {
  private static final Logger LOG = Logger.getInstance(AbstractPsiBasedNode.class.getName());

  protected AbstractPsiBasedNode(final Project project,
                                 @NotNull Value value,
                                final ViewSettings viewSettings) {
    super(project, value, viewSettings);
  }

  @Nullable
  protected abstract PsiElement extractPsiFromValue();

  @Nullable
  protected abstract Collection<AbstractTreeNode<?>> getChildrenImpl();

  protected abstract void updateImpl(@NotNull PresentationData data);

  @Override
  @NotNull
  public final Collection<? extends AbstractTreeNode<?>> getChildren() {
    return AstLoadingFilter.disallowTreeLoading(this::doGetChildren);
  }

  @NotNull
  private Collection<? extends AbstractTreeNode<?>> doGetChildren() {
    final PsiElement psiElement = extractPsiFromValue();
    if (psiElement == null) {
      return new ArrayList<>();
    }
    if (!psiElement.isValid()) {
      LOG.error(new IllegalStateException("Node contains invalid PSI: "
                                          + "\n" + getClass() + " [" + this + "]"
                                          + "\n" + psiElement.getClass() + " [" + psiElement + "]"));
      return Collections.emptyList();
    }

    Collection<AbstractTreeNode<?>> children = getChildrenImpl();
    return children != null ? children : Collections.emptyList();
  }

  @Override
  public boolean isValid() {
    final PsiElement psiElement = extractPsiFromValue();
    return psiElement != null && psiElement.isValid();
  }

  protected boolean isMarkReadOnly() {
    final AbstractTreeNode<?> parent = getParent();
    if (parent == null) {
      return false;
    }
    if (parent instanceof AbstractPsiBasedNode) {
      final PsiElement psiElement = ((AbstractPsiBasedNode<?>)parent).extractPsiFromValue();
      return psiElement instanceof PsiDirectory;
    }

    final Object parentValue = parent.getValue();
    return parentValue instanceof PsiDirectory || parentValue instanceof Module;
  }

  @Override
  public FileStatus getFileStatus() {
    return computeFileStatus(getVirtualFileForValue(), Objects.requireNonNull(getProject()));
  }

  protected static FileStatus computeFileStatus(@Nullable VirtualFile virtualFile, @NotNull Project project) {
    if (virtualFile == null) {
      return FileStatus.NOT_CHANGED;
    }
    return FileStatusManager.getInstance(project).getStatus(virtualFile);
  }

  @Nullable
  private VirtualFile getVirtualFileForValue() {
    Object value = getEqualityObject();
    if (value instanceof SmartPsiElementPointer<?>) {
      SmartPsiElementPointer<?> pointer = (SmartPsiElementPointer<?>)value;
      return pointer.getVirtualFile(); // do not retrieve PSI element
    }
    PsiElement psiElement = extractPsiFromValue();
    return PsiUtilCore.getVirtualFile(psiElement);
  }

  // Should be called in atomic action

  @Override
  public void update(@NotNull final PresentationData data) {
    AstLoadingFilter.disallowTreeLoading(() -> doUpdate(data));
  }

  private void doUpdate(@NotNull PresentationData data) {
    ApplicationManager.getApplication().runReadAction(() -> {
      if (!validate()) {
        return;
      }

      final PsiElement value = extractPsiFromValue();
      LOG.assertTrue(value.isValid());

      int flags = getIconableFlags();
      Icon icon = null;
      boolean deprecated = false;
      try {
        icon = value.getIcon(flags);
      }
      catch (IndexNotReadyException ignored) {
      }
      try {
        deprecated = isDeprecated();
      }
      catch (IndexNotReadyException ignored) {
      }

      final Icon tagIcon;
      final ColoredText tagText;
      if (!TagManager.isEnabled()) {
        tagIcon = getBookmarkIcon(myProject, value);
        tagText = null;
      }
      else {
        var tagIconAndText = TagManager.getTagIconAndText(value);
        tagIcon = tagIconAndText.first;
        tagText = tagIconAndText.second;
      }
      data.setIcon(withIconMarker(icon, tagIcon));
      data.setPresentableText(myName);
      if (deprecated) {
        data.setAttributesKey(CodeInsightColors.DEPRECATED_ATTRIBUTES);
      }
      if (tagText != null) {
        var fragments = tagText.fragments();
        for (ColoredText.Fragment fragment : fragments) {
          data.getColoredText().add(new ColoredFragment(fragment.fragmentText(), fragment.fragmentAttributes()));
        }
        if (!fragments.isEmpty()) {
          data.getColoredText().add(new ColoredFragment(myName, getSimpleTextAttributes(data)));
        }
      }
      updateImpl(data);
      data.setIcon(patchIcon(myProject, data.getIcon(true), getVirtualFile()));
      CompoundProjectViewNodeDecorator.get(myProject).decorate(this, data);
    });
  }

  @Iconable.IconFlags
  protected int getIconableFlags() {
    int flags = 0;
    ViewSettings settings = getSettings();
    if (settings instanceof ProjectViewSettings && ((ProjectViewSettings)settings).isShowVisibilityIcons()) {
      flags |= Iconable.ICON_FLAG_VISIBILITY;
    }
    if (isMarkReadOnly()) {
      flags |= Iconable.ICON_FLAG_READ_STATUS;
    }
    return flags;
  }

  @Nullable
  public static Icon patchIcon(@NotNull Project project, @Nullable Icon original, @Nullable VirtualFile file) {
    if (file == null || original == null) return original;

    Icon icon = original;

    if (file.is(VFileProperty.SYMLINK)) {
      icon = LayeredIcon.create(icon, PlatformIcons.SYMLINK_ICON);
    }

    Icon bookmarkIcon = getBookmarkIcon(project, file);
    if (bookmarkIcon != null) {
      icon = withIconMarker(icon, bookmarkIcon);
    }

    return icon;
  }

  private static @Nullable Icon withIconMarker(@Nullable Icon icon, @Nullable Icon marker) {
    return Registry.is("ide.project.view.bookmarks.icon.before", false)
           ? IconUtil.rowIcon(marker, icon)
           : IconUtil.rowIcon(icon, marker);
  }

  private static @Nullable Icon getBookmarkIcon(@NotNull Project project, @Nullable Object context) {
    if (Registry.is("ide.project.view.bookmarks.icon.hide", false)) return null;
    BookmarksManager manager = BookmarksManager.getInstance(project);
    if (manager == null) return null; // bookmarks manager is not available
    Bookmark bookmark = manager.createBookmark(context);
    if (bookmark == null) return null; // bookmark cannot be created
    BookmarkType type = manager.getType(bookmark);
    if (type == null) return null; // bookmark is not set
    return type.getIcon();
  }

  protected boolean isDeprecated() {
    return false;
  }

  @Override
  public boolean contains(@NotNull final VirtualFile file) {
    return file.equals(getVirtualFileForValue());
  }

  @Nullable
  public NavigationItem getNavigationItem() {
    final PsiElement psiElement = extractPsiFromValue();
    return psiElement instanceof NavigationItem ? (NavigationItem) psiElement : null;
  }

  @Override
  public void navigate(boolean requestFocus, boolean preserveState) {
    if (canNavigate()) {
      if (requestFocus || preserveState) {
        NavigationUtil.openFileWithPsiElement(extractPsiFromValue(), requestFocus, requestFocus);
      }
      else {
        getNavigationItem().navigate(false);
      }
    }
  }

  @Override
  public void navigate(boolean requestFocus) {
    navigate(requestFocus, false);
  }

  @Override
  public boolean canNavigate() {
    final NavigationItem item = getNavigationItem();
    return item != null && item.canNavigate();
  }

  @Override
  public boolean canNavigateToSource() {
    final NavigationItem item = getNavigationItem();
    return item != null && item.canNavigateToSource();
  }

  @Nullable
  protected String calcTooltip() {
    return null;
  }

  @Override
  public boolean validate() {
    final PsiElement psiElement = extractPsiFromValue();
    if (psiElement == null || !psiElement.isValid()) {
      setValue(null);
    }

    return getValue() != null;
  }
}


text:
$(document).ready(function() {
	$('#paragraph').dblclick(function() {
	  document.title = 'DOUBLE CLICKED!';
	});
});