text:
#ifndef _GDFONTG_H_
#define _GDFONTG_H_ 1

#ifdef __cplusplus
extern "C" {
#endif

#include "gd.h"

extern gdFontPtr gdFontGiant;
extern gdFontPtr gdFontGetGiant(void);

#ifdef __cplusplus
}
#endif

#endif


text:
#ifndef FOLLY_DETAIL_MALLOC_H
#define FOLLY_DETAIL_MALLOC_H

#include <stdlib.h>

#include <folly/Portability.h>

extern "C" {

#if FOLLY_HAVE_WEAK_SYMBOLS
void* mallocx(size_t, int) __attribute__((__weak__));
void* rallocx(void*, size_t, int) __attribute__((__weak__));
size_t xallocx(void*, size_t, size_t, int) __attribute__((__weak__));
size_t sallocx(const void*, int) __attribute__((__weak__));
void dallocx(void*, int) __attribute__((__weak__));
void sdallocx(void*, size_t, int) __attribute__((__weak__));
size_t nallocx(size_t, int) __attribute__((__weak__));
int mallctl(const char*, void*, size_t*, void*, size_t)
      __attribute__((__weak__));
int mallctlnametomib(const char*, size_t*, size_t*) __attribute__((__weak__));
int mallctlbymib(const size_t*, size_t, void*, size_t*, void*, size_t)
      __attribute__((__weak__));
#elif defined(_MSC_VER)
// MSVC doesn't have weak symbols, so do some linker magic
// to emulate them.
extern void* (*mallocx)(size_t, int);
extern const char* mallocxWeak = nullptr;
#pragma comment(linker, "/alternatename:_mallocx=_mallocxWeak")
extern void* (*rallocx)(void*, size_t, int);
extern const char* rallocxWeak = nullptr;
#pragma comment(linker, "/alternatename:_rallocx=_rallocxWeak")
extern size_t(*xallocx)(void*, size_t, size_t, int);
extern const char* xallocxWeak = nullptr;
#pragma comment(linker, "/alternatename:_xallocx=_xallocxWeak")
extern size_t(*sallocx)(const void*, int);
extern const char* sallocxWeak = nullptr;
#pragma comment(linker, "/alternatename:_sallocx=_sallocxWeak")
extern void(*dallocx)(void*, int);
extern const char* dallocxWeak = nullptr;
#pragma comment(linker, "/alternatename:_dallocx=_dallocxWeak")
extern void(*sdallocx)(void*, size_t, int);
extern const char* sdallocxWeak = nullptr;
#pragma comment(linker, "/alternatename:_sdallocx=_sdallocxWeak")
extern size_t(*nallocx)(size_t, int);
extern const char* nallocxWeak = nullptr;
#pragma comment(linker, "/alternatename:_nallocx=_nallocxWeak")
extern int(*mallctl)(const char*, void*, size_t*, void*, size_t);
extern const char* mallctlWeak = nullptr;
#pragma comment(linker, "/alternatename:_mallctl=_mallctlWeak")
extern int(*mallctlnametomib)(const char*, size_t*, size_t*);
extern const char* mallctlnametomibWeak = nullptr;
#pragma comment(linker, "/alternatename:_mallctlnametomib=_mallctlnametomibWeak")
extern int(*mallctlbymib)(const size_t*, size_t, void*, size_t*, void*, size_t);
extern const char* mallctlbymibWeak = nullptr;
#pragma comment(linker, "/alternatename:_mallctlbymib=_mallctlbymibWeak")
#else
extern void* (*mallocx)(size_t, int);
extern void* (*rallocx)(void*, size_t, int);
extern size_t (*xallocx)(void*, size_t, size_t, int);
extern size_t (*sallocx)(const void*, int);
extern void (*dallocx)(void*, int);
extern void (*sdallocx)(void*, size_t, int);
extern size_t (*nallocx)(size_t, int);
extern int (*mallctl)(const char*, void*, size_t*, void*, size_t);
extern int (*mallctlnametomib)(const char*, size_t*, size_t*);
extern int (*mallctlbymib)(const size_t*, size_t, void*, size_t*, void*,
                           size_t);
#endif

}

#endif

redpajama_set_name: RedPajamaGithub


text:
package org.ehcache.impl.internal.store.offheap;

import org.ehcache.config.EvictionAdvisor;
import org.ehcache.config.ResourcePools;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.core.internal.store.StoreConfigurationImpl;
import org.ehcache.config.SizedResourcePool;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.expiry.ExpiryPolicy;
import org.ehcache.impl.internal.events.TestStoreEventDispatcher;
import org.ehcache.core.spi.time.SystemTimeSource;
import org.ehcache.core.spi.time.TimeSource;
import org.ehcache.impl.serialization.JavaSerializer;
import org.ehcache.internal.store.StoreFactory;
import org.ehcache.internal.tier.AuthoritativeTierFactory;
import org.ehcache.internal.tier.AuthoritativeTierSPITest;
import org.ehcache.core.internal.service.ServiceLocator;
import org.ehcache.core.spi.store.Store;
import org.ehcache.core.spi.store.tiering.AuthoritativeTier;
import org.ehcache.spi.serialization.Serializer;
import org.ehcache.spi.service.ServiceConfiguration;
import org.junit.Before;

import java.util.Arrays;

import static org.ehcache.config.ResourceType.Core.OFFHEAP;
import static org.ehcache.core.internal.service.ServiceLocator.dependencySet;

/**
 * OffHeapStoreSPITest
 */
public class OffHeapStoreSPITest extends AuthoritativeTierSPITest<String, String> {

  private AuthoritativeTierFactory<String, String> authoritativeTierFactory;

  @Before
  public void setUp() {
    authoritativeTierFactory = new AuthoritativeTierFactory<String, String>() {
      @Override
      public AuthoritativeTier<String, String> newStore() {
        return newStore(null, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE);
      }

      @Override
      public AuthoritativeTier<String, String> newStoreWithCapacity(long capacity) {
        return newStore(capacity, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE);
      }

      @Override
      public AuthoritativeTier<String, String> newStoreWithExpiry(ExpiryPolicy<? super String, ? super String> expiry, TimeSource timeSource) {
        return newStore(null, null, expiry, timeSource);
      }

      @Override
      public AuthoritativeTier<String, String> newStoreWithEvictionAdvisor(EvictionAdvisor<String, String> evictionAdvisor) {
        return newStore(null, evictionAdvisor, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE);
      }

      private AuthoritativeTier<String, String> newStore(Long capacity, EvictionAdvisor<String, String> evictionAdvisor, ExpiryPolicy<? super String, ? super String> expiry, TimeSource timeSource) {
        Serializer<String> keySerializer = new JavaSerializer<>(getClass().getClassLoader());
        Serializer<String> valueSerializer = new JavaSerializer<>(getClass().getClassLoader());

        ResourcePools resourcePools = getOffHeapResourcePool(capacity);
        SizedResourcePool offheapPool = resourcePools.getPoolForResource(OFFHEAP);
        MemoryUnit unit = (MemoryUnit)offheapPool.getUnit();

        Store.Configuration<String, String> config = new StoreConfigurationImpl<>(getKeyType(), getValueType(),
          evictionAdvisor, getClass().getClassLoader(), expiry, resourcePools, 0, keySerializer, valueSerializer);
        OffHeapStore<String, String> store = new OffHeapStore<>(config, timeSource, new TestStoreEventDispatcher<>(), unit
          .toBytes(offheapPool.getSize()));
        OffHeapStore.Provider.init(store);
        return store;
      }

      private ResourcePools getOffHeapResourcePool(Comparable<Long> capacityConstraint) {
        if (capacityConstraint == null) {
          capacityConstraint = 10L;
        }
        return ResourcePoolsBuilder.newResourcePoolsBuilder().offheap((Long)capacityConstraint, MemoryUnit.MB).build();
      }

      @Override
      public Store.ValueHolder<String> newValueHolder(String value) {
        return new BasicOffHeapValueHolder<>(-1, value, SystemTimeSource.INSTANCE.getTimeMillis(), OffHeapValueHolder.NO_EXPIRE);
      }

      @Override
      public Class<String> getKeyType() {
        return String.class;
      }

      @Override
      public Class<String> getValueType() {
        return String.class;
      }

      @Override
      public ServiceConfiguration<?>[] getServiceConfigurations() {
        return new ServiceConfiguration<?>[0];
      }

      @Override
      public ServiceLocator getServiceProvider() {
        ServiceLocator serviceLocator = dependencySet().build();
        try {
          serviceLocator.startAllServices();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
        return serviceLocator;
      }

      @Override
      public String createKey(long seed) {
        return Long.toString(seed);
      }

      @Override
      public String createValue(long seed) {
        char[] chars = new char[600 * 1024];
        Arrays.fill(chars, (char) (0x1 + (seed & 0x7e)));
        return new String(chars);
      }

      @Override
      public void close(final Store<String, String> store) {
        OffHeapStore.Provider.close((OffHeapStore)store);
      }
    };
  }

  @Override
  protected AuthoritativeTierFactory<String, String> getAuthoritativeTierFactory() {
    return authoritativeTierFactory;
  }

  @Override
  protected StoreFactory<String, String> getStoreFactory() {
    return getAuthoritativeTierFactory();
  }

  public static void initStore(OffHeapStore<?, ?> offHeapStore) {
    OffHeapStore.Provider.init(offHeapStore);
  }

  public static void closeStore(OffHeapStore<?, ?> offHeapStore) {
    OffHeapStore.Provider.close(offHeapStore);
  }

}


text:
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using FluentFTP;

namespace Examples {
	internal static class ExecuteFTPCommandExample {

		public static void Execute() {
			using (var conn = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
				conn.Connect();

				FtpReply reply;
				if (!(reply = conn.Execute("SITE CHMOD 640 FOO.TXT")).Success) {
					throw new FtpCommandException(reply);
				}
			}
		}

		public static async Task ExecuteAsync() {
			var token = new CancellationToken();
			using (var conn = new AsyncFtpClient("127.0.0.1", "ftptest", "ftptest")) {
				await conn.Connect(token);

				FtpReply reply;
				if (!(reply = await conn.Execute("SITE CHMOD 640 FOO.TXT", token)).Success) {
					throw new FtpCommandException(reply);
				}
			}
		}

	}
}


text:
package expect

import "testing"

// BEG
func TestRun(t *testing.T) {
	expect := New(t)

	expect(nil).ToBeNil()
	expect("").ToNotBeNil()

	expect("test").ToHavePrefix("te")
	expect("test").ToHaveSuffix("st")
	expect("test").ToContain("es")
	expect("a").ToNotBeNil()
	expect("a").ToEqual("a")
	expect("a").ToNotEqual("b")

	expect(int64(1)).ToEqual(1)
	expect(1).ToEqual(1)

	expect("test").ToContain("es")

	arr := []string{"a", "b", "c"}
	expect(arr).ToHaveLength(3)
	expect(arr).ToContain("a")
}

// END


text:
/*
 * Project name: Pang Game
 * Version 1
 * Student : Albert Eduard Merino Pulido
 */
#ifndef ai_h
#define ai_h
#include <climits>
#include "pangScenario.h"
#include "constants.h"
#include "vector3.h"

class AI  {
public:
    AI();
    virtual bool computeMove(PangScenario * ps, PlayerID playerNumber, Action * move);
    virtual double heuristic(PangScenario * ps, PlayerID playerNumber);
    Ball * getBallPositionXClosest(PangScenario * ps, Character * character);
    bool isMoreClose(double mostDangerousBallDistance, double distance);
    void simulateMove(PangScenario * ps, float timeLimit);
    void resolve(PangScenario * ps, float t);
    void checkColBallPlaneVert(Ball * ball, Plane plane);
    void checkColCharPlaneVert(Character * character, Plane plane);
    void checkColBallPlaneHoriz(Ball * ball, Plane plane);
    void checkColBulletBall(PangScenario * ps, Ball * ball, Character * character, int i);
    void checkColBallBall(PangScenario * ps, Ball * ball, int i);
    void checkColBallBall(Ball * ball1, Ball * ball2);
    void checkColCharBall(Character * character, Ball * ball2);
    double getRandomTargetPosition();
private:
    double targetPosition;
    double tZero;
    double elapsedTime;
    double timeLimit;
    ParticleContact * colDetect;
    ColType colType;
    Character * chara;
    Ball * balli;
    int ballIndex;
};
#endif // ifndef ai_h


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Diagnostics;
using Accountants_Personal_Bookkeeper.DB;
using Accountants_Personal_Bookkeeper.Model;
using Accountants_Personal_Bookkeeper.ViewModel;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace Accountants_Personal_Bookkeeper.View
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class JournalTypeList : Page
    {
        List<JournalType> journalTypes;
        SQLite.Net.SQLiteConnection conn;
        JournalTypeViewModel viewModel;
        AccountViewModel accountVM;

        public JournalTypeList()
        {
            this.InitializeComponent();
            conn = new Connection().GetConnection();
            viewModel = new JournalTypeViewModel();
            journalTypes = viewModel.JournalTypeList();
            accountVM = new AccountViewModel();
        }

        private async void ViewJournalTypeButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int id = (Int32)((Button)sender).Tag;
                var journaltype = (from sub in conn.Table<JournalType>()
                                      where sub.id == id
                                      select sub
                                  ).First<JournalType>();
                string message = "Name : " + journaltype.name + "\nCode : " + journaltype.prefix + "\nStart NO : " + journaltype.start_number +
                    "\nDebit Account : " + accountVM.Get(journaltype.debit_account_id).name +
                    "\nCredit Account : " + accountVM.Get(journaltype.credit_account_id).name;

                var dialog = new Windows.UI.Popups.MessageDialog(message, journaltype.name);
                var result = await dialog.ShowAsync();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Processor Usage" + ex.Message);
            }
        }

        private void EditJournalTypeButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int id = (Int32)((Button)sender).Tag;
                var accountSubtype = viewModel.Get(id);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Processor Usage" + ex.Message);
            }
        }
    }
}


text:
load('sort.js');

new BenchmarkSuite('SortCustomCompareFnIntTypes', [1000],
                   CreateBenchmarks(typedArrayIntConstructors,
                                    [cmp_smaller, cmp_greater]));


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Bidaud, Moënne-Loccoz, Reumaux & Henry, Atlas des Cortinaires, Hors-Serie 1: 149 (1997)

#### Original name
Cortinarius milvinicolor Moënne-Locc. & Reumaux

### Remarks
null


text:
package com.google.gerrit.server.change;

import com.google.gerrit.common.errors.EmailException;
import com.google.gerrit.extensions.api.changes.CherryPickInput;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.extensions.webui.UiAction;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.change.ChangeJson.ChangeInfo;
import com.google.gerrit.server.git.MergeException;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.project.InvalidChangeOperationException;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.project.RefControl;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;

import java.io.IOException;

public class CherryPick implements RestModifyView<RevisionResource, CherryPickInput>,
    UiAction<RevisionResource> {
  private final Provider<ReviewDb> dbProvider;
  private final Provider<CherryPickChange> cherryPickChange;
  private final ChangeJson json;

  @Inject
  CherryPick(Provider<ReviewDb> dbProvider,
      Provider<CherryPickChange> cherryPickChange,
      ChangeJson json) {
    this.dbProvider = dbProvider;
    this.cherryPickChange = cherryPickChange;
    this.json = json;
  }

  @Override
  public ChangeInfo apply(RevisionResource revision, CherryPickInput input)
      throws AuthException, BadRequestException, ResourceConflictException,
      ResourceNotFoundException, OrmException, IOException, EmailException {
    final ChangeControl control = revision.getControl();

    if (input.message == null || input.message.trim().isEmpty()) {
      throw new BadRequestException("message must be non-empty");
    } else if (input.destination == null || input.destination.trim().isEmpty()) {
      throw new BadRequestException("destination must be non-empty");
    }

    ReviewDb db = dbProvider.get();
    if (!control.isVisible(db)) {
      throw new AuthException("Cherry pick not permitted");
    }

    String refName = input.destination;
    if (!refName.startsWith("refs/")) {
      refName = "refs/heads/" + input.destination;
    }

    RefControl refControl = control.getProjectControl().controlForRef(refName);
    if (!refControl.canUpload()) {
      throw new AuthException("Not allowed to cherry pick "
          + revision.getChange().getId().toString() + " to "
          + input.destination);
    }

    final PatchSet.Id patchSetId = revision.getPatchSet().getId();
    try {
      Change.Id cherryPickedChangeId = cherryPickChange.get().cherryPick(
          patchSetId, input.message,
          input.destination, refControl);
      return json.format(cherryPickedChangeId);
    } catch (InvalidChangeOperationException e) {
      throw new BadRequestException(e.getMessage());
    } catch (MergeException  e) {
      throw new ResourceConflictException(e.getMessage());
    } catch (NoSuchChangeException e) {
      throw new ResourceNotFoundException(e.getMessage());
    }
  }

  @Override
  public UiAction.Description getDescription(RevisionResource resource) {
    return new UiAction.Description()
      .setLabel("Cherry Pick")
      .setTitle("Cherry pick change to a different branch")
      .setVisible(resource.getControl().getProjectControl().canUpload());
  }
}


text:
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using XData.Data.Configuration;
using XData.Data.Element;
using XData.Data.Objects;
using XData.Data.Schema;

namespace XData.Data.Services
{
    public class UsersService
    {
        protected ElementContext ElementContext = ConfigurationCreator.CreateElementContext();

        private Database _database = null;
        protected Database Database
        {
            get
            {
                if (_database == null)
                {
                    _database = ElementContext.Database;
                }
                return _database;
            }
        }

        private ElementQuerier _elementQuerier = null;
        protected ElementQuerier ElementQuerier
        {
            get
            {
                if (_elementQuerier == null)
                {
                    _elementQuerier = new ElementQuerier(ElementContext);
                }
                return _elementQuerier;
            }
        }

        public void Create(int employeeId, string userName, bool isDisabled)
        {
            XElement databaseSchema = ElementContext.SchemaManager.PrimarySchemaObject.DatabaseSchema;
            string sql = "SELECT * FROM InitialPassword";
            IEnumerable<XElement> xInitials = Database.SqlQuery(databaseSchema, "InitialPassword", sql);
            int count = xInitials.Count();

            string password;
            string format;
            string algorithm;
            string salt;
            if (count == 0)
            {
                XElement elementSchema = databaseSchema.GetElementSchema("InitialPassword");
                XElement fieldSchema = elementSchema.Element("Password");
                XElement defaultSchema = fieldSchema.Element("DefaultValue");
                password = defaultSchema.Element("Value").Value;

                fieldSchema = elementSchema.Element("PasswordFormat");
                defaultSchema = fieldSchema.Element("DefaultValue");
                format = defaultSchema.Element("Value").Value;

                fieldSchema = elementSchema.Element("PasswordAlgorithm");
                defaultSchema = fieldSchema.Element("DefaultValue");
                algorithm = (defaultSchema == null) ? string.Empty : defaultSchema.Element("Value").Value;

                fieldSchema = elementSchema.Element("PasswordSalt");
                defaultSchema = fieldSchema.Element("DefaultValue");
                salt = (defaultSchema == null) ? string.Empty : defaultSchema.Element("Value").Value;
            }
            else
            {
                XElement xInitialPassword = xInitials.Elements().First();
                password = xInitialPassword.Element("Password").Value;
                format = xInitialPassword.Element("PasswordFormat").Value;
                algorithm = xInitialPassword.Element("PasswordAlgorithm").Value;
                salt = xInitialPassword.Element("PasswordSalt").Value;
            }

            if (Database is SqlDatabase)
            {
                sql = "SELECT MAX(Id) Id FROM Users";
                IEnumerable<XElement> xIds = Database.SqlQuery("User", sql);
                int id = int.Parse(xIds.First().Element("Id").Value) + 1;

                algorithm = string.IsNullOrWhiteSpace(algorithm) ? "null" : algorithm;
                salt = string.IsNullOrWhiteSpace(salt) ? "null" : salt;

                sql = @"
 INSERT INTO Users
 (Id, EmployeeId, UserName, LoweredUserName, Password, PasswordFormat, PasswordAlgorithm, PasswordSalt, IsDisabled)
 VALUES
 ({0}, {1}, @UserName, @LoweredUserName, '{2}', {3}, {4}, {5}, @IsDisabled)";
                sql = string.Format(sql, id, employeeId, password, format, algorithm, salt);

                DbParameter[] parameters = new DbParameter[2];
                parameters[0] = Database.CreateDbParameter("@UserName", userName);
                parameters[1] = Database.CreateDbParameter("@LoweredUserName", userName.ToLower());
                parameters[2] = Database.CreateDbParameter("@IsDisabled", isDisabled);

                int i = Database.ExecuteSqlCommand(sql, parameters);
                return;
            }

            string typeName = Database.GetType().FullName;
            if (typeName == "XData.Data.Objects.OracleDatabase")
            {
                sql = "SELECT MAX(Id) Id FROM Users";
                IEnumerable<XElement> xIds = Database.SqlQuery("User", sql);
                int id = int.Parse(xIds.First().Element("Id").Value) + 1;

                sql = @"
 INSERT INTO Users
 (Id, EmployeeId, UserName, LoweredUserName, Password, PasswordFormat, PasswordAlgorithm, PasswordSalt, IsDisabled)
 VALUES
 (:Id, :EmployeeId, :UserName, :LoweredUserName, :Password, :Format, :Algorithm, :Salt, :IsDisabled)";

                DbParameter[] parameters = new DbParameter[8];
                parameters[0] = Database.CreateDbParameter(":Id", id);
                parameters[1] = Database.CreateDbParameter(":EmployeeId", employeeId);
                parameters[2] = Database.CreateDbParameter(":UserName", userName);
                parameters[3] = Database.CreateDbParameter(":LoweredUserName", userName.ToLower());
                parameters[4] = Database.CreateDbParameter(":Password", password);
                parameters[5] = Database.CreateDbParameter(":Format", int.Parse(format));
                parameters[6] = Database.CreateDbParameter(":IsDisabled", isDisabled ? 1 : 0);

                if (string.IsNullOrWhiteSpace(algorithm))
                {
                    parameters[6] = Database.CreateDbParameter(":Algorithm", DBNull.Value);
                }
                else
                {
                    parameters[6] = Database.CreateDbParameter(":Algorithm", Guid.Parse(algorithm));
                }
                if (string.IsNullOrWhiteSpace(salt))
                {
                    parameters[7] = Database.CreateDbParameter(":Salt", DBNull.Value);
                }
                else
                {
                    parameters[7] = Database.CreateDbParameter(":Salt", salt);
                }

                int i = Database.ExecuteSqlCommand(sql, parameters);
                return;
            }

            throw new NotSupportedException(typeName);
        }

        public void SetPassword(int id, string newPassword)
        {
            AccountService.SetPassword(id, newPassword, Database);
        }

        public bool ValidatePassword(string password, out string errorMessage)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                errorMessage = "The new password is required and cannot be empty.";
                return false;
            }
            if (password.Length < 6 || password.Length > 20)
            {
                errorMessage = "The password must be at least 6 and not more than 20 characters long.";
                return false;
            }

            errorMessage = null;
            return true;
        }

        public void SetUserName(int id, string newUserName)
        {
            if (Database is SqlDatabase)
            {
                string sql = string.Format("UPDATE Users SET UserName = @UserName, LoweredUserName = @LoweredUserName WHERE Id = {0}", id);
                DbParameter parameter1 = Database.CreateDbParameter("@UserName", newUserName);
                DbParameter parameter2 = Database.CreateDbParameter("@LoweredUserName", newUserName.ToLower());
                int i = Database.ExecuteSqlCommand(sql, parameter1, parameter2);
                return;
            }

            string typeName = Database.GetType().FullName;
            if (typeName == "XData.Data.Objects.OracleDatabase")
            {
                string sql = string.Format("UPDATE Users SET UserName = :UserName, LoweredUserName = :LoweredUserName WHERE Id = {0}", id);
                DbParameter parameter1 = Database.CreateDbParameter(":UserName", newUserName);
                DbParameter parameter2 = Database.CreateDbParameter(":LoweredUserName", newUserName.ToLower());
                int i = Database.ExecuteSqlCommand(sql, parameter1, parameter2);
                return;
            }

            throw new NotSupportedException(typeName);
        }

        public void Enable(int id)
        {
            string sql = string.Format("UPDATE Users SET IsDisabled = 0 WHERE Id = {0} AND IsDisabled = 1", id);
            int i = Database.ExecuteSqlCommand(sql);
        }

        public void Disable(int id)
        {
            string sql = string.Format("UPDATE Users SET IsDisabled = 1 WHERE Id = {0} AND IsDisabled = 0", id);
            int i = Database.ExecuteSqlCommand(sql);
        }

        public void Unlock(int id)
        {
            string sql = string.Format("UPDATE Users SET IsLockedOut = 0, FailedPasswordAttemptCount = 0 WHERE Id = {0} AND IsLockedOut = 1", id);
            int i = Database.ExecuteSqlCommand(sql);
        }

        public void GrantRoles(int id, string roleIds)
        {
            XElement element = new XElement("User");
            element.SetElementValue("Id", id);
            XElement xRoles = new XElement("Roles");
            element.Add(xRoles);

            if (!string.IsNullOrWhiteSpace(roleIds))
            {
                string[] roles = roleIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string role in roles)
                {
                    XElement xRole = new XElement("Role");
                    xRole.SetElementValue("Id", role);
                    xRoles.Add(xRole);
                }
            }

            ElementContext.Update(element);
        }

        public void SetInitialPassword(string initialPassword)
        {
            int format;
            Guid algorithm;
            string salt;
            string encrypted = AccountService.Encrypt(initialPassword, out format, out algorithm, out salt);

            string sql = "SELECT * FROM InitialPassword";
            IEnumerable<XElement> result = Database.SqlQuery(ElementContext.SchemaManager.PrimarySchemaObject.DatabaseSchema, "InitialPassword", sql);
            int count = result.Count();

            if (Database is SqlDatabase)
            {
                if (count == 0)
                {
                    sql = "INSERT INTO InitialPassword (Password, PasswordFormat, PasswordAlgorithm, PasswordSalt) VALUES (@Password, @Format, @Algorithm, @Salt)";
                }
                else
                {
                    sql = "UPDATE InitialPassword SET Password = @Password, PasswordFormat = @Format, PasswordAlgorithm = @Algorithm, PasswordSalt = @Salt";
                }
                DbParameter[] parameters = new DbParameter[4];
                parameters[0] = Database.CreateDbParameter("@Password", encrypted);
                parameters[1] = Database.CreateDbParameter("@Format", format);
                if (algorithm == null)
                {
                    parameters[2] = Database.CreateDbParameter("@Algorithm", DBNull.Value);
                }
                else
                {
                    parameters[2] = Database.CreateDbParameter("@Algorithm", algorithm);
                }
                if (string.IsNullOrWhiteSpace(salt))
                {
                    parameters[3] = Database.CreateDbParameter("@Salt", DBNull.Value);
                }
                else
                {
                    parameters[3] = Database.CreateDbParameter("@Salt", salt);
                }

                int i = Database.ExecuteSqlCommand(sql, parameters);
                return;
            }

            string typeName = Database.GetType().FullName;
            if (typeName == "XData.Data.Objects.OracleDatabase")
            {
                if (count == 0)
                {
                    sql = "INSERT INTO InitialPassword (Password, PasswordFormat, PasswordAlgorithm, PasswordSalt) VALUES (:Password, :Format, :Algorithm, :Salt)";
                }
                else
                {
                    sql = "UPDATE InitialPassword SET Password = :Password, PasswordFormat = :Format, PasswordAlgorithm = :Algorithm, PasswordSalt = :Salt";
                }
                DbParameter[] parameters = new DbParameter[4];
                parameters[0] = Database.CreateDbParameter(":Password", encrypted);
                parameters[1] = Database.CreateDbParameter(":Format", format);
                if (algorithm == null)
                {
                    parameters[2] = Database.CreateDbParameter(":Algorithm", DBNull.Value);
                }
                else
                {
                    parameters[2] = Database.CreateDbParameter(":Algorithm", algorithm);
                }
                if (string.IsNullOrWhiteSpace(salt))
                {
                    parameters[3] = Database.CreateDbParameter(":Salt", DBNull.Value);
                }
                else
                {
                    parameters[3] = Database.CreateDbParameter(":Salt", salt);
                }

                int i = Database.ExecuteSqlCommand(sql, parameters);
                return;
            }

            throw new NotSupportedException(typeName);
        }

        public bool IsUniqueUserNameByReferrer(string userName, string referrer)
        {
            bool isUnique = false;

            // .../Admin/Users/SetUserName/1 // .../Admin/Users/Create
            string[] ss = referrer.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (ss[ss.Length - 2] == "SetUserName" && ss[ss.Length - 3] == "Users" && ss[ss.Length - 4] == "Admin")
            {
                string id = ss[ss.Length - 1];
                isUnique = IsUniqueUserName(userName, id);
            }
            else if (ss[ss.Length - 1] == "Create" && ss[ss.Length - 2] == "Users" && ss[ss.Length - 3] == "Admin")
            {
                isUnique = IsUniqueUserName(userName);
            }

            return isUnique;
        }

        public bool IsUniqueUserName(string userName)
        {
            return ElementQuerier.IsUnique("User", string.Format("LoweredUserName eq '{0}'", userName.ToLower()), ElementContext.PrimarySchema);
        }

        public bool IsUniqueUserName(string userName, string id)
        {
            return ElementQuerier.IsUnique("User", string.Format("LoweredUserName eq '{0}'", userName.ToLower()), id, ElementContext.PrimarySchema);
        }

        public void Update(XElement element)
        {
            ElementContext.Update(element);
        }

        public XElement GetUser(string userName)
        {
            DbParameter parameter;
            string sql = GetUserSql(userName, out parameter);
            IEnumerable<XElement> result = Database.SqlQuery("User", sql, parameter);
            return result.First();
        }

        protected string GetUserSql(string userName, out DbParameter parameter)
        {
            if (Database is SqlDatabase) // XData.Data.Objects.SqlDatabase
            {
                string sql =
@"SELECT Id, EmployeeId, UserName, IsDisabled, IsLockedOut FROM Users WHERE LoweredUserName = @LoweredUserName";

                parameter = Database.CreateDbParameter("@LoweredUserName", userName);
                return sql;
            }

            string typeName = Database.GetType().FullName;
            if (typeName == "XData.Data.Objects.OracleDatabase")
            {
                string sql =
@"SELECT Id, EmployeeId, UserName, IsDisabled, IsLockedOut FROM Users WHERE LoweredUserName = :LoweredUserName";

                parameter = Database.CreateDbParameter(":LoweredUserName", userName.ToLower());
                return sql;
            }

            throw new NotSupportedException(typeName);
        }

    }
}


text:
<?xml version="1.0"?>
<cart>
  <add key="SiteURL" value="http://website.eonic.co.uk" />
  <add key="SecureURL" value="http://website.eonic.co.uk" />
  <!-- settings -->
  <add key="MerchantName" value="Website" />
  <add key="MerchantEmail" value="sales@eonic.co.uk" />
  <add key="TaxRate" value="0" />
  <add key="VatAtUnit" value="yes" />
  <add key="OrderNoPrefix" value="REF-" />
  <add key="CurrencySymbol" value="£" />
  <add key="StockControl" value="off" />
  <add key="TermsAndConditions" value="t's and c's" />
  <add key="TermsContentId" value="1"/>
  <add key="Deposit" value="0" />
  <add key="DepositAmount" value="0" />
  <add key="Discounts" value="off" />
  <add key="PriceModOrder" value="" />
  <add key="AddBehaviour" value=""/>
  <add key="ClearOnAdd" value="off"/>
  <add key="PriorityCountries" value="" />
  <add key="SavePayments" value="off" />
  <!-- forms -->
  <add key="NotesXForm" value="" />
  <add key="BillingAddressXForm" value="" />
  <add key="DeliveryAddressXForm" value="" />
  <add key="NoDeliveryAddress" value="off" />
  <!-- emails -->
  <add key="OrderEmailSubject" value="Web order" />
  <add key="MerchantEmailTemplatePath" value="\xsl\Cart\mailOrderMerchant.xsl" />
  <add key="CustomerEmailTemplatePath" value="\xsl\Cart\mailOrderCustomer.xsl"/>
</cart>


text:
using LibNoise;
using LibNoise.Generator;
using System;
using Microsoft.Xna.Framework;
using ProceduralQuadSphere.KSP;

namespace ProceduralQuadSphere
{
    /// <summary>
    /// A mod that applies a noise on top of the output of a float curve
    /// </summary>
    /// <seealso cref="PQSMod" />
    public class PQSMod_VertexHeightNoiseVertHeightCurve2 : PQSMod
    {
        /// <summary>
        /// The float curve
        /// </summary>
        public Curve simplexCurve;

        /// <summary>
        /// The resulting Simplex
        /// </summary>
        private Simplex simplex;

        /// <summary>
        /// The resulting ridged noises
        /// </summary>
        private RidgedMultifractal ridgedAdd;
        private RidgedMultifractal ridgedSub;

        #region Noise Values
        public Single deformity;
        public Double simplexHeightStart;
        public Double simplexHeightEnd;
        public Int32 simplexSeed;
        public Double simplexOctaves;
        public Double simplexPersistence;
        public Double simplexFrequency;
        public Int32 ridgedAddSeed;
        public Single ridgedAddFrequency;
        public Single ridgedAddLacunarity;
        public Int32 ridgedAddOctaves;
        public Int32 ridgedSubSeed;
        public Single ridgedSubFrequency;
        public Single ridgedSubLacunarity;
        public Int32 ridgedSubOctaves;
        public QualityMode ridgedMode;
        #endregion

        /// <summary>
        /// Gets the maximum height of the mod.
        /// </summary>
        public override Double GetVertexMaxHeight()
        {
            return deformity;
        }

        /// <summary>
        /// Gets the minimum height of the mod.
        /// </summary>
        public override Double GetVertexMinHeight()
        {
            return 0;
        }

        /// <summary>
        /// Initializes the base mod
        /// </summary>
        public override void OnSetup()
        {
            ridgedAdd = new RidgedMultifractal(ridgedAddFrequency, ridgedAddLacunarity, ridgedAddOctaves, ridgedAddSeed, ridgedMode);
            ridgedSub = new RidgedMultifractal(ridgedSubFrequency, ridgedSubLacunarity, ridgedSubOctaves, ridgedSubSeed, ridgedMode);
            simplex = new Simplex(simplexSeed, simplexOctaves, simplexPersistence, simplexFrequency);
        }

        /// <summary>
        /// Called when the parent sphere builds it's height
        /// </summary>
        public override void OnVertexBuildHeight(VertexBuildData data)
        {
            Double h = data.vertHeight - sphere.radiusMin;
            Single t;
            if (h <= this.simplexHeightStart)
                t = 0f;
            else if (h < simplexHeightEnd)
                t = (Single)((h - simplexHeightStart) * (1 / (simplexHeightEnd - simplexHeightStart)));
            else
                t = 1f;
            Double s = simplex.noiseNormalized(data.directionFromCenter) * simplexCurve.Evaluate(t);
            if (s == 0f)
                return;
            Double r = ridgedAdd.GetValue(data.directionFromCenter) - ridgedSub.GetValue(data.directionFromCenter);
            if (r < -1)
                r = -1;
            if (r > 1)
                r = 1;
            data.vertHeight += (r + 1) * 0.5 * deformity * s;
        }

        public enum NoiseType
        {
            Perlin,
            RiggedMultifractal,
            Billow
        }
    }
}


text:
describe('Font Method TEST', function() {

    describe('Font.prototype.getSize', function() {

        it('should return "16px"', function() {
            var font = new Font('Helvetica', 'italic', '16px');

            expect(font.getSize()).toEqual('16px');
        });

    });

});


text:
"""Observable base class for iterables."""

class ObservableMixin(object):
  """An observable iterable.

  Subclasses need to call self.notify_observers with any object yielded.
  """

  def __init__(self):
    self.observers = []

  def register_observer(self, callback):
    self.observers.append(callback)

  def notify_observers(self, value, **kwargs):
    # self.observers is almost always empty
    if self.observers:
      for o in self.observers:
        o(value, **kwargs)


text:
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package com.tunnelvisionlabs.util.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

/**
 *
Copied from Microsoft/vs-threading@14f77875.

 */
public class AsyncQueueTest extends TestBase {
	private final AsyncQueue<GenericParameterHelper> queue = new AsyncQueue<>();

	@Test
	public void testJustInitialized() {
		Assert.assertEquals(0, queue.size());
		Assert.assertTrue(queue.isEmpty());
		Assert.assertFalse(queue.getFuture().isDone());
	}

	@Test
	public void testAdd() {
		GenericParameterHelper value = new GenericParameterHelper(1);
		queue.add(value);
		Assert.assertEquals(1, queue.size());
		Assert.assertFalse(queue.isEmpty());
	}

	@Test
	public void testTryAdd() {
		GenericParameterHelper value = new GenericParameterHelper(1);
		Assert.assertTrue(queue.tryAdd(value));
		Assert.assertEquals(1, queue.size());
		Assert.assertFalse(queue.isEmpty());
	}

	@Test
	public void testPeekReturnsNullOnEmptyQueue() {
		Assert.assertNull(queue.peek());
	}

//        [Fact]
//        public void TryPeek()
//        {
//            GenericParameterHelper value;
//            Assert.False(this.queue.TryPeek(out value));
//            Assert.Null(value);
//
//            var enqueuedValue = new GenericParameterHelper(1);
//            this.queue.Enqueue(enqueuedValue);
//            GenericParameterHelper peekedValue;
//            Assert.True(this.queue.TryPeek(out peekedValue));
//            Assert.Same(enqueuedValue, peekedValue);
//        }

	@Test
	public void testPeek() {
		GenericParameterHelper addedValue = new GenericParameterHelper(1);
		queue.add(addedValue);
		GenericParameterHelper peekedValue = queue.peek();
		Assert.assertSame(addedValue, peekedValue);

		// Peeking again should yield the same result.
		peekedValue = queue.peek();
		Assert.assertSame(addedValue, peekedValue);

		// Adding another element shouldn't change the peeked value.
		GenericParameterHelper secondValue = new GenericParameterHelper(2);
		queue.add(secondValue);
		peekedValue = queue.peek();
		Assert.assertSame(addedValue, peekedValue);

		GenericParameterHelper polledValue = queue.poll();
		Assert.assertNotNull(polledValue);
		Assert.assertSame(addedValue, polledValue);

		peekedValue = this.queue.peek();
		Assert.assertSame(secondValue, peekedValue);
	}

	@Test
	public void testPollAsyncCompletesSynchronouslyForNonEmptyQueue() {
		GenericParameterHelper addedValue = new GenericParameterHelper(1);
		queue.add(addedValue);
		CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync();
		Assert.assertTrue(pollFuture.isDone());

		CompletableFuture<Void> future = Async.awaitAsync(
			pollFuture,
			polledValue -> {
				Assert.assertSame(addedValue, polledValue);
				Assert.assertEquals(0, queue.size());
				Assert.assertTrue(queue.isEmpty());
				return Futures.completedNull();
			});

		future.join();
	}

	@Test
	public void testPollAsyncNonBlockingWait() {
		CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync();
		Assert.assertFalse(pollFuture.isDone());

		GenericParameterHelper addedValue = new GenericParameterHelper(1);
		queue.add(addedValue);

		CompletableFuture<Void> future = Async.awaitAsync(
			pollFuture,
			polledValue -> {
				Assert.assertSame(addedValue, polledValue);

				Assert.assertEquals(0, queue.size());
				Assert.assertTrue(queue.isEmpty());
				return Futures.completedNull();
			});
		future.join();
	}

	@Test
	public void testPollAsyncCancelledBeforeComplete() {
		CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync();
		Assert.assertFalse(pollFuture.isDone());

		Assert.assertTrue(pollFuture.cancel(true));

		try {
			thrown.expect(CancellationException.class);
			pollFuture.join();
		} finally {
			GenericParameterHelper addedValue = new GenericParameterHelper(1);
			queue.add(addedValue);

			Assert.assertEquals(1, this.queue.size());
		}
	}

	@Test
	public void testPollAsyncCancelledTokenBeforeComplete() {
		CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
		CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync(cancellationTokenSource.getToken());
		Assert.assertFalse(pollFuture.isDone());

		cancellationTokenSource.cancel();

		try {
			thrown.expect(CancellationException.class);
			pollFuture.join();
		} finally {
			GenericParameterHelper addedValue = new GenericParameterHelper(1);
			queue.add(addedValue);

			Assert.assertEquals(1, this.queue.size());
		}
	}

	@Test
	public void testPollAsyncPrecancelled() {
		CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
		cancellationTokenSource.cancel();
		CompletableFuture<GenericParameterHelper> dequeueTask = queue.pollAsync(cancellationTokenSource.getToken());
		Assert.assertTrue(dequeueTask.isDone());
		CompletableFuture<Void> asyncTest = Async.awaitAsync(
			AsyncAssert.assertCancelsAsync(() -> dequeueTask),
			() -> {
				GenericParameterHelper enqueuedValue = new GenericParameterHelper(1);
				this.queue.add(enqueuedValue);

				Assert.assertEquals(1, this.queue.size());
				return Futures.completedNull();
			});

		asyncTest.join();
	}

	@Test
	public void testPollAsyncCancelledAfterComplete() {
		CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync();
		Assert.assertFalse(pollFuture.isDone());

		GenericParameterHelper addedValue = new GenericParameterHelper(1);
		queue.add(addedValue);

		Assert.assertFalse(pollFuture.cancel(true));

		CompletableFuture<Void> asyncTest = Async.awaitAsync(
			pollFuture,
			polledValue -> {
				Assert.assertTrue(queue.isEmpty());
				Assert.assertSame(addedValue, polledValue);
				return Futures.completedNull();
			});

		asyncTest.join();
	}

	@Test
	public void testMultiplePollers() {
		List<CompletableFuture<GenericParameterHelper>> pollers = new ArrayList<>();
		for (int i = 0; i < 5; i++) {
			pollers.add(queue.pollAsync());
		}

		for (int i = 0; i < pollers.size(); i++) {
			long completedCount = pollers.stream().filter(CompletableFuture::isDone).count();
			Assert.assertEquals(i, completedCount);
			queue.add(new GenericParameterHelper(i));
		}

		for (int i = 0; i < pollers.size(); i++) {
			final int index = i;
			Assert.assertTrue(pollers.stream().anyMatch(d -> d.join().getData() == index));
		}
	}

	@Test
	public void testMultiplePollersCancelled() {
		List<CompletableFuture<GenericParameterHelper>> pollers = new ArrayList<>();
		for (int i = 0; i < 5; i++) {
			pollers.add(queue.pollAsync());
		}

		// cancel some of them
		for (int i = 0; i < pollers.size(); i += 2) {
			pollers.get(i).cancel(true);
		}

		for (int i = 0; i < pollers.size(); i++) {
			Assert.assertEquals(i % 2 == 0, pollers.get(i).isCancelled());

			if (!pollers.get(i).isCancelled()) {
				this.queue.add(new GenericParameterHelper(i));
			}
		}

		Assert.assertTrue(pollers.stream().allMatch(CompletableFuture::isDone));
	}

	@Test
	public void testMultiplePollersCancelledToken() {
		CancellationTokenSource[] cancellationTokenSources = new CancellationTokenSource[2];
		for (int i = 0; i < cancellationTokenSources.length; i++) {
			cancellationTokenSources[i] = new CancellationTokenSource();
		}

		List<CompletableFuture<GenericParameterHelper>> pollers = new ArrayList<>();
		for (int i = 0; i < 5; i++) {
			pollers.add(queue.pollAsync(cancellationTokenSources[i % 2].getToken()));
		}

		// cancel some of them
		cancellationTokenSources[0].cancel();

		for (int i = 0; i < pollers.size(); i++) {
			Assert.assertEquals(i % 2 == 0, pollers.get(i).isCancelled());

			if (!pollers.get(i).isCancelled()) {
				this.queue.add(new GenericParameterHelper(i));
			}
		}

		Assert.assertTrue(pollers.stream().allMatch(CompletableFuture::isDone));
	}

	@Test
	public void testPoll() {
		GenericParameterHelper addedValue = new GenericParameterHelper(1);
		queue.add(addedValue);
		GenericParameterHelper polledValue = queue.poll();
		Assert.assertNotNull(polledValue);
		Assert.assertSame(addedValue, polledValue);
		Assert.assertEquals(0, queue.size());
		Assert.assertTrue(queue.isEmpty());

		polledValue = queue.poll();
		Assert.assertNull(polledValue);
		Assert.assertEquals(0, queue.size());
		Assert.assertTrue(queue.isEmpty());
	}

	@Test
	public void testComplete() {
		queue.complete();
		Assert.assertTrue(queue.getFuture().isDone());
	}

	@Test
	public void testCompleteThenPollAsync() {
		GenericParameterHelper enqueuedValue = new GenericParameterHelper(1);
		queue.add(enqueuedValue);
		queue.complete();
		Assert.assertFalse(queue.getFuture().isDone());

		CompletableFuture<Void> asyncTest = Async.awaitAsync(
			queue.pollAsync(),
			dequeuedValue -> {
				Assert.assertSame(enqueuedValue, dequeuedValue);
				Assert.assertTrue(queue.getFuture().isDone());
				return Futures.completedNull();
			});

		asyncTest.join();
	}

	@Test
	public void testCompleteThenPoll() {
		GenericParameterHelper enqueuedValue = new GenericParameterHelper(1);
		queue.add(enqueuedValue);
		queue.complete();
		Assert.assertFalse(queue.getFuture().isDone());

		GenericParameterHelper dequeuedValue = queue.poll();
		Assert.assertNotNull(dequeuedValue);
		Assert.assertSame(enqueuedValue, dequeuedValue);
		Assert.assertTrue(queue.getFuture().isDone());
	}

	@Test
	public void testCompleteWhilePollersWaiting() {
		CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync();
		queue.complete();
		Assert.assertTrue(queue.getFuture().isDone());
		Assert.assertTrue(pollFuture.isCancelled());
	}

	@Test
	public void testCompletedQueueRejectsAdd() {
		queue.complete();

		try {
			thrown.expect(IllegalStateException.class);
			queue.add(new GenericParameterHelper(1));
		} finally {
			Assert.assertTrue(queue.isEmpty());
		}
	}

	@Test
	public void testCompletedQueueRejectsTryAdd() {
		queue.complete();
		Assert.assertFalse(queue.tryAdd(new GenericParameterHelper(1)));
		Assert.assertTrue(queue.isEmpty());
	}

//        [Fact]
//        public void DequeueCancellationAndCompletionStress()
//        {
//            var queue = new AsyncQueue<GenericParameterHelper>();
//            queue.Complete();
//
//            // This scenario was proven to cause a deadlock before a bug was fixed.
//            // This scenario should remain to protect against regressions.
//            int iterations = 0;
//            var stopwatch = Stopwatch.StartNew();
//            while (stopwatch.ElapsedMilliseconds < TestTimeout / 2)
//            {
//                var cts = new CancellationTokenSource();
//                using (var barrier = new Barrier(2))
//                {
//                    var otherThread = Task.Run(delegate
//                    {
//                        barrier.SignalAndWait();
//                        queue.DequeueAsync(cts.Token);
//                        barrier.SignalAndWait();
//                    });
//
//                    barrier.SignalAndWait();
//                    cts.Cancel();
//                    barrier.SignalAndWait();
//
//                    otherThread.Wait();
//                }
//
//                iterations++;
//            }
//
//            this.Logger.WriteLine("Iterations: {0}", iterations);
//        }

	@Test
	public void testNoLockHeldForCancellationContinuation() {
		CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync();
		CompletableFuture<Void> handled = pollFuture.handle((result, exception) -> {
			try {
				ForkJoinPool.commonPool().submit(ExecutionContext.wrap(() -> {
					// Add presumably requires a private lock internally.
					// Since we're calling it on a different thread than the
					// blocking cancellation continuation, this should deadlock
					// if and only if the queue is holding a lock while invoking
					// our cancellation continuation (which they shouldn't be doing).
					queue.add(new GenericParameterHelper(1));
				})).get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
				return null;
			} catch (InterruptedException | ExecutionException | TimeoutException ex) {
				throw new CompletionException(ex);
			}
		});

		pollFuture.cancel(true);

		handled.join();
		Assert.assertEquals(1, queue.size());
	}

	@Test
	public void testNoLockHeldForCancellationTokenContinuation() {
		CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
		CompletableFuture<GenericParameterHelper> pollFuture = queue.pollAsync(cancellationTokenSource.getToken());
		CompletableFuture<Void> handled = pollFuture.handle((result, exception) -> {
			try {
				ForkJoinPool.commonPool().submit(ExecutionContext.wrap(() -> {
					// Add presumably requires a private lock internally.
					// Since we're calling it on a different thread than the
					// blocking cancellation continuation, this should deadlock
					// if and only if the queue is holding a lock while invoking
					// our cancellation continuation (which they shouldn't be doing).
					queue.add(new GenericParameterHelper(1));
				})).get(ASYNC_DELAY.toMillis(), TimeUnit.MILLISECONDS);
				return null;
			} catch (InterruptedException | ExecutionException | TimeoutException ex) {
				throw new CompletionException(ex);
			}
		});

		cancellationTokenSource.cancel();

		handled.join();
		Assert.assertEquals(1, queue.size());
	}

	@Test
	public void testOnAddedNotAlreadyDispatched() {
		DerivedQueue<Integer> queue = new DerivedQueue<>();
		AtomicBoolean callbackFired = new AtomicBoolean(false);
		queue.onAddedHandler = (value, alreadyDispatched) -> {
			Assert.assertEquals(5, (int)value);
			Assert.assertFalse(alreadyDispatched);
			callbackFired.set(true);
		};

		queue.add(5);
		Assert.assertTrue(callbackFired.get());
	}

	@Test
	public void testOnAddedAlreadyDispatched() {
		DerivedQueue<Integer> queue = new DerivedQueue<>();
		AtomicBoolean callbackFired = new AtomicBoolean(false);
		queue.onAddedHandler = (value, alreadyDispatched) -> {
			Assert.assertEquals(5, (int)value);
			Assert.assertTrue(alreadyDispatched);
			callbackFired.set(true);
		};

		CompletableFuture<Integer> poller = queue.pollAsync();
		queue.add(5);
		Assert.assertTrue(callbackFired.get());
		Assert.assertTrue(poller.isDone());
	}

	@Test
	public void testOnPolled() {
		DerivedQueue<Integer> queue = new DerivedQueue<>();
		AtomicBoolean callbackFired = new AtomicBoolean(false);
		queue.onPolledHandler = value -> {
			Assert.assertEquals(5, (int)value);
			callbackFired.set(true);
		};

		queue.add(5);
		Integer polledValue = queue.poll();
		Assert.assertNotNull(polledValue);
		Assert.assertTrue(callbackFired.get());
	}

	@Test
	public void testOnCompletedInvoked() {
		DerivedQueue<GenericParameterHelper> queue = new DerivedQueue<>();
		AtomicInteger invoked = new AtomicInteger(0);
		queue.onCompletedHandler = invoked::incrementAndGet;
		queue.complete();
		Assert.assertEquals(1, invoked.get());

		// Call it again to make sure it's only invoked once.
		queue.complete();
		Assert.assertEquals(1, invoked.get());
	}

	//[Fact, Trait("GC", "true"), Trait("TestCategory", "FailsInCloudTest")]
	@Test
	@Ignore("GC test is unreliable")
	public void testUnusedQueueGCPressure() {
		checkGCPressure(() -> {
			AsyncQueue<GenericParameterHelper> queue = new AsyncQueue<>();
			queue.complete();
			Assert.assertTrue(queue.isCompleted());
		},
			/*maxBytesAllocated:*/ 80); // NOTE: .NET has this at 81
	}

	private static class DerivedQueue<T> extends AsyncQueue<T> {

		BiConsumer<T, Boolean> onAddedHandler;
		Runnable onCompletedHandler;
		Consumer<T> onPolledHandler;

		@Override
		protected void onAdded(T value, boolean alreadyDispatched) {
			super.onAdded(value, alreadyDispatched);

			if (onAddedHandler != null) {
				onAddedHandler.accept(value, alreadyDispatched);
			}
		}

		@Override
		protected void onPolled(T value) {
			super.onPolled(value);

			if (onPolledHandler != null) {
				onPolledHandler.accept(value);
			}
		}

		@Override
		protected void onCompleted() {
			super.onCompleted();

			if (onCompletedHandler != null) {
				onCompletedHandler.run();
			}
		}
	}

}


text:
import pyperclip

aaa = ' - '.join(['a', 'b', 'c'])
print(aaa)

print('La sarlanga'.replace(' ', '').isalpha())
bbb = 'hola, cómo te va'.split()
print(bbb)
print('hola'.rjust(20, '*'))
print(aaa.strip('a'))  # saca los caracteres del principio y el final de la cadena
#copiar y pegar del portapapeles
pyperclip.copy('sarasaaaaaaa')
print(pyperclip.paste)


text:
from twisted.application.service import Service
from twisted.internet import reactor
from twisted.internet.defer import Deferred, DeferredList
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.protocols.basic import Int32StringReceiver
from carbon.conf import settings
from carbon.util import pickle
from carbon import log, state, events, instrumentation

SEND_QUEUE_LOW_WATERMARK = settings.MAX_QUEUE_SIZE * 0.8

class CarbonClientProtocol(Int32StringReceiver):
  def connectionMade(self):
    log.clients("%s::connectionMade" % self)
    self.paused = False
    self.connected = True
    self.transport.registerProducer(self, streaming=True)
    # Define internal metric names
    self.destinationName = self.factory.destinationName
    self.queuedUntilReady = 'destinations.%s.queuedUntilReady' % self.destinationName
    self.sent = 'destinations.%s.sent' % self.destinationName

    self.factory.connectionMade.callback(self)
    self.factory.connectionMade = Deferred()
    self.sendQueued()

  def connectionLost(self, reason):
    log.clients("%s::connectionLost %s" % (self, reason.getErrorMessage()))
    self.connected = False

  def pauseProducing(self):
    self.paused = True

  def resumeProducing(self):
    self.paused = False
    self.sendQueued()

  def stopProducing(self):
    self.disconnect()

  def disconnect(self):
    if self.connected:
      self.transport.unregisterProducer()
      self.transport.loseConnection()
      self.connected = False

  def sendDatapoint(self, metric, datapoint):
    if self.paused:
      self.factory.enqueue(metric, datapoint)
      instrumentation.increment(self.queuedUntilReady)

    elif self.factory.hasQueuedDatapoints():
      self.factory.enqueue(metric, datapoint)
      self.sendQueued()

    else:
      self._sendDatapoints([(metric, datapoint)])

  def _sendDatapoints(self, datapoints):
      self.sendString(pickle.dumps(datapoints, protocol=-1))
      instrumentation.increment(self.sent, len(datapoints))
      self.factory.checkQueue()

  def sendQueued(self):
    while (not self.paused) and self.factory.hasQueuedDatapoints():
      datapoints = self.factory.takeSomeFromQueue()
      self._sendDatapoints(datapoints)

    queueSize = self.factory.queueSize
    if queueSize < SEND_QUEUE_LOW_WATERMARK:
      self.factory.queueHasSpace.callback(queueSize)
      log.clients('%s send queue has space available' % self)

      if (settings.USE_FLOW_CONTROL and
          state.metricReceiversPaused):
        log.clients('%s resuming paused clients' % self)
        events.resumeReceivingMetrics()

  def __str__(self):
    return 'CarbonClientProtocol(%s:%d:%s)' % (self.factory.destination)
  __repr__ = __str__

class CarbonClientFactory(ReconnectingClientFactory):
  maxDelay = 5

  def __init__(self, destination):
    self.destination = destination
    self.destinationName = ('%s:%d:%s' % destination).replace('.', '_')
    self.host, self.port, self.carbon_instance = destination
    self.addr = (self.host, self.port)
    self.started = False
    # This factory maintains protocol state across reconnects
    self.queue = [] # including datapoints that still need to be sent
    self.connectedProtocol = None
    self.queueEmpty = Deferred()
    self.queueFull = Deferred()
    self.queueFull.addCallback(self.queueFullCallback)
    self.queueHasSpace = Deferred()
    self.queueHasSpace.addCallback(self.queueSpaceCallback)
    self.connectFailed = Deferred()
    self.connectionMade = Deferred()
    self.connectionLost = Deferred()
    # Define internal metric names
    self.attemptedRelays = 'destinations.%s.attemptedRelays' % self.destinationName
    self.fullQueueDrops = 'destinations.%s.fullQueueDrops' % self.destinationName
    self.queuedUntilConnected = 'destinations.%s.queuedUntilConnected' % self.destinationName

  def queueFullCallback(self, result):
    log.clients('%s send queue is full (%d datapoints)' % (self, result))

  def queueSpaceCallback(self, result):
    if self.queueFull.called:
      self.queueFull = Deferred()
      self.queueFull.addCallback(self.queueFullCallback)
    self.queueHasSpace = Deferred()
    self.queueHasSpace.addCallback(self.queueSpaceCallback)

  def buildProtocol(self, addr):
    self.connectedProtocol = CarbonClientProtocol()
    self.connectedProtocol.factory = self
    return self.connectedProtocol

  def startConnecting(self): # calling this startFactory yields recursion problems
    self.started = True
    self.connector = reactor.connectTCP(self.host, self.port, self)

  def stopConnecting(self):
    self.started = False
    self.stopTrying()
    if self.connectedProtocol and self.connectedProtocol.connected:
      return self.connectedProtocol.disconnect()

  @property
  def queueSize(self):
    return len(self.queue)

  def hasQueuedDatapoints(self):
    return bool(self.queue)

  def takeSomeFromQueue(self):
    datapoints = self.queue[:settings.MAX_DATAPOINTS_PER_MESSAGE]
    self.queue = self.queue[settings.MAX_DATAPOINTS_PER_MESSAGE:]
    return datapoints

  def checkQueue(self):
    if not self.queue:
      self.queueEmpty.callback(0)
      self.queueEmpty = Deferred()

  def enqueue(self, metric, datapoint):
    self.queue.append((metric, datapoint))

  def sendDatapoint(self, metric, datapoint):
    instrumentation.increment(self.attemptedRelays)
    queueSize = self.queueSize
    if queueSize >= settings.MAX_QUEUE_SIZE:
      if not self.queueFull.called:
        self.queueFull.callback(queueSize)
      instrumentation.increment(self.fullQueueDrops)
    elif self.connectedProtocol:
      self.connectedProtocol.sendDatapoint(metric, datapoint)
    else:
      self.enqueue(metric, datapoint)
      instrumentation.increment(self.queuedUntilConnected)

  def startedConnecting(self, connector):
    log.clients("%s::startedConnecting (%s:%d)" % (self, connector.host, connector.port))

  def clientConnectionLost(self, connector, reason):
    ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
    log.clients("%s::clientConnectionLost (%s:%d) %s" % (self, connector.host, connector.port, reason.getErrorMessage()))
    self.connectedProtocol = None
    self.connectionLost.callback(0)
    self.connectionLost = Deferred()

  def clientConnectionFailed(self, connector, reason):
    ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
    log.clients("%s::clientConnectionFailed (%s:%d) %s" % (self, connector.host, connector.port, reason.getErrorMessage()))
    self.connectFailed.callback(dict(connector=connector, reason=reason))
    self.connectFailed = Deferred()

  def disconnect(self):
    self.queueEmpty.addCallback(lambda result: self.stopConnecting())
    readyToStop = DeferredList(
      [self.connectionLost, self.connectFailed],
      fireOnOneCallback=True,
      fireOnOneErrback=True)
    self.checkQueue()

    # This can happen if the client is stopped before a connection is ever made
    if (not readyToStop.called) and (not self.started):
      readyToStop.callback(None)

    return readyToStop

  def __str__(self):
    return 'CarbonClientFactory(%s:%d:%s)' % self.destination
  __repr__ = __str__

class CarbonClientManager(Service):
  def __init__(self, router):
    self.router = router
    self.client_factories = {} # { destination : CarbonClientFactory() }

  def startService(self):
    Service.startService(self)
    for factory in self.client_factories.values():
      if not factory.started:
        factory.startConnecting()

  def stopService(self):
    Service.stopService(self)
    self.stopAllClients()

  def startClient(self, destination):
    if destination in self.client_factories:
      return

    log.clients("connecting to carbon daemon at %s:%d:%s" % destination)
    self.router.addDestination(destination)
    factory = self.client_factories[destination] = CarbonClientFactory(destination)
    connectAttempted = DeferredList(
        [factory.connectionMade, factory.connectFailed],
        fireOnOneCallback=True,
        fireOnOneErrback=True)
    if self.running:
      factory.startConnecting() # this can trigger & replace connectFailed

    return connectAttempted

  def stopClient(self, destination):
    factory = self.client_factories.get(destination)
    if factory is None:
      return

    self.router.removeDestination(destination)
    stopCompleted = factory.disconnect()
    stopCompleted.addCallback(lambda result: self.disconnectClient(destination))
    return stopCompleted

  def disconnectClient(self, destination):
    factory = self.client_factories.pop(destination)
    c = factory.connector
    if c and c.state == 'connecting' and not factory.hasQueuedDatapoints():
      c.stopConnecting()

  def stopAllClients(self):
    deferreds = []
    for destination in list(self.client_factories):
      deferreds.append( self.stopClient(destination) )
    return DeferredList(deferreds)

  def sendDatapoint(self, metric, datapoint):
    for destination in self.router.getDestinations(metric):
      self.client_factories[destination].sendDatapoint(metric, datapoint)

  def __str__(self):
    return "<%s[%x]>" % (self.__class__.__name__, id(self))


text:
Implement the `keep` and `discard` operation on collections. Given a collection
and a predicate on the collection's elements, `keep` returns a new collection
containing those elements where the predicate is true, while `discard` returns
a new collection containing those elements where the predicate is false.

For example, given the collection of numbers:

- 1, 2, 3, 4, 5

And the predicate:

- is the number even?

Then your keep operation should produce:

- 2, 4

While your discard operation should produce:

- 1, 3, 5

Note that the union of keep and discard is all the elements.

The functions may be called `keep` and `discard`, or they may need different
names in order to not clash with existing functions or concepts in your
language.

## Restrictions

Keep your hands off that filter/reject/whatchamacallit functionality
provided by your standard library!  Solve this one yourself using other
basic tools instead.

### Submitting Exercises

Note that, when trying to submit an exercise, make sure the solution is in the `exercism/python/<exerciseName>` directory.

For example, if you're submitting `bob.py` for the Bob exercise, the submit command would be something like `exercism submit <path_to_exercism_dir>/python/bob/bob.py`.

For more detailed information about running tests, code style and linting,
please see the [help page](http://exercism.io/languages/python).

## Source

Conversation with James Edward Gray II [https://twitter.com/jeg2](https://twitter.com/jeg2)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
	<title>Profiling</title>
	<script src="../../node_modules/requirejs/require.js" data-main="../../lib/assets/htmlMatcher.js"></script>
	<script>
		require.config({
			paths: {lodash: '../../node_modules/lodash/lodash'},
		});
	</script>
</head>
<body>

<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '../stubs/webkit.html', false);
xhr.send(null);

require(['htmlMatcher'], function(htmlMatcher) {
	setTimeout(function() {
		console.profile('Matcher');
		var m = htmlMatcher.find(xhr.responseText, 20697);
		console.profileEnd('Matcher');
		console.log(m);
	}, 1);
});

</script>
</body>
</html>


text:
from __future__ import with_statement

import difflib
import fnmatch
import os
import re
import sys
import subprocess
import tempfile
import unittest

from xml.etree.ElementTree import fromstring, tostring

import pyboleto

try:
    from pyboleto.pdf import BoletoPDF
except ImportError as err:
    if sys.version_info >= (3,):
        pass  # Reportlab doesn;t support Python3
    else:
        raise(err)

def list_recursively(directory, pattern):
    """Returns files recursively from directory matching pattern
    :param directory: directory to list
    :param pattern: glob mattern to match
    """
    matches = []
    for root, _, filenames in os.walk(directory):
        for filename in fnmatch.filter(filenames, pattern):
            # skip backup files
            if (filename.startswith('.#') or
                    filename.endswith('~')):
                continue
            matches.append(os.path.join(root, filename))
    return matches

def get_sources(root):
    for dirpath in ['pyboleto', 'tests']:
        path = os.path.join(root, dirpath)
        for fname in list_recursively(path, '*.py'):
            if fname.endswith('__init__.py'):
                continue
            yield fname

        # yield os.path.join(root, 'setup.py')

def _diff(orig, new, short, verbose):
    lines = difflib.unified_diff(orig, new)
    if not lines:
        return ''

    return ''.join('%s: %s' % (short, line) for line in lines)

def diff_files(orig, new, verbose=False):
    with open(orig) as f_orig:
        with open(new) as f_new:
            return _diff(f_orig.readlines(),
                         f_new.readlines(),
                         short=os.path.basename(orig),
                         verbose=verbose)

def diff_pdf_htmls(original_filename, filename):
    # REPLACE all generated dates with %%DATE%%
    for fname in [original_filename, filename]:
        with open(fname) as f:
            data = f.read()
            data = re.sub(r'name="date" content="(.*)"',
                          r'name="date" content="%%DATE%%"', data)
            data = re.sub(r'<pdf2xml[^>]+>', r'<pdf2xml>', data)
        with open(fname, 'w') as f:
            f.write(data)

    return diff_files(original_filename, filename)

class ClassInittableMetaType(type):
    # pylint fails to understand this is a metaclass
    def __init__(self, name, bases, namespace):
        type.__init__(self, name, bases, namespace)
        self.__class_init__(namespace)

class SourceTest(object):
    __metaclass__ = ClassInittableMetaType

    @classmethod
    def __class_init__(cls, namespace):
        root = os.path.dirname(os.path.dirname(pyboleto.__file__))
        cls.root = root
        for filename in get_sources(root):
            testname = filename[len(root):]
            if not cls.filename_filter(testname):
                continue
            testname = testname[:-3].replace('/', '_')
            name = 'test_%s' % (testname, )
            # func = lambda self, r=root, f=filename: self.check_filename(r, f)

            def func(self, r=root, f=filename):
                self.check_filename(r, f)
            func.__name__ = name
            setattr(cls, name, func)

    def check_filename(self, root, filename):
        pass

    @classmethod
    def filename_filter(cls, filename):
        if cls.__name__ == 'SourceTest':
            return False
        else:
            return True

def indent(elem, level=0):
    i = "\n" + level * "  "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "  "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level + 1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

def pdftoxml(filename, output):
    p = subprocess.Popen(['pdftohtml',
                          '-stdout',
                          '-xml',
                          '-noframes',
                          '-i',
                          '-q',
                          filename],
                         stdout=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if stderr:
        raise SystemExit("Error while runnig pdftohtml: %s" % (stderr, ))

    root = fromstring(stdout)
    indent(root)
    with open(output, 'wb') as f:
        f.write(tostring(root))

class BoletoTestCase(unittest.TestCase):
    def _get_expected(self, bank, generated):
        fname = os.path.join(os.path.dirname(pyboleto.__file__),
                             "..", "tests", "xml", bank + '-expected.xml')
        if not os.path.exists(fname):
            with open(fname, 'wb') as f:
                with open(generated) as g:
                    f.write(g.read())
        return fname

    def test_pdf_triplo_rendering(self):
        bank = type(self.dados[0]).__name__
        filename = tempfile.mktemp(prefix="pyboleto-triplo-",
                                   suffix=".pdf")
        boleto = BoletoPDF(filename, True)
        for d in self.dados:
            boleto.drawBoleto(d)
            boleto.nextPage()
        boleto.save()

        generated = filename + '.xml'
        pdftoxml(filename, generated)
        expected = self._get_expected('Triplo-' + bank, generated)
        diff = diff_pdf_htmls(expected, generated)
        if diff:
            self.fail("Error while checking xml for %r:\n%s" % (
                bank, diff))
        os.unlink(generated)

    def test_pdf_rendering(self):
        dados = self.dados[0]
        bank = type(dados).__name__
        filename = tempfile.mktemp(prefix="pyboleto-",
                                   suffix=".pdf")
        boleto = BoletoPDF(filename, True)
        boleto.drawBoleto(dados)
        boleto.nextPage()
        boleto.save()

        generated = filename + '.xml'
        pdftoxml(filename, generated)
        expected = self._get_expected(bank, generated)
        diff = diff_pdf_htmls(expected, generated)
        if diff:
            self.fail("Error while checking xml for %r:\n%s" % (
                bank, diff))
        os.unlink(generated)


text:
var moment = require('moment-timezone'),
    Promise = require('bluebird'),
    _ = require('lodash'),
    errors = require('../../errors');

module.exports = function (Bookshelf) {
    var ParentModel = Bookshelf.Model,
        Model;

    Model = Bookshelf.Model.extend({
        /**
         * Update collision protection.
         *
         * IMPORTANT NOTES:
         * The `sync` method is called for any query e.g. update, add, delete, fetch
         *
         * We had the option to override Bookshelf's `save` method, but hooking into the `sync` method gives us
         * the ability to access the `changed` object. Bookshelf already knows which attributes has changed.
         *
         * Bookshelf's timestamp function can't be overridden, as it's synchronous, there is no way to return an Error.
         *
         * If we want to enable the collision plugin for other tables, the queries might need to run in a transaction.
         * This depends on if we fetch the model before editing. Imagine two concurrent requests come in, both would fetch
         * the same current database values and both would succeed to update and override each other.
         */
        sync: function timestamp(options) {
            var parentSync = ParentModel.prototype.sync.apply(this, arguments),
                originalUpdateSync = parentSync.update,
                self = this;

            // CASE: only enabled for posts table
            if (this.tableName !== 'posts' ||
                !self.serverData ||
                ((options.method !== 'update' && options.method !== 'patch') || !options.method)
            ) {
                return parentSync;
            }

            /**
             * Only hook into the update sync
             *
             * IMPORTANT NOTES:
             * Even if the client sends a different `id` property, it get's ignored by bookshelf.
             * Because you can't change the `id` of an existing post.
             *
             * HTML is always auto generated, ignore.
             */
            parentSync.update = function update() {
                var changed = _.omit(self.changed, [
                        'created_at', 'updated_at', 'author_id', 'id',
                        'published_by', 'updated_by', 'html', 'plaintext'
                    ]),
                    clientUpdatedAt = moment(self.clientData.updated_at || self.serverData.updated_at),
                    serverUpdatedAt = moment(self.serverData.updated_at);

                if (Object.keys(changed).length) {
                    if (clientUpdatedAt.diff(serverUpdatedAt) !== 0) {
                        return Promise.reject(new errors.InternalServerError({
                            message: 'Saving failed! Someone else is editing this post.',
                            code: 'UPDATE_COLLISION'
                        }));
                    }
                }

                return originalUpdateSync.apply(this, arguments);
            };

            return parentSync;
        },

        /**
         * We have to remember current server data and client data.
         * The `sync` method has no access to it.
         * `updated_at` is already set to "Date.now" when the overridden `sync.update` is called.
         * See https://github.com/tgriesser/bookshelf/blob/79c526870e618748caf94e7476a0bc796ee090a6/src/model.js#L955
         */
        save: function save(data) {
            this.clientData = _.cloneDeep(data) || {};
            this.serverData = _.cloneDeep(this.attributes);

            return ParentModel.prototype.save.apply(this, arguments);
        }
    });

    Bookshelf.Model = Model;
};


text:
package com.stfl.ss;

import com.stfl.misc.Util;
import org.bouncycastle.crypto.StreamBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;

import javax.crypto.SecretKey;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger;

/**
 * Crypt base class implementation
 */
public abstract class CryptBase implements ICrypt {

    protected abstract StreamBlockCipher getCipher(boolean isEncrypted) throws InvalidAlgorithmParameterException;
    protected abstract SecretKey getKey();
    protected abstract void _encrypt(byte[] data, ByteArrayOutputStream stream);
    protected abstract void _decrypt(byte[] data, ByteArrayOutputStream stream);

    protected final String _name;
    protected final SecretKey _key;
    protected final ShadowSocksKey _ssKey;
    protected final int _ivLength;
    protected final int _keyLength;
    protected boolean _encryptIVSet;
    protected boolean _decryptIVSet;
    protected byte[] _encryptIV;
    protected byte[] _decryptIV;
    protected final Lock encLock = new ReentrantLock();
    protected final Lock decLock = new ReentrantLock();
    protected StreamBlockCipher encCipher;
    protected StreamBlockCipher decCipher;
    private Logger logger = Logger.getLogger(CryptBase.class.getName());

    public CryptBase(String name, String password) {
        _name = name.toLowerCase();
        _ivLength = getIVLength();
        _keyLength = getKeyLength();
        _ssKey = new ShadowSocksKey(password, _keyLength);
        _key = getKey();
    }

    protected void setIV(byte[] iv, boolean isEncrypt)
    {
        if (_ivLength == 0) {
            return;
        }

        if (isEncrypt)
        {
            _encryptIV = new byte[_ivLength];
            System.arraycopy(iv, 0, _encryptIV, 0, _ivLength);
            try {
                encCipher = getCipher(isEncrypt);
                ParametersWithIV parameterIV = new ParametersWithIV(new KeyParameter(_key.getEncoded()), _encryptIV);
                encCipher.init(isEncrypt, parameterIV);
            } catch (InvalidAlgorithmParameterException e) {
                logger.info(e.toString());
            }
        }
        else
        {
            _decryptIV = new byte[_ivLength];
            System.arraycopy(iv, 0, _decryptIV, 0, _ivLength);
            try {
                decCipher = getCipher(isEncrypt);
                ParametersWithIV parameterIV = new ParametersWithIV(new KeyParameter(_key.getEncoded()), _decryptIV);
                decCipher.init(isEncrypt, parameterIV);
            } catch (InvalidAlgorithmParameterException e) {
                logger.info(e.toString());
            }
        }
    }

    @Override
    public void encrypt(byte[] data, ByteArrayOutputStream stream) {
        synchronized (encLock) {
            stream.reset();
            if (!_encryptIVSet) {
                _encryptIVSet = true;
                byte[] iv = Util.randomBytes(_ivLength);
                setIV(iv, true);
                try {
                    stream.write(iv);
                } catch (IOException e) {
                    logger.info(e.toString());
                }

            }

            _encrypt(data, stream);
        }
    }

    @Override
    public void encrypt(byte[] data, int length, ByteArrayOutputStream stream) {
        byte[] d = new byte[length];
        System.arraycopy(data, 0, d, 0, length);
        encrypt(d, stream);
    }

    @Override
    public void decrypt(byte[] data, ByteArrayOutputStream stream) {
        byte[] temp;

        synchronized (decLock) {
            stream.reset();
            if (!_decryptIVSet) {
                _decryptIVSet = true;
                setIV(data, false);
                temp = new byte[data.length - _ivLength];
                System.arraycopy(data, _ivLength, temp, 0, data.length - _ivLength);
            } else {
                temp = data;
            }

            _decrypt(temp, stream);
        }
    }

    @Override
    public void decrypt(byte[] data, int length, ByteArrayOutputStream stream) {
        byte[] d = new byte[length];
        System.arraycopy(data, 0, d, 0, length);
        decrypt(d, stream);
    }
}


text:
'use strict';

var util = require('util');
var EventEmitter = require('events').EventEmitter;

var SerialTrigger = require('../lib/SerialTrigger');

function MockPort() {
}
util.inherits(MockPort, EventEmitter);
MockPort.prototype.write = function(data, cb) {
	this.data = data;
	process.nextTick(cb);
};
MockPort.prototype.drain = function(cb) {
	this.emit('drain');
	process.nextTick(cb);
};
MockPort.prototype.flush = function(cb) {
	this.emit('flush');
	process.nextTick(cb);
};

describe('SerialTrigger', function() {
	it('should trigger when prompt is at beginning of line', function(done) {
		var port = new MockPort();
		var st = new SerialTrigger(port);
		st.addTrigger('SSID: ', function() {
			st.stop();
			done();
		});
		st.start();
		port.emit('data', 'SSID: ');
	});

	it('should not trigger when data does not match', function(done) {
		var port = new MockPort();
		var st = new SerialTrigger(port);
		var to = setTimeout(function () {
			done();
		}, 100);
		st.addTrigger('SSID: ', function() {
			clearTimeout(to);
			st.stop();
			done(new Error('triggered when it should not'));
		});
		st.start();
		port.emit('data', 'ASDF: ');
	});

	it('should write the response from the trigger', function(done) {
		var port = new MockPort();
		var st = new SerialTrigger(port);
		port.on('drain', function() {
			if (port.data !== 'particle') {
				return done(new Error('Response data does not match'));
			}
			st.stop();
			port.removeAllListeners();
			done();
		});
		st.addTrigger('SSID: ', function(cb) {
			cb('particle');
		});
		st.start();
		port.emit('data', 'SSID: ');
	});
});


text:
package com.navigation.reactnative;

import android.content.Context;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.UIManagerHelper;
import com.facebook.react.uimanager.events.Event;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.uimanager.events.RCTEventEmitter;

import java.util.ArrayList;
import java.util.List;

public class TabBarPagerView extends ViewPager implements TabBarItemView.ChangeListener {
    private final Fragment fragment;
    int selectedTab = 0;
    boolean scrollsToTop;
    private boolean layoutRequested = false;
    private boolean measured = false;
    int nativeEventCount;
    int mostRecentEventCount;
    private boolean dataSetChanged = false;

    public TabBarPagerView(Context context) {
        super(context);
        ViewCompat.setLayoutDirection(this, ViewCompat.LAYOUT_DIRECTION_LTR);
        addOnPageChangeListener(new TabChangeListener());
        FragmentActivity activity = (FragmentActivity) ((ReactContext) context).getCurrentActivity();
        fragment = new TabBarPagerFragment(this);
        if (activity != null) {
            FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
            transaction.add(fragment, "TabBarPager" + getId());
            transaction.commitNowAllowingStateLoss();
        }
        Adapter adapter = new Adapter(fragment.getChildFragmentManager());
        adapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                if (getCurrentItem() != selectedTab && getTabsCount() > selectedTab)
                    setCurrentItem(selectedTab, false);
            }
        });
        setAdapter(adapter);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        requestLayout();
        if (getTabLayout() != null)
            getTabLayout().setupWithViewPager(this);
        populateTabs();
        if (!measured) {
            measure(
                MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
            layout(getLeft(), getTop(), getRight(), getBottom());
            measured = true;
            getAdapter().notifyDataSetChanged();
        }
    }

    void populateTabs() {
        TabLayoutView tabView = getTabLayout();
        if (tabView != null && getAdapter() != null) {
            for(int i = 0; i < getAdapter().tabFragments.size(); i++) {
                getAdapter().tabFragments.get(i).tabBarItem.setTabView(tabView, i);
            }
        }
    }

    private TabLayoutView getTabLayout() {
        ViewGroup parent = (ViewGroup) getParent();
        if (parent instanceof CoordinatorLayout) {
            parent = (ViewGroup) parent.getChildAt(0);
            if (parent.getChildAt(0) instanceof CollapsingBarView)
                parent = (ViewGroup) parent.getChildAt(0);
        }
        for(int i = 0; parent != null && i < parent.getChildCount(); i++) {
            View child = parent.getChildAt(i);
            if (child instanceof TabView)
                return (TabLayoutView) child;
        }
        return null;
    }

    void scrollToTop() {
        if (!scrollsToTop)
            return;
        View tabBarItem = getTabAt(getCurrentItem()).content.get(0);
        if (tabBarItem instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) tabBarItem;
            for(int i = 0; i < viewGroup.getChildCount(); i++) {
                if (viewGroup.getChildAt(i) instanceof NavigationBarView)
                    ((NavigationBarView) viewGroup.getChildAt(i)).setExpanded(true);
                if (viewGroup.getChildAt(i) instanceof ScrollView)
                    ((ScrollView) viewGroup.getChildAt(i)).smoothScrollTo(0,0);
                if (viewGroup.getChildAt(i) instanceof TabBarPagerView)
                    ((TabBarPagerView) viewGroup.getChildAt(i)).scrollToTop();
            }
        }
        if (tabBarItem instanceof ScrollView)
            ((ScrollView) tabBarItem).smoothScrollTo(0, 0);
        if (tabBarItem instanceof NavigationStackView)
            ((NavigationStackView) tabBarItem).scrollToTop();
    }

    @Override
    public void requestLayout() {
        super.requestLayout();
        if (!layoutRequested) {
            layoutRequested = true;
            post(measureAndLayout);
        }
    }

    private final Runnable measureAndLayout = new Runnable() {
        @Override
        public void run() {
            layoutRequested = false;
            measure(
                MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
            layout(getLeft(), getTop(), getRight(), getBottom());
        }
    };

    @Nullable
    @Override
    public Adapter getAdapter() {
        return (Adapter) super.getAdapter();
    }

    int getTabsCount() {
        return getAdapter() != null ? getAdapter().tabFragments.size() : 0;
    }

    TabBarItemView getTabAt(int index) {
        return getAdapter() != null ? getAdapter().tabFragments.get(index).tabBarItem : null;
    }

    void addTab(TabBarItemView tab, int index) {
        if (getAdapter() != null) {
            getAdapter().addTab(tab, index);
            populateTabs();
        }
    }

    void removeTab(int index) {
        if (getAdapter() != null) {
            getAdapter().removeTab(index);
            populateTabs();
        }
    }

    void removeFragment() {
        FragmentActivity activity = (FragmentActivity) ((ReactContext) getContext()).getCurrentActivity();
        if (activity != null && fragment != null) {
            FragmentManager fragmentManager = activity.getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.remove(fragment);
            fragmentTransaction.commitAllowingStateLoss();
        }
    }

    @Override
    public void onChange(TabBarItemView tabBarItemView) {
        getAdapter().notifyDataSetChanged();
    }

    private class Adapter extends FragmentPagerAdapter {
        private final List<TabFragment> tabFragments = new ArrayList<>();

        Adapter(FragmentManager fragmentManager) {
            super(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        }

        void addTab(TabBarItemView tab, int index) {
            tabFragments.add(index, new TabFragment(tab));
            dataSetChanged = true;
            notifyDataSetChanged();
            dataSetChanged = false;
        }

        void removeTab(int index) {
            tabFragments.remove(index);
            dataSetChanged = true;
            notifyDataSetChanged();
            dataSetChanged = false;
        }

        @Override
        public int getCount() {
            return tabFragments.size();
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return tabFragments.get(position);
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return tabFragments.get(position).tabBarItem.styledTitle;
        }

        @Override
        public int getItemPosition(@NonNull Object object) {
            for(int i = 0; i < tabFragments.size(); i++) {
                TabFragment tabFragment = tabFragments.get(i);
                if (tabFragment == object && !tabFragment.viewChanged())
                    return POSITION_UNCHANGED;
                if (tabFragment.viewChanged())
                    tabFragments.set(i, new TabFragment(tabFragments.get(i).tabBarItem));
            }
            return POSITION_NONE;
        }

        @Override
        public long getItemId(int position) {
            return tabFragments.get(position).hashCode();
        }
    }

    private class TabChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            if (!dataSetChanged)
                nativeEventCount++;
            selectedTab = position;
            ReactContext reactContext = (ReactContext) getContext();
            EventDispatcher eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, getId());
            eventDispatcher.dispatchEvent(new TabBarPagerView.TabSelectedEvent(getId(), position, nativeEventCount));
            if (getAdapter() != null)
                getAdapter().tabFragments.get(position).tabBarItem.pressed();
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            ReactContext reactContext = (ReactContext) getContext();
            EventDispatcher eventDispatcher = UIManagerHelper.getEventDispatcherForReactTag(reactContext, getId());
            eventDispatcher.dispatchEvent(new TabBarPagerView.TabSwipeStateChangedEvent(getId(), state == ViewPager.SCROLL_STATE_DRAGGING));
        }
    }

    public static class TabBarPagerFragment extends Fragment {
        private TabBarPagerView tabBarPager;

        public TabBarPagerFragment() {
            super();
        }

        TabBarPagerFragment(TabBarPagerView tabBarPager) {
            super();
            this.tabBarPager = tabBarPager;
        }

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            return tabBarPager != null ? tabBarPager : new View(getContext());
        }
    }

    static class TabSelectedEvent extends Event<TabBarPagerView.TabSelectedEvent> {
        private final int tab;
        private final int eventCount;

        public TabSelectedEvent(int viewId, int tab, int eventCount) {
            super(viewId);
            this.tab = tab;
            this.eventCount = eventCount;
        }

        @Override
        public String getEventName() {
            return "topOnTabSelected";
        }

        @Override
        public void dispatch(RCTEventEmitter rctEventEmitter) {
            WritableMap event = Arguments.createMap();
            event.putInt("tab", this.tab);
            event.putInt("eventCount", this.eventCount);
            rctEventEmitter.receiveEvent(getViewTag(), getEventName(), event);
        }
    }

    static class TabSwipeStateChangedEvent extends Event<TabBarPagerView.TabSwipeStateChangedEvent> {
        private final boolean swiping;

        public TabSwipeStateChangedEvent(int viewId, boolean swiping) {
            super(viewId);
            this.swiping = swiping;
        }

        @Override
        public String getEventName() {
            return "topOnTabSwipeStateChanged";
        }

        @Override
        public void dispatch(RCTEventEmitter rctEventEmitter) {
            WritableMap event = Arguments.createMap();
            event.putBoolean("swiping", this.swiping);
            rctEventEmitter.receiveEvent(getViewTag(), getEventName(), event);
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: MXS34
 * Date: 17.05.2017
 * Time: 17:12
 */

namespace app\modules\chat\models;

use yii\base\Object;
use app\modules\chat\services\MessageFilesHandler;
use app\modules\chat\records\ { MessageRecord, MessageReferenceRecord };

/**
 * Class MessageN
 * @package app\modules\chat\models
 *
 * @property MessageFilesHandler $filesHandler
 */
class MessageN extends Object{

    /** @var int */
    protected $userId;

    /** @var MessageRecord  */
    public $messageRecord;

    /** @var array|MessageReferenceRecord */
    public $messageReferences;

    /** @var  MessageFilesHandler */
    protected $_filesHandler;

    public function __construct(MessageRecord $messageRecord, array $messageReferences) {
        parent::__construct();

        $this->messageRecord     = $messageRecord;
        $this->messageReferences = $messageReferences;
        $this->userId            = \Yii::$app->user->getId();
    }

    public function getFilesHandler(){
        if (empty($this->_filesHandler)){
            $this->_filesHandler = new MessageFilesHandler($this);
        }

        return $this->_filesHandler;
    }

    public function getId(){
        return $this->messageRecord->id;
    }

    public function getContent(){
        return $this->messageRecord->content;
    }

    public function getCreationDate(){
        return $this->messageRecord->createdAt;
    }

    public function isNew(){
        return $this->messageReferences[$this->userId] -> isNew;
    }

    public function isAuthor(int $userId = null) {
        if (empty($userId)){
            return $this->messageRecord->createdBy == $this->userId;

        } else {
            return $this->messageRecord->createdBy == $userId;
        }
    }

    public function getAuthorId() {
        return $this->messageRecord->createdBy;
    }

    public function getFiles(){
        return $this->messageRecord->getFiles();
    }

}