text:
<?php

namespace SolveX\ViewModel;

use ReflectionClass;
use ReflectionException;
use ReflectionProperty;
use RuntimeException;

/**
 * Class ViewModel.
 */
class ViewModel
{
    /**
     * @var DataSourceInterface|null
     */
    protected $data;

    /**
     * ViewModel constructor.
     *
     * @param DataSourceInterface|null $data
     * @throws RuntimeException
     * @throws ReflectionException
     * @throws ViewModelException
     */
    public function __construct(DataSourceInterface $data = null)
    {
        // $data is null when a viewmodel class (extending this one) was
        // instantiated manually with new MyViewModel().
        // In this case we do nothing. This is useful for testing.
        if ($data === null) {
            return;
        }

        $this->data = $data;

        $this->setProperties();

        // TODO: optional validation (illuminate/validation)
    }

    /**
     * Maps source data to properties of the extended class.
     *
     * @throws RuntimeException
     * @throws ViewModelException
     * @throws ReflectionException
     */
    protected function setProperties()
    {
        foreach ($this->getPropertiesByReflection() as $reflectionProperty) {
            $property = new Property($reflectionProperty);
            $propertyName = $property->getName();

            if (! $this->data->has($propertyName)) {
                if ($property->isNonNullableBoolean()) {
                    $this->{$propertyName} = false;
                    continue;
                }

                if (! $property->isNullable()) {
                    throw new ViewModelException("Expected value missing for property {$propertyName}!");
                }

                continue;
            }

            $value = $this->data->get($propertyName);
            $this->{$propertyName} = $property->getMappedValue($value);
        }
    }

    /**
     * Uses reflection to retrieve public properties of the extended class.
     *
     * @return ReflectionProperty[]
     * @throws ReflectionException
     */
    protected function getPropertiesByReflection()
    {
        return (new ReflectionClass(static::class))->getProperties(ReflectionProperty::IS_PUBLIC);
    }
}


text:
<!--
Copyright (c) 2011 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="options.css"></link>
<link rel="stylesheet" type="text/css" href="grid.css"></link>
<title>DevTools Save Extension Options</title>
</head>
<body>
<script src="file_mapping.js"></script>
<script src="grid.js"></script>
<script src="mapping_editor.js"></script>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
module Bot
  module DiscordCommands
    # Document your command
    # in some YARD comments here!
    module UserInfo
      extend Discordrb::Commands::CommandContainer
      module_function
      $bank = YAML.load(File.read('data/userinfo.yaml'))

      command(:bank, bucket: :bank, rate_limit_message:'I can\'t spread the wealth that fast!',
                   description: "Fetches your balance, or @user's balance") do |event, mention|
        check = event.bot.profile.on(event.server).roles.map {|x| x.name }  & ["banker", "unlocksfw"]
        next event.respond "I need the `banker` or `unlocksfw` role for that, silly" if check.empty?
           def save
             file = File.open("bank.yaml", "w")
             file.write($bank.to_yaml)
           end
         begin
         user = $bank['users'][event.user.id]
         if user == true
         event << "You're already registered sweetheart."
         end
         if user.nil?
         $bank['users'][event.user.id] = Hash["name" => event.user.display_name, "refs" => [], "hearts" => 0, "salt" => 0, "stipend" => 25]
         event << "User added! You now have `0 HEARTS`, `0 SALT`, `25 STIPEND`, and can add refs!"
         save
         nil
         end
         rescue => e
         puts e
         end

         if mention.nil?
           mention = event.user.id.to_i
         else
           mention = event.message.mentions.at(0).id.to_i
         end

          #load user from $bank, report if user is invalid or not registered.
          user = $bank["users"][mention]
          if user.nil?
            event << "User does not exist, sorry sweety."
            return
          end

          #report bank
          total = user['hearts'] + user['salt']
          percent_hearts = (user['hearts'].to_f / total.to_f) * 100.0
          percent_hearts = percent_hearts.round(2)
          percent_salty = (user['salt'].to_f / total.to_f) * 100.0
          percent_salty = percent_salty.round(2)
          event << "You are **#{percent_hearts}%** lovely :kissing_heart: and **#{percent_salty}%** salty! :unamused:"
          event << ""
          event << "Heart balance: #{user['hearts']}"
          event << "Salt balance: #{user['salt']}"
          event << "Stipend balance: #{user['stipend']}"

         nil
      end

      command(:give, min_args: 3,
                  description: "give currency",
                  usage: '~give @user # hearts or salt') do |event, to, value, type|
        next event.respond "I need the `banker` role for that, silly" unless
        check = event.bot.profile.on(event.server).roles.map {|x| x.name }  & ["banker", "unlocksfw"]
        next event.respond "I need the `banker` or `unlocksfw` role for that, silly" if check.empty?
         value = value.to_i

            #checks to make sure people aren't stealing (giving negative values)
         next "No negatives allowed" if value < 1
            #pick up user
          fromUser = $bank["users"][event.user.id]

          #return if invalid user
          if fromUser.nil?
            event << "User does not exist :x:"
            return
          end

          #check if they have enough first
          if (fromUser["stipend"] - value) < 0
            event << "You do not have enough currency to make this transaction. :disappointed_relieved:"
            return
          end

          #pick up user to receive currency
          toUser = $bank["users"][event.bot.parse_mention(to).id]

          if toUser == event.bot.profile.id
            event << "Is that all you have to offer, hun?"
            event << "https://i.imgur.com/SZAppZR.jpg"
            return
          end

          #check that they exist
          if toUser.nil?
            event << "User does not exist :x:"
            return
          end

          if fromUser == toUser
            event << "You can't give yourself things, sweety."
           return
          end

        #transfer currency
        #remove from stipend
        fromUser["stipend"] -= value

        #give toUser the desired currency
        if type == 'salt'
            toUser['salt'] += value
          elsif type == 'hearts'
            toUser['hearts'] += value

        else
          event << "Hey hun? Choose `salt` or `hearts`, I can't do that for you!"
          return
        end

        #notification
        event << "**#{event.user.display_name}** awarded **#{event.message.mentions.at(0).on(event.server).display_name}** with **#{value.to_s} #{type}** :yum:"
        def save
          file = File.open("bank.yaml", "w")
          file.write($bank.to_yaml)
        end
        save
          nil
      end

      command(:refs,
              description: "Get the reference of a fellow artist!",
              usage: '~refs @user') do |event, mention|
        user = $bank['users'][event.bot.parse_mention(mention).id]

        if user.nil?
          event << "User not found.. sorry sweetheart!"
          return
        end

        if user['refs'].nil?
          event << "They don't have a ref, yet"
          return
        end

        event << "#{user['name']}'s refs:"
        user['refs'].each { |x| event << x }
        nil
      end

      command(:addref,
              description: 'Add a reference for yourself or your character!',
              usage: "`~addref (URL)`") do |event, url|
                  def save
                    file = File.open("db.yaml", "w")
                    file.write($bank.to_yaml)
                  end
        user = $bank['users'][event.user.id]
               if user.nil?
             $bank['users'][event.user.id] = Hash["name" => event.user.display_name, "refs" => [], "hearts" => 0, "salt" => 0, "stipend" => 25]
                 event << "User added"
               end
        user = $bank['users'][event.user.id]
             user['refs'] << url.to_s
             event << "Ref added! :wink:"
             save
             nil
      end
    end
  end
end


text:
<?php

namespace PHPExiftool\Driver\Tag\MXF;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class SignatureTuneFlag extends AbstractTag
{

    protected $Id = '060e2b34.0101.0103.05010401.00000000';

    protected $Name = 'SignatureTuneFlag';

    protected $FullName = 'MXF::Main';

    protected $GroupName = 'MXF';

    protected $g0 = 'MXF';

    protected $g1 = 'MXF';

    protected $g2 = 'Video';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Signature Tune Flag';

}


text:
package som.interpreter.nodes;

import java.lang.reflect.Field;
import java.util.Arrays;

import com.oracle.truffle.api.dsl.TypeSystemReference;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.instrumentation.InstrumentableFactory.WrapperNode;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.source.SourceSection;

import som.interpreter.InliningVisitor;
import som.interpreter.Types;

@TypeSystemReference(Types.class)
public abstract class SOMNode extends Node {

  protected final SourceSection sourceSection;

  public SOMNode(final SourceSection sourceSection) {
    super();
    this.sourceSection = sourceSection;
  }

  @Override
  public SourceSection getSourceSection() {
    return sourceSection;
  }

  /**
   * This method is called by a visitor to adjust nodes that access lexical
   * elements such as locals or arguments. This is necessary after changes in
   * the scope tree. This can be caused by method splitting to obtain
   * independent copies, or inlining of blocks to adjust context levels.
   *
   * <p>When such changes occurred, all blocks within that tree need to be adjusted.
   */
  public void replaceAfterScopeChange(final InliningVisitor inliner) {
    // do nothing!
    // only a small subset of nodes needs to implement this method.
    // Most notably, nodes using FrameSlots, and block nodes with method
    // nodes.
    assert assertNodeHasNoFrameSlots();
  }

  private static Field[] getAllFields(final Class<? extends Object> clazz) {
    Field[] declaredFields = clazz.getDeclaredFields();
    if (clazz.getSuperclass() != null) {
      return concatArrays(getAllFields(clazz.getSuperclass()), declaredFields);
    }
    return declaredFields;
  }

  private static <T> T[] concatArrays(final T[] first, final T[] second) {
    T[] result = Arrays.copyOf(first, first.length + second.length);
    System.arraycopy(second, 0, result, first.length, second.length);
    return result;
  }

  private boolean assertNodeHasNoFrameSlots() {
    if (this.getClass().desiredAssertionStatus()) {
      for (Field f : getAllFields(getClass())) {
        assert f.getType() != FrameSlot.class;
        if (f.getType() == FrameSlot.class) {
          return false;
        }
      }
    }
    return true;
  }

  /**
   * @return body of a node that just wraps the actual method body.
   */
  public abstract ExpressionNode getFirstMethodBodyNode();

  @SuppressWarnings("unchecked")
  public static <T extends Node> T unwrapIfNecessary(final T node) {
    if (node instanceof WrapperNode) {
      return (T) ((WrapperNode) node).getDelegateNode();
    } else {
      return node;
    }
  }

  public static Node getParentIgnoringWrapper(final Node node) {
    assert !(node instanceof WrapperNode) : "A correct usage will not see nodes that are wrappers. This is to detect bugs";

    Node parent = node.getParent();
    if (parent instanceof WrapperNode) {
      return parent.getParent();
    } else {
      return parent;
    }
  }
}


text:
namespace Animal_Hierarchy.Animals
{
    using System;

    public class Frog : Animal,ISound
    {
          public Frog(int age, string name,string sex):base(age,name,sex)
        {

        }

        public override string Sound()
        {
            return base.Sound() + " krek!";
        }
    }
}


text:
#ifndef __SMACCM_uart_types__H
#define __SMACCM_uart_types__H

#include <smaccm_test_uart_impl_types.h>

/**************************************************************************

<<<<<<< HEAD
   File: C:\Users\jdbackes\git\smaccm\models\Trusted_Build_Test\test_uart_active\components\uart\include\smaccm_uart.h
   Created on: 2015/04/09 14:16:46
=======
   File: C:\docs\git_smaccm\smaccm\models\Trusted_Build_Test\test_uart_active\components\uart\include\smaccm_uart.h
   Created on: 2015/04/12 08:07:03
>>>>>>> 992bd954ada572337e9d70ddb6d7d0444deee5de
   using Dulcimer AADL system build tool suite

   ***AUTOGENERATED CODE: DO NOT MODIFY***

  This header section contains the AADL gluecode interfaces used by the client
  for the thread implementations.

 **************************************************************************/
	void send_handler(const test_uart__uart_packet_impl * send);

	bool recv_data(const test_uart__uart_packet_impl * recv);
	bool uart_read_send(test_uart__uart_packet_impl * send);
		//////////////////////////////////////////////////////////////////////////
		//
		// Note: thread is declared EXTERNAL; user should provide run() function.
		//
		//////////////////////////////////////////////////////////////////////////

/* endif for: #ifndef __SMACCM_uart_types__H */
#endif

/**************************************************************************
  End of autogenerated file: C:\Users\jdbackes\git\smaccm\models\Trusted_Build_Test\test_uart_active\components\uart\include\smaccm_uart.h
 **************************************************************************/


text:
// Copyright © 2012 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//    * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VirtualRadar.Interface;
using Moq;
using InterfaceFactory;
using Test.Framework;
using System.IO;

namespace Test.VirtualRadar.Library
{
    [TestClass]
    public class DirectoryCacheTests
    {
        #region TestFileInfo
        class TestFileInfo : IDirectoryCacheProviderFileInfo
        {
            public string Name { get; set; }
            public DateTime LastWriteTimeUtc { get; set; }

            public TestFileInfo(string name) : this(name, _StandardDate)
            {
            }

            public TestFileInfo(string name, DateTime lastModified) : base()
            {
                Name = name;
                LastWriteTimeUtc = lastModified;
            }
        }
        #endregion

        #region TestContext, Fields, TestIntialise, TestCleanup
        public TestContext TestContext { get; set; }

        private static readonly DateTime _StandardDate = new DateTime(2001, 2, 3, 4, 5, 6, 789);
        private IClassFactory _ClassFactorySnapshot;
        private IDirectoryCache _DirectoryCache;
        private ClockMock _Clock;
        private Mock<IDirectoryCacheProvider> _Provider;
        private Mock<IBackgroundWorker> _BackgroundWorker;
        private Mock<IHeartbeatService> _HeartbeatService;
        private const int SecondsBetweenRefreshes = 60;
        private DateTime _LastModifiedUtc;
        private Dictionary<string, List<TestFileInfo>> _Files;
        private List<string> _Folders;

        private EventRecorder<EventArgs> _CacheChangedEvent;
        private Mock<ILog> _Log;

        [TestInitialize]
        public void TestInitialise()
        {
            _ClassFactorySnapshot = Factory.TakeSnapshot();

            _Clock = new ClockMock() { UtcNowValue = _StandardDate };
            Factory.Singleton.RegisterInstance<IClock>(_Clock.Object);

            CreateBackgroundWorkerMock();
            _HeartbeatService = TestUtilities.CreateMockSingleton<IHeartbeatService>();
            _Log = TestUtilities.CreateMockSingleton<ILog>();
            _Log.Setup(g => g.WriteLine(It.IsAny<string>(), It.IsAny<string>(),  It.IsAny<string>())).Callback(() => { throw new InvalidOperationException("Log was unexpectedly written"); });

            _CacheChangedEvent = new EventRecorder<EventArgs>();

            _LastModifiedUtc = new DateTime(2009, 8, 7, 6, 5, 4, 321);
            _Files = new Dictionary<string,List<TestFileInfo>>();
            _Folders = new List<string>();

            _Provider = new Mock<IDirectoryCacheProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _Provider.Setup(p => p.FolderExists(It.IsAny<string>())).Returns((string folder) => {
                if(folder != null && folder.EndsWith(@"\")) folder = folder.Substring(0, folder.Length - 1);
                return _Folders.Contains(folder.ToLower());
            });
            _Provider.Setup(p => p.GetSubFoldersInFolder(It.IsAny<string>())).Returns((string folder) => {
                if(folder != null && !folder.EndsWith(@"\")) folder += '\\';
                var subFolders = _Folders.Where(r =>
                        r.StartsWith(folder, StringComparison.OrdinalIgnoreCase) &&
                        r.IndexOf('\\', folder.Length) == -1)
                    .Select(r => Path.GetFileName(r))
                    .ToList();
                return subFolders;
            });
            _Provider.Setup(p => p.GetFilesInFolder(It.IsAny<string>())).Returns((string folder) => {
                List<TestFileInfo> files;
                if(folder != null && folder.EndsWith(@"\")) folder = folder.Substring(0, folder.Length - 1);
                _Files.TryGetValue(folder.ToLower(), out files);
                return (IEnumerable<TestFileInfo>)files ?? new TestFileInfo[0];
            });
            _Provider.Setup(p => p.GetFileInfo(It.IsAny<string>())).Returns((string fullPath) => {
                TestFileInfo result = null;
                var folder = (Path.GetDirectoryName(fullPath) ?? "").ToLower();
                var fileName = Path.GetFileName(fullPath);
                List<TestFileInfo> files;
                if(_Files.TryGetValue(folder, out files)) result = files.FirstOrDefault(r => r.Name.Equals(fileName, StringComparison.OrdinalIgnoreCase));
                return result;
            });

            _DirectoryCache = Factory.Singleton.Resolve<IDirectoryCache>();
            _DirectoryCache.Provider = _Provider.Object;
        }

        [TestCleanup]
        public void TestCleanup()
        {
            Factory.RestoreSnapshot(_ClassFactorySnapshot);
        }

        private void CreateBackgroundWorkerMock()
        {
            _BackgroundWorker = TestUtilities.CreateMockImplementation<IBackgroundWorker>();
            _BackgroundWorker.Setup(w => w.StartWork(It.IsAny<object>())).Callback((object obj) => {
                _BackgroundWorker.Setup(w => w.State).Returns(obj);
                _BackgroundWorker.Raise(w => w.DoWork += null, EventArgs.Empty);
            });
        }

        private void AddToFolders(string folder)
        {
            if(!String.IsNullOrEmpty(folder)) {
                if(folder[folder.Length - 1] == '\\') folder = folder.Substring(0, folder.Length - 1);
                folder = folder.ToLower();

                var previousFolder = folder;
                do {
                    if(!_Folders.Contains(folder)) _Folders.Add(folder);
                    try {
                        previousFolder = folder;
                        folder = Path.GetDirectoryName(folder);
                    } catch {
                        folder = null;
                    }
                } while(folder != null && folder != previousFolder);
            }
        }

        private TestFileInfo AddToFiles(string directory, TestFileInfo fileInfo)
        {
            if(!String.IsNullOrEmpty(directory)) {
                directory = directory.ToLower();

                AddToFolders(directory);

                List<TestFileInfo> files;
                if(!_Files.TryGetValue(directory, out files)) {
                    files = new List<TestFileInfo>();
                    _Files.Add(directory, files);
                }
                files.Add(fileInfo);
            }

            return fileInfo;
        }

        private TestFileInfo AddToFiles(string fullPath)
        {
            return AddToFiles(fullPath, _StandardDate);
        }

        private TestFileInfo AddToFiles(string fullPath, DateTime lastModified)
        {
            try {
                var directory = Path.GetDirectoryName(fullPath);
                var fileName = Path.GetFileName(fullPath);

                return AddToFiles(directory, new TestFileInfo(fileName, lastModified));
            } catch {
                return null;
            }
        }

        private void RemoveFromFiles(string fullPath)
        {
            try {
                var directory = Path.GetDirectoryName(fullPath).ToLower();
                var fileName = Path.GetFileName(fullPath);
                List<TestFileInfo> files;
                if(_Files.TryGetValue(directory, out files)) {
                    var testFileInfo = files.FirstOrDefault(r => r.Name.Equals(fileName, StringComparison.OrdinalIgnoreCase));
                    if(testFileInfo != null) files.Remove(testFileInfo);
                    if(files.Count == 0) _Files.Remove(directory);
                }
            } catch {}
        }
        #endregion

        #region Constructor and Properties
        [TestMethod]
        public void DirectoryCache_Constructor_Initialises_To_Known_State_And_Properties_Work()
        {
            var cache = Factory.Singleton.Resolve<IDirectoryCache>();
            Assert.IsNotNull(cache.Provider);
            TestUtilities.TestProperty(cache, r => r.Provider, cache.Provider, _Provider.Object);
            TestUtilities.TestProperty(cache, r => r.Folder, null, "Abc");
            TestUtilities.TestProperty(cache, r => r.CacheSubFolders, false);
        }

        [TestMethod]
        public void DirectoryCache_Folder_Change_Triggers_Background_File_Load()
        {
            AddToFiles(@"xyz\a");

            _DirectoryCache.Folder = "XyZ";

            _BackgroundWorker.Verify(w => w.StartWork(It.IsAny<object>()), Times.Once());
            _Provider.Verify(p => p.GetFilesInFolder("XyZ"), Times.Once());
            _Provider.Verify(p => p.GetFilesInFolder(It.IsAny<string>()), Times.Once());
        }

        [TestMethod]
        public void DirectoryCache_CacheSubFolders_Change_Triggers_Background_File_Load()
        {
            _DirectoryCache.Folder = "x";
            _DirectoryCache.CacheSubFolders = true;

            _BackgroundWorker.Verify(w => w.StartWork(It.IsAny<object>()), Times.Exactly(2));
        }

        [TestMethod]
        public void DirectoryCache_CacheSubFolders_No_Change_Does_Not_Trigger_Background_File_Load()
        {
            _DirectoryCache.CacheSubFolders = false;

            _BackgroundWorker.Verify(w => w.StartWork(It.IsAny<object>()), Times.Never());
        }

        [TestMethod]
        public void DirectoryCache_Folder_Change_Does_Not_Load_Files_If_Folder_Does_Not_Exist()
        {
            _Provider.Setup(p => p.FolderExists(It.IsAny<string>())).Returns(false);
            _DirectoryCache.Folder = "XyZ";

            Assert.AreEqual("XyZ", _DirectoryCache.Folder);
            _Provider.Verify(p => p.GetFilesInFolder("XyZ"), Times.Never());
        }

        [TestMethod]
        public void DirectoryCache_CacheSubFolders_Change_Does_Not_Trigger_Background_File_Load_If_Folder_Not_Set()
        {
            _DirectoryCache.CacheSubFolders = true;

            _BackgroundWorker.Verify(w => w.StartWork(It.IsAny<object>()), Times.Never());
        }

        [TestMethod]
        public void DirectoryCache_Folder_Set_To_Null_Does_Not_Search_For_Files()
        {
            AddToFiles(@"xyz\a");
            _DirectoryCache.Folder = "xyz";
            _DirectoryCache.Folder = null;

            Assert.AreEqual(null, _DirectoryCache.Folder);
            _Provider.Verify(p => p.GetFilesInFolder("xyz"), Times.Once());
            _Provider.Verify(p => p.GetFilesInFolder(It.IsAny<string>()), Times.Once());
        }

        [TestMethod]
        public void DirectoryCache_Folder_Set_To_Null_Does_Check_For_Existence_Of_Folder()
        {
            _DirectoryCache.Folder = "xyz";
            _DirectoryCache.Folder = null;

            _Provider.Verify(p => p.FolderExists("xyz"), Times.Once());
            _Provider.Verify(p => p.FolderExists(null), Times.Never());
        }

        [TestMethod]
        public void DirectoryCache_Folder_Set_To_Self_Does_Not_Search_For_Files_Again()
        {
            AddToFiles(@"xyz\a");
            _DirectoryCache.Folder = "xyz";
            _DirectoryCache.Folder = "xyz";

            _Provider.Verify(p => p.GetFilesInFolder("xyz"), Times.Once());
        }
        #endregion

        #region BeginRefresh
        [TestMethod]
        public void DirectoryCache_BeginRefresh_Loads_Files_On_Background_Thread()
        {
            _DirectoryCache.Folder = "XyZ";
            CreateBackgroundWorkerMock();
            _DirectoryCache.BeginRefresh();

            _BackgroundWorker.Verify(w => w.StartWork(It.IsAny<object>()), Times.Once());
        }

        [TestMethod]
        public void DirectoryCache_BeginRefresh_Checks_That_Folder_Exists()
        {
            _DirectoryCache.Folder = "Xyz";
            CreateBackgroundWorkerMock();
            _DirectoryCache.BeginRefresh();

            _Provider.Verify(p => p.FolderExists("Xyz"), Times.Exactly(2));
        }

        [TestMethod]
        public void DirectoryCache_BeginRefresh_Does_Not_Check_For_Folder_Existence_If_Null()
        {
            _DirectoryCache.BeginRefresh();

            _Provider.Verify(p => p.FolderExists(It.IsAny<string>()), Times.Never());
        }

        [TestMethod]
        public void DirectoryCache_BeginRefresh_Loads_Files_If_Folder_Exists()
        {
            AddToFiles(@"xyz\a");
            _DirectoryCache.Folder = "Xyz";
            CreateBackgroundWorkerMock();
            _DirectoryCache.BeginRefresh();

            _Provider.Verify(p => p.GetFilesInFolder("Xyz"), Times.Exactly(2));
        }

        [TestMethod]
        public void DirectoryCache_BeginRefresh_Does_Not_Load_Files_If_Folder_Does_Not_Exist()
        {
            _Provider.Setup(p => p.FolderExists("Xyz")).Returns(false);

            _DirectoryCache.Folder = "Xyz";
            CreateBackgroundWorkerMock();
            _DirectoryCache.BeginRefresh();

            _Provider.Verify(p => p.GetFilesInFolder("Xyz"), Times.Never());
        }
        #endregion

        #region Heartbeat Tick
        [TestMethod]
        public void DirectoryCache_Heartbeat_Triggers_Refresh()
        {
            _DirectoryCache.Folder = "Xyz";

            _Clock.UtcNowValue = _Clock.UtcNowValue.AddSeconds(SecondsBetweenRefreshes);
            _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty);

            _Provider.Verify(p => p.FolderExists("Xyz"), Times.Exactly(2));
        }

        [TestMethod]
        public void DirectoryCache_Heartbeat_Does_Not_Trigger_Refresh_If_Timeout_Has_Not_Elapsed()
        {
            _DirectoryCache.Folder = "Xyz";

            _Clock.UtcNowValue = _Clock.UtcNowValue.AddSeconds(SecondsBetweenRefreshes).AddMilliseconds(-1);
            _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty);

            _Provider.Verify(p => p.FolderExists("Xyz"), Times.Exactly(1));
        }
        #endregion

        #region SetConfiguration
        [TestMethod]
        public void DirectoryCache_SetConfiguration_Change_Folder_Triggers_Single_Refresh()
        {
            var result = _DirectoryCache.SetConfiguration("x", _DirectoryCache.CacheSubFolders);

            Assert.AreEqual(true, result);
            _BackgroundWorker.Verify(w => w.StartWork(It.IsAny<object>()), Times.Once());
        }

        [TestMethod]
        public void DirectoryCache_SetConfiguration_Change_CacheSubFolders_Triggers_Single_Refresh()
        {
            var result = _DirectoryCache.SetConfiguration(_DirectoryCache.Folder, !_DirectoryCache.CacheSubFolders);

            Assert.AreEqual(true, result);
            _BackgroundWorker.Verify(w => w.StartWork(It.IsAny<object>()), Times.Once());
        }

        [TestMethod]
        public void DirectoryCache_SetConfiguration_Change_Both_Triggers_Single_Refresh()
        {
            var result = _DirectoryCache.SetConfiguration("x", !_DirectoryCache.CacheSubFolders);

            Assert.AreEqual(true, result);
            _BackgroundWorker.Verify(w => w.StartWork(It.IsAny<object>()), Times.Once());
        }

        [TestMethod]
        public void DirectoryCache_SetConfiguration_Change_Neither_Triggers_No_Refresh()
        {
            _DirectoryCache.SetConfiguration("x", !_DirectoryCache.CacheSubFolders);
            var result = _DirectoryCache.SetConfiguration(_DirectoryCache.Folder, _DirectoryCache.CacheSubFolders);

            Assert.AreEqual(false, result);
            _BackgroundWorker.Verify(w => w.StartWork(It.IsAny<object>()), Times.Once());
        }
        #endregion

        #region GetFullPath, FileExists, Add, Remove spreadsheet tests
        [TestMethod]
        [DataSource("Data Source='LibraryTests.xls';Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Extended Properties='Excel 8.0'",
                    "DirectoryCacheGetFullPath$")]
        public void DirectoryCache_GetFullPath_Returns_Correct_Value()
        {
            SpreadsheetTests(null);
        }

        [TestMethod]
        [DataSource("Data Source='LibraryTests.xls';Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Extended Properties='Excel 8.0'",
                    "DirectoryCacheAdd$")]
        public void DirectoryCache_Add_Behaves_Correctly()
        {
            SpreadsheetTests((w) => { _DirectoryCache.Add(w.EString("FileName")); });
        }

        [TestMethod]
        [DataSource("Data Source='LibraryTests.xls';Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Extended Properties='Excel 8.0'",
                    "DirectoryCacheRemove$")]
        public void DirectoryCache_Remove_Behaves_Correctly()
        {
            SpreadsheetTests((w) => {
                var fileName = w.EString("FileName");
                if(!String.IsNullOrEmpty(fileName)) RemoveFromFiles(fileName);
                _DirectoryCache.Remove(fileName);
            });
        }

        private void SpreadsheetTests(Action<ExcelWorksheetData> afterSetFolder)
        {
            var worksheet = new ExcelWorksheetData(TestContext);
            bool checkCacheChanged = worksheet.ColumnExists("CacheChanged");

            for(int i = 1;i <= 2;++i) {
                string nameColumn = String.Format("File{0}", i);
                string lastModifiedColumn = String.Format("Time{0}", i);

                if(!worksheet.ColumnExists(nameColumn)) continue;

                var name = worksheet.String(nameColumn);
                var time = worksheet.ColumnExists(lastModifiedColumn) ? worksheet.DateTime(lastModifiedColumn) : new DateTime(2999, 12, 31);
                if(name != null) AddToFiles(name, time);
            }

            var folder = worksheet.String("Folder");
            if(folder != null) {
                AddToFolders(folder);
                _DirectoryCache.Folder = folder;
            }

            if(worksheet.ColumnExists("CacheSubFolders")) {
                _DirectoryCache.CacheSubFolders = worksheet.Bool("CacheSubFolders");
            }

            if(worksheet.ColumnExists("LastModified")) {
                if(worksheet.String("LastModified") != null) AddToFiles(worksheet.String("FileName"), worksheet.DateTime("LastModified"));
            }

            if(checkCacheChanged) _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            if(afterSetFolder != null) afterSetFolder(worksheet);

            Assert.AreEqual(folder, _DirectoryCache.Folder);
            var result = _DirectoryCache.GetFullPath(worksheet.EString("SearchFor"));
            Assert.AreEqual(worksheet.EString("Result"), result, true);

            if(checkCacheChanged) Assert.AreEqual(worksheet.Bool("CacheChanged") ? 1 : 0, _CacheChangedEvent.CallCount);
        }
        #endregion

        #region CacheChanged
        [TestMethod]
        public void DirectoryCache_CacheChanged_Raised_When_Folder_Set()
        {
            AddToFiles(@"x\a");
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _CacheChangedEvent.EventRaised += (s, a) => { Assert.AreEqual(@"x\a", _DirectoryCache.GetFullPath("a")); };

            _DirectoryCache.Folder = "x";

            Assert.AreEqual(1, _CacheChangedEvent.CallCount);
            Assert.AreSame(_DirectoryCache, _CacheChangedEvent.Sender);
            Assert.IsNotNull(_CacheChangedEvent.Args);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Raised_When_BeginRefresh_Finished()
        {
            _DirectoryCache.Folder = "x";

            AddToFiles(@"x\a");
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _CacheChangedEvent.EventRaised += (s, a) => { Assert.AreEqual(@"x\a", _DirectoryCache.GetFullPath("a"));  };

            CreateBackgroundWorkerMock();
            _DirectoryCache.BeginRefresh();

            Assert.AreEqual(1, _CacheChangedEvent.CallCount);
            Assert.AreSame(_DirectoryCache, _CacheChangedEvent.Sender);
            Assert.IsNotNull(_CacheChangedEvent.Args);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Raised_When_Heartbeat_Tick_Raised()
        {
            _DirectoryCache.Folder = "x";

            AddToFiles(@"x\a");
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _CacheChangedEvent.EventRaised += (s, a) => { Assert.AreEqual(@"x\a", _DirectoryCache.GetFullPath("a")); };

            CreateBackgroundWorkerMock();
            _Clock.UtcNowValue = _Clock.UtcNowValue.AddSeconds(SecondsBetweenRefreshes);
            _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty);

            Assert.AreEqual(1, _CacheChangedEvent.CallCount);
            Assert.AreSame(_DirectoryCache, _CacheChangedEvent.Sender);
            Assert.IsNotNull(_CacheChangedEvent.Args);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Raised_If_Modified_Date_Changes()
        {
            var testFileInfo = AddToFiles(@"x\a", new DateTime(2001, 2, 3));

            _DirectoryCache.Folder = "x";

            testFileInfo.LastWriteTimeUtc = new DateTime(2008, 7, 6);
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;

            CreateBackgroundWorkerMock();
            _Clock.UtcNowValue = _Clock.UtcNowValue.AddSeconds(SecondsBetweenRefreshes);
            _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty);

            Assert.AreEqual(1, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Not_Raised_If_Added_Entry_Seen_In_Subsequent_Refresh()
        {
            AddToFiles(@"x\c", new DateTime(2001, 2, 3));

            _DirectoryCache.Folder = "x";

            AddToFiles(@"x\b", new DateTime(2002, 3, 4));
            _DirectoryCache.Add(@"x\b");

            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            CreateBackgroundWorkerMock();
            _Clock.UtcNowValue = _Clock.UtcNowValue.AddSeconds(SecondsBetweenRefreshes);
            _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty);

            Assert.AreEqual(0, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Not_Raised_If_Removed_Entry_Still_Missing_In_Subsequent_Refresh()
        {
            AddToFiles(@"x\c", new DateTime(2001, 2, 3));
            _DirectoryCache.Folder = "x";

            _Files.Clear();
            _DirectoryCache.Remove(@"x\c");

            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            CreateBackgroundWorkerMock();
            _Clock.UtcNowValue = _Clock.UtcNowValue.AddSeconds(SecondsBetweenRefreshes);
            _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty);

            Assert.AreEqual(0, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Not_Raised_If_Folder_Does_Not_Change()
        {
            _DirectoryCache.Folder = "x";

            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _DirectoryCache.Folder = "x";

            Assert.AreEqual(0, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Not_Raised_If_CacheSubFolders_Does_Not_Change()
        {
            _DirectoryCache.Folder = "x";
            _DirectoryCache.CacheSubFolders = true;

            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _DirectoryCache.CacheSubFolders = true;

            Assert.AreEqual(0, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Not_Raised_If_Content_Does_Not_Change()
        {
            AddToFiles(@"x\a");
            _DirectoryCache.Folder = "x";

            CreateBackgroundWorkerMock();
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _Clock.UtcNowValue = _Clock.UtcNowValue.AddSeconds(SecondsBetweenRefreshes);
            _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty);

            Assert.AreEqual(0, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Not_Raised_If_Content_Does_Not_Change_But_Order_Does()
        {
            AddToFiles(@"x\a");
            AddToFiles(@"x\b");

            _DirectoryCache.Folder = "x";

            _Files.Clear();
            AddToFiles(@"x\b");
            AddToFiles(@"x\a");

            CreateBackgroundWorkerMock();
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _Clock.UtcNowValue = _Clock.UtcNowValue.AddSeconds(SecondsBetweenRefreshes);
            _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty);

            Assert.AreEqual(0, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Not_Raised_If_Content_Does_Not_Change_But_Case_Does()
        {
            AddToFiles(@"x\a");
            AddToFiles(@"x\b");
            _DirectoryCache.Folder = "x";

            _Files.Clear();
            AddToFiles(@"x\A");
            AddToFiles(@"x\B");

            CreateBackgroundWorkerMock();
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _Clock.UtcNowValue = _Clock.UtcNowValue.AddSeconds(SecondsBetweenRefreshes);
            _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty);

            Assert.AreEqual(0, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Not_Raised_If_BeginRefresh_Sees_No_Change()
        {
            AddToFiles(@"x\a");
            _DirectoryCache.Folder = "x";

            CreateBackgroundWorkerMock();
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _DirectoryCache.BeginRefresh();

            Assert.AreEqual(0, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Raised_If_Folder_Changes_But_File_Names_Are_Same()
        {
            AddToFiles(@"x\a");
            AddToFiles(@"y\a");
            _DirectoryCache.Folder = "x";

            CreateBackgroundWorkerMock();
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _DirectoryCache.Folder = "y";

            Assert.AreEqual(1, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Raised_If_Cache_Cleared()
        {
            AddToFiles(@"x\a");
            _DirectoryCache.Folder = "x";

            CreateBackgroundWorkerMock();
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _DirectoryCache.Folder = null;

            Assert.AreEqual(1, _CacheChangedEvent.CallCount);
        }

        [TestMethod]
        public void DirectoryCache_CacheChanged_Not_Raised_For_Heartbeats_After_Cache_Cleared()
        {
            AddToFiles(@"x\a");
            _DirectoryCache.Folder = "x";
            _DirectoryCache.Folder = null;

            CreateBackgroundWorkerMock();
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _Clock.UtcNowValue = _Clock.UtcNowValue.AddSeconds(SecondsBetweenRefreshes);
            _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty);

            Assert.AreEqual(0, _CacheChangedEvent.CallCount);
        }
        #endregion

        #region Exception Handling
        [TestMethod]
        public void DirectoryCache_Logs_Exceptions_Thrown_By_Provider_FolderExists()
        {
            var exception = new Exception();
            _Provider.Setup(p => p.FolderExists(It.IsAny<string>())).Throws(exception);
            _Log.Setup(g => g.WriteLine(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback(() => { ; });

            _DirectoryCache.Folder = "x";

            _Log.Verify(g => g.WriteLine(It.IsAny<string>(), "x", exception.ToString()), Times.Once());
        }

        [TestMethod]
        public void DirectoryCache_Logs_Exceptions_Thrown_By_Provider_GetFilesInFolder()
        {
            AddToFiles(@"x\a");

            var exception = new Exception();
            _Provider.Setup(p => p.GetFilesInFolder(It.IsAny<string>())).Throws(exception);
            _Log.Setup(g => g.WriteLine(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback(() => { ; });

            _DirectoryCache.Folder = "x";

            _Log.Verify(g => g.WriteLine(It.IsAny<string>(), "x", exception.ToString()), Times.Once());
        }

        [TestMethod]
        public void DirectoryCache_Logs_Exceptions_Thrown_By_CacheCleared_Event_Handlers()
        {
            var exception = new Exception();
            _DirectoryCache.CacheChanged += _CacheChangedEvent.Handler;
            _CacheChangedEvent.EventRaised += (s, a) => { throw exception; };
            _Log.Setup(g => g.WriteLine(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Callback(() => { ; });

            AddToFiles(@"x\a");
            _DirectoryCache.Folder = "x";

            _Log.Verify(g => g.WriteLine(It.IsAny<string>(), "x", exception.ToString()), Times.Once());
        }
        #endregion
    }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item android:id="@+id/action_reload"
        android:title="@string/action_reload"
        android:icon="@android:drawable/ic_menu_rotate"
        app:showAsAction="ifRoom"/>

    <item android:id="@+id/action_basic_auth"
        android:title="@string/action_basic_auth"
        app:showAsAction="never" />

    <item android:id="@+id/action_rx"
        android:title="@string/action_rx"
        app:showAsAction="never" />

    <item android:id="@+id/action_playstore"
        android:title="@string/action_playstore"
        app:showAsAction="never" />

</menu>


text:
using global::System;
using global::System.Reflection;
using global::System.Reflection.Runtime.General;

namespace Internal.Reflection.Core
{
    //=====================================================================================================================================
    // This object encapsulates the customization parameters for Reflection domains.
    //=====================================================================================================================================
    public abstract class ReflectionDomainSetup
    {
        protected ReflectionDomainSetup() { }
        public abstract AssemblyBinder AssemblyBinder { get; }
        public abstract FoundationTypes FoundationTypes { get; }
        public abstract Exception CreateMissingMetadataException(TypeInfo pertainant);
        public abstract Exception CreateMissingMetadataException(Type pertainant);
        public abstract Exception CreateMissingMetadataException(TypeInfo pertainant, string nestedTypeName);
        public abstract Exception CreateNonInvokabilityException(MemberInfo pertainant);
    }
}


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Metadata;

namespace coremanage.Data.Storage.MSSQL.Migrations
{
    public partial class IdentityServerDbContext : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "AspNetRoles",
                columns: table => new
                {
                    Id = table.Column<string>(nullable: false),
                    ConcurrencyStamp = table.Column<string>(nullable: true),
                    Name = table.Column<string>(maxLength: 256, nullable: true),
                    NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
                    RoleType = table.Column<int>(nullable: false),
                    TenantId = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AspNetRoles", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "AspNetUsers",
                columns: table => new
                {
                    Id = table.Column<string>(nullable: false),
                    AccessFailedCount = table.Column<int>(nullable: false),
                    AccountExpires = table.Column<DateTime>(nullable: true),
                    ConcurrencyStamp = table.Column<string>(nullable: true),
                    Email = table.Column<string>(maxLength: 256, nullable: true),
                    EmailConfirmed = table.Column<bool>(nullable: false),
                    LockoutEnabled = table.Column<bool>(nullable: false),
                    LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
                    NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
                    NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
                    PasswordHash = table.Column<string>(nullable: true),
                    PhoneNumber = table.Column<string>(nullable: true),
                    PhoneNumberConfirmed = table.Column<bool>(nullable: false),
                    SecurityStamp = table.Column<string>(nullable: true),
                    TwoFactorEnabled = table.Column<bool>(nullable: false),
                    UserName = table.Column<string>(maxLength: 256, nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AspNetUsers", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "IdentityRoleHierarchies",
                columns: table => new
                {
                    RoleId = table.Column<string>(nullable: false),
                    ChildRoleId = table.Column<string>(nullable: false),
                    Id = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_IdentityRoleHierarchies", x => new { x.RoleId, x.ChildRoleId });
                });

            migrationBuilder.CreateTable(
                name: "PersonalClaims",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    ClaimType = table.Column<string>(nullable: true),
                    ClaimValue = table.Column<string>(nullable: true),
                    Description = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_PersonalClaims", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Tenants",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    CreatedAt = table.Column<DateTime>(nullable: true),
                    CreatedBy = table.Column<string>(nullable: true),
                    Description = table.Column<string>(nullable: true),
                    IsDeleted = table.Column<bool>(nullable: true),
                    IsGroup = table.Column<bool>(nullable: true),
                    LastModifiedAt = table.Column<DateTime>(nullable: true),
                    LastModifiedBy = table.Column<string>(nullable: true),
                    Name = table.Column<string>(nullable: true),
                    ParentTenantId = table.Column<int>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Tenants", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "UserProfiles",
                columns: table => new
                {
                    Id = table.Column<string>(nullable: false),
                    CreatedAt = table.Column<DateTime>(nullable: true),
                    CreatedBy = table.Column<string>(nullable: true),
                    Email = table.Column<string>(nullable: true),
                    FirstName = table.Column<string>(nullable: true),
                    IsDeleted = table.Column<bool>(nullable: true),
                    LastAccess = table.Column<DateTime>(nullable: false),
                    LastModifiedAt = table.Column<DateTime>(nullable: true),
                    LastModifiedBy = table.Column<string>(nullable: true),
                    LastName = table.Column<string>(nullable: true),
                    MiddleName = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_UserProfiles", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "AspNetUserTokens",
                columns: table => new
                {
                    UserId = table.Column<string>(nullable: false),
                    LoginProvider = table.Column<string>(nullable: false),
                    Name = table.Column<string>(nullable: false),
                    Value = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
                });

            migrationBuilder.CreateTable(
                name: "AspNetRoleClaims",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    ClaimType = table.Column<string>(nullable: true),
                    ClaimValue = table.Column<string>(nullable: true),
                    RoleId = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
                    table.ForeignKey(
                        name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
                        column: x => x.RoleId,
                        principalTable: "AspNetRoles",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "AspNetUserClaims",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    ClaimType = table.Column<string>(nullable: true),
                    ClaimValue = table.Column<string>(nullable: true),
                    UserId = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
                    table.ForeignKey(
                        name: "FK_AspNetUserClaims_AspNetUsers_UserId",
                        column: x => x.UserId,
                        principalTable: "AspNetUsers",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "AspNetUserLogins",
                columns: table => new
                {
                    LoginProvider = table.Column<string>(nullable: false),
                    ProviderKey = table.Column<string>(nullable: false),
                    ProviderDisplayName = table.Column<string>(nullable: true),
                    UserId = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
                    table.ForeignKey(
                        name: "FK_AspNetUserLogins_AspNetUsers_UserId",
                        column: x => x.UserId,
                        principalTable: "AspNetUsers",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "AspNetUserRoles",
                columns: table => new
                {
                    UserId = table.Column<string>(nullable: false),
                    RoleId = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
                    table.ForeignKey(
                        name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
                        column: x => x.RoleId,
                        principalTable: "AspNetRoles",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_AspNetUserRoles_AspNetUsers_UserId",
                        column: x => x.UserId,
                        principalTable: "AspNetUsers",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "PersonalTenantClaims",
                columns: table => new
                {
                    PersonalClaimId = table.Column<int>(nullable: false),
                    TenantId = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_PersonalTenantClaims", x => new { x.PersonalClaimId, x.TenantId });
                    table.ForeignKey(
                        name: "FK_PersonalTenantClaims_PersonalClaims_PersonalClaimId",
                        column: x => x.PersonalClaimId,
                        principalTable: "PersonalClaims",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_PersonalTenantClaims_Tenants_TenantId",
                        column: x => x.TenantId,
                        principalTable: "Tenants",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "UserProfileTenants",
                columns: table => new
                {
                    UserProfileId = table.Column<string>(nullable: false),
                    TenantId = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_UserProfileTenants", x => new { x.UserProfileId, x.TenantId });
                    table.ForeignKey(
                        name: "FK_UserProfileTenants_Tenants_TenantId",
                        column: x => x.TenantId,
                        principalTable: "Tenants",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_UserProfileTenants_UserProfiles_UserProfileId",
                        column: x => x.UserProfileId,
                        principalTable: "UserProfiles",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "RoleNameIndex",
                table: "AspNetRoles",
                column: "NormalizedName",
                unique: true);

            migrationBuilder.CreateIndex(
                name: "EmailIndex",
                table: "AspNetUsers",
                column: "NormalizedEmail");

            migrationBuilder.CreateIndex(
                name: "UserNameIndex",
                table: "AspNetUsers",
                column: "NormalizedUserName",
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_PersonalTenantClaims_TenantId",
                table: "PersonalTenantClaims",
                column: "TenantId");

            migrationBuilder.CreateIndex(
                name: "IX_UserProfileTenants_TenantId",
                table: "UserProfileTenants",
                column: "TenantId");

            migrationBuilder.CreateIndex(
                name: "IX_AspNetRoleClaims_RoleId",
                table: "AspNetRoleClaims",
                column: "RoleId");

            migrationBuilder.CreateIndex(
                name: "IX_AspNetUserClaims_UserId",
                table: "AspNetUserClaims",
                column: "UserId");

            migrationBuilder.CreateIndex(
                name: "IX_AspNetUserLogins_UserId",
                table: "AspNetUserLogins",
                column: "UserId");

            migrationBuilder.CreateIndex(
                name: "IX_AspNetUserRoles_RoleId",
                table: "AspNetUserRoles",
                column: "RoleId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "IdentityRoleHierarchies");

            migrationBuilder.DropTable(
                name: "PersonalTenantClaims");

            migrationBuilder.DropTable(
                name: "UserProfileTenants");

            migrationBuilder.DropTable(
                name: "AspNetRoleClaims");

            migrationBuilder.DropTable(
                name: "AspNetUserClaims");

            migrationBuilder.DropTable(
                name: "AspNetUserLogins");

            migrationBuilder.DropTable(
                name: "AspNetUserRoles");

            migrationBuilder.DropTable(
                name: "AspNetUserTokens");

            migrationBuilder.DropTable(
                name: "PersonalClaims");

            migrationBuilder.DropTable(
                name: "Tenants");

            migrationBuilder.DropTable(
                name: "UserProfiles");

            migrationBuilder.DropTable(
                name: "AspNetRoles");

            migrationBuilder.DropTable(
                name: "AspNetUsers");
        }
    }
}


text:
package com.vaadin.data.validator;

import java.util.Objects;

import com.vaadin.data.ValidationResult;
import com.vaadin.data.Validator;
import com.vaadin.server.SerializableFunction;

/**
 * An abstract base class for typed validators.
 *
 * @param <T>
 *            The value type
 * @author Vaadin Ltd.
 * @since 8.0
 */
public abstract class AbstractValidator<T> implements Validator<T> {

    private final SerializableFunction<T, String> messageProvider;

    /**
     * Constructs a validator with the given error message. The substring "{0}"
     * is replaced by the value that failed validation.
     *
     * @param errorMessage
     *            the message to be included in a failed result, not null
     */
    protected AbstractValidator(String errorMessage) {
        Objects.requireNonNull(errorMessage, "error message cannot be null");
        this.messageProvider = value -> errorMessage.replace("{0}",
                String.valueOf(value));
    }

    /**
     * Returns the error message for the given value.
     *
     * @param value
     *            an invalid value
     * @return the formatted error message
     */
    protected String getMessage(T value) {
        return messageProvider.apply(value);
    }

    /**
     * A helper method for creating a {@code Result} from a value and a validity
     * flag. If the flag is true, returns {@code Result.ok}, otherwise yields
     * {@code Result.error} bearing the error message returned by
     * {@link #getMessage(T)}.
     *

     * For instance, the following {@code apply} method only accepts even
     * numbers:
     *
     *

     * @Override
     * public Result<T> apply(Integer value) {
     *     return toResult(value, value % 2 == 0);
     * }
     *

     *
     * @param value
     *            the validated value
     * @param isValid
     *            whether the value is valid or not
     * @return the validation result
     */
    protected ValidationResult toResult(T value, boolean isValid) {
        return isValid ? ValidationResult.ok()
                : ValidationResult.error(getMessage(value));
    }
}


text:
package org.apache.cloudstack.resourcedetail.dao;

import org.apache.cloudstack.resourcedetail.ResourceDetailsDaoBase;
import org.apache.cloudstack.resourcedetail.UserDetailVO;
import org.springframework.stereotype.Component;

@Component
public class UserDetailsDaoImpl extends ResourceDetailsDaoBase<UserDetailVO> implements UserDetailsDao {

    @Override
    public void addDetail(long resourceId, String key, String value, boolean display) {
        super.addDetail(new UserDetailVO(resourceId, key, value));
    }
}


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\Definition\Value;

use Nelmio\Alice\Definition\ValueInterface;

/**
 * @covers \Nelmio\Alice\Definition\Value\VariableValue
 */
class VariableValueTest extends \PHPUnit_Framework_TestCase
{
    public function testIsAValue()
    {
        $this->assertTrue(is_a(VariableValue::class, ValueInterface::class, true));
    }

    public function testReadAccessorsReturnPropertiesValues()
    {
        $variable = 'username';
        $value = new VariableValue($variable);

        $this->assertEquals($variable, $value->getValue());
    }

    public function testCanBeCastedIntoAString()
    {
        $value = new VariableValue('username');

        $this->assertEquals('$username', $value);
    }
}


text:
@interface CheckInViewController : UIViewController <UIScrollViewDelegate,UIImagePickerControllerDelegate, UIActionSheetDelegate, MKMapViewDelegate, UINavigationControllerDelegate, UITextViewDelegate, LocationPickerControllerDelegate, SportsCollectionViewControllerDelegate, InstagramCollectionViewControllerDelegate, MFMailComposeViewControllerDelegate, InviteUsersFollowViewControllerDelegate>

@property (nonatomic, strong) PFFile *photoFile;
@property (nonatomic, strong) PlayProfileImageView *profilePictureImageView;
@property (strong, nonatomic) UITextView *eventCaption;
@property (strong, nonatomic) UIButton *timeTextView;
@property (strong, nonatomic) UIButton *locationTextView;
@property (strong, nonatomic) NSString *locationName;
@property (strong, nonatomic) ActionSheetDatePicker *actionSheetDatePicker;
@property (strong, nonatomic) MKMapView *mapView;
@property (strong,nonatomic) CLLocation *currentLocation;
@property (strong,nonatomic) CLLocation *userCurrentLocation;
@property (strong, nonatomic) UIButton *createEventButton;
@property (strong, nonatomic) UIButton *chooseAPhoto;
@property (nonatomic, assign) UIButton *bioStringCount;
@property (strong,nonatomic) UISegmentedControl *segmentedControl;
@property (strong, nonatomic) NSNumber *segmentControlNumber;

@property (strong, nonatomic) UIButton *facebookPost;
@property (nonatomic) BOOL *shouldPostToFacebook;
@property (strong, nonatomic) UIButton *twitterPost;
@property (nonatomic) BOOL *shouldPostTwitter;
@property (strong, nonatomic) UIButton *emailPost;
@property (strong, nonatomic) UIButton *inviteFriends;

@property (strong, nonatomic) NSString *timeTillEvent;
@property (strong, nonatomic) NSMutableArray *locationInfo;
@property (strong, nonatomic) NSNumber *eventIconType;
@property (strong, nonatomic) NSString *eventType;
@property (strong, nonatomic) NSString *searchTerm;
@property (nonatomic, strong) SportsCollectionViewController *sportsCollectionController;
@property (nonatomic, strong) InstagramCollectionViewController *instaCollectionController;
@property (nonatomic, strong) LocationPickerController *locationPickerController;
@property (nonatomic, strong) InviteUsersFollowViewController *inviteUsersController;

@property (strong, nonatomic) UIImageView *addEventImage;
@property (strong, nonatomic) UIImageView *addSportImage;
@property (strong, nonatomic) UIImagePickerController *picker;

@property (strong,nonatomic) NSDateFormatter *dateFormatterForTime;
@property (strong, nonatomic) NSDate *timeofEvent;
@property (strong, nonatomic) NSDate *endtimeofEvent;
@property (nonatomic, assign) int utcOffset;
@property (strong, nonatomic) NSDate *displayStartTimeofEvent;

@property (nonatomic, assign) UIBackgroundTaskIdentifier fileUploadBackgroundTaskId;
@property (nonatomic, assign) UIBackgroundTaskIdentifier photoPostBackgroundTaskId;

@property (nonatomic, strong) NSMutableSet *invitedUsersSet;
@property (nonatomic, strong) NSMutableSet *pushUsersSet;

- (void) loadAddEventPic:(id) sender;
- (BOOL) uploadImage:(UIImage *)anImage;
- (void) createEvent:(id)sender;
- (void) backButton:(id)sender;

- (void)setBackground:(UIImage*)bkgdImage;
- (void) animateTextField:(UITextView*)textField up:(BOOL)up;
- (void) getVenueData4sq:(NSArray *)venueArray index:(NSInteger)index;
- (void) showTime;
- (void) initiateMap:(CLLocation*)location;
- (void) setMap:(CLLocation*)location;
- (void) openLocationPicker:(id)sender;
- (void) launchInstagram;

- (void)pressedPostToFacebookButton:(UIButton*)sender;
- (void)pressedPostToTwitterButton:(UIButton*)sender;
- (void)pressedPostToEmailButton:(UIButton*)sender;

- (void)dateWasSelected:(NSDate *)selectedDate element:(id)element;
- (void)selectADate:(UIControl *)sender;
- (void)dateButtonTapped:(UIBarButtonItem *)sender;

- (void)pressedInviteFriends:(UIButton*)sender;
- (void) segmentChanged:(id)sender;

@end


text:
from __future__ import unicode_literals

import data_sources.fields
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('data_sources', '0002_auto_20160505_2002'),
    ]

    operations = [
        migrations.AddField(
            model_name='datasource',
            name='file_type',
            field=models.CharField(blank=True, choices=[('TEXT', 'text'), ('FASTA', 'FASTA'), ('FASTQ', 'FASTQ'), ('BINARY', 'binary')], max_length=32, verbose_name='file type'),
        ),
        migrations.AddField(
            model_name='datasource',
            name='metadata',
            field=django.contrib.postgres.fields.jsonb.JSONField(default={}, verbose_name='metadata'),
        ),
        migrations.AddField(
            model_name='datasource',
            name='sample_name',
            field=models.CharField(blank=True, max_length=512, verbose_name='sample name'),
        ),
        migrations.AlterField(
            model_name='datasource',
            name='checksum',
            field=data_sources.fields.SHA256ChecksumField(blank=True, help_text='Hexadecimal checksum generated by SHA256 hash algorithm.', verbose_name='SHA256 checksum'),
        ),
        migrations.AlterField(
            model_name='datasource',
            name='file_path',
            field=models.CharField(help_text="Relative path under user's data source directory.", max_length=1023, verbose_name='file path'),
        ),
    ]


text:
package org.jboss.weld.tests;

import org.jboss.weld.tests.Categories.ExcludeCategory;
import org.jboss.weld.tests.Categories.IncludeCategory;
import org.jboss.weld.tests.category.Broken;
import org.jboss.weld.tests.category.Integration;
import org.jboss.weld.tests.category.Performance;
import org.junit.runner.RunWith;
import org.junit.runners.Suite.SuiteClasses;

/**
 * IntegrationSuite
 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
@RunWith(Categories.class)
@IncludeCategory({Integration.class, Performance.class})
@ExcludeCategory(Broken.class)
@SuiteClasses(AllTests.class)
public class IntegrationPerformanceSuite {

}


text:
function stripped_str = strip_str_literals_from_line(str)

    assert(is_string(str), 'Exactly one string argument expected');

    quot = quote_delimiters;
    PrevNonBlankChar = ';';
    PrevCharIsBlank = false;
    strStart = 0;
    n = length(str);
    keep = true(1, n);
    for k = 1 : n

        if strStart == 0 ...
                && any(str(k) == quot) ...
                && (isempty(regexp(PrevNonBlankChar, '[\w})\]]', 'once')) ...
                || PrevCharIsBlank)
            # Current character is the opening quote delimiter for a string
            # literal. The
            # isempty(regexp(PrevNonBlankChar, '[\w})\]]', 'once'))
            # test avoids (hopefully) that the Matlab programming language
            # transposition operator ("'") is taken for a string literal
            # opening.

            q = str(k);
            qCount = 1;
            strStart = k;
        elseif strStart ~= 0 ...
                && str(k) == q ...
                && (k == n || (str(k + 1) ~= q && ~is_even(qCount)))
            # Current character is the closing quote for a string literal.

            keep(strStart : k) = false;
            strStart = 0;
        elseif strStart ~= 0 && str(k) == q
            # Current character is a quote in a string literal.

            qCount = qCount + 1;
        endif

        if isempty(regexp(str(k), '\s', 'once'))
            PrevNonBlankChar = str(k);
            PrevCharIsBlank = false;
        else
            PrevCharIsBlank = true;
        endif
    endfor

    stripped_str = str(keep);
    if numel(stripped_str) == 0
        stripped_str = '';
    endif

endfunction


text:
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">

		<title>appNodeMap application</title>

		<link rel="stylesheet" type="text/css" href="css/styles.css">
		<script type="text/javascript" src="js/node-library.js"></script>

	</head>
	<body>

	</body>
</html>


text:
package org.terasology.math;

import com.google.common.base.Objects;
import com.google.common.collect.ImmutableList;

import gnu.trove.map.TByteObjectMap;
import gnu.trove.map.hash.TByteObjectHashMap;

import java.util.List;

import org.terasology.math.geom.Quat4f;

/**
 * Rotation provides easy access to 90 degree increments of rotations - intended for block-related rotations.
 *

 * Uses the fly weight pattern to cache the 64 combinations of rotation.
 *
 * @author Immortius
 */
public final class Rotation {

    private static final TByteObjectMap<Rotation> ROTATIONS;
    private static final ImmutableList<Rotation> HORIZONTAL_ROTATIONS;

    private Yaw yaw;
    private Pitch pitch;
    private Roll roll;

    private Rotation(Yaw yaw, Pitch pitch, Roll roll) {
        this.pitch = pitch;
        this.yaw = yaw;
        this.roll = roll;
    }

    public static Rotation none() {
        return ROTATIONS.get(indexFor(Yaw.NONE, Pitch.NONE, Roll.NONE));
    }

    public static Rotation rotate(Pitch pitch) {
        return ROTATIONS.get(indexFor(Yaw.NONE, pitch, Roll.NONE));
    }

    public static Rotation rotate(Yaw yaw) {
        return ROTATIONS.get(indexFor(yaw, Pitch.NONE, Roll.NONE));
    }

    public static Rotation rotate(Roll roll) {
        return ROTATIONS.get(indexFor(Yaw.NONE, Pitch.NONE, roll));
    }

    public static Rotation rotate(Yaw yaw, Pitch pitch) {
        return ROTATIONS.get(indexFor(yaw, pitch, Roll.NONE));
    }

    public static Rotation rotate(Pitch pitch, Roll roll) {
        return ROTATIONS.get(indexFor(Yaw.NONE, pitch, roll));
    }

    public static Rotation rotate(Yaw yaw, Roll roll) {
        return ROTATIONS.get(indexFor(yaw, Pitch.NONE, roll));
    }

    public static Rotation rotate(Yaw yaw, Pitch pitch, Roll roll) {
        return ROTATIONS.get(indexFor(yaw, pitch, roll));
    }

    public static List<Rotation> horizontalRotations() {
        return HORIZONTAL_ROTATIONS;
    }

    static {
        ROTATIONS = new TByteObjectHashMap<>();
        for (Pitch pitch : Pitch.values()) {
            for (Yaw yaw : Yaw.values()) {
                for (Roll roll : Roll.values()) {
                    ROTATIONS.put(indexFor(yaw, pitch, roll), new Rotation(yaw, pitch, roll));
                }
            }
        }
        HORIZONTAL_ROTATIONS = ImmutableList.of(
                ROTATIONS.get(indexFor(Yaw.NONE, Pitch.NONE, Roll.NONE)),
                ROTATIONS.get(indexFor(Yaw.CLOCKWISE_90, Pitch.NONE, Roll.NONE)),
                ROTATIONS.get(indexFor(Yaw.CLOCKWISE_180, Pitch.NONE, Roll.NONE)),
                ROTATIONS.get(indexFor(Yaw.CLOCKWISE_270, Pitch.NONE, Roll.NONE)));
    }

    private static byte indexFor(Yaw yaw, Pitch pitch, Roll roll) {
        return (byte) ((yaw.getIndex() << 4) + (pitch.getIndex() << 2) + roll.getIndex());
    }

    public Yaw getYaw() {
        return yaw;
    }

    public Pitch getPitch() {
        return pitch;
    }

    public Roll getRoll() {
        return roll;
    }

    public Quat4f getQuat4f() {
        Quat4f rotation = new Quat4f(yaw.getRadians(), pitch.getRadians(), roll.getRadians());
        rotation.normalize();
        return rotation;
    }

    public Side rotate(Side side) {
        Side result = side;
        result = result.rollClockwise(roll.getIncrements());
        result = result.pitchClockwise(pitch.getIncrements());
        result = result.yawClockwise(yaw.getIncrements());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof Rotation) {
            Rotation other = (Rotation) obj;
            return yaw == other.yaw && pitch == other.pitch && roll == other.roll;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(yaw, pitch, roll);
    }

    public static Iterable<Rotation> values() {
        return ROTATIONS.valueCollection();
    }
}


text:
var express = require('express');
var router = express.Router();
var filter = require('./../passport.js');
var Wexinshare = require('../../db/wexinshare');

router.post('/', function (req, res, next) {
    filter.authorize(req, res, function (req, res) {
        var wexinsharedata = req.body.wexinshare;
        wexinsharedata.project = req.body.projectId;
        var newWexinsharedata = new Wexinshare(wexinsharedata);
        newWexinsharedata.save(function (err, wexinshareEntity) {
            if (err) {
                res.status('500');
                res.send({
                    success: false, // 标记失败
                    model: {
                        error: '系统错误'
                    }
                });
            } else {
                res.status('200');
                res.send({
                    success: true,
                    model: wexinshareEntity
                });
            }
        });

    });
});

module.exports = router;


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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.transcoder.v1.model;

/**
 * Animation types.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Transcoder API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Animation extends com.google.api.client.json.GenericJson {

  /**
   * End previous animation.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private AnimationEnd animationEnd;

  /**
   * Display overlay object with fade animation.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private AnimationFade animationFade;

  /**
   * Display static overlay object.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private AnimationStatic animationStatic;

  /**
   * End previous animation.
   * @return value or {@code null} for none
   */
  public AnimationEnd getAnimationEnd() {
    return animationEnd;
  }

  /**
   * End previous animation.
   * @param animationEnd animationEnd or {@code null} for none
   */
  public Animation setAnimationEnd(AnimationEnd animationEnd) {
    this.animationEnd = animationEnd;
    return this;
  }

  /**
   * Display overlay object with fade animation.
   * @return value or {@code null} for none
   */
  public AnimationFade getAnimationFade() {
    return animationFade;
  }

  /**
   * Display overlay object with fade animation.
   * @param animationFade animationFade or {@code null} for none
   */
  public Animation setAnimationFade(AnimationFade animationFade) {
    this.animationFade = animationFade;
    return this;
  }

  /**
   * Display static overlay object.
   * @return value or {@code null} for none
   */
  public AnimationStatic getAnimationStatic() {
    return animationStatic;
  }

  /**
   * Display static overlay object.
   * @param animationStatic animationStatic or {@code null} for none
   */
  public Animation setAnimationStatic(AnimationStatic animationStatic) {
    this.animationStatic = animationStatic;
    return this;
  }

  @Override
  public Animation set(String fieldName, Object value) {
    return (Animation) super.set(fieldName, value);
  }

  @Override
  public Animation clone() {
    return (Animation) super.clone();
  }

}


text:
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from addresses.djinni

#ifndef DJINNI_GENERATED_TEZOSLIKEEXTENDEDPUBLICKEY_HPP
#define DJINNI_GENERATED_TEZOSLIKEEXTENDEDPUBLICKEY_HPP

#include <cstdint>
#include <memory>
#include <string>
#include <vector>
#ifndef LIBCORE_EXPORT
    #if defined(_MSC_VER)
       #include <libcore_export.h>
    #else
       #define LIBCORE_EXPORT
    #endif
#endif

namespace ledger { namespace core { namespace api {

class TezosLikeAddress;

/** The xPUB definition for Tezos. */
class LIBCORE_EXPORT TezosLikeExtendedPublicKey {
public:
    virtual ~TezosLikeExtendedPublicKey() {}

    /** Derive an address from an xPUB and a path. */
    virtual std::shared_ptr<TezosLikeAddress> derive(const std::string & path) = 0;

    /** Derive a public key from an xPUB and a path. */
    virtual std::vector<uint8_t> derivePublicKey(const std::string & path) = 0;

    /** Derive a shorten version of a public key (SHA256 + RIPEMD160) from an xPUB and a path. */
    virtual std::vector<uint8_t> deriveHash160(const std::string & path) = 0;

    /** Get the xPUB in base 58. */
    virtual std::string toBase58() = 0;

    /** Get the root path of the xPUB. */
    virtual std::string getRootPath() = 0;
};

} } }  // namespace ledger::core::api
#endif //DJINNI_GENERATED_TEZOSLIKEEXTENDEDPUBLICKEY_HPP


text:
"""Extract embeddings for a corpus of audio."""

import time
from typing import Sequence

from absl import app
from absl import flags
from absl import logging
import apache_beam as beam
from apache_beam.io.filesystem import CompressionTypes
from chirp import config_utils
from chirp.configs import config_globals
from chirp.configs.inference import raw_soundscapes
from chirp.inference import embed_lib
from etils import epath
import numpy as np

FLAGS = flags.FLAGS

_DRY_RUN_ONLY = flags.DEFINE_bool('dry_run', False,
                                  'Whether to execute a dry-run only.')

def dry_run(config, source_files):
  """Perform a dry run: check that the model loads and can process a file."""
  test_embed_fn = embed_lib.EmbedFn(**config.embed_fn_config)
  print('starting dry run....')
  test_embed_fn.setup()
  print('   loaded test model....')
  start = time.time()
  test_file = np.random.choice(source_files)
  print(f'   processing test file {test_file}')
  if test_embed_fn.embedding_model.window_size_s > 0:
    crop_s = 2 * test_embed_fn.embedding_model.window_size_s
  else:
    crop_s = 10
  got = test_embed_fn.process(
      embed_lib.SourceInfo(test_file, 0, 1), crop_s=crop_s)
  elapsed = time.time() - start
  if not got:
    raise Exception('Something went wrong; no results found.')
  test_embed_fn.teardown()
  print(f'Dry run successful! Party! Inference time : {elapsed:5.3f}')

def main(unused_argv: Sequence[str]) -> None:
  logging.info('Loading config')
  # TODO(tomdenton): Find a better config system that works for Beam workers.
  config = raw_soundscapes.get_config()
  config = config_utils.parse_config(config, config_globals.get_globals())

  logging.info('Locating source files...')
  source_files = []
  for pattern in config.source_file_patterns:
    for source_file in epath.Path('').glob(pattern):
      source_files.append(source_file)
  output_dir = epath.Path(config.output_dir)
  output_dir.mkdir(exist_ok=True)
  logging.info('Found %d source files.', len(source_files))
  if _DRY_RUN_ONLY.value:
    dry_run(config, source_files)
    return

  # Create and run the beam pipeline.
  source_infos = embed_lib.create_source_infos(source_files,
                                               config.num_shards_per_file)
  pipeline = beam.Pipeline()
  _ = (
      pipeline
      | beam.Create(source_infos)
      | beam.ParDo(embed_lib.EmbedFn(**config.embed_fn_config))
      # When a file is corrupted and can't be loaded EmbedFn
      # returns None. In this case the lambda below returns false, which then
      # filters it out.
      | beam.Filter(lambda x: x)
      | beam.io.tfrecordio.WriteToTFRecord(
          config.output_dir,
          compression_type=CompressionTypes.GZIP,
          file_name_suffix='.gz'))
  pipeline.run()

if __name__ == '__main__':
  app.run(main)


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

var assert = require("assert");
var ByteBuffer = require("protobufjs").ByteBuffer;
var openchain = require("../index");
var RecordKey = openchain.RecordKey;

describe("RecordKey", function () {
    it("toString", function () {
        assert.equal(new RecordKey("/account/path/", "ACC", "/asset/path/").toString(), "/account/path/:ACC:/asset/path/");
    });

    it("toByteBuffer", function () {
        assert.equal(
            new RecordKey("/account/path/", "ACC", "/asset/path/").toByteBuffer().toHex(),
            "2f6163636f756e742f706174682f3a4143433a2f61737365742f706174682f");
    });

    it("parse string", function () {
        var result1 = RecordKey.parse("/account/path/:ACC:/asset/path/");
        var result2 = RecordKey.parse("/account/path/:DATA:record:name");

        assert.equal(result1.path.toString(), "/account/path/");
        assert.equal(result1.recordType, "ACC");
        assert.equal(result1.name, "/asset/path/");
        assert.equal(result2.path.toString(), "/account/path/");
        assert.equal(result2.recordType, "DATA");
        assert.equal(result2.name, "record:name");
    });

    it("parse ByteBuffer", function () {
        var result = RecordKey.parse(ByteBuffer.fromHex("2f6163636f756e742f706174682f3a4143433a2f61737365742f706174682f"));

        assert.equal(result.path.toString(), "/account/path/");
        assert.equal(result.recordType, "ACC");
        assert.equal(result.name, "/asset/path/");
    });

    it("parse invalid", function () {
        assert.throws(function () { RecordKey.parse("/account/path/:ACC"); }, Error);
    });
});


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NPCBiped : MonoBehaviour
{
  const float IdealWalkSpeed = 1f;
  const float IdealRunSpeed = 6f;

  [SerializeField] IBipedDriver driver;
  [SerializeField] bool ignoreLook = false;
  [SerializeField] float inputDampTime = 0.15f;

  // Full run animation is for 5m/s.
  // Full value is 1.
  [SerializeField] float throttleToInputScale = 1f / 5f;

  Animator animator;
  HeadLookController lookController;

  float heightFromGround;

  Vector3 dampedForward = Vector3.forward;
  Vector3 prevDampedThrottle = Vector3.zero;

  ////////////////////////////////////////////////////////////////////////////

  private void Awake()
  {
    animator = GetComponent<Animator>();
    lookController = GetComponent<HeadLookController>();

    if (driver == null)
    {
      SetDriver(GetComponentInParent<IBipedDriver>());
    }
  }

  public void SetDriver(IBipedDriver newDriver)
  {
    if (newDriver == driver) return;
    if (driver != null)
    {
      driver.onJump -= OnJump;
    }
    driver = newDriver;
    if (driver != null)
    {
      driver.onJump += OnJump;
    }
  }

  void OnEnable()
  {
  }

  void OnDisable()
  {
    SetDriver(null);
  }

  Vector3 DampDirection(Vector3 current, Vector3 target)
  {
    Quaternion fullRot = Quaternion.FromToRotation(current, target);
    // TODO make this dependent on deltaTime.
    Quaternion partialRot = Quaternion.Slerp(Quaternion.identity, fullRot, LerpForHalfLife(0.15f));
    return partialRot * current;
  }

  Vector3 DampHeading(Vector3 current, Vector3 target)
  {
    Debug.Assert(current.y == 0);
    Debug.Assert(target.y == 0);

    float degs = Vector2.SignedAngle(current.GetXZ(), target.GetXZ());
    // Debug.DrawRay(transform.position, prevMoveForward.AsXZVec(), Color.red, 0f, false);
    // Debug.DrawRay(transform.position, targetMove2.AsXZVec(), Color.green, 0f, false);
    // Debug.Log($"degs {degs}");
    float frameDegs = degs * LerpForHalfLife(0.14f);
    Quaternion xzRot = Quaternion.AngleAxis(-frameDegs, Vector3.up);
    return xzRot * current;
  }

  void DrawOffset(Vector3 offset, Color color)
  {
    Debug.DrawLine(transform.position, transform.position + offset, color, 0f, false);
  }

  ////////////////////////////////////////////////////////////////////////////

  // This is something I made up..essentially, if you just do a normal lerp
  // for throttle, it's kinda weird when you switch between backwards and
  // forwards and you're at an angle (so imagine with WASD controls, you have
  // W+A held, then you suddenly just have S held). When that kind of switch
  // happens, this lerp will first go through zero, effectively stopping the
  // legs animation for a bit, then continuing in the other direction.
  Vector3 ThroughZeroLerp(Vector3 a, Vector3 b, Vector3 forward, float t)
  {
    if (a.magnitude < 1e-4 || b.magnitude < 1e-4)
    {
      return Vector3.Lerp(a, b, t);
    }
    else if (Mathf.Sign(Vector3.Dot(forward, a)) == Mathf.Sign(Vector3.Dot(forward, b)))
    {
      // Both forward or both backward
      // Normal lerp
      return Vector3.Lerp(a, b, t);
    }
    else
    {
      // Go through zero first...
      float ma = a.magnitude;
      float mb = b.magnitude;
      float zt = ma / (ma + mb);
      if (t < zt)
      {
        return (1f - t / zt) * a;
      }
      else
      {
        return ((t - zt) / (1 - zt)) * b;
      }
    }
  }

  float LerpForHalfLife(float halfLife)
  {
    return 1f - Mathf.Pow(0.5f, Time.deltaTime / halfLife);
  }

  void Update()
  {
    if (driver == null || !driver.IsValid())
    {
      lookController.enabled = false;
      return;
    }

    // Damp any change to our root heading.
    dampedForward = DampHeading(dampedForward, driver.GetLookDirection().GetForwardHeading());
    transform.rotation = Quaternion.LookRotation(dampedForward, Vector3.up);
    Debug.Assert(Mathf.Abs(transform.forward.y) < 1e-4);

    // Damp throttle to avoid pops. See the comment for ThroughZeroLerp for
    // details.
    prevDampedThrottle = ThroughZeroLerp(prevDampedThrottle, driver.GetMoveThrottle(), transform.forward, LerpForHalfLife(0.1f));
    //TEMP
    prevDampedThrottle = driver.GetMoveThrottle();

    // This code gives the throttle *relative* to the look
    // direction. So if inputX is positive, then we're strafing right by
    // some amount. If we're just moving forward, inputX should be 0, and
    // inputY should be positive. If inputX is 0 and inputY is negative,
    // we're moving straight backward.
    Vector3 relThrottle = transform.InverseTransformDirection(prevDampedThrottle.normalized) * prevDampedThrottle.magnitude;
    float speed = relThrottle.magnitude;
    float blendMagnitude = 1f;
    if (speed < 4.0f)
    {
      Debug.Assert(speed < IdealRunSpeed);
      // Walking.
      blendMagnitude = 0.5f;
      animator.SetFloat("LocomotionSpeedScale", speed / IdealWalkSpeed);
    }
    else
    {
      // Running
      blendMagnitude = 1f;
      animator.SetFloat("LocomotionSpeedScale", speed / IdealRunSpeed);
    }
    Vector2 blendCoord = new Vector2(relThrottle.x, relThrottle.z).normalized * blendMagnitude;
    animator.SetFloat("InputX", blendCoord.x, inputDampTime, Time.deltaTime);
    animator.SetFloat("InputY", blendCoord.y, inputDampTime, Time.deltaTime);

    // calculate the distance to the ground (which is on it's own layer) and pass that info to the animator so we know how high up we are
    int layer_mask = LayerMask.GetMask("Ground");

    RaycastHit hit = new RaycastHit();
    if (Physics.Raycast(transform.position, -Vector3.up, out hit, layer_mask))
    {
      heightFromGround = hit.distance;
    }

    animator.SetFloat("HeightFromGround", heightFromGround);
    animator.SetBool("IsGrounded", driver.IsGrounded());

    if (!ignoreLook)
    {
      lookController.enabled = true;
      lookController.lookDirWorld = driver.GetLookDirection();
    }
    else
    {
      lookController.enabled = false;
    }

    DrawOffset(driver.GetLookDirection().GetForwardHeading(), Color.red);
    DrawOffset(driver.GetMoveThrottle(), Color.yellow);
    DrawOffset(prevDampedThrottle, Color.blue);
    DrawOffset(transform.forward, Color.green);
  }

  ////////////////////////////////////////////////////////////////////////////

  // if we're jumping, set the animator trigger
  void OnJump()
  {
    animator.SetTrigger("IsJumping");
  }

  ////////////////////////////////////////////////////////////////////////////
}


text:
namespace SDL2
{
	namespace Mixer
	{
		SoundEffect::SoundEffect()
		{
			mChunk = NULL;
		}

		SoundEffect::~SoundEffect()
		{
			Mix_FreeChunk(mChunk);
		}

		bool SoundEffect::Load(const char* pFilename)
		{
			mChunk = Mix_LoadWAV(pFilename);

			return mChunk != NULL;
		}

		bool SoundEffect::Load(Uint8* pMemory)
		{
			mChunk = Mix_QuickLoad_WAV(pMemory);

			return mChunk != NULL;
		}

		int SoundEffect::SetVolume(int pVolume)
		{
			if(pVolume < 0)
				pVolume = 0;

			if(pVolume > MIX_MAX_VOLUME)
				pVolume = MIX_MAX_VOLUME;

			return Mix_VolumeChunk(mChunk, pVolume);
		}
	}
}


text:
+++
title = "Update 0. Open Beta."
date = "2017-02-21T15:00:00+01:00"
tags = ["event","maintenance"]
categories = ["news"]
banner = "img/banners/roundbanner-nkinani_200px_spaced.jpg"
author = "nkinani"
+++

## Open Beta

Update 0.

---

#### Minors update :

* team now follow actual composition. *Maybe we should add phd affiliate ? Under a specific section ? or not ?*.

* team mate now have a pretty face, a correct role & branch/department/unit classification.

* corrected some error...

* add binding to disqus. It allow visitor to freely discuss around blog article.

#### Next update :

* finalize team mate board (picture + role)

* add labsim API key for Google Maps binding. (**[Contact](https://labsim.github.io/contact/)** section bug)

* generated LABSIM technical doc site + binding.

* personnal scienfic profile + procedure "HOW TO". Probably based on *[Academic Theme for HUGO](https://gcushen.github.io/hugo-academic-demo/)*.

* correct the other, yet undiscovered, error.

<br>*Cheers.*