text:
var fs = require('fs');
var glob = require('glob');
var crypto = require('crypto');
var defaults = require('lodash.defaults');
var through = require('through2');
var colors = require('colors/safe');

var caches;
var option;

/**
 * @param {String} opts.path
 * @return {Function}
 */
module.exports = function(opts) {
  option = defaults(opts || {}, {
    path: '.gulpcache',
    verbose: false
  });

  try {
    caches = JSON.parse(fs.readFileSync(opts.path));
  } catch (e) {
    caches = {};
  }

  return pcache;
};

/**
 * @param {String} name
 * @param {Object} opts
 * @return {Stream}
 */
function pcache(name, opts) {
  opts = defaults(opts || {},  {}, {deps: []});

  // create cache space for task.
  caches[name] = caches[name] || {};

  // return Strema.
  var isAllCached = true;
  return through.obj(function(file, enc, callback) {

    // skip if stream.
    if (file.isStream() || !file.contents) {
      this.push(file);
      return callback();
    }

    var isMiss = false;
    getDependencies(file.path, file.contents).forEach(function(dep) {
      if (caches[name][dep.path] === dep.hash) {
        return;
      }
      caches[name][dep.path] = dep.hash;

      isMiss = true;
    });

    if (isMiss) {
      isAllCached = false;
      this.push(file);
    }

    callback();
  }, function(callback) {
    if (isAllCached && option.verbose) {
      console.log('%s: cached all files', colors.underline.yellow(name));
    }

    // reset default value.
    isAllCached = true;
    callback();
  });

  /**
   * @param {String} targetPath
   * @param {String|Buffer} contents
   * @return {Array.<String, String>}
   */
  function getDependencies(targetPath, contents) {
    var deps = [{path: targetPath, hash: hash(contents)}];
    for (var dep of opts.deps) {
      // is matching option dependencies?
      if (dep.test.test(targetPath)) {

        // add dependencies from glob pattern.
        for (var depPath of glob.sync(dep.glob)) {
          deps.push({
            path: depPath,
            hash: hash(fs.readFileSync(depPath))
          });
        }
      }
    }
    return deps;
  }

  /**
   * @param {String|Buffer} contents
   * @return {String}
   */
  function hash(contents) {
    return crypto.createHash('md5').update(contents.toString('utf8')).digest('hex');
  }
}

pcache.path = function() {
  return option.path;
};

pcache.clear = function() {
  try {
    caches = {};
    fs.unlinkSync(option.path);
  } catch(e) {}
  return Promise.resolve();
};

pcache.save = function() {
  fs.writeFileSync(option.path, JSON.stringify(caches));
  return Promise.resolve();
};


text:
<?php

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\YamlFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $loader = new YamlFileLoader();
        $resource = __DIR__ . '/../fixtures/resources.yml';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    public function testLoadDoesNothingIfEmpty()
    {
        $loader = new YamlFileLoader();
        $resource = __DIR__ . '/../fixtures/empty.yml';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array(), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new YamlFileLoader();
        $resource = __DIR__ . '/../fixtures/non-existing.yml';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadThrowsAnExceptionIfFileNotLocal()
    {
        $loader = new YamlFileLoader();
        $resource = 'http://example.com/resources.yml';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadThrowsAnExceptionIfNotAnArray()
    {
        $loader = new YamlFileLoader();
        $resource = __DIR__ . '/../fixtures/non-valid.yml';
        $loader->load($resource, 'en', 'domain1');
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef PEGR_SCRIPT_SCRIPT_HPP
#define PEGR_SCRIPT_SCRIPT_HPP

#include <memory>

#include <lua.hpp>

namespace pegr {
namespace Script {

/**
 * @brief An index into the lua registry, created using luaL_ref().
 */
typedef int Regref;

/**
 * @brief An integer index into a Lua array (a table with consecutive integer
 * keys starting at 1)
 */
typedef lua_Number Arridx;

/**
 * @class Unique_Regref
 * @brief Handles the release of a value referenced in the lua registry (RAII)
 * Note that these must go out of scope before Script::cleanup() is called.
 */
class Unique_Regref {
public:
    /**
     * @brief Guards nothing
     */
    Unique_Regref();

    /**
     * @brief Guards the given reference. When this guard is deleted (for
     * example, by going out of scope) the reference is freed from the lua
     * registry, possibly causing that value to be gc'd.
     */
    Unique_Regref(Regref ref);

    /**
     * @brief Copy construction not allowed
     * (there should only be one guard for a single reference)
     */
    Unique_Regref(const Unique_Regref& rhs) = delete;

    /**
     * @brief Copy assignment not allowed
     * (there should only be one guard for a single reference)
     */
    Unique_Regref& operator =(const Unique_Regref& rhs) = delete;

    /**
     * @brief Move construction
     */
    Unique_Regref(Unique_Regref&& rhs);

    /**
     * @brief Move assignment
     */
    Unique_Regref& operator =(Unique_Regref&& rhs);

    /**
     * @brief Deconstructor. Drops whatever reference it is guarding.
     */
    ~Unique_Regref();

    /**
     * @brief Get the Lua reference that this is guarding
     * @return the Lua reference that this is guarding
     */
    Regref get() const;

    /**
     * @return Iff this is guarding nothing (nil via LUA_REFNIL)
     */
    bool is_nil() const;

    /**
     * @brief Replaces the currently guarded reference with this one. Properly
     * release the previously guarded value
     * @param value Reference to the new value to be guarded.
     */
    void reset(Regref value = LUA_REFNIL);

    /**
     * @brief Releases ownership of the held Regref (does not release the value
     * from the Lua registry) and returns it
     * @return The formerly guarded Regref
     */
    Regref release();
private:

    Regref m_reference;
};

/**
 * @brief A shared pointer for a guard. Useful for having multiple references
 * to the same Lua object. Uses reference counting.
 */
typedef std::shared_ptr<Unique_Regref> Shared_Regref;

/**
 * @brief Make a referenced Lua value into a shared RAII object
 * @param ref The Lua reference to make shared
 * @return A shared RAII object for the provided reference
 */
Shared_Regref make_shared(Regref ref);

/**
 * @brief Make a referenced Lua value into a shared RAII object
 * @param ref The Lua reference to make shared
 * @return A shared RAII object for the provided reference
 */
Shared_Regref make_shared(Unique_Regref&& ref);

extern const char* PEGR_MODULE_NAME;

extern const Regref NO_SANDBOX;
extern Regref m_pristine_sandbox;

extern Regref m_luaglob_tostring;
extern Regref m_luaglob__VERISON;
extern Regref m_luaglob_print;

/**
 * @class Pop_Guard
 * @brief RAII for stack size. When this object is destructed, the specified
 * number of elements are popped off the Lua stack (calls lua_pop)
 */
class Pop_Guard {
public:
    Pop_Guard(int n = 0, lua_State* l = nullptr);
    ~Pop_Guard();

    /**
     * @brief Pops n values prematurely (before destructor is called)
     * @param n The number of values to pop. Must be <= m_n
     */
    void pop(int n);

    /**
     * @brief Increases total number of values to pop when the destructor
     * is called. Effectively increases how many stack entries are
     * being guarded.
     * @param n The number of unguarded values that have just been pushed
     * onto the stack.
     */
    void on_push(int n);

    /**
     * @brief Decreases total number of values to pop when the destructor
     * is called. Effectively decreases how many stack entries are
     * being guarded.
     * @param n The number of previously guarded values that have just
     * been popped off the stack.
     */
    void on_pop(int n);
private:
    int m_n;
    lua_State* m_lstate;
};

int debug_get_total_grab_delta();

/**
 * @brief Creates the lua state and loads standard libraries
 */
void initialize();

/**
 * @brief Returns if the lua scripting system is initialized
 * @return if the lua scripting system is initialized
 */
bool is_initialized();

/**
 * @brief Frees all lua resources, invalidates all registry references
 */
void cleanup();

/**
 * @brief Loads a c function
 * @param func Pointer to the function to add
 * @param closure_size
 * @return
 */
Unique_Regref load_c_function(lua_CFunction func, int closure_size = 0);

/**
 * @brief Loads a function from a lua file
 * @param filename The file to read
 * @param environment The environment (closure upvalue table) for this function
 * @param chunkname The name of the chunk used for debugging purposes
 * @return A lua reference to the new function
 */
Unique_Regref load_lua_function(const char* filename, Regref environment,
                            const char* chunkname = nullptr);

/**
 * @brief Runs the function on the stack. Behaves exactly like lua_pcall,
 * except Lua errors are turned into thrown runtime exceptions.
 * Guaranteed to pop off the expected number of values from the stack regardless
 * of errors.
 * @param nargs The number of arguments this function will consume
 * @param nresults The number of values this function will return
 */
void run_function(int nargs, int nresults);

/**
 * @brief Produces a new sandbox environment for running user scripts in.
 * @return A lua reference to the new sandbox
 */
Unique_Regref new_sandbox();

/**
 * @brief Releases the reference to the lua value, allowing for it to be gc'd
 * @param reference The reference you would like to be liberated
 */
void drop_reference(Regref reference);

/**
 * @brief Pushes the referenced value onto the lua stack.
 * @param reference The reference you would like to be pushed onto the stack
 */
void push_reference(Regref reference);

/**
 * @brief Makes a new reference to the element on the top of the stack and pops
 * it from the stack.
 * @return The new reference
 */
Regref grab_reference();

/**
 * @brief Same as grab_reference(), but puts it into a unique reference instead.
 * @return The new reference
 */
Unique_Regref grab_unique_reference();

/**
 * @brief Get the global lua state
 * @return The global lua state
 */
lua_State* get_lua_state();

/**
 * @brief Adds a lua value to the pegr table, making it accessible in lua.
 * @param key The key
 * @param value Lua reference to the value
 * @param safe If true, then this value is accessible in sandboxes
 */
void expose_referenced_value(const char* key, Regref value, bool safe = true);

/**
 * @brief Adds a number to the pegr table
 * @param key The key
 * @param num The number
 * @param safe If true, then this value is accessible in sandboxes
 */
void expose_number(const char* key, lua_Number num, bool safe = true);

/**
 * @brief Adds a string to the pegr table
 * @param key The key
 * @param str The string
 * @param safe If true, then this value is accessible in sandboxes
 */
void expose_string(const char* key, const char* str, bool safe = true);

/**
 * @brief Exposes multiple c functions to lua. Faster than repeatedly calling
 * expose_referenced_value with referenced functions.
 * [BALANCED]
 * @param api Multiple registry entries. Array must end with a pair of nullptrs.
 * @param safe If true, then these values are accessible in sandboxes
 */
void multi_expose_c_functions(const luaL_Reg* api, bool safe = true);

/**
 * @brief Turns an index relative to the top of the stack (negative indices)
 * into ones relative to the bottom of the stack (absolute indices)
 * @param idx The index, can be negative
 * @return An index that points to the same position on the stack
 */
int absolute_idx(int idx);

namespace LI {

/**
 * @brief Replacement print for lua, uses logger
 */
int li_print(lua_State* l);

} // namespace LI
} // namespace Script
} // namespace pegr

#endif // PEGR_SCRIPT_SCRIPT_HPP


text:
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
      '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/animations': 'npm:@angular/animations/bundles/animations.umd.js',
      '@angular/animations/browser': 'npm:@angular/animations/bundles/animations-browser.umd.js',
      '@angular/platform-browser/animations': 'npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',
      //material
      '@angular/material': 'npm:@angular/material/bundles/material.umd.js',
      '@angular/cdk': 'npm:@angular/cdk/bundles/cdk.umd.js',
      '@angular/cdk/a11y': 'npm:@angular/cdk/bundles/cdk-a11y.umd.js',
      '@angular/cdk/bidi': 'npm:@angular/cdk/bundles/cdk-bidi.umd.js',
      '@angular/cdk/coercion': 'npm:@angular/cdk/bundles/cdk-coercion.umd.js',
      '@angular/cdk/collections': 'npm:@angular/cdk/bundles/cdk-collections.umd.js',
      '@angular/cdk/keycodes': 'npm:@angular/cdk/bundles/cdk-keycodes.umd.js',
      '@angular/cdk/observers': 'npm:@angular/cdk/bundles/cdk-observers.umd.js',
      '@angular/cdk/overlay': 'npm:@angular/cdk/bundles/cdk-overlay.umd.js',
      '@angular/cdk/platform': 'npm:@angular/cdk/bundles/cdk-platform.umd.js',
      '@angular/cdk/portal': 'npm:@angular/cdk/bundles/cdk-portal.umd.js',
      '@angular/cdk/accordion': 'npm:@angular/cdk/bundles/cdk-accordion.umd.js',
      '@angular/cdk/layout': 'npm:@angular/cdk/bundles/cdk-layout.umd.js',
      '@angular/cdk/scrolling': 'npm:@angular/cdk/bundles/cdk-scrolling.umd.js',
      '@angular/cdk/table': 'npm:@angular/cdk/bundles/cdk-table.umd.js',
      '@angular/cdk/stepper': 'npm:@angular/cdk/bundles/cdk-stepper.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'hammerjs': 'npm:hammerjs',
      'tslib': 'npm:tslib/tslib.js'
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      "rxjs/operators": {
        "main": "index.js",
        "defaultExtension": "js"
      },
      hammerjs:{
        main: './hammer.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Crm
{
    public static class ServiceFactory
    {
        private static readonly Dictionary<Type, Func<object>> _typeMap = new Dictionary<Type, Func<object>>();

        public static void Register<T>(Func<T> instanceFactory)
        {
            lock (_typeMap) _typeMap.Add(typeof(T), () => instanceFactory());
        }

        public static void Register<T>(IFactory factory)
        {
            lock (_typeMap) _typeMap.Add(typeof(T), factory.GetInstance);
        }

        public static void Override<T>(Func<T> instanceFactory)
        {
            lock (_typeMap) _typeMap[typeof(T)] = () => instanceFactory();
        }

        public static void Override<T>(IFactory factory)
        {
            lock (_typeMap) _typeMap[typeof(T)] = factory.GetInstance;
        }

        public static T Resolve<T>()
        {
            lock (_typeMap) return (T)(_typeMap[typeof(T)]());
        }

        static ServiceFactory()
        {
            foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsClass && !t.IsNested && !t.IsAbstract))
            {
                var attr = type.GetCustomAttribute<ServiceAttribute>();
                if (attr == null) continue;

                var interfaces = type.GetInterfaces().Where(ifc => ifc.IsPublic).ToList();
                if (interfaces.Count <= 0) continue;

                Func<object> factory;
                switch (attr.Option)
                {
                    case ServiceOption.Singleton:
                        factory = new Singleton(type).GetInstance;
                        break;
                    case ServiceOption.PerResolve:
                        factory = new PerResolve(type).GetInstance;
                        break;
                    default:
                        throw new Exception("Invalid instantiation mode");
                }
                foreach (var i in interfaces) _typeMap.Add(i, factory);
            }
        }

        public interface IFactory
        {
            object GetInstance();
        }

        public class Singleton : IFactory
        {
            private readonly object _lock = new object();
            private readonly Type _type;
            private object _instance;

            public object GetInstance()
            {
                lock (_lock)
                    return _instance ?? (_instance = Activator.CreateInstance(_type));
            }

            public Singleton(Type type)
            {
                if (type == null) throw new ArgumentNullException("type");
                _type = type;
            }
        }

        public class Singleton<T> : Singleton
        {
            public Singleton() : base(typeof(T)) { }
        }

        public class PerResolve : IFactory
        {
            private readonly Type _type;

            public object GetInstance()
            {
                return Activator.CreateInstance(_type);
            }

            public PerResolve(Type type)
            {
                if (type == null) throw new ArgumentNullException("type");
                _type = type;
            }
        }

        public class PerResolve<T> : PerResolve
        {
            public PerResolve() : base(typeof(T)) { }
        }
    }
}


text:
package com.dazito.kafka.consumer;

import kafka.consumer.*;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.serializer.StringDecoder;
import kafka.utils.VerifiableProperties;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by daz on 22/11/2015.
 */
public class SimpleConsumer {

    private Properties kafkaProperties = new Properties();
    private ConsumerConnector consumerConnector;
    private ConsumerConfig consumerConfig;
    private KafkaStream<String, String> stream;

    private String zookeeperUrl;
    private String groupId;
    private String topic;
    private String waitTime;

    public SimpleConsumer(String zookeeperUrl, String groupId, String topic, String waitTime) {
        this.zookeeperUrl = zookeeperUrl;
        this.groupId = groupId;
        this.topic = topic;
        this.waitTime = waitTime;
    }

    /**
     * Zookeeper to coordinate all the consumers in the consumer group and track the offsets
     */
    public void configure() {
        kafkaProperties.put("zookeeper.connect", zookeeperUrl);
        kafkaProperties.put("group.id", groupId);
        kafkaProperties.put("auto.commit.internal.ms", "1000");
        kafkaProperties.put("auto.offset.reset", "largest");

        // If you want to manually control the offset commit set this config to false
        kafkaProperties.put("auto.commit.enable", "true");

        // By default it waits till infinite otherwise specify a wait time for new messages.
        kafkaProperties.put("consumer.timeout.ms", waitTime);

        consumerConfig = new ConsumerConfig(kafkaProperties);
    }

    public void start() {

        consumerConnector = Consumer.createJavaConsumerConnector(consumerConfig);

        /**
         * Define how many threads will read from each topic. We have one topic and one thread.
         *
         * Can be multi thread (one topic 2+ threads). With the high level consumer we usually don't multi thread them.
         * This is because if I want to manually commit offsets it will commit for all the threads that have this
         * consumer instance, at the same time. To avoid this we can create multiple consumer instances and have each
         * of them their own thread.
         */
        Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
        topicCountMap.put(topic, 1);

        /**
         * We will use a decoder to get Kafka to convert messages to Strings
         * valid property will be deserializer.encoding with the charset to use
         * default UTF8 which works for us
         */
        StringDecoder decoder = new StringDecoder(new VerifiableProperties());

        /**
         * Kafka will give us a list of streams of messages for each topic.
         * In this case it is just one topic with a list of a single stream
         */
        stream = consumerConnector.createMessageStreams(topicCountMap, decoder, decoder).get(topic).get(0);

    }

    public String fetchMessage() {
        ConsumerIterator<String, String> it = stream.iterator();

        try {
            return it.next().message();
        }
        catch (ConsumerTimeoutException ex) {
            System.out.println("Waited " + waitTime + " but no messages arrived... Exiting...");
            return null;
        }
    }
}


text:
namespace QuotesDB
{
    partial class ManageTags
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.cancelButton = new System.Windows.Forms.Button();
            this.tagList = new System.Windows.Forms.CheckedListBox();
            this.deleteButton = new System.Windows.Forms.Button();
            this.insertBox = new System.Windows.Forms.TextBox();
            this.insertButton = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // cancelButton
            //
            this.cancelButton.Location = new System.Drawing.Point(483, 189);
            this.cancelButton.Name = "cancelButton";
            this.cancelButton.Size = new System.Drawing.Size(75, 23);
            this.cancelButton.TabIndex = 0;
            this.cancelButton.Text = "Cancel";
            this.cancelButton.UseVisualStyleBackColor = true;
            this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
            //
            // tagList
            //
            this.tagList.CheckOnClick = true;
            this.tagList.FormattingEnabled = true;
            this.tagList.Location = new System.Drawing.Point(13, 13);
            this.tagList.Name = "tagList";
            this.tagList.Size = new System.Drawing.Size(545, 169);
            this.tagList.TabIndex = 1;
            //
            // deleteButton
            //
            this.deleteButton.Location = new System.Drawing.Point(401, 189);
            this.deleteButton.Name = "deleteButton";
            this.deleteButton.Size = new System.Drawing.Size(75, 23);
            this.deleteButton.TabIndex = 2;
            this.deleteButton.Text = "Delete";
            this.deleteButton.UseVisualStyleBackColor = true;
            this.deleteButton.Click += new System.EventHandler(this.deleteButton_Click);
            //
            // insertBox
            //
            this.insertBox.Location = new System.Drawing.Point(13, 189);
            this.insertBox.Name = "insertBox";
            this.insertBox.Size = new System.Drawing.Size(102, 20);
            this.insertBox.TabIndex = 3;
            //
            // insertButton
            //
            this.insertButton.Location = new System.Drawing.Point(122, 189);
            this.insertButton.Name = "insertButton";
            this.insertButton.Size = new System.Drawing.Size(75, 23);
            this.insertButton.TabIndex = 4;
            this.insertButton.Text = "Insert";
            this.insertButton.UseVisualStyleBackColor = true;
            this.insertButton.Click += new System.EventHandler(this.insertButton_Click);
            //
            // ManageTags
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(570, 219);
            this.Controls.Add(this.insertButton);
            this.Controls.Add(this.insertBox);
            this.Controls.Add(this.deleteButton);
            this.Controls.Add(this.tagList);
            this.Controls.Add(this.cancelButton);
            this.Name = "ManageTags";
            this.Text = "Manage Tags";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button cancelButton;
        private System.Windows.Forms.CheckedListBox tagList;
        private System.Windows.Forms.Button deleteButton;
        private System.Windows.Forms.TextBox insertBox;
        private System.Windows.Forms.Button insertButton;
    }
}


text:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;

namespace FluentAssertions.Analyzers
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    public class AssertIsNotNullAnalyzer : MsTestAssertAnalyzer
    {
        public const string DiagnosticId = Constants.Tips.MsTest.AssertIsNotNull;
        public const string Category = Constants.Tips.Category;

        public const string Message = "Use .Should().NotBeNull() instead.";

        protected override DiagnosticDescriptor Rule => new DiagnosticDescriptor(DiagnosticId, Title, Message, Category, DiagnosticSeverity.Info, true);
        protected override IEnumerable<FluentAssertionsCSharpSyntaxVisitor> Visitors
        {
            get
            {
                yield return new AssertIsNotNullSyntaxVisitor();
            }
        }

        public class AssertIsNotNullSyntaxVisitor : FluentAssertionsCSharpSyntaxVisitor
        {
            public AssertIsNotNullSyntaxVisitor() : base(new MemberValidator("IsNotNull"))
            {
            }
        }
    }

    [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AssertIsNotNullCodeFix)), Shared]
    public class AssertIsNotNullCodeFix : MsTestAssertCodeFixProvider
    {
        public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(AssertIsNotNullAnalyzer.DiagnosticId);

        protected override ExpressionSyntax GetNewExpression(ExpressionSyntax expression, FluentAssertionsDiagnosticProperties properties)
            => RenameMethodAndReplaceWithSubjectShould(expression, "IsNotNull", "NotBeNull");
    }
}


text:
<?php
class ControllerSaleCannedMessage extends Controller {
	private $error = array();
	protected function CannedMessagedbCheck(){
		$query = $this->db->query("SHOW TABLES LIKE '".DB_PREFIX."cannedmessage'");
			if(!$query->num_rows){
				$this->db->query("CREATE TABLE `".DB_PREFIX."cannedmessage` (
				  `cannedmessage_id` int(11) NOT NULL AUTO_INCREMENT,
				  `sort_order` int(3) NOT NULL DEFAULT '0',
				  `status` tinyint(1) NOT NULL DEFAULT '1',
				  `title` varchar(64) COLLATE utf8_bin NOT NULL DEFAULT '',
				  `description` text COLLATE utf8_bin NOT NULL,
				  PRIMARY KEY (`cannedmessage_id`)
				) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_bin;");
			}
	}
	public function index() {
		$this->CannedMessagedbCheck();
		$this->load->language('sale/cannedmessage');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/cannedmessage');

		$this->getList();
	}

	public function insert() {
		$this->load->language('sale/cannedmessage');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/cannedmessage');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_sale_cannedmessage->addCannedMessage($this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->redirect($this->url->link('sale/cannedmessage', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function update() {
		$this->load->language('sale/cannedmessage');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/cannedmessage');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_sale_cannedmessage->editCannedMessage($this->request->get['cannedmessage_id'], $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->redirect($this->url->link('sale/cannedmessage', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function delete() {
		$this->load->language('sale/cannedmessage');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('sale/cannedmessage');

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $cannedmessage_id) {
				$this->model_sale_cannedmessage->deleteCannedMessage($cannedmessage_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->redirect($this->url->link('sale/cannedmessage', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getList();
	}

	private function getList() {
		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'id.title';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

  		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
   		);

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('sale/cannedmessage', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      		'separator' => ' :: '
   		);

		$this->data['insert'] = $this->url->link('sale/cannedmessage/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$this->data['delete'] = $this->url->link('sale/cannedmessage/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

		$this->data['cannedmessages'] = array();

		$data = array(
			'sort'  => $sort,
			'order' => $order,
			'start' => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit' => $this->config->get('config_admin_limit')
		);

		$CannedMessage_total = $this->model_sale_cannedmessage->getTotalcannedmessages();

		$results = $this->model_sale_cannedmessage->getcannedmessages($data);

    	foreach ($results as $result) {
			$action = array();

			$action[] = array(
				'text' => $this->language->get('text_edit'),
				'href' => $this->url->link('sale/cannedmessage/update', 'token=' . $this->session->data['token'] . '&cannedmessage_id=' . $result['cannedmessage_id'] . $url, 'SSL')
			);

			$this->data['cannedmessages'][] = array(
				'cannedmessage_id' => $result['cannedmessage_id'],
				'title'          => $result['title'],
				'sort_order'     => $result['sort_order'],
				'selected'       => isset($this->request->post['selected']) && in_array($result['cannedmessage_id'], $this->request->post['selected']),
				'action'         => $action
			);
		}

		$this->data['heading_title'] = $this->language->get('heading_title');

		$this->data['text_no_results'] = $this->language->get('text_no_results');

		$this->data['column_title'] = $this->language->get('column_title');
		$this->data['column_sort_order'] = $this->language->get('column_sort_order');
		$this->data['column_action'] = $this->language->get('column_action');

		$this->data['button_insert'] = $this->language->get('button_insert');
		$this->data['button_delete'] = $this->language->get('button_delete');

 		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$this->data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$this->data['success'] = '';
		}

		$url = '';

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$this->data['sort_title'] = $this->url->link('sale/cannedmessage', 'token=' . $this->session->data['token'] . '&sort=id.title' . $url, 'SSL');
		$this->data['sort_sort_order'] = $this->url->link('sale/cannedmessage', 'token=' . $this->session->data['token'] . '&sort=i.sort_order' . $url, 'SSL');

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $CannedMessage_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('sale/cannedmessage', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$this->data['pagination'] = $pagination->render();

		$this->data['sort'] = $sort;
		$this->data['order'] = $order;

		$this->template = 'sale/cannedmessage_list.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render());
	}

	private function getForm() {
		$this->data['heading_title'] = $this->language->get('heading_title');

		$this->data['text_default'] = $this->language->get('text_default');
		$this->data['text_enabled'] = $this->language->get('text_enabled');
    		$this->data['text_disabled'] = $this->language->get('text_disabled');

		$this->data['entry_title'] = $this->language->get('entry_title');
		$this->data['entry_description'] = $this->language->get('entry_description');
		$this->data['entry_sort_order'] = $this->language->get('entry_sort_order');
		$this->data['entry_status'] = $this->language->get('entry_status');

		$this->data['button_save'] = $this->language->get('button_save');
		$this->data['button_cancel'] = $this->language->get('button_cancel');

 		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}

 		if (isset($this->error['title'])) {
			$this->data['error_title'] = $this->error['title'];
		} else {
			$this->data['error_title'] = '';
		}

	 	if (isset($this->error['description'])) {
			$this->data['error_description'] = $this->error['description'];
		} else {
			$this->data['error_description'] = '';
		}

		$url = '';

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

  		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => false
   		);

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('sale/cannedmessage', 'token=' . $this->session->data['token'] . $url, 'SSL'),
      		'separator' => ' :: '
   		);

		if (!isset($this->request->get['cannedmessage_id'])) {
			$this->data['action'] = $this->url->link('sale/cannedmessage/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
		} else {
			$this->data['action'] = $this->url->link('sale/cannedmessage/update', 'token=' . $this->session->data['token'] . '&cannedmessage_id=' . $this->request->get['cannedmessage_id'] . $url, 'SSL');
		}

		$this->data['cancel'] = $this->url->link('sale/cannedmessage', 'token=' . $this->session->data['token'] . $url, 'SSL');

		if (isset($this->request->get['cannedmessage_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$cannedmessage_info = $this->model_sale_cannedmessage->getCannedMessage($this->request->get['cannedmessage_id']);
		}

		$this->data['token'] = $this->session->data['token'];
		$this->load->model('localisation/language');

		$this->data['languages'] = $this->model_localisation_language->getLanguages();

		if (isset($this->request->post['cannedmessage_description'])) {
			$this->data['cannedmessage_description'] = $this->request->post['cannedmessage_description'];
		} elseif (!empty($cannedmessage_info)) {
			$this->data['cannedmessage_description'] = $cannedmessage_info['description'];
		} else {
			$this->data['cannedmessage_description'] = '';
		}

		if (isset($this->request->post['cannedmessage_title'])) {
			$this->data['cannedmessage_title'] = $this->request->post['cannedmessage_title'];
		} elseif (!empty($cannedmessage_info)) {
			$this->data['cannedmessage_title'] = $cannedmessage_info['title'];
		} else {
			$this->data['cannedmessage_title'] = '';
		}

		if (isset($this->request->post['status'])) {
			$this->data['status'] = $this->request->post['status'];
		} elseif (!empty($cannedmessage_info)) {
			$this->data['status'] = $cannedmessage_info['status'];
		} else {
			$this->data['status'] = 1;
		}

		if (isset($this->request->post['sort_order'])) {
			$this->data['sort_order'] = $this->request->post['sort_order'];
		} elseif (!empty($cannedmessage_info)) {
			$this->data['sort_order'] = $cannedmessage_info['sort_order'];
		} else {
			$this->data['sort_order'] = '';
		}

		$this->template = 'sale/cannedmessage_form.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render());
	}

	private function validateForm() {
		if (!$this->user->hasPermission('modify', 'sale/cannedmessage')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

					if ((utf8_strlen($this->request->post['cannedmessage_title']) < 3) || (utf8_strlen($this->request->post['cannedmessage_title']) > 64)) {
				$this->error['title'] = $this->language->get('error_title');
			}

			if (utf8_strlen($this->request->post['cannedmessage_description']) < 3) {
				$this->error['description'] = $this->language->get('error_description');
			}

		if ($this->error && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_warning');
		}

		if (!$this->error) {
			return true;
		} else {
			return false;
		}
	}

	private function validateDelete() {
		if (!$this->user->hasPermission('modify', 'sale/cannedmessage')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		$this->load->model('setting/store');

		if (!$this->error) {
			return true;
		} else {
			return false;
		}
	}
}
?>


text:
#pragma once

#include <optixu/optixu_vector_types.h>

struct BasicLight
{
#if defined(__cplusplus)
  typedef optix::float3 float3;
#endif
  float3 pos;
  float3 color;
  int    casts_shadow;
  int    padding;      // make this structure 32 bytes -- powers of two are your friend!
};


text:
title: Object Methods
---
Following is a list of the object methods that I find most useful daily. For a complete list you can go to [the Mozzila JavaScript documentation for objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object).

`Object.assign(target, ...sources )` -- `target` is a target object and `sources` are source objects. Mainly used to shallow clone an object. (easiest way to deep clone is by using JSON.parse with JSON.stringify).

  __example__
  ```javaScript
  let obj = { somekey: 100 };
  let cloneOfObject = Object.assign({}, obj);
  ```

  `Object.entries(obj)` -- returns an array of the object's values mixed with keys.

  `Object.keys(obj)`  -- returns an array of the object's keys.

<div class="nextArticle">

Next Article: [Useful patterns with Objects](/Learning/19_objectUsefulPatterns/)
</div>


text:
@interface PodsDummy_Pods_Tests_sails_ios : NSObject
@end
@implementation PodsDummy_Pods_Tests_sails_ios
@end


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.flowable.eventregistry.api;

import java.util.Set;

import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.api.query.Query;

/**
 * Allows programmatic querying of {@link EventDefinition}s.
 *
 * @author Tijs Rademakers
 * @author Joram Barrez
 */
public interface EventDefinitionQuery extends Query<EventDefinitionQuery, EventDefinition> {

    /** Only select eventdefinition with the given id. */
    EventDefinitionQuery eventDefinitionId(String eventDefinitionId);

    /** Only select forms with the given ids. */
    EventDefinitionQuery eventDefinitionIds(Set<String> eventDefinitionIds);

    /** Only select event definitions with the given category. */
    EventDefinitionQuery eventCategory(String category);

    /**
     * Only select event definitions where the category matches the given parameter. The syntax that should be used is the same as in SQL, eg. %test%
     */
    EventDefinitionQuery eventCategoryLike(String categoryLike);

    /**
     * Only select event definitions that have a different category then the given one.
     *
     * @see EventDeploymentBuilder#category(String)
     */
    EventDefinitionQuery eventCategoryNotEquals(String categoryNotEquals);

    /** Only select event definitions with the given name. */
    EventDefinitionQuery eventDefinitionName(String eventDefinitionName);

    /**
     * Only select event definitions where the name matches the given parameter. The syntax that should be used is the same as in SQL, eg. %test%
     */
    EventDefinitionQuery eventDefinitionNameLike(String eventDefinitionNameLike);

    /**
     * Only select event definitions where the name matches the given parameter (case-insensitive).
     * The syntax that should be used is the same as in SQL, eg. %test%
     */
    EventDefinitionQuery eventDefinitionNameLikeIgnoreCase(String nameLikeIgnoreCase);

    /**
     * Only select event definitions that are deployed in a deployment with the given deployment id
     */
    EventDefinitionQuery deploymentId(String deploymentId);

    /**
     * Select event definitions that are deployed in deployments with the given set of ids
     */
    EventDefinitionQuery deploymentIds(Set<String> deploymentIds);

    /**
     * Only select event definitions that are deployed in a deployment with the given parent deployment id
     */
    EventDefinitionQuery parentDeploymentId(String parentDeploymentId);

    /**
     * Only select event definition with the given key.
     */
    EventDefinitionQuery eventDefinitionKey(String eventDefinitionKey);

    /**
     * Only select event definitions where the key matches the given parameter. The syntax that should be used is the same as in SQL, eg. %test%
     */
    EventDefinitionQuery eventDefinitionKeyLike(String eventDefinitionKeyLike);

    /**
     * Only select event definitions where the key matches the given parameter (case-insensitive).
     * The syntax that should be used is the same as in SQL, eg. %test%
     */
    EventDefinitionQuery eventDefinitionKeyLikeIgnoreCase(String keyLikeIgnoreCase);

    /**
     * Only select event definitions with a certain version. Particularly useful when used in combination with {@link #eventDefinitionKey(String)}
     */
    EventDefinitionQuery eventVersion(Integer eventVersion);

    /**
     * Only select event definitions which version are greater than a certain version.
     */
    EventDefinitionQuery eventVersionGreaterThan(Integer eventVersion);

    /**
     * Only select event definitions which version are greater than or equals a certain version.
     */
    EventDefinitionQuery eventVersionGreaterThanOrEquals(Integer eventVersion);

    /**
     * Only select event definitions which version are lower than a certain version.
     */
    EventDefinitionQuery eventVersionLowerThan(Integer eventVersion);

    /**
     * Only select event definitions which version are lower than or equals a certain version.
     */
    EventDefinitionQuery eventVersionLowerThanOrEquals(Integer eventVersion);

    /**
     * Only select the event definitions which are the latest deployed (ie. which have the highest version number for the given key).
     *
     * Can also be used without any other criteria (ie. query.latestVersion().list()), which will then give all the latest versions of all the deployed event definitions.
     *
     * @throws FlowableIllegalArgumentException
     *             if used in combination with {{@link #eventVersion(Integer)} or {@link #deploymentId(String)}
     */
    EventDefinitionQuery latestVersion();

    /** Only select event definition with the given resource name. */
    EventDefinitionQuery eventDefinitionResourceName(String resourceName);

    /** Only select event definition with a resource name like the given . */
    EventDefinitionQuery eventDefinitionResourceNameLike(String resourceNameLike);

    /**
     * Only select event definitions that have the given tenant id.
     */
    EventDefinitionQuery tenantId(String tenantId);

    /**
     * Only select event definitions with a tenant id like the given one.
     */
    EventDefinitionQuery tenantIdLike(String tenantIdLike);

    /**
     * Only select event definitions that do not have a tenant id.
     */
    EventDefinitionQuery withoutTenantId();

    // ordering ////////////////////////////////////////////////////////////

    /**
     * Order by the category of the event definitions (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    EventDefinitionQuery orderByEventDefinitionCategory();

    /**
     * Order by event definition key (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    EventDefinitionQuery orderByEventDefinitionKey();

    /**
     * Order by the id of the event definitions (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    EventDefinitionQuery orderByEventDefinitionId();

    /**
     * Order by the name of the event definitions (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    EventDefinitionQuery orderByEventDefinitionName();

    /**
     * Order by deployment id (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    EventDefinitionQuery orderByDeploymentId();

    /**
     * Order by tenant id (needs to be followed by {@link #asc()} or {@link #desc()}).
     */
    EventDefinitionQuery orderByTenantId();

}


text:
//
//  LatticeLineExtractor.m
//  CocoaGCDTests
//
//  Created by Christos Sotiriou on 8/11/13.
//  Copyright (c) 2013 Oramind. All rights reserved.
//

#import "LatticeLineExtractor.h"

@implementation LatticeLineExtractor

- (void)obtainHorizontallLinesForLattice:(id<LatticeCommon>)lattice withLineCompletionBlock:(void (^)(NSString *line))block
{
	for (int i=0; i<lattice.sideNumber; i++) {		//change lattice
		for (int j=0; j<lattice.sideNumber; j++) {
			@autoreleasepool {
				char text[lattice.sideNumber+1];

				for (int k=0; k<lattice.sideNumber; k++) {
					text[k] = [lattice getItemAti:i andJ:j andK:k]; //add the characters
				}
				text[lattice.sideNumber] = '\0'; //make it a valid string
				NSString *line = [NSString stringWithCString:text encoding:NSUTF8StringEncoding];
				block(line);
			}
		}
	}
}

- (void)obtainVerticalLinesForLattice:(id<LatticeCommon>)lattice withLineCompletionBlock:(void (^)(NSString *line))block
{

	for (int i=0; i < lattice.sideNumber; i++) {		//change lattice
		for (int k=0; k < lattice.sideNumber; k++) {
			@autoreleasepool {
				char text2[lattice.sideNumber+1];
				for (int j=0; j<lattice.sideNumber; j++) {
					//				NSLog(@"character: %c", [lattice getItemAti:i andJ:j andK:k]);
					text2[j] = [lattice getItemAti:i andJ:j andK:k]; //add the characters
				}
				text2[lattice.sideNumber] = '\0'; //make it a valid string
				NSString *line = [NSString stringWithCString:text2 encoding:NSUTF8StringEncoding];
				block(line);
			}
		}
	}
}

- (void)obtainLinesInIntraLatticeForLattice:(id<LatticeCommon>)lattice withLineCompletionBlock:(void (^)(NSString *line))block
{

	for (int i=0; i<lattice.sideNumber; i++) {		//change lattice
		for (int j=0; j<lattice.sideNumber; j++) {
			@autoreleasepool {
				char text[lattice.sideNumber+1];
				for (int k=0; k<lattice.sideNumber; k++) {
					text[k] = [lattice getItemAti:k andJ:j andK:i]; //add the characters
				}
				text[lattice.sideNumber] = '\0'; //make it a valid string
				NSString *line = [NSString stringWithCString:text encoding:NSUTF8StringEncoding];
				block(line);
			}
		}
	}
}

- (void)obtainDiagonalLinesTopLeftBottomRightForLattice:(id<LatticeCommon>)lattice withLineCompletionBlock:(void (^)(NSString *line))block
{
	for (int constantDimension=0; constantDimension < lattice.sideNumber; constantDimension++) {
		int sideCount = lattice.sideNumber;
		int currentHorizontal = 1;
		int currentVertical = 0;

		NSMutableString *currentString = [NSMutableString string];

		while (currentHorizontal < sideCount) {
			[currentString appendFormat:@"%c", [lattice getItemAti:constantDimension andJ:currentHorizontal andK:currentVertical]];

			currentVertical++;
			currentHorizontal++;
			if (currentHorizontal >= sideCount) {
				block(currentString);
				[currentString setString:@""];
				currentHorizontal = sideCount - (currentVertical -1 /*undo last step */);//since this is a square matrix
				currentVertical = 0;
			}
		}

		currentHorizontal = 0;
		currentVertical = 0;

		while (currentVertical < sideCount) {
			[currentString appendFormat:@"%c", [lattice getItemAti:constantDimension andJ:currentHorizontal andK:currentVertical]];
			currentVertical++;
			currentHorizontal++;

			if (currentVertical >= sideCount) {
				block(currentString);
				[currentString setString:@""];
				currentVertical = sideCount - (currentHorizontal -1);
				currentHorizontal = 0;
			}
		}
	}

}

- (void)obtainDiagonalLinesBottomLeftTopRightForLattice:(id<LatticeCommon>)lattice withLineCompletionBlock:(void (^)(NSString *line))block
{
	@autoreleasepool {
		for (int lat=0; lat<lattice.sideNumber; lat++) {
			@autoreleasepool {
				int sideCount = lattice.sideNumber;
				int currentHorizontal = 0;
				int currentVertical = sideCount-2;

				NSMutableString *currentString = [NSMutableString string];

				while (currentVertical >= 0) {
					[currentString appendFormat:@"%c", [lattice getItemAti:lat andJ:currentHorizontal andK:currentVertical]];
					currentVertical--;
					currentHorizontal++;
					if (currentVertical<0) {
						block(currentString);
						[currentString setString:@""];
						currentVertical = currentHorizontal-2;//since this is a square matrix
						currentHorizontal = 0;
					}
				}
				[currentString setString:@""];

				currentHorizontal = sideCount-1;
				currentVertical = sideCount-1;

				while (currentHorizontal >= 0) {
					[currentString appendFormat:@"%c", [lattice getItemAti:lat andJ:currentHorizontal andK:currentVertical]];
					currentVertical--;
					currentHorizontal++;

					if (currentHorizontal>=sideCount) {
						block(currentString);
						[currentString setString:@""];
						currentHorizontal = currentVertical;
						currentVertical = sideCount-1;
					}
				}
			}
		}
	}
}

- (void)obtainDiagonalHeightConstantZ1ForLattice:(id<LatticeCommon>)lattice withLineCompletionBlock:(void (^)(NSString *line))block
{
	for (int constantDimension=0; constantDimension < lattice.sideNumber; constantDimension++) {
		int sideCount = lattice.sideNumber;
		int currentHorizontal = 0;
		int currentVertical = sideCount-2;

		NSMutableString *currentString = [NSMutableString string];

		while (currentVertical >= 0) {
			[currentString appendFormat:@"%c", [lattice getItemAti:currentVertical andJ:currentHorizontal andK:constantDimension]];
			currentVertical--;
			currentHorizontal++;
			if (currentVertical<0) {
				block(currentString);
				[currentString setString:@""];
				currentVertical = currentHorizontal-2;//since this is a square matrix
				currentHorizontal = 0;
			}
		}
		currentHorizontal = sideCount-1;
		currentVertical = sideCount-1;

		while (currentHorizontal >= 0) {
			[currentString appendFormat:@"%c", [lattice getItemAti:currentVertical andJ:currentHorizontal andK:constantDimension]];
			currentVertical--;
			currentHorizontal++;

			if (currentHorizontal>=sideCount) {
				block(currentString);
				[currentString setString:@""];
				currentHorizontal = currentVertical;
				currentVertical = sideCount-1;
			}
		}
	}
}

- (void)obtainDiagonalHeightConstantZ2ForLattice:(id<LatticeCommon>)lattice withLineCompletionBlock:(void (^)(NSString *line))block
{
	for (int constantDimension=0; constantDimension < lattice.sideNumber; constantDimension++) {
		int sideCount = lattice.sideNumber;
		int currentHorizontal = 1;
		int currentVertical = 0;

		NSMutableString *currentString = [NSMutableString string];

		while (currentHorizontal < sideCount) {
			[currentString appendFormat:@"%c", [lattice getItemAti:currentVertical andJ:currentHorizontal andK:constantDimension]];

			currentVertical++;
			currentHorizontal++;
			if (currentHorizontal >= sideCount) {
				block(currentString);
				[currentString setString:@""];
				currentHorizontal = sideCount - (currentVertical -1 /*undo last step */);//since this is a square matrix
				currentVertical = 0;
			}
		}

		currentHorizontal = 0;
		currentVertical = 0;

		while (currentVertical < sideCount) {
			[currentString appendFormat:@"%c", [lattice getItemAti:currentVertical andJ:currentHorizontal andK:constantDimension]];
			currentVertical++;
			currentHorizontal++;

			if (currentVertical >= sideCount) {
				block(currentString);
				[currentString setString:@""];
				currentVertical = sideCount - (currentHorizontal -1);
				currentHorizontal = 0;
			}
		}
	}
}

@end


text:
namespace P03_SalesDatabase
{
    public class Configuration
    {
        public static string ConnectionString { get; set; } = @"Server=.;Database=Sales;Integrated Security=True";
    }
}


text:
package javax.security.auth.kerberos;

import gnu.classpath.NotImplementedException;
import gnu.classpath.SystemProperties;

import java.io.Serializable;
import java.security.Principal;

/**
 * This represents a Kerberos principal.  See the Kerberos
 * authentication RFC for more information:
 * RFC 1510.
 *
 * @since 1.4
 */
public final class KerberosPrincipal
    implements Serializable, Principal
{
  // Uncomment when serialization is correct.
  // private static final long serialVersionUID = -7374788026156829911L;

  /**
   * Constant from the RFC: "Just the name of the principal as in DCE, or
   * for users".
   */
  public static final int KRB_NT_PRINCIPAL = 1;

  /**
   * Constant from the RFC: "Service and other unique instance (krbtgt)".
   */
  public static final int KRB_NT_SRV_HST = 3;

  /**
   * Constant from the RFC: "Service with host name as instance (telnet,
   * rcommands)".
   */
  public static final int KRB_NT_SRV_INST = 2;

  /**
   * Constant from the RFC: "Service with host as remaining components".
   */
  public static final int KRB_NT_SRV_XHST = 4;

  /**
   * Constant from the RFC: "Unique ID".
   */
  public static final int KRB_NT_UID = 5;

  /**
   * Constant from the RFC: "Name type not known".
   */
  public static final int KRB_NT_UNKNOWN = 0;

  private String name;
  private int type;
  private String realm;

  /**
   * Create a new instance with the given name and a type of
   * {@link #KRB_NT_PRINCIPAL}.
   * @param name the principal's name
   */
  public KerberosPrincipal(String name)
  {
    this(name, KRB_NT_PRINCIPAL);
  }

  /**
   * Create a new instance with the given name and type.  The name is
   * parsed according to the rules in the RFC.  If there is no realm,
   * then the local realm is used instead.
   *
   * @param name the principal's name
   * @param type the principal's type
   */
  public KerberosPrincipal(String name, int type)
  // Marked as unimplemented because we don't look for the realm as needed.
    throws NotImplementedException
  {
    if (type < KRB_NT_UNKNOWN || type > KRB_NT_UID)
      throw new IllegalArgumentException("unknown type: " + type);
    this.name = name;
    this.type = type;
    this.realm = parseRealm();
  }

  private String parseRealm()
  {
    // Handle quoting as specified by the Kerberos RFC.
    int i, len = name.length();
    boolean quoted = false;
    for (i = 0; i < len; ++i)
      {
        if (quoted)
          {
            quoted = false;
            continue;
          }
        char c = name.charAt(i);
        if (c == '\\')
          {
            quoted = true;
            continue;
          }
        if (c == '@')
          break;
      }
    if (quoted || i == len - 1)
      throw new IllegalArgumentException("malformed principal: " + name);
    if (i < len)
      {
        // We have the realm.  FIXME: verify its syntax?
        return name.substring(i + 1);
      }
    // Try to find the default realm.
    String def = SystemProperties.getProperty("java.security.krb5.realm");
    if (def != null)
      return def;
    // Now ask the system.
    // FIXME: use java.security.krb5.conf,
    // or $JAVA_HOME/lib/security/krb5.conf to find the krb config file.
    // Then pass to native code using krb5_set_config_files() and
    // krb5_get_default_realm().  But... what about /etc/krb5.conf?
    throw new IllegalArgumentException("default realm can't be found");
  }

  /**
   * Return the name of this principal.
   */
  public String getName()
  {
    return name;
  }

  /**
   * Return the realm of this principal.
   */
  public String getRealm()
  {
    return realm;
  }

  /**
   * Return the type of this principal.
   */
  public int getNameType()
  {
    return type;
  }

  public int hashCode()
  {
    return name.hashCode();
  }

  public boolean equals(Object other)
  {
    if (! (other instanceof KerberosPrincipal))
      return false;
    KerberosPrincipal kp = (KerberosPrincipal) other;
    return name.equals(kp.name) && type == kp.type;
  }

  public String toString()
  {
    // This is what came to mind.
    return name + ":" + type;
  }
}


text:
from __future__ import absolute_import, division, print_function

from cryptography import utils
from cryptography.exceptions import (
    AlreadyFinalized, UnsupportedAlgorithm, _Reasons
)
from cryptography.hazmat.backends.interfaces import CMACBackend
from cryptography.hazmat.primitives import ciphers

class CMAC(object):
    def __init__(self, algorithm, backend, ctx=None):
        if not isinstance(backend, CMACBackend):
            raise UnsupportedAlgorithm(
                "Backend object does not implement CMACBackend.",
                _Reasons.BACKEND_MISSING_INTERFACE
            )

        if not isinstance(algorithm, ciphers.BlockCipherAlgorithm):
            raise TypeError(
                "Expected instance of BlockCipherAlgorithm."
            )
        self._algorithm = algorithm

        self._backend = backend
        if ctx is None:
            self._ctx = self._backend.create_cmac_ctx(self._algorithm)
        else:
            self._ctx = ctx

    def update(self, data):
        if self._ctx is None:
            raise AlreadyFinalized("Context was already finalized.")

        utils._check_bytes("data", data)
        self._ctx.update(data)

    def finalize(self):
        if self._ctx is None:
            raise AlreadyFinalized("Context was already finalized.")
        digest = self._ctx.finalize()
        self._ctx = None
        return digest

    def verify(self, signature):
        utils._check_bytes("signature", signature)
        if self._ctx is None:
            raise AlreadyFinalized("Context was already finalized.")

        ctx, self._ctx = self._ctx, None
        ctx.verify(signature)

    def copy(self):
        if self._ctx is None:
            raise AlreadyFinalized("Context was already finalized.")
        return CMAC(
            self._algorithm,
            backend=self._backend,
            ctx=self._ctx.copy()
        )


text:
<?php

declare(strict_types=1);

namespace Remorhaz\JSON\Pointer\Query;

use Remorhaz\JSON\Data\Value\NodeValueInterface;
use Remorhaz\JSON\Pointer\Locator\ReferenceInterface;

final class QueryResult implements QueryResultInterface
{

    private $source;

    private $selection;

    private $parent;

    private $lastReference;

    public function __construct(
        string $source,
        ?NodeValueInterface $selection = null,
        ?NodeValueInterface $parent = null,
        ?ReferenceInterface $lastReference = null
    ) {
        $this->source = $source;
        $this->selection = $selection;
        $this->parent = $parent;
        $this->lastReference = $lastReference;
    }

    public function getSource(): string
    {
        return $this->source;
    }

    public function getSelection(): NodeValueInterface
    {
        if (isset($this->selection)) {
            return $this->selection;
        }

        throw new Exception\SelectionNotFoundException($this->source);
    }

    public function hasSelection(): bool
    {
        return isset($this->selection);
    }

    public function getParent(): NodeValueInterface
    {
        if (isset($this->parent)) {
            return $this->parent;
        }

        throw new Exception\ParentNotFoundException($this->source);
    }

    public function hasParent(): bool
    {
        return isset($this->parent);
    }

    public function getLastReference(): ReferenceInterface
    {
        if (isset($this->lastReference)) {
            return $this->lastReference;
        }

        throw new Exception\LastReferenceNotFoundException($this->source);
    }

    public function hasLastReference(): bool
    {
        return isset($this->lastReference);
    }
}


text:
**Outline**

1. Introduction
  1. Instructor Info - You are special to me!
  2. Student Information Sheet
  3. How this course may be helpful to you
  4. Group Projects

2. Data Journalism
  1. What is data journalism?
  2. Why should journalists use data?
  3. Why is data journalism important?

3. Class format
  1. Two-module format
  2. Information Visualization
  3. You can help improve the course!

4. Syllabus
  1. Office Hours
  2. Learning objectives
  3. Readings
  4. Grading components and scale
  5. Participation, assignments and project
  6. Policies: Deadlines, leave, academic integrity
  7. Course schedule


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Persoonia 9(4): 426 (1978)

#### Original name
Pulveroboletus leucomycelinus Singer & M.H. Ivory

### Remarks
null


text:
const express = require('express');
const router = express.Router();
const debug = require('debug')('idm:saml_model');

// SAML2 Controller
const saml2_controller = require('../../controllers/saml2/saml2');
// OAUTH2 Controller
const oauth_controller = require('../../controllers/oauth2/oauth2');

// Routes for Saml2
router.post(
  '/login',
  oauth_controller.load_application,
  saml2_controller.search_eidas_credentials,
  saml2_controller.login
);

// catch 404 and forward to error handler
router.use(function(req, res) {
  const err = new Error('Path not Found');

  err.status = 404;
  if (req.useragent.isDesktop) {
    res.locals.error = err;
    res.render('errors/not_found');
  } else {
    res.status(404).json(err.message);
  }
});

// Error handler
/* eslint-disable no-unused-vars */
router.use(function(err, req, res, next) {
  /* eslint-enable no-unused-vars */
  debug(err);

  err.status = err.status || 500;
  // set locals, only providing error in development
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status);
  res.render('errors/saml');
});

module.exports = router;


text:
package io.reactivesocket.exceptions;

public abstract class SetupException extends RuntimeException {
	public SetupException(String message) {
		super(message);
	}

}


text:
package fr.keemto.core;

/**
 * A NullEvent (from NullPattern) created at EPOCH.
 */
public class InitializationEvent extends Event {

    public InitializationEvent(Account account) {
        super(0, "initialization event", account);
    }

}


text:
import time
from datetime import datetime
from os.path import basename, dirname, normpath

from wsgidav import util
from wsgidav.addons.tracim import Session, sql_resources, role
from wsgidav.addons.tracim.sql_model import ItemRevision, User, UserWorkspace, Workspace
from wsgidav.dav_provider import DAVProvider

from wsgidav.lock_manager import LockManager
from wsgidav.addons.tracim.lock_storage import LockStorage

__docformat__ = "reStructuredText"
_logger = util.getModuleLogger(__name__)

# ============================================================
# PostgreSQLProvider
# ============================================================
class Provider(DAVProvider):
    def __init__(self, manage_lock=True):
        super(Provider, self).__init__()

        self.session = Session()
        self.init_db()

        if manage_lock:
            self.lockManager = LockManager(LockStorage())

    def init_db(self):
        if self.session.query(Workspace).all() == []:
            workspaces = [
                Workspace(label="workspace_manager"),
                Workspace(label="content_manager"),
                Workspace(label="contributor"),
                Workspace(label="reader"),
                Workspace(label="not_applicable")
            ]

            user = User(display_name="test", password="test")
            user2 = User(display_name="test2", password="test2")

            self.session.add(user)
            self.session.add(user2)

            for workspace in workspaces:
                self.session.add(workspace)

            self.session.commit()
            user_workspace = [
                UserWorkspace(
                    role='WORKSPACE_MANAGER',
                    workspace_id=workspaces[0].workspace_id,
                    user_id=user.user_id),
                UserWorkspace(
                    role='CONTENT_MANAGER',
                    workspace_id=workspaces[1].workspace_id,
                    user_id=user.user_id),
                UserWorkspace(
                    role='CONTRIBUTOR',
                    workspace_id=workspaces[2].workspace_id,
                    user_id=user.user_id),
                UserWorkspace(
                    role='READER',
                    workspace_id=workspaces[3].workspace_id,
                    user_id=user.user_id),
                UserWorkspace(
                    role='NOT_APPLICABLE',
                    workspace_id=workspaces[4].workspace_id,
                    user_id=user.user_id)
            ]

            for uw in user_workspace:
                self.session.add(uw)

            self.session.commit()

    def __repr__(self):
        return 'Provider'

    #########################################################
    # Everything override from DAVProvider
    def getResourceInst(self, path, environ):
        if not self.exists(path, environ):
            return None
        if path == "/":
            return sql_resources.Root(path, environ)

        norm_path = normpath(path)

        if dirname(norm_path) == "/":
            workspace_id = self.get_workspace_id_from_path(norm_path)
            workspace = self.get_workspace({'workspace_id': workspace_id})
            return sql_resources.Workspace(path, environ, workspace)

        working_path = norm_path
        item_id = None

        not_last = False

        if self.is_history(working_path):
            working_path = dirname(norm_path)
        elif self.is_history(dirname(working_path)):
            working_path = dirname(dirname(working_path)) + "/" + basename(working_path)
        elif dirname(dirname(working_path)).endswith('.history'):
            name_and_revision = basename(working_path).split('-', 1)
            item_id = name_and_revision[0]
            file_name = name_and_revision[1]
            not_last = True

        if item_id is None:
            item_id = self.get_id_from_path(working_path)

        if not_last:
            item = self.get_item({'id': item_id})
        else:
            item = self.get_item({'id': item_id, 'child_revision_id': None})

        if item is None:
            return None
        elif item.item_type in ["FOLDER"]:
            if self.is_history(normpath(path)):
                return sql_resources.HistoryFolder(path, environ, item)
            return sql_resources.Folder(path, environ, item)
        elif item.item_type in ["FILE"]:
            if self.is_history(dirname(norm_path)):
                return sql_resources.HistoryFileFolder(path, environ, item)
            elif self.is_history(dirname(dirname(norm_path))):
                return sql_resources.HistoryFile(path, environ, item)
            else:
                return sql_resources.File(path, environ, item)
        else:
            if self.is_history(dirname(norm_path)):
                return sql_resources.HistoryFileFolder(path, environ, item)
            elif self.is_history(dirname(dirname(norm_path))):
                return sql_resources.HistoryOtherFile(path, environ, item)
            else:
                return sql_resources.OtherFile(path, environ, item)

    def exists(self, path, environ):
        start = time.time()
        if path == "/":
            return True

        norm_path = normpath(path)
        if norm_path.endswith('.history'):
            norm_path = dirname(norm_path)
        elif dirname(norm_path).endswith('.history'):
            norm_path = dirname(dirname(norm_path)) + "/" + basename(norm_path)
        elif dirname(dirname(norm_path)).endswith('.history'):
            parts = basename(norm_path).split('-',1)
            if len(parts) < 2:
                return False
            item_name = parts[1]
            item_id = parts[0]
            norm_path = dirname(dirname(dirname(norm_path))) + "/" + item_name
            return self.from_name_to_id(norm_path) is not None and self.exist_revision(item_name, item_id)

        path_id = self.from_name_to_id(norm_path)

        end = time.time()
        return path_id is not None

    def isCollection(self, path, environ):
        norm_path = normpath(path)
        if norm_path == "/" or dirname(norm_path) == "/":
            return True

        item_id = basename(self.from_name_to_id(norm_path))
        item = self.get_item({'id': item_id})

        return item.item_type in ["FOLDER"]

    #########################################################
    # Everything that transform path
    def from_id_to_name(self, path):
        path_ret = ''

        for item_id in path.split('/'):
            if item_id == '':
                pass
            elif path_ret == '':
                path_ret += '/' + self.get_workspace({'workspace_id': item_id}).label
            else:
                path_ret += '/' + self.get_item({'id': item_id}).item_name

        return path_ret

    def from_name_to_id(self, path):
        if path == '/':
            return '/'
        path_ret = ""
        last_id = None
        workspace_id = None

        for item_name in path.split("/"):
            if item_name == '':
                pass
            elif path_ret == '':
                workspace = self.get_workspace({'label': item_name})
                if workspace is None:
                    return None

                workspace_id = workspace.workspace_id
                path_ret += '/' + str(workspace_id)
            else:
                item = self.get_item(
                    {
                        'parent_id': last_id,
                        'item_name': item_name,
                        'workspace_id': workspace_id,
                        'child_revision_id': None
                    }
                )

                if item is None:
                    return None

                last_id = item.id
                path_ret += '/' + str(last_id)

        return path_ret

    #########################################################
    # Everything that check things (lol) ...
    def has_right(self, username, workspace_id, expected=0):
        ret = self.session.query(UserWorkspace.role).filter(
            UserWorkspace.workspace_id == workspace_id,
            User.user_id == UserWorkspace.user_id,
            User.display_name == username
        ).one_or_none()

        return ret is not None and role[ret.role] >= expected

    def exist_revision(self, item_name, item_id):
        return self.get_item({'id': item_id, 'item_name': item_name}) is not None

    @staticmethod
    def is_history(path):
        return normpath(path).endswith('.history')

    #########################################################
    # Everything that goes with "delete"
    def delete_item(self, element):
        self.session.delete(element)
        self.session.commit()

    def delete_workspace(self, workspace):

        self.session.query(UserWorkspace).filter(
            UserWorkspace.workspace_id == workspace.workspace_id
        ).delete(synchronize_session=False)

        self.delete_item(workspace)

    #########################################################
    # Everything that goes with "add"
    def add_item(self, item_name, item_type, workspace_id, parent_id=None, parent_revision_id=None,
                 child_revision_id=None, item_content=None, created=None, updated=None):
        item = ItemRevision(
            item_name=item_name,
            item_type=item_type,
            item_content=item_content,
            workspace_id=workspace_id,
            parent_id=parent_id,
            created=created,
            updated=updated,
            parent_revision_id=parent_revision_id,
            child_revision_id=child_revision_id
        )

        self.session.add(item)
        self.session.commit()

        return item

    def add_workspace(self, environ, label):
        workspace = Workspace(label=label)

        self.session.add(workspace)

        user = self.get_user_with_name(environ['http_authenticator.username'])

        user_workspace = UserWorkspace(
            role='WORKSPACE_MANAGER',
            workspace_id=workspace.workspace_id,
            user_id=user.user_id
        )

        self.session.add(user_workspace)
        self.session.commit()

        return workspace

    #########################################################
    # Everything that goes with "set"
    def set_workspace_label(self, workspace, label):
        workspace.label = label
        self.session.commit()

    #########################################################
    # Everything that goes with "get"
    def get_all_revisions_from_item(self, item, only_id=False, even_first=False):
        ret = []
        current_item = item
        while current_item is not None:
            if only_id:
                ret.insert(0,current_item.id)
            else:
                ret.insert(0,current_item)

            current_item = self.get_item(
                {
                    'child_revision_id': current_item.id
                }
            )

        return ret

    def get_item(self, keys_dict):
        query = self.session.query(ItemRevision)

        for key, value in keys_dict.items():
            query = query.filter(getattr(ItemRevision, key) == value)
        return query.first()

    def get_item_children(self, item_id):
        items_result = self.session.query(ItemRevision.id).filter(
            ItemRevision.parent_id == item_id,
            ItemRevision.child_revision_id.is_(None)
        )

        ret_id = []
        for item in items_result:
            ret_id.append(item.id)

        return ret_id

    def get_workspace_id_from_path(self, path):
        return int(self.get_id_from_path('/' + path.split('/')[1]))

    def get_workspace_children_id(self, workspace):
        items_result = self.session.query(ItemRevision.id).filter(
            ItemRevision.parent_id.is_(None),
            ItemRevision.workspace_id == workspace.workspace_id
        )

        ret = []
        for item in items_result:
            ret.append(item.id)

        return ret

    # on workspaces
    def get_workspace(self, keys_dict):
        query = self.session.query(Workspace)

        for key, value in keys_dict.items():
            query = query.filter(getattr(Workspace, key) == value)
        return query.one_or_none()

    def get_all_workspaces(self, only_name=False):
        retlist = []
        for workspace in self.session.query(Workspace).all():
            if only_name:
                retlist.append(workspace.label)
            else:
                retlist.append(workspace)

        return retlist

    # on users
    def get_user_with_name(self, username):
        return self.session.query(User).filter(
            User.display_name == username
        ).one_or_none()

    # on path
    def get_id_from_path(self, path):
        path_id = self.from_name_to_id(path)

        if path_id == '/':
            return None
        else:
            return int(basename(path_id))

    def get_parent_id_from_path(self, path):
        return self.get_id_from_path(dirname(path))

    #########################################################
    # Everything that goes with "move"
    def move_item(self, item, destpath):
        path = normpath(destpath)

        if dirname(dirname(path)) == '/':
            new_parent = None
        else:
            new_parent = self.get_parent_id_from_path(path)

        item.parent_id = new_parent
        item.workspace_id = self.get_workspace_id_from_path(path)
        item.item_name = basename(path)
        self.session.commit()

    def move_all_revisions(self, item, destpath):
        path = normpath(destpath)
        new_parent = self.get_parent_id_from_path(path)
        new_workspace = self.get_workspace_id_from_path(destpath)

        items = self.get_all_revisions_from_item(item)

        for current_item in items:
            current_item.parent_id = new_parent
            current_item.workspace_id = new_workspace

        new_name = basename(normpath(destpath))

        new_item = self.add_item(
            item_name=new_name,
            item_type=item.item_type,
            workspace_id=item.workspace_id,
            parent_id=item.parent_id,
            parent_revision_id=item.id,
            child_revision_id=None,
            item_content=item.item_content,
            created=item.created,
            updated=datetime.now()
        )

        item.child_revision_id = new_item.id

        self.session.commit()

    #########################################################
    # Everything that goes with "copy"
    def copy_item(self, item, destpath):
        path = normpath(destpath)

        new_parent = self.get_parent_id_from_path(path)
        new_workspace = self.get_workspace_id_from_path(path)
        new_name = basename(destpath)
        items = self.get_all_revisions_from_item(item)

        first = True
        last_item = None

        for current_item in items:
            new_item = self.add_item(
                item_name=current_item.item_name,
                item_type=current_item.item_type,
                workspace_id=new_workspace,
                parent_id=new_parent,
                parent_revision_id=None,
                child_revision_id=None,
                item_content=current_item.item_content,
                created=current_item.created,
                updated=current_item.updated
            )

            if not first:
                last_item.child_revision_id = new_item.id
                new_item.parent_revision_id = last_item.id

            first = False
            last_item = new_item

        new_item = self.add_item(
            item_name=new_name,
            item_type=item.item_type,
            workspace_id=new_workspace,
            parent_id=new_parent,
            parent_revision_id=last_item.id,
            child_revision_id=None,
            item_content=item.item_content,
            created=datetime.now(),
            updated=datetime.now()
        )

        last_item.child_revision_id = new_item.id

        self.session.commit()


text:
package org.sleuthkit.autopsy.experimental.autoingest;

import java.util.ArrayList;
import java.util.List;
import javax.swing.Action;
import org.sleuthkit.autopsy.casemodule.multiusercases.CaseNodeData;
import org.sleuthkit.autopsy.casemodule.multiusercasesbrowser.MultiUserCaseBrowserCustomizer;

/**
 * A customizer for the multi-user case browser panel used in the administrative
 * dashboard for auto ingest cases to present a tabular view of the multi-user
 * cases known to the coordination service.
 */
final class CasesDashboardCustomizer implements MultiUserCaseBrowserCustomizer {

    private final DeleteCaseAction deleteCaseAction;
    private final DeleteCaseInputAction deleteCaseInputAction;
    private final DeleteCaseOutputAction deleteCaseOutputAction;
    private final DeleteCaseInputAndOutputAction deleteCaseInputAndOutputAction;

    /**
     * Constructs a customizer for the multi-user case browser panel used in the
     * administrative dashboard for auto ingest cases to present a tabular view
     * of the multi-user cases known to the coordination service.
     *
     * @param executor An executor for tasks for actions that do work in the
     *                 background.
     */
    CasesDashboardCustomizer() {
        /*
         * These actions are shared by all nodes in order to support multiple
         * selection.
         */
        deleteCaseAction = new DeleteCaseAction();
        deleteCaseInputAction = new DeleteCaseInputAction();
        deleteCaseOutputAction = new DeleteCaseOutputAction();
        deleteCaseInputAndOutputAction = new DeleteCaseInputAndOutputAction();
    }

    @Override
    public List<Column> getColumns() {
        List<Column> properties = new ArrayList<>();
        properties.add(Column.CREATE_DATE);
        properties.add(Column.LAST_ACCESS_DATE);
        properties.add(Column.DIRECTORY);
        properties.add(Column.MANIFEST_FILE_ZNODES_DELETE_STATUS);
        if (AutoIngestDashboard.extendedFeaturesAreEnabled()) {
            properties.add(Column.DATA_SOURCES_DELETE_STATUS);
        }
        properties.add(Column.TEXT_INDEX_DELETE_STATUS);
        properties.add(Column.CASE_DB_DELETE_STATUS);
        properties.add(Column.CASE_DIR_DELETE_STATUS);
        return properties;
    }

    @Override
    public List<SortColumn> getSortColumns() {
        List<SortColumn> sortColumns = new ArrayList<>();
        sortColumns.add(new SortColumn(Column.DISPLAY_NAME, true, 1));
        return sortColumns;
    }

    @Override
    public boolean allowMultiSelect() {
        return true;
    }

    @Override
    public List<Action> getActions(CaseNodeData nodeData) {
        List<Action> actions = new ArrayList<>();
        actions.add(new OpenCaseAction(nodeData));
        actions.add(new OpenAutoIngestLogAction(nodeData));
        if (AutoIngestDashboard.extendedFeaturesAreEnabled()) {
            actions.add(deleteCaseInputAction);
            actions.add(deleteCaseOutputAction);
            actions.add(deleteCaseInputAndOutputAction);
        } else {
            actions.add(deleteCaseAction);
        }
        return actions;
    }

    @Override
    public Action getPreferredAction(CaseNodeData nodeData) {
        return new OpenCaseAction(nodeData);
    }

}


text:
from __future__ import unicode_literals

from django.db import migrations
import markdownx.models

class Migration(migrations.Migration):

    dependencies = [("impart", "0017_content_markdown")]

    operations = [
        migrations.RemoveField(model_name="content", name="markdown"),
        migrations.AlterField(
            model_name="content",
            name="value",
            field=markdownx.models.MarkdownxField(max_length=4069),
        ),
    ]


text:
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class ElfoVerdeTest{
    @After
    public void gc()
    {
        System.gc();
    }

    @Test
    public void criarElfoVerdeComEspadaValiriana(){
        ElfoVerde finwe = new ElfoVerde("Finwe");
        Item item = new Item(1, "Espada de aço valiriano");

        finwe.adicionarItem(item);

        assertEquals(item, finwe.getInventario().getItens().get(0));
    }

    @Test
    public void criarElfoVerdeComSacoDeBolasDeGude(){
        ElfoVerde finwe = new ElfoVerde("Finwe");
        Item item = new Item(1, "Saco de bolas de gude");

        finwe.adicionarItem(item);

        assertFalse(finwe.getInventario().getItens().contains(item));
    }

    @Test
    public void criarElfoVerdeGanhar2Experiencia(){
        ElfoVerde finwe = new ElfoVerde("Finwe");
        int esperado = 2;

        finwe.atirarFlecha(new Dwarf("Bombur"));
        int obtido = finwe.getExperiencia();

        assertEquals(esperado, obtido);
    }
}


text:
package org.frameworkset.spi.support;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;

import org.frameworkset.spi.assemble.ServiceProviderManager;
import org.frameworkset.util.Assert;
import org.frameworkset.util.io.ClassPathResource;
import org.frameworkset.util.io.ContextResource;
import org.frameworkset.util.io.Resource;
import org.frameworkset.util.io.ResourceLoader;
import org.frameworkset.util.io.UrlResource;

import com.frameworkset.util.SimpleStringUtil;

/**
 *
Title: DefaultResourceLoader.java

 *
Description:

 *
bboss workgroup

 *
Copyright (c) 2007

 * @Date 2010-9-24 下午05:29:08
 * @author biaoping.yin
 * @version 1.0
 */
public class HotResourceLoader implements ResourceLoader {

	private ClassLoader classLoader;

	/**
	 * Create a new DefaultResourceLoader.
	 *
ClassLoader access will happen using the thread context class loader
	 * at the time of this ResourceLoader's initialization.
	 * @see java.lang.Thread#getContextClassLoader()
	 */
	public HotResourceLoader() {
		this.classLoader = HotResourceLoader.class.getClassLoader();
	}

	/**
	 * Create a new DefaultResourceLoader.
	 * @param classLoader the ClassLoader to load class path resources with, or null
	 * for using the thread context class loader at the time of actual resource access
	 */
	public HotResourceLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
	}

	/**
	 * Specify the ClassLoader to load class path resources with, or null
	 * for using the thread context class loader at the time of actual resource access.
	 *
The default is that ClassLoader access will happen using the thread context
	 * class loader at the time of this ResourceLoader's initialization.
	 */
	public void setClassLoader(ClassLoader classLoader) {
		this.classLoader = classLoader;
	}

	/**
	 * Return the ClassLoader to load class path resources with,
	 * or null if using the thread context class loader on actual access
	 * (applying to the thread that constructs the ClassPathResource object).
	 *
Will get passed to ClassPathResource's constructor for all
	 * ClassPathResource objects created by this resource loader.
	 * @see ClassPathResource
	 */
	public ClassLoader getClassLoader() {
		return this.classLoader;
	}

	private static ClassLoader getTCL() throws IllegalAccessException, InvocationTargetException {
        Method method = null;
        try {
            method = (java.lang.Thread.class).getMethod("getContextClassLoader", null);
        } catch (NoSuchMethodException e) {
            return null;
        }
        return (ClassLoader)method.invoke(Thread.currentThread(), null);
    }
	public Resource getResource(String location) {
		Assert.notNull(location, "Location must not be null");
		if (location.startsWith(CLASSPATH_URL_PREFIX)) {
			return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
		}
		else {
			try {
				// Try to parse the location as a URL...
//
//				URL url = new URL(location);
//				return new UrlResource(url);
				String url = null;
				URL confURL = ServiceProviderManager.class.getClassLoader().getResource(location);
	            if (confURL == null)
	                confURL = ServiceProviderManager.class.getClassLoader().getResource("/" + location);

	            if (confURL == null)
	                confURL = getTCL().getResource(location);
	            if (confURL == null)
	                confURL = getTCL().getResource("/" + location);
	            if (confURL == null)
	                confURL = ClassLoader.getSystemResource(location);
	            if (confURL == null)
	                confURL = ClassLoader.getSystemResource("/" + location);

//	            if (confURL == null) {
//	                url = System.getProperty("user.dir");
//	                url += "/" + location;
//	            } else {
//	                url = confURL.toString();
//	            }
	            return new UrlResource(confURL);
			}
			catch (Exception ex) {
				// No URL -> resolve as resource path.
				return getResourceByPath(location);
			}
		}
	}

	/**
	 * Return a Resource handle for the resource at the given path.
	 *
The default implementation supports class path locations. This should
	 * be appropriate for standalone implementations but can be overridden,
	 * e.g. for implementations targeted at a Servlet container.
	 * @param path the path to the resource
	 * @return the corresponding Resource handle
	 * @see ClassPathResource

	 */
	protected Resource getResourceByPath(String path) {
		return new ClassPathContextResource(path, getClassLoader());
	}

	/**
	 * ClassPathResource that explicitly expresses a context-relative path
	 * through implementing the ContextResource interface.
	 */
	private static class ClassPathContextResource extends ClassPathResource implements ContextResource {

		public ClassPathContextResource(String path, ClassLoader classLoader) {
			super(path, classLoader);
		}

		public String getPathWithinContext() {
			return getPath();
		}

		public Resource createRelative(String relativePath) {
			String pathToUse = SimpleStringUtil.applyRelativePath(getPath(), relativePath);
			return new ClassPathContextResource(pathToUse, getClassLoader());
		}
	}

}