text:
namespace {

// OSCrypt has a setting that determines whether a backend will be used.
// The presense of this file in the file system means that the backend
// should be ignored. It's absence means we should use the backend.
constexpr const char kPreferenceFileName[] = "Disable Local Encryption";

bool ReadBackendUse(const base::FilePath& user_data_dir, bool* use) {
  if (user_data_dir.empty())
    return false;
  base::FilePath pref_path = user_data_dir.Append(kPreferenceFileName);
  *use = !base::PathExists(pref_path);
  return true;
}

}  // namespace

namespace os_crypt {

SelectedLinuxBackend SelectBackend(const std::string& type,
                                   bool use_backend,
                                   base::nix::DesktopEnvironment desktop_env) {
  // Explicitly requesting a store overrides other production logic.
  if (type == "kwallet")
    return SelectedLinuxBackend::KWALLET;
  if (type == "kwallet5")
    return SelectedLinuxBackend::KWALLET5;
  if (type == "gnome")
    return SelectedLinuxBackend::GNOME_ANY;
  if (type == "gnome-keyring")
    return SelectedLinuxBackend::GNOME_KEYRING;
  if (type == "gnome-libsecret")
    return SelectedLinuxBackend::GNOME_LIBSECRET;
  if (type == "basic")
    return SelectedLinuxBackend::BASIC_TEXT;

  // Ignore the backends if requested to.
  if (!use_backend)
    return SelectedLinuxBackend::BASIC_TEXT;

  // Detect the store to use automatically.
  const char* name = base::nix::GetDesktopEnvironmentName(desktop_env);
  VLOG(1) << "Password storage detected desktop environment: "
          << (name ? name : "(unknown)");
  switch (desktop_env) {
    case base::nix::DESKTOP_ENVIRONMENT_KDE4:
      return SelectedLinuxBackend::KWALLET;
    case base::nix::DESKTOP_ENVIRONMENT_KDE5:
      return SelectedLinuxBackend::KWALLET5;
    case base::nix::DESKTOP_ENVIRONMENT_CINNAMON:
    case base::nix::DESKTOP_ENVIRONMENT_GNOME:
    case base::nix::DESKTOP_ENVIRONMENT_PANTHEON:
    case base::nix::DESKTOP_ENVIRONMENT_UNITY:
    case base::nix::DESKTOP_ENVIRONMENT_XFCE:
      return SelectedLinuxBackend::GNOME_ANY;
    // KDE3 didn't use DBus, which our KWallet store uses.
    case base::nix::DESKTOP_ENVIRONMENT_KDE3:
    case base::nix::DESKTOP_ENVIRONMENT_OTHER:
      return SelectedLinuxBackend::BASIC_TEXT;
  }

  NOTREACHED();
  return SelectedLinuxBackend::BASIC_TEXT;
}

bool WriteBackendUse(const base::FilePath& user_data_dir, bool use) {
  if (user_data_dir.empty())
    return false;
  base::FilePath pref_path = user_data_dir.Append(kPreferenceFileName);
  if (use)
    return base::DeleteFile(pref_path);
  FILE* f = base::OpenFile(pref_path, "w");
  return f != nullptr && base::CloseFile(f);
}

bool GetBackendUse(const base::FilePath& user_data_dir) {
  bool setting;
  if (ReadBackendUse(user_data_dir, &setting))
    return setting;
  return true;
}

}  // namespace os_crypt


text:
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using CacheAspect;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;

namespace TestCache
{
    [TestClass]
    public class TestUserRepository
    {

        UserRepository target;
        IUserDal dal;
        ICache cache;

        // Use TestInitialize to run code before running each test
        [TestInitialize]
        public void SetUp()
        {
            dal = MockRepository.GenerateStrictMock<IUserDal>();
            cache = new InProcessMemoryCache();

            CacheService.Cache = cache;
            target = new UserRepository();
            target.Dal = dal;
        }

        [TestMethod]
        public void GetAllUsers_TryRetrievingDataTwice_DalShouldBeHitOnce()
        {
            //Arrange
            dal.Expect(d => d.GetAllUsers()).Return(GetUsers());
            dal.Expect(d => d.DeleteUserById(1234)).IgnoreArguments();

            target.DeleteUserById(1234);

            //Act
            target.GetAllUsers();
            target.GetAllUsers();

            //Assert
            dal.VerifyAllExpectations();

        }

        [TestMethod]
        public void GetUserById_TryRetrievingDataTwice_DalShouldBeHitOnce()
        {
            //Arrange
            int id = 1;
            dal.Expect(d => d.GetUserById(id)).Return(GetUsers().First());
            dal.Expect(d => d.DeleteUserById(id)).IgnoreArguments();

            target.DeleteUserById(id);

            //Act
            target.GetUserById(id);
            target.GetUserById(id);

            //Assert
            dal.VerifyAllExpectations();
        }

        [TestMethod]
        public void GetUserById_TryRetrievingUsingDifferentIds_DalShouldBeHitTwice()
        {
            //Arrange
            int id1 = 1;
            int id2 = 2;
            dal.Expect(d => d.GetUserById(id1)).Return(GetUsers().First());
            dal.Expect(d => d.GetUserById(id2)).Return(GetUsers().Last());
            dal.Expect(d => d.DeleteUserById(id1)).IgnoreArguments();
            dal.Expect(d => d.DeleteUserById(id2)).IgnoreArguments();

            //Act
            target.DeleteUserById(id1);
            target.DeleteUserById(id2);
            target.GetUserById(id1);
            target.GetUserById(id2);

            //Assert
            dal.VerifyAllExpectations();
        }

        [TestMethod]
        public void GetAllUsers_AddUserAfterCaching_CacheShouldBeInvalidated()
        {
            //Arrange
            dal.Expect(d => d.GetAllUsers())
                .Return(GetUsers())
                .Repeat.Twice();                    //Second call expected after cache is invalidated
            dal.Expect(d => d.AddUser(null)).IgnoreArguments();
            dal.Expect(d => d.DeleteUserById(5678)).IgnoreArguments();

            //Act
            target.DeleteUserById(5678);
            target.GetAllUsers();
            target.AddUser(new User{ Id = 1234});   //Should trigger invalidation
            target.GetAllUsers();

            //Assert
            dal.VerifyAllExpectations();
        }

        [TestMethod]
        public void GetUserById_EditUserAfterCaching_CacheShouldBeInvalidated() {
            //Arrange
            dal.Expect(d => d.GetUserById(1))
                .Return(GetUsers().First())
                .Repeat.Twice();                    //Second call expected after cache is invalidated
            dal.Expect(d => d.EditUser(GetUsers().First())).IgnoreArguments();
            dal.Expect(d => d.DeleteUserById(5678)).IgnoreArguments();

            //Act
            target.DeleteUserById(5678);
            target.GetUserById(1);
            target.EditUser(new User { Id = 1 });   //Should trigger invalidation
            target.GetUserById(1);

            //Assert
            dal.VerifyAllExpectations();
        }

        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }
        private List<User> GetUsers()
        {
            return new List<User>{
            new User{ Id = 1},
            new User{ Id = 2}
        };
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package net.sourceforge.plantuml.svek;

import java.awt.geom.Dimension2D;

import net.sourceforge.plantuml.graphic.AbstractTextBlock;
import net.sourceforge.plantuml.graphic.HtmlColor;
import net.sourceforge.plantuml.graphic.StringBounder;
import net.sourceforge.plantuml.graphic.TextBlock;
import net.sourceforge.plantuml.ugraphic.UGraphic;

public class DecorateEntityImage3 extends AbstractTextBlock  implements TextBlockBackcolored {

	private final TextBlock original;
	private final HtmlColor color;

	public DecorateEntityImage3(TextBlock original, HtmlColor color) {
		this.original = original;
		this.color = color;
	}

	public Dimension2D calculateDimension(StringBounder stringBounder) {
		return original.calculateDimension(stringBounder);
	}

	public void drawU(UGraphic ug) {
		original.drawU(ug);
	}

	public HtmlColor getBackcolor() {
		return color;
	}

}


text:
//
//  PUDConstants.m
//  PushDemo
//
//  Created by Matt Lathrop on 4/29/14.
//  Copyright © 2015 Salesforce Marketing Cloud. All rights reserved.
//

#import "PUDConstants.h"

#pragma mark - App Defaults
CGFloat const kPUDAppCustomTextSize = 15.0;
NSString *const kPUDAppBarcodeFont = @"Free3of9Extended";
NSString *const kPUDAppSettingsPlistName = @"settings.plist";

#pragma mark - Attributes
NSString *const kPUDAttributeFirstName = @"FirstName";
NSString *const kPUDAttributeLastName = @"LastName";

#pragma mark - CloudPage Inbox
NSUInteger const kPUDCloudPageFilterSegmentControlAllIndex = 0;
NSUInteger const kPUDCloudPageFilterSegmentControlUnreadIndex = 1;
NSUInteger const kPUDCloudPageFilterSegmentControlReadIndex = 2;

#pragma mark - Info Table View
NSString *const kPUDInfoAppVersion = @"k_APP_VERSION";
NSString *const kPUDInfoAppBundleID = @"k_APP_BUNDLE_ID";
NSString *const kPUDInfoBuildNumber = @"k_BUILD_NUMBER";
NSString *const kPUDInfoSDKVersion = @"k_SDK_VERSION";
NSString *const kPUDInfoBuildType = @"k_BUILD_TYPE";
NSString *const kPUDInfoConfigName = @"k_CONFIG_NAME";
NSString *const kPUDInfoAppID = @"k_APP_ID";
NSString *const kPUDInfoAccessToken = @"k_ACCESS_TOKEN";
NSString *const kPUDInfoClientID = @"k_CLIENT_ID";
NSString *const kPUDInfoClientSecret = @"k_CLIENT_SECRET";
NSString *const kPUDInfoMessageIDVanilla = @"k_MESSAGE_ID_VANILLA";
NSString *const kPUDInfoMessageIDCloudPage = @"k_MESSAGE_ID_CLOUDPAGE";
NSString *const kPUDInfoPushEnabled = @"k_PUSH_ENABLED";
NSString *const kPUDInfoDeviceToken = @"k_DEVICE_TOKEN";
NSString *const kPUDInfoDeviceID = @"k_DEVICE_ID";
NSString *const kPUDInfoOpenDirectDelegate = @"k_OPENDIRECT_DELEGATE";
NSString *const kPUDInfoLocationEnabled = @"k_LOCATION_ENABLED";
NSString *const kPUDInfoAttributeFirstName = @"k_ATTR_FIRST";
NSString *const kPUDInfoAttributeLastName = @"k_ATTR_LAST";
NSString *const kPUDInfoAttributeActivityTags = @"k_ACTIVITY_TAGS";

#pragma mark - Message Detail Table View

// tags
NSUInteger const kPUDMessageDetailSendButtonTag = 7645745;
NSUInteger const kPUDMessageDetailSwitchTag = 4322;
NSUInteger const kPUDMessageDetailTextFieldTag = 1234324;
NSUInteger const kPUDMessageDetailSegmentedControlTag = 7437381;

// custom keys
NSString *const kPUDMessageDetailCustomKeyDiscountCode = @"discount_code";

// textfield defaults
NSString *const kPUDAppMessageDetailDefaultMessageText = @"Type something...";
NSString *const kPUDMessageDetailDefaultOpenDirect = @"http://www.exacttarget.com";

// push method segment
NSUInteger const kPUDMessageDetailAlertSegmentIndex = 0;
NSUInteger const kPUDMessageDetailAlertCloudPageSegmentIndex = 1;

// custom sound picker
NSUInteger const kPUDMessageDetailPickerSoundDefaultIndex = 0;
NSUInteger const kPUDMessageDetailPickerSoundCustomIndex = 1;
NSUInteger const kPUDMessageDetailPickerSoundNoneIndex = 2;

// custom key picker
NSUInteger const kPUDMessageDetailPickerCustomKeyNoneIndex = 0;
NSUInteger const kPUDMessageDetailPickerCustomKey10Index = 1;
NSUInteger const kPUDMessageDetailPickerCustomKey20Index = 2;
NSUInteger const kPUDMessageDetailPickerCustomKey30Index = 3;

#pragma mark - Messages Payload
NSString *const kPUDMessagePayloadSoundKey = @"sound";
NSString *const kPUDMessagePayloadMessageTextKey = @"messageText";
NSString *const kPUDMessagePayloadOverrideKey = @"override";
NSString *const kPUDMessagePayloadDeviceTokensKey = @"deviceTokens";
NSString *const kPUDMessagePayloadBadgeKey = @"badge";
NSString *const kPUDMessagePayloadTagsKey = @"inclusionTags";
NSString *const kPUDMessagePayloadOpenDirectKey = @"openDirect";
NSString *const kPUDMessagePayloadCustomKeysKey = @"customKeys";
NSString *const kPUDMessagePayloadCloudPageKey = @"cloudPage";

// badge values
NSString *const kPUDMessagePayloadDefaultBadgeValue = @"+0";

// sound values
NSString *const kPUDMessagePayloadSoundDefault = @"default";
NSString *const kPUDMessagePayloadSoundCustom = @"custom.caf";
NSString *const kPUDMessagePayloadSoundNone = nil;

// custom key values
NSString *const kPUDMessagePayloadCustomKeyNone = @"None";
NSString *const kPUDMessagePayloadCustomKey10 = @"10%";
NSString *const kPUDMessagePayloadCustomKey20 = @"20%";
NSString *const kPUDMessagePayloadCustomKey30 = @"30%";

#pragma mark - Messages Table View
NSUInteger const kPUDMessagesLastReceivedSectionIndex = 0;
NSUInteger const kPUDMessagesPushTestsSectionIndex = 1;

#pragma mark - Message Types
NSString *const kPUDMessageTypeLocation = @"Location";
NSString *const kPUDMessageTypeOutbound = @"Outbound";

#pragma mark - Push Defines
NSString *const kPUDPushDefineOpenDirectPayloadKey = @"_od";
NSString *const kPUDPushDefineCloudPagePayloadKey = @"_x";

#pragma mark - Reuse Identifiers
NSString *const kPUDReuseIdentifierDiscountCell = @"ruid_discountCell";
NSString *const kPUDReuseIdentifierInfoCell = @"ruid_infoCell";
NSString *const kPUDReuseIdentifierMessageCell = @"ruid_messageCell";
NSString *const kPUDReuseIdentifierMessageDetailCell = @"ruid_messageDetailCell";
NSString *const kPUDReuseIdentifierPushReceivedCell = @"ruid_pushReceivedCell";
NSString *const kPUDReuseIdentifierSettingCell = @"ruid_settingCell";
NSString *const kPUDReuseIdentifierTagCell = @"ruid_tagCell";
NSString *const kPUDReuseIdentifierCloudPageInboxCell = @"ruid_cloudPageInboxCell";
NSString *const kPUDReuseIdentifierPushConfigCell = @"ruid_pushConfigCell";

#pragma mark - Segues
NSString *const kPUDSegueMessagesToLastReceivedPush = @"seg_messagesToLastReceivedPush";
NSString *const kPUDSegueMessagesToMessageDetail = @"seg_messagesToMessagesDetail";
NSString *const kPUDSeguePushReceivedToDiscount = @"seg_pushReceivedToDiscount";

#pragma mark - Settings Table View
NSUInteger const kPUDSettingsPersonalInformationSectionIndex = 0;
NSUInteger const kPUDSettingsActivitySectionIndex = 1;

#pragma mark - Storyboard Identifiers
NSString *const kPUDStoryboardIdentifierPushReceivedTableViewController = @"sb_pushReceivedTableViewController";
NSString *const kPUDStoryboardIdentifierDiscountCodeViewController = @"sb_discountCodeViewController";
NSString *const kPUDStoryboardIdentifierPushConfigTable = @"sb_pushConfigTableViewController";

#pragma mark - Storyboard Name
NSString *const kPUDStoryboardMain = @"Main";

#pragma mark - Tags
NSString *const kPUDTagCampingGear = @"Camping Gear";
NSString *const kPUDTagHikingSupplies= @"Hiking Supplies";
NSString *const kPUDTagBoatingGear = @"Boating Gear";
NSString *const kPUDTagFishingSupplies = @"Fishing Supplies";
NSString *const kPUDTagHuntingGear = @"Hunting Gear";

#pragma mark - User Defaults
NSString *const kPUDUserDefaultsFirstName = @"ud_firstName";
NSString *const kPUDUserDefaultsLastName = @"ud_lastName";
NSString *const kPUDUserDefaultsLastPushReceivedDate = @"ud_lastPushReceivedDate";
NSString *const kPUDUserDefaultsPushUserInfo = @"ud_pushUserInfo";
NSString *const kPUDUserDefaultsMessageType = @"ud_messageType";
NSString *const kPUDUserDefaultsAlertText = @"ud_alertText";

#pragma mark - Configs UserDefaults
NSString *const kPUDUserDefaultsConfigName = @"ud_configName";
NSString *const kPUDUserDefaultsAppID = @"ud_appId";
NSString *const kPUDUserDefaultsAccessToken = @"ud_accessToken";
NSString *const kPUDUserDefaultsClientID = @"ud_clientId";
NSString *const kPUDUserDefaultsClientSecret = @"ud_clientSecret";
NSString *const kPUDUserDefaultsMessageIDVanilla = @"ud_standardMessageId";
NSString *const kPUDUserDefaultsMessageIDCloudPage = @"ud_CloudpageMessageId";
NSString *const kPUDUserDefaultsRestUrl = @"ud_RestUrl";

#pragma mark - Configs Table View
NSUInteger const kPUDConfigsDefaultIndex = 0;
//NSUInteger const kPUDConfigsCustomIndex = 1;

#pragma mark - Notifications
NSString *const kPUDPushConfigChangedNotification = @"PushConfigChangedNotification";
NSString *const kPUDNewPushConfigAddedNotication =  @"PushConfigAddedNotification";
NSString *const kPUDPreferencesChanged =  @"PreferencesChanged";


text:
package sql_statement

import (
	"fmt"

	"github.com/thcyron/sqlbuilder"

	"github.com/go-zero-boilerplate/databases"
	"github.com/go-zero-boilerplate/databases/sql"
)

type UpdateStatement interface {
	BaseStatement
}

type updateStatement struct {
	dialect databases.Dialect
	db      databases.Database

	TableName string
	Wheres    []*sql.WhereCondition
	Sets      []*sql.ColumnNameAndValue

	RowsAffectedDest *int64
}

func (u *updateStatement) Execute() error {
	builder := sqlbuilder.Update().Dialect(u.dialect).Table(u.TableName)

	for _, c := range u.Sets {
		builder = builder.Set(c.Name, c.Value)
	}

	for _, w := range u.Wheres {
		builder = builder.Where(w.Condition, w.Args...)
	}

	query, args := builder.Build()

	result, err := u.db.Exec(query, args...)
	if err != nil {
		return err
	}

	if u.RowsAffectedDest != nil {
		rowsAffected, err := result.RowsAffected()
		if err != nil {
			return fmt.Errorf("Unable to get RowsAffected, error: %s", err.Error())
		}
		*u.RowsAffectedDest = rowsAffected
	}

	return nil
}


text:
using System.ComponentModel;
using Memoria.Client.GameObjectExplorer.Views.TypeEditors;
using Memoria.Test;
using UnityEngine;

namespace Memoria.Client
{
    public class TransformView<T> : ComponentView<T> where T : TransformMessage
    {
        public TransformView(T message, RemoteGameObjects context)
            : base(message, context)
        {
        }

        [Category("Transform")]
        [DisplayName("LocalPosition")]
        [Description("Position of the transform relative to the parent transform.")]
        [Editor(typeof(Vector3Editor), typeof(Vector3Editor))]
        public Vector3 LocalPosition
        {
            get { return Native.LocalPosition; }
            set
            {
                {
                    Native.LocalPosition = value;
                    SendPropertyChanged(nameof(Transform.localPosition), new Vector3Message(value));
                }
            }
        }

        [Category("Transform")]
        [DisplayName("LocalScale")]
        [Description("The scale of the transform relative to the parent.")]
        [Editor(typeof(Vector3Editor), typeof(Vector3Editor))]
        public Vector3 LocalScale
        {
            get { return Native.LocalScale; }
            set
            {
                {
                    Native.LocalScale = value;
                    SendPropertyChanged(nameof(Transform.localScale), new Vector3Message(value));
                }
            }
        }

        [Category("Transform")]
        [DisplayName("LocalEulerAngles")]
        [Description("The rotation as Euler angles in degrees relative to the parent transform's rotation.")]
        [Editor(typeof(Vector3Editor), typeof(Vector3Editor))]
        public Vector3 LocalEulerAngles
        {
            get { return Native.LocalEulerAngles; }
            set
            {
                {
                    Native.LocalEulerAngles = value;
                    SendPropertyChanged(nameof(Transform.localEulerAngles), new Vector3Message(value));
                }
            }
        }

        [Category("Transform")]
        [DisplayName("LocalRotation")]
        [Description("The rotation of the transform relative to the parent transform's rotation.")]
        [Editor(typeof(QuaternionEditor), typeof(QuaternionEditor))]
        public Quaternion LocalRotation
        {
            get { return Native.LocalRotation; }
            set
            {
                {
                    Native.LocalRotation = value;
                    SendPropertyChanged(nameof(Transform.localRotation), new QuaternionMessage(value));
                }
            }
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Chondrioderma friesianum Rostaf.

### Remarks
null


text:
namespace process {
namespace io {
namespace internal {

#ifndef ENABLE_LIBWINIO
Future<size_t> read(int_fd fd, void* data, size_t size);
#else
Future<size_t> read(
    int_fd fd,
    void* data,
    size_t size,
    bool bypassZeroByteRead);
#endif // ENABLE_LIBWINIO

Future<size_t> write(int_fd fd, const void* data, size_t size);

Try<Nothing> prepare_async(int_fd fd);

Try<bool> is_async(int_fd fd);

} // namespace internal {
} // namespace io {
} // namespace process {

#endif // __IO_INTERNAL_HPP__


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

using OpenTK;

using FarseerPhysics.Dynamics;
using FarseerPhysics.Collision.Shapes;

using Duality.Editor;
using Duality.Cloning;

namespace Duality.Components.Physics
{
	/// <summary>
	/// Describes a <see cref="RigidBody">Colliders</see> primitive shape. A Colliders overall shape may be combined of any number of primitive shapes.
	/// </summary>
	[Serializable]
	public abstract class ShapeInfo : Duality.Cloning.ICloneExplicit
	{
		[NonSerialized]
		protected	Fixture		fixture		= null;
		private		RigidBody	parent		= null;
		private		float		density		= 1.0f;
		private		float		friction	= 0.3f;
		private		float		restitution	= 0.3f;
		private		bool		sensor		= false;

		/// <summary>
		/// [GET] The shape's parent <see cref="RigidBody"/>.
		/// </summary>
		[EditorHintFlags(MemberFlags.Invisible)]
		public RigidBody Parent
		{
			get { return this.parent; }
			internal set { this.parent = value; }
		}
		/// <summary>
		/// [GET / SET] The shapes density.
		/// </summary>
		[EditorHintIncrement(0.05f)]
		[EditorHintRange(0.0f, 100.0f)]
		public float Density
		{
			get { return this.density; }
			set
			{
				this.density = value;
				if (this.parent != null) // Full update to recalculate mass
					this.parent.FlagBodyShape();
				else
					this.UpdateFixture();
			}
		}
		/// <summary>
		/// [GET / SET] Whether or not the shape acts as sensor i.e. is not part of a rigid body.
		/// </summary>
		public bool IsSensor
		{
			get { return this.sensor; }
			set { this.sensor = value; this.UpdateFixture(); }
		}
		/// <summary>
		/// [GET / SET] The shapes friction value. Usually a value between 0.0 and 1.0, but higher values can be used to indicate unusually strong friction.
		/// </summary>
		[EditorHintIncrement(0.05f)]
		[EditorHintRange(0.0f, 10000.0f)]
		public float Friction
		{
			get { return this.friction; }
			set { this.friction = value; this.UpdateFixture(); }
		}
		/// <summary>
		/// [GET / SET] The shapes restitution value. Should be a value between 0.0 and 1.0.
		/// </summary>
		[EditorHintIncrement(0.05f)]
		[EditorHintRange(0.0f, 1.0f)]
		public float Restitution
		{
			get { return this.restitution; }
			set { this.restitution = value; this.UpdateFixture(); }
		}
		/// <summary>
		/// [GET] Whether or not the shape is a valid part of the physical simulation
		/// </summary>
		[EditorHintFlags(MemberFlags.Invisible)]
		public bool IsValid
		{
			get { return this.fixture != null || (this.parent != null && this.parent.IsFlaggedForSync); }
		}
		/// <summary>
		/// [GET] Returns the Shapes axis-aligned bounding box
		/// </summary>
		[EditorHintFlags(MemberFlags.Invisible)]
		public abstract Rect AABB { get; }

		protected ShapeInfo()
		{
		}
		protected ShapeInfo(float density)
		{
			this.density = density;
		}

		/// <summary>
		/// Updates the internal <see cref="RigidBody"/> Shape according to its properties.
		/// </summary>
		public void UpdateShape()
		{
			this.UpdateFixture(true);
		}

		internal void DestroyFixture(Body body, bool isBodyDisposing)
		{
			if (this.fixture == null) return;
			if (!isBodyDisposing)
				body.DestroyFixture(this.fixture);
			this.fixture = null;
		}
		protected abstract Fixture CreateFixture(Body body);
		internal virtual void UpdateFixture(bool updateShape = false)
		{
			// When updating fixture shapes at runtime, we'll need to re-initialize the whole body
			if (updateShape && this.fixture != null && (DualityApp.ExecContext == DualityApp.ExecutionContext.Game || DualityApp.ExecEnvironment == DualityApp.ExecutionEnvironment.Editor))
			{
				if (this.parent != null && this.parent.FlagBodyShape())
				{
					this.DestroyFixture(this.parent.PhysicsBody, false); // Also, kill the changed fixture, so it gets re-registered.
					return;
				}
			}

			// Create the fixture, if not done yet
			if (this.fixture == null)
			{
				if (this.parent != null && this.parent.PhysicsBody != null)
				{
					this.fixture = this.CreateFixture(this.parent.PhysicsBody);
					if (this.fixture == null) return;
					this.fixture.UserData = this;
				}
				else return;
			}

			this.fixture.Shape.Density = this.density;
			this.fixture.IsSensor = this.sensor;
			this.fixture.Restitution = this.restitution;
			this.fixture.Friction = this.friction;
		}

		/// <summary>
		/// Copies this ShapeInfos data to another one. It is assumed that both are of the same type.
		/// </summary>
		/// <param name="target"></param>
		protected virtual void OnCopyTo(ShapeInfo target)
		{
			// Don't copy the parent!
			target.density = this.density;
			target.sensor = this.sensor;
			target.friction = this.friction;
			target.restitution = this.restitution;
		}
		/// <summary>
		/// Clones the ShapeInfo.
		/// </summary>
		/// <returns></returns>
		public ShapeInfo Clone()
		{
			return Cloning.CloneProvider.DeepClone(this);
		}
		public void CopyTo(ShapeInfo other)
		{
			Cloning.CloneProvider.DeepCopyTo(this, other);
		}

		void ICloneExplicit.CopyDataTo(object targetObj, CloneProvider provider)
		{
			ShapeInfo targetShape = targetObj as ShapeInfo;
			this.OnCopyTo(targetShape);
		}
	}
}


text:
<?php
require_once __DIR__.'/../../../unit.php';
require_once MISAGO."/lib/Misago/ActionView/Helpers/TagHelper.php";
require_once MISAGO."/lib/Misago/ActionView/Helpers/FormTagHelper.php";
require_once MISAGO."/lib/Misago/ActionView/Helpers/UrlHelper.php";
use Misago\ActionController;

class Test_ActionView_Helpers_UrlHelper extends Misago\Unit\TestCase
{
  function test_link_to()
  {
    $this->assert_equal(link_to('abcd', '/'), 'abcd');
    $this->assert_equal(link_to('azerty', '/page/123'), 'azerty');
    $this->assert_equal(link_to('azerty', '/page/123', array('class' => 'toto')), 'azerty');
    $this->assert_equal(link_to('azerty', '/posts/tag/abcd', array('rel' => 'tag')), 'azerty');

    $this->assert_equal(link_to('categories', array(':controller' => 'archives', ':action' => 'categories')),
      'categories');

    $this->assert_equal(link_to('products (desc)',
      array(':controller' => 'products', 'order' => 'desc')),
      'products (desc)');
    $this->assert_equal(link_to('products',
      array(':controller' => 'products', 'order' => 'desc', 'field' => 'date')),
      'products');

    $this->assert_equal(link_to('azerty', 'http://www.domain.com/posts/tag/abcd', array('rel' => 'tag')),
      'azerty');
    $this->assert_equal(link_to('http://toto.com/'), 'http://toto.com/');
  }

  function test_link_to_with_non_get_methods()
  {
    $html_link = link_to('delete me', new ActionController\Routing\Path('DELETE', 'page/123'));
    $this->assert_equal($html_link, 'delete me');

    $html_link = link_to('destroy me', new ActionController\Routing\Path('DELETE', 'page/459'), array('class' => 'destroy'));
    $this->assert_equal($html_link, 'destroy me');

    $html_link = link_to('update me', new ActionController\Routing\Url('PUT', 'page/456'));
    $this->assert_equal($html_link, 'update me');

    $html_link = link_to('update me', '/page/123', array('method' => 'put'));
    $this->assert_equal($html_link, 'update me');

    $html_link = link_to('delete', new ActionController\Routing\Path('DELETE', 'posts/2'), array('method' => 'put'));
    $this->assert_equal($html_link, 'delete');
  }

  function test_link_to_with_javascript_confirm()
  {
    $html_link = link_to('read me', '/posts/1', array('confirm' => 'Are you sure?'));
    $this->assert_equal($html_link, 'read me');

    $html_link = link_to('delete', new ActionController\Routing\Path('DELETE', 'posts/1'), array('confirm' => 'Are you sure?'));
    $this->assert_equal($html_link, 'delete');

    $html_link = link_to('delete', '/posts/2', array('confirm' => 'sample text with "quotes" and \'single quotes\''));
    $this->assert_equal($html_link, 'delete');

    $html_link = link_to('delete', new ActionController\Routing\Path('DELETE', 'posts/1'), array('confirm' => 'sample text with \'single quotes\' and "double quotes"'));
    $this->assert_equal($html_link, 'delete');
  }

  function test_link_to_if()
  {
    $this->assert_equal('destroy this', link_to_if(true, 'destroy this', '/delete'));
    $this->assert_equal('destroy this', link_to_if(false, 'destroy this', '/delete'));
    $this->assert_equal('events', link_to_if(true, 'events', events_path()));
  }

  function test_link_to_unless()
  {
    $this->assert_equal('destroy this', link_to_unless(false, 'destroy this', '/delete'));
    $this->assert_equal('destroy this', link_to_unless(true, 'destroy this', '/delete'));
    $this->assert_equal('events', link_to_unless(false, 'events', events_path()));
  }

  function test_current_page()
  {
#    $map = ActionController\Routing\Routes::draw();
#    $map->reset();
#    $map->connect(':controller/:action/:id.:format');

    $_SERVER['REQUEST_URI'] = '/archives';
    $this->assert_true(current_page('/archives'));
    $this->assert_false(current_page('/articles'));
    $this->assert_true(current_page(array(':controller' => 'archives')));
    $this->assert_false(current_page(array(':controller' => 'accounts')));
    $this->assert_false(current_page(array(':controller' => 'archives', ':action' => 'categories')));
    $this->assert_true(current_page(new ActionController\Routing\Path('GET', 'archives')));
    $this->assert_false(current_page(new ActionController\Routing\Path('GET', 'articles')));
#    $this->assert_true(current_page(new ActionController\Routing\Url('GET', 'archives')));
#    $this->assert_false(current_page(new ActionController\Routing\Url('GET', 'archives/mine')));

    $_SERVER['REQUEST_URI'] = '/mailbox/show/45';
    $this->assert_false(current_page(array(':controller' => 'archives', ':action' => 'show', ':id' => 45)));
    $this->assert_true(current_page(array(':controller' => 'mailbox', ':action' => 'show', ':id' => 45)));

    $_SERVER['REQUEST_URI'] = '/mailbox?order=desc';
    $this->assert_true(current_page(array(':controller' => 'mailbox')));
    $this->assert_false(current_page(array(':controller' => 'mailbox', 'order' => 'asc')));
    $this->assert_true(current_page(array(':controller' => 'mailbox', 'order' => 'desc')));
  }

  function test_link_to_unless_current()
  {
    $_SERVER['REQUEST_URI'] = '/archives';
    $this->assert_equal(link_to_unless_current('Archives', '/archives'),
      'Archives');
    $this->assert_equal(link_to_unless_current('Products', '/products'),
      'Products');
    $this->assert_equal(link_to_unless_current('archives', array(':controller' => 'archives')),
      'archives');
    $this->assert_equal(link_to_unless_current('List', array(':controller' => 'accounts')),
      'List');
    $this->assert_equal(link_to_unless_current('categories',
      array(':controller' => 'archives', ':action' => 'categories')),
      'categories');

    $_SERVER['REQUEST_URI'] = '/article/45';
    $this->assert_equal(link_to_unless_current('more details',
      array(':controller' => 'products', ':action' => 'show', ':id' => 45)),
      'more details');
    $this->assert_equal(link_to_unless_current('article',
      array(':controller' => 'articles', ':action' => 'show', ':id' => 45)),
      'article');

    $_SERVER['REQUEST_URI'] = '/articles?order=desc';
    $this->assert_equal(link_to_unless_current('articles', array(':controller' => 'articles')),
      'articles');
    $this->assert_equal(link_to_unless_current('articles (asc)', array(':controller' => 'articles', 'order' => 'asc')),
      'articles (asc)');
    $this->assert_equal(link_to_unless_current('articles (desc)', array(':controller' => 'articles', 'order' => 'desc')),
      'articles (desc)');
  }

  function test_button_to()
  {
    $html = button_to('new', array(':controller' => 'products', ':action' => 'new'));
    $this->assert_equal($html, '<form action="/products/new" method="post" class="button-to">'.
      '
<input type="submit" value="new"/>
'.
      '</form>');

    $html = button_to('new', array(':controller' => 'products', ':action' => 'new', 'field' => 'a', 'param' => 'b'));
    $this->assert_equal($html, '<form action="/products/new?field=a&param=b" method="post" class="button-to">'.
      '
<input type="submit" value="new"/>
'.
      '</form>');

    $html = button_to('new', array(':controller' => 'products', ':action' => 'delete', ':id' => 2), array('method' => 'delete', 'confirm' => 'Are you sure?'));
    $this->assert_equal($html, '<form action="/product/2" method="post" class="button-to" onsubmit="return confirm(\'Are you sure?\');">'.
      '<input type="hidden" name="_method" value="delete"/>'.
      '
<input type="submit" value="new"/>
'.
      '</form>');
  }

  function test_mail_to()
  {
    $html = mail_to('me@webcomics.fr');
    $this->assert_equal($html, 'me@webcomics.fr');

    $html = mail_to('me@webcomics.fr', 'julien');
    $this->assert_equal($html, 'julien');

    $html = mail_to('another@bd-en-ligne.fr', 'sabrina', array('class' => 'email'));
    $this->assert_equal($html, 'sabrina');
  }
}

?>


text:
@echo off

tools\nuget setApiKey <API_KEY> -ConfigFile tools\NuGet.Config
tools\nuget pack materialnote.nuspec -version <VERSION> -OutputDirectory build


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * QuotationListInternalFrame.java
 *
 * Created on Apr 7, 2013, 11:24:35 AM
 */
package com.freebasicacc.ui;

import com.freebasicacc.ui.action.MainFrameAction;
import javax.swing.ImageIcon;
import javax.swing.JFrame;

/**
 *
 * @author benzyaa
 */
public class QuotationListInternalFrame extends javax.swing.JInternalFrame {

    /** Creates new form QuotationListInternalFrame */
    public QuotationListInternalFrame() {
        initComponents();
        this.SetIcon();
        this.setTitleFont();
    }

    public QuotationListInternalFrame(JFrame mainFrame) {
        initComponents();
        this.SetIcon();
        this.setTitleFont();
        this.quotationInfoListPanel1.setMainFrame(mainFrame);
    }

     private void SetIcon(){
        ImageIcon mainIcon = new ImageIcon(getClass().getResource("/com/freebasicacc/ui/image/Document1616.png"));
        this.setFrameIcon(mainIcon);
    }

    private void setTitleFont(){
        MainFrameAction action = new MainFrameAction();
        action.setInternalFramTitle(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        quotationInfoListPanel1 = new com.freebasicacc.ui.QuotationInfoListPanel();

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        setClosable(true);
        setResizable(true);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("com/freebasicacc/ui/bundle"); // NOI18N
        setTitle(bundle.getString("list.quotation")); // NOI18N
        setPreferredSize(new java.awt.Dimension(1024, 768));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(quotationInfoListPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(quotationInfoListPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 551, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    protected com.freebasicacc.ui.QuotationInfoListPanel quotationInfoListPanel1;
    // End of variables declaration//GEN-END:variables
}


text:
import os
import re
import sys

import pandas

from rpy2.robjects.lib import ggplot2
from rpy2.robjects import pandas2ri

from crawlplot import PLOTDIR, GGPLOT2_THEME

from crawlstats import CST, MultiCount
from crawl_size import CrawlSizePlot

pandas2ri.activate()

class CrawlerMetrics(CrawlSizePlot):

    metrics_map = {
        'fetcher:aggr:redirect': ('fetcher:temp_moved', 'fetcher:moved',
                                  'fetcher:redirect_count_exceeded',
                                  'fetcher:redirect_deduplicated'),
        'fetcher:aggr:denied':   ('fetcher:access_denied',
                                  'fetcher:robots_denied',
                                  'fetcher:robots_denied_maxcrawldelay',
                                  'fetcher:filter_denied'),
        'fetcher:aggr:failed':   ('fetcher:gone', 'fetcher:notfound',
                                  'fetcher:exception'),
        'fetcher:aggr:skipped':  ('fetcher:hitByThrougputThreshold',
                                  'fetcher:hitByTimeLimit',
                                  'fetcher:AboveExceptionThresholdInQueue',
                                  'fetcher:filtered')
    }

    def __init__(self):
        super().__init__()
        self.sum_counts = True

    def add(self, key, val):
        cst = CST[key[0]]
        item_type = key[1]
        crawl = key[2]
        if not (cst == CST.crawl_status or
                (cst == CST.size and item_type in ('page', 'url'))
                or cst == CST.scheme):
            return
        if cst == CST.scheme:
            item_type = 'scheme:' + item_type
            val = MultiCount.get_count(1, val)
        self.add_by_type(crawl, item_type, val)
        for metric in self.metrics_map:
            if item_type in self.metrics_map[metric]:
                self.add_by_type(crawl, metric, val)

    def save_data(self):
        self.size.sort_values(['crawl'], inplace=True)
        self.size.to_csv('data/crawlmetrics.csv')
        self.size_by_type.to_csv('data/crawlmetricsbytype.csv')

    def add_percent(self):
        for crawl in self.crawls:
            for item_type in self.type_index:
                if self.crawls[crawl] not in self.size[item_type]:
                    continue
                count = self.size[item_type][self.crawls[crawl]]
                _N = self.type_index[item_type][self.crawls[crawl]]
                if (item_type.startswith('fetcher:') and
                    item_type != 'fetcher:total' and
                    self.crawls[crawl] in self.size['fetcher:total']):
                    total = self.size['fetcher:total'][self.crawls[crawl]]
                    self.size_by_type['percentage'][_N] = 100.0*count/total
                elif item_type.startswith('scheme:'):
                    total = self.size['url'][self.crawls[crawl]]
                    self.size_by_type['percentage'][_N] = 100.0*count/total

    @staticmethod
    def row2title(row):
        row = re.sub('(?<=^fetch)er(?::aggr)?|^generator:', '', row)
        row = re.sub('[:_]', ' ', row)
        if row == 'page':
            row = 'pages released'
        return row

    def plot(self):
        # -- line plot
        row_types = [# 'generator:crawldb_size',
                     'generator:fetch_list',
                     'fetcher:success', 'fetcher:total',
                     'fetcher:aggr:redirect', 'fetcher:notmodified',
                     'fetcher:aggr:failed', 'fetcher:aggr:denied',
                     'fetcher:aggr:skipped', 'page']
        self.size_plot(self.size_by_type, row_types, CrawlerMetrics.row2title,
                       'Crawler Metrics', 'Pages',
                       'crawler/metrics.png')
        # -- stacked bar plot
        row_types = ['fetcher:success', 'fetcher:notmodified',
                     'fetcher:aggr:redirect', 'fetcher:aggr:failed',
                     'fetcher:aggr:denied', 'fetcher:aggr:skipped']
        ratio = 0.1 + self.ncrawls * .05
        self.plot_fetch_status(self.size_by_type, row_types,
                               'crawler/fetch_status_percentage.png',
                               ratio=ratio)
        # -- status of pages in CrawlDb
        row_types = ['crawldb:status:db_fetched',
                     'crawldb:status:db_notmodified',
                     'crawldb:status:db_redir_perm',
                     'crawldb:status:db_redir_temp',
                     'crawldb:status:db_duplicate',
                     'crawldb:status:db_gone',
                     'crawldb:status:db_unfetched',
                     'crawldb:status:db_orphan']
        self.plot_crawldb_status(self.size_by_type, row_types,
                                 'crawler/crawldb_status.png',
                                 ratio=ratio)
        # successfully fetched http:// vs https:// URLs
        self.size_plot(self.size_by_type, ['scheme:http', 'scheme:https'], lambda x: x.split(':')[1],
                       'HTTP vs HTTPS URLs', 'Successfully fetched URLs',
                       'crawler/url_protocols.png')
        self.size_plot(self.size_by_type, ['scheme:http', 'scheme:https'], lambda x: x.split(':')[1],
                       'Percentage of HTTP vs HTTPS URLs', 'Percentage of successfully fetched URLs',
                       'crawler/url_protocols_percentage.png', y='percentage')

    def plot_fetch_status(self, data, row_filter, img_file, ratio=1.0):
        if row_filter:
            data = data[data['type'].isin(row_filter)]
        data = data[['crawl', 'percentage', 'type']]
        categories = []
        for value in row_filter:
            if re.search('^fetcher:(?:aggr:)?', value):
                replacement = re.sub('^fetcher:(?:aggr:)?', '', value)
                categories.append(replacement)
                data.replace(to_replace=value, value=replacement, inplace=True)
        data['type'] = pandas.Categorical(data['type'], ordered=True,
                                          categories=categories.reverse())
        ratio = 0.1 + len(data['crawl'].unique()) * .03
        # print(data)
        p = ggplot2.ggplot(data) \
            + ggplot2.aes_string(x='crawl', y='percentage', fill='type') \
            + ggplot2.geom_bar(stat='identity', position='stack', width=.9) \
            + ggplot2.coord_flip() \
            + ggplot2.scale_fill_brewer(palette='RdYlGn', type='sequential',
                                        guide=ggplot2.guide_legend(reverse=True)) \
            + GGPLOT2_THEME \
            + ggplot2.theme(**{'legend.position': 'bottom',
                               'aspect.ratio': ratio}) \
            + ggplot2.labs(title='Percentage of Fetch Status',
                           x='', y='', fill='')
        img_path = os.path.join(PLOTDIR, img_file)
        p.save(img_path, height = int(7 * ratio), width = 7)
        return p

    def plot_crawldb_status(self, data, row_filter, img_file, ratio=1.0):
        if row_filter:
            data = data[data['type'].isin(row_filter)]
        categories = []
        for value in row_filter:
            if re.search('^crawldb:status:db_', value):
                replacement = re.sub('^crawldb:status:db_', '', value)
                categories.append(replacement)
                data.replace(to_replace=value, value=replacement, inplace=True)
        data['type'] = pandas.Categorical(data['type'], ordered=True,
                                          categories=categories.reverse())
        data['size'] = data['size'].astype(float)
        ratio = 0.1 + len(data['crawl'].unique()) * .03
        print(data)
        p = ggplot2.ggplot(data) \
            + ggplot2.aes_string(x='crawl', y='size', fill='type') \
            + ggplot2.geom_bar(stat='identity', position='stack', width=.9) \
            + ggplot2.coord_flip() \
            + ggplot2.scale_fill_brewer(palette='Pastel1', type='sequential',
                                        guide=ggplot2.guide_legend(reverse=False)) \
            + GGPLOT2_THEME \
            + ggplot2.theme(**{'legend.position': 'bottom',
                               'aspect.ratio': ratio}) \
            + ggplot2.labs(title='CrawlDb Size and Status Counts (before crawling)',
                           x='', y='', fill='')
        img_path = os.path.join(PLOTDIR, img_file)
        p.save(img_path, height = int(7 * ratio), width = 7)
        return p

if __name__ == '__main__':
    plot = CrawlerMetrics()
    plot.read_data(sys.stdin)
    plot.add_percent()
    plot.transform_data()
    plot.save_data()
    plot.plot()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Equalizer</title>
<meta name="date" content="2012-12-12">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javazoom.jl.decoder

Class Equalizer

java.lang.Object

javazoom.jl.decoder.Equalizer

public final class Equalizer
extends java.lang.Object

The Equalizer class can be used to specify
 equalization settings for the MPEG audio decoder.

 The equalizer consists of 32 band-pass filters.
 Each band of the equalizer can take on a fractional value between
 -1.0 and +1.0.
 At -1.0, the input signal is attenuated by 6dB, at +1.0 the signal is
 amplified by 6dB.

Author:

MDM

See Also:

Decoder

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
Equalizer.EQFunction

Field Summary

Fields

Modifier and Type
Field and Description

static float
BAND_NOT_PRESENT

Equalizer setting to denote that a given band will not be
 present in the output signal.

static Equalizer
PASS_THRU_EQ

Constructor Summary

Constructors

Constructor and Description

Equalizer()

Creates a new Equalizer instance.

Equalizer(Equalizer.EQFunction eq)

Equalizer(float[] settings)

Method Summary

Methods

Modifier and Type
Method and Description

float
getBand(int band)

Retrieves the eq setting for a given band.

int
getBandCount()

Retrieves the number of bands present in this equalizer.

void
reset()

Sets all bands to 0.0

float
setBand(int band,
       float neweq)

void
setFrom(Equalizer.EQFunction eq)

void
setFrom(Equalizer eq)

Sets the bands of this equalizer to the value the bands of
 another equalizer.

void
setFrom(float[] eq)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

BAND_NOT_PRESENT

public static final float BAND_NOT_PRESENT

Equalizer setting to denote that a given band will not be
 present in the output signal.

See Also:

Constant Field Values

PASS_THRU_EQ

public static final Equalizer PASS_THRU_EQ

Constructor Detail

Equalizer

public Equalizer()

Creates a new Equalizer instance.

Equalizer

public Equalizer(float[] settings)

Equalizer

public Equalizer(Equalizer.EQFunction eq)

Method Detail

setFrom

public void setFrom(float[] eq)

setFrom

public void setFrom(Equalizer.EQFunction eq)

setFrom

public void setFrom(Equalizer eq)

Sets the bands of this equalizer to the value the bands of
 another equalizer. Bands that are not present in both equalizers are ignored.

reset

public void reset()

Sets all bands to 0.0

getBandCount

public int getBandCount()

Retrieves the number of bands present in this equalizer.

setBand

public float setBand(int band,
            float neweq)

getBand

public float getBand(int band)

Retrieves the eq setting for a given band.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package ca.kanoa.rodstwo.rods;

import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ShapedRecipe;

import ca.kanoa.rodstwo.config.ConfigOptions;

public class Default extends Rod {

	public Default() throws Exception {
	    super("Debug", 1, 280, new ConfigOptions(new String[]{}, new Object[]{}), 500);
	    setRecipe(new ShapedRecipe(super.getItem()).shape("DDD", "DBD", "DDD").setIngredient('D', Material.SPONGE).setIngredient('B', Material.STICK));
	}

	@Override
	public boolean run(Player player, ConfigurationSection config) {
	    return false;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>PHP Oxford User Group</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/freelancer.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                PHP Oxford

                        About

                        Next meetup

                        Past meetups

                        Code of conduct

                        IRC

PHP Oxford User Group

                        On the last Wednesday of every month. View details of all our meet-ups on
                        our Meetup page.

                    Do you use Drupal or Symfony? Do you use Wordpress or Laravel? Whatever your flavour of PHP we'd love to meet you and share our knowledge.
                    We gather once a month for a quiet drink in a local public house, to get to know each other. See you there!

We're always looking for speakers for future events. Do you have something to say? Would you like to tell us about your latest project? If you do, please ping us on twitter.

Sponsored by Haybrook IT.
The leading IT recruitment specialists for Oxfordshire and the surrounding counties.

Next Meetup

                        <time datetime="2016-10-26 19:30">Wednesday 26th October</time> at
                        The Basement, Oxford.

                        Postgres for MySQL users
                        [view Meetup event]

                        Presented by Liam Wiltshire (@l_wiltshire)

                        Postgres - a powerful DBMS with a big feature set, good performance, and is built stability. Yet in PHP,
                        it's commonly overlooked for mySQL (and its forks) or NoSQL options.

                        If you're a mySQL user, Postgres might seem strange - from the way you install and configure it to the way
                        you interact with it and create schemas. Things are different.

                        Join Liam as he discusses reasons you might use Postgres, and looks at the differences between the two.

                        --

                        Liam is a UK based Senior PHP Developer & Business Manager at Tebex, creators of Buycraft.net, the first
                        e-commerce platform for Minecraft. In his nine years as a dev, he's tackled projects large and small,
                        from multi-million pound eCommerce sites to the plumber down the road looking for 'mates' rates. These
                        days Liam focuses on providing gCommerce platforms for multiplayer sandbox games, and in his spare time
                        is trying to learn the secret to actually having some spare time.

                            Please sign up on meetup.com
                        so that we have a good idea of numbers.

                        Lightning talks

                        Got an idea you would like to talk about for 5-10
                        minutes? Let us know.

                        Social

                        Afterwards we'll head to a local watering hole for a
                        beer or two.

Past Meetups

                        Please see our Meetup.com page to see details of past meet-ups.

Code of conduct

                        Please note that all of our meet-ups are subject to our code of conduct.
                        Please read before attending. PHPOxford is committed to ensuring a safe and inclusive environment for all of our members and guests.

IRC & Calendar

                        We use irc to stay in touch, do join us at #phpoxford on freenode.
                        If you need a hand setting up irc these resources should help:

Wikipedia's guide to using irc

Fedora guide to irc

List of Ubuntu/Debian clients

List of Mac clients

List of Windows clients

Around the Web

                        Copyright © 2015-2016


text:
var app = angular.module('tictactoe', ['firebase']);
app.controller('TicTacToeCtrl', function Chat($scope, $firebaseObject) {
  // Get a reference to the Firebase
  var boardRef = new Firebase('https://angularfire.firebaseio-demo.com/tictactoe');

  // If the query string contains a push ID, use that as the child for data storage;
  // otherwise, generate a new random push ID
  var pushId;
  if (window.location && window.location.search) {
    pushId = window.location.search.substr(1).split('=')[1];
  }
  if (pushId) {
    boardRef = boardRef.child(pushId);
  } else {
    boardRef = boardRef.push();
  }

  // Put the random push ID into the DOM so that the test suite can grab it
  document.getElementById('pushId').innerHTML = boardRef.key();

  // Get the board as an AngularFire object
  $scope.boardObject = $firebaseObject(boardRef);

  // Create a 3-way binding to Firebase
  $scope.boardObject.$bindTo($scope, 'board');

  // Verify that $inst() works
  verify($scope.boardObject.$ref() === boardRef, 'Something is wrong with $firebaseObject.$ref().');

  // Initialize $scope variables
  $scope.whoseTurn = 'X';

  /* Resets the tictactoe Firebase reference */
  $scope.resetRef = function () {
    ["x0", "x1", "x2"].forEach(function (xCoord) {
      $scope.board[xCoord] = {
        y0: "",
        y1: "",
        y2: ""
      };
    });
  };

  /* Makes a move at the current cell */
  $scope.makeMove = function(rowId, columnId) {
    // Only make a move if the current cell is not already taken
    if ($scope.board[rowId][columnId] === "") {
      // Update the board
      $scope.board[rowId][columnId] = $scope.whoseTurn;

      // Change whose turn it is
      $scope.whoseTurn = ($scope.whoseTurn === 'X') ? 'O' : 'X';
    }
  };

  /* Destroys all AngularFire bindings */
  $scope.destroy = function() {
    $scope.boardObject.$destroy();
  };

  /* Logs a message and throws an error if the inputted expression is false */
  function verify(expression, message) {
    if (!expression) {
      console.log(message);
      throw new Error(message);
    }
  }
});


text:
package lendings

import (
	"strconv"
	"time"

	"github.com/deckarep/golang-set"
	"github.com/jinzhu/gorm"
	"github.com/thrasher-/gocryptotrader/exchanges/poloniex"
)

type Sync struct {
	db  *gorm.DB
	api *poloniex.Poloniex
}

func NewSync(db *gorm.DB, api *poloniex.Poloniex) *Sync {
	return &Sync{
		db:  db,
		api: api,
	}
}

func (sync *Sync) Sync(start, end time.Time) (int, error) {
	startTime := strconv.FormatInt(start.Unix(), 10)
	endTime := strconv.FormatInt(end.Unix(), 10)
	retval, err := sync.api.GetLendingHistory(startTime, endTime)
	if err != nil {
		return -1, err
	}

	var existRows []Lending
	sync.db.Select("lending_id").Find(&existRows)
	idSet := mapset.NewSet()
	for _, r := range existRows {
		idSet.Add(r.LendingID)
	}

	rows := []Lending{}
	for _, history := range retval {
		if idSet.Contains(history.ID) {
			continue
		}
		row := NewLendingRow(history)
		rows = append(rows, row)
	}
	for _, row := range rows {
		sync.db.Create(&row)
	}
	return len(rows), nil
}

func (sync *Sync) SyncAll() (int, error) {
	start := time.Unix(0, 0)
	end := time.Now()
	return sync.Sync(start, end)
}

func (sync *Sync) SyncRecent() (int, error) {
	start := sync.GetLastTime()
	end := time.Now()
	return sync.Sync(start, end)
}

func (sync *Sync) GetLastTime() time.Time {
	var last Lending
	sync.db.Order("open desc").First(&last)
	if last.ID == 0 {
		return time.Unix(0, 0)
	}
	return last.Open
}


text:
package com.hazelcast.client.connection;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.spi.impl.ConnectionHeartbeatListener;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.ConnectionListenable;

import java.io.IOException;

/**
 * Responsible for managing {@link com.hazelcast.client.connection.nio.ClientConnection} objects.
 */
public interface ClientConnectionManager extends ConnectionListenable {

    /**
     * Shutdown clientConnectionManager
     */
    void shutdown();

    /**
     * Check if client connection manager is alive.
     * ClientConnectionManager is not alive only when client is closing.
     *
     * @return true if alive, false otherwise.
     */
    boolean isAlive();

    /**
     * Start clientConnectionManager
     */
    void start();

    /**
     * @param address to be connected
     * @return connection if available, null otherwise
     */
    Connection getConnection(Address address);

    /**
     * @param address to be connected
     * @param asOwner true if connection should be authenticated as owner, false otherwise
     * @return associated connection if available, creates new connection otherwise
     * @throws IOException if connection is not established
     */
    Connection getOrConnect(Address address, boolean asOwner) throws IOException;

    /**
     * @param address to be connected
     * @param asOwner true if connection should be authenticated as owner, false otherwise
     * @return associated connection if available, returns null and triggers new connection creation otherwise
     */
    Connection getOrTriggerConnect(Address address, boolean asOwner);

    /**
     * Handles incoming network package
     *
     * @param message    to be processed
     * @param connection that client message come from
     */
    void handleClientMessage(ClientMessage message, Connection connection);

    void addConnectionHeartbeatListener(ConnectionHeartbeatListener connectionHeartbeatListener);
}


text:
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool

from .models import Plaintext

class PlaintextPlugin(CMSPluginBase):
    model = Plaintext
    render_template = 'cms/plugins/plaintext.html'

    def render(self, context, instance, placeholder):
        context['body'] = instance.body
        return context

plugin_pool.register_plugin(PlaintextPlugin)


text:
<?php
/**
 * Mondido
 *
 * PHP version 5.6
 *
 * @category Mondido
 * @package  Mondido_Mondido
 * @author   Andreas Karlsson <andreas@kodbruket.se>
 * @license  MIT License https://opensource.org/licenses/MIT
 * @link     https://www.mondido.com
 */

namespace Mondido\Mondido\Block\Info;

use Magento\Payment\Block\Info;

/**
 * Hosted Window info block
 *
 * @category Mondido
 * @package  Mondido_Mondido
 * @author   Andreas Karlsson <andreas@kodbruket.se>
 * @license  MIT License https://opensource.org/licenses/MIT
 * @link     https://www.mondido.com
 */
class HostedWindow extends Info
{
    /**
     * @var string
     */
    protected $_template = 'Mondido_Mondido::info/hostedwindow.phtml';

    /**
     * Prepare specific information
     *
     * @param null|\Magento\Framework\DataObject|array $transport Information
     *
     * @return \Magento\Framework\DataObject
     */
    protected function _prepareSpecificInformation($transport = null)
    {
        if (null !== $this->_paymentSpecificInformation) {
            return $this->_paymentSpecificInformation;
        }

        $info = $this->getInfo();
        $transport = new \Magento\Framework\DataObject();
        $transport->setData('ID', $info->getAdditionalInformation('id'));
        $transport->setData('URL', $info->getAdditionalInformation('href'));
        $transport->setData('Status', $info->getAdditionalInformation('status'));

        $transport = parent::_prepareSpecificInformation($transport);

        return $transport;
    }
}


text:
var todoMainTemplate = '
Add a Todo
' +
  '
' +
    'Todo Title' +
    '<input id="todo-input" class="form-control" type="text">' +
    '
' +
    'Todo Description' +
    '<input id="description-input" class="form-control" type="text">' +
    '
' +
    '<button id="add-todo" class="btn btn-success">Add todo</button>' +
    '
' +
  '
' +
  '

' +
  '
My Todos
' +
  '
' +
  '
';

var TodoMainView = Backbone.View.extend({
  el: '#my-app',
  initialize: function () {
    this.collection.fetch();
    $(this.el).html(todoMainTemplate);
  },
  render: function () {
    var todoListView = new TodoListView({collection: todos});
    todoListView.render();
    $('#todo-list').html(todoListView.$el);

    var todoInputView = new TodoInputView({collection: todos});

  }

});


text:
{% if page.comments %}

    Please enable JavaScript to view the comments powered by Disqus.
{% endif %}


text:
package org.apache.uima.fit.cpe;

import static java.util.Arrays.asList;
import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngineDescription;
import static org.apache.uima.fit.factory.ExternalResourceFactory.createExternalResourceDescription;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.uima.UIMAFramework;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.component.Resource_ImplBase;

import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.descriptor.ExternalResource;
import org.apache.uima.fit.factory.CollectionReaderFactory;
import org.apache.uima.fit.factory.ExternalResourceFactory;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.DataResource;
import org.apache.uima.resource.ExternalResourceDescription;
import org.apache.uima.resource.ParameterizedDataResource;
import org.apache.uima.resource.ResourceInitializationException;

import org.apache.uima.fit.cpe.CpePipelineTest.Reader;

import org.junit.Test;

/**
 * Test case for {@link ExternalResource} annotations.
 *
 */
public class ExternalResourceFactoryTest {

  @Test
  public void testMultiBinding() throws Exception {
    ExternalResourceDescription extDesc = createExternalResourceDescription(ResourceWithAssert.class);

    // Binding external resource to each Annotator individually
    AnalysisEngineDescription aed1 = createEngineDescription(MultiBindAE.class,
            MultiBindAE.RES_KEY, extDesc);
    AnalysisEngineDescription aed2 = createEngineDescription(MultiBindAE.class,
            MultiBindAE.RES_KEY, extDesc);

    // Check the external resource was injected
    MultiBindAE.reset();
    AnalysisEngineDescription aaed = createEngineDescription(aed1, aed2);
    CpePipeline.runPipeline(CollectionReaderFactory.createReaderDescription(Reader.class), aaed);
  }

  /**
   * Test resource list.
   */
  @Test
  public void testMultiValue() throws Exception {
    ExternalResourceDescription extDesc1 = createExternalResourceDescription(ResourceWithAssert.class);
    ExternalResourceDescription extDesc2 = createExternalResourceDescription(ResourceWithAssert.class);

    AnalysisEngineDescription aed = createEngineDescription(MultiValuedResourceAE.class,
            MultiValuedResourceAE.RES_RESOURCE_ARRAY, asList(extDesc1, extDesc2));

    CpePipeline.runPipeline(CollectionReaderFactory.createReaderDescription(Reader.class), aed);
  }

  /**
   * Test sharing a resource list between two AEs on the same aggregate.
   */
  @Test
  public void testMultiValue2() throws Exception {
    MultiValuedResourceAE.resources.clear();

    ExternalResourceDescription extDesc1 = createExternalResourceDescription(ResourceWithAssert.class);
    ExternalResourceDescription extDesc2 = createExternalResourceDescription(ResourceWithAssert.class);

    AnalysisEngineDescription aed = createEngineDescription(
            createEngineDescription(MultiValuedResourceAE.class,
                    MultiValuedResourceAE.RES_RESOURCE_ARRAY, asList(extDesc1, extDesc2)),
            createEngineDescription(MultiValuedResourceAE.class,
                    MultiValuedResourceAE.RES_RESOURCE_ARRAY, asList(extDesc1, extDesc2)));

    CpePipeline.runPipeline(CollectionReaderFactory.createReaderDescription(Reader.class), aed);

    // Check that the shared resources are really the same
    assertEquals(MultiValuedResourceAE.resources.get(0), MultiValuedResourceAE.resources.get(2));
    assertEquals(MultiValuedResourceAE.resources.get(1), MultiValuedResourceAE.resources.get(3));
  }

  /**
   * Test sharing a resource list across aggregates.
   */
  @Test
  public void testMultiValue3() throws Exception {
    MultiValuedResourceAE.resources.clear();

    ExternalResourceDescription extDesc1 = createExternalResourceDescription(ResourceWithAssert.class);
    ExternalResourceDescription extDesc2 = createExternalResourceDescription(ResourceWithAssert.class);

    AnalysisEngineDescription aed = createEngineDescription(
            createEngineDescription(MultiValuedResourceAE.class,
                    MultiValuedResourceAE.RES_RESOURCE_ARRAY, asList(extDesc1, extDesc2)),
            createEngineDescription(createEngineDescription(MultiValuedResourceAE.class,
                    MultiValuedResourceAE.RES_RESOURCE_ARRAY, asList(extDesc1, extDesc2))));

    CpePipeline.runPipeline(CollectionReaderFactory.createReaderDescription(Reader.class), aed);

    // Check that the shared resources are really the same
    assertEquals(MultiValuedResourceAE.resources.get(0), MultiValuedResourceAE.resources.get(2));
    assertEquals(MultiValuedResourceAE.resources.get(1), MultiValuedResourceAE.resources.get(3));
  }

  /**
   * Test nested resource lists.
   */
  @Test
  public void testMultiValue4() throws Exception {
    ExternalResourceDescription extDesc1 = createExternalResourceDescription(ResourceWithAssert.class);
    ExternalResourceDescription extDesc2 = createExternalResourceDescription(ResourceWithAssert.class);

    ExternalResourceDescription extDesc3 = createExternalResourceDescription(ResourceWithAssert.class);
    ExternalResourceDescription extDesc4 = createExternalResourceDescription(ResourceWithAssert.class);

    ExternalResourceDescription mv1 = createExternalResourceDescription(MultiValuedResource.class,
            MultiValuedResource.RES_RESOURCE_LIST, new ExternalResourceDescription[] { extDesc1,
                extDesc2 });

    ExternalResourceDescription mv2 = createExternalResourceDescription(MultiValuedResource.class,
            MultiValuedResource.RES_RESOURCE_LIST, new ExternalResourceDescription[] { extDesc3,
                extDesc4 });

    AnalysisEngineDescription aed = createEngineDescription(MultiValuedResourceAE.class,
            MultiValuedResourceAE.RES_RESOURCE_ARRAY, asList(mv1, mv2));

    CpePipeline.runPipeline(CollectionReaderFactory.createReaderDescription(Reader.class), aed);
  }

  public static final class MultiValuedResourceAE extends
          org.apache.uima.fit.component.JCasAnnotator_ImplBase {
    static final String RES_RESOURCE_ARRAY = "resourceArray";

    @ExternalResource(key = RES_RESOURCE_ARRAY)
    ResourceWithAssert[] resourceArray;

    public static List<ResourceWithAssert> resources = new ArrayList<ResourceWithAssert>();

    @Override
    public void process(JCas aJCas) throws AnalysisEngineProcessException {
      assertNotNull("Resource array is null", resourceArray);
      assertEquals(2, resourceArray.length);
      assertTrue("Resource array element 0 is not a DummyResource",
              resourceArray[0] instanceof ResourceWithAssert);
      assertTrue("Resource array element 1 is not a DummyResource",
              resourceArray[1] instanceof ResourceWithAssert);
      assertTrue(resourceArray[0] != resourceArray[1]);

      resources.add(resourceArray[0]);
      resources.add(resourceArray[1]);

      System.out.printf("Element object 0: %d%n", resourceArray[0].hashCode());
      System.out.printf("Element object 1: %d%n", resourceArray[1].hashCode());

      for (ResourceWithAssert res : resourceArray) {
        res.doAsserts();
      }
    }
  }

  public static final class MultiValuedResource extends ResourceWithAssert {
    static final String RES_RESOURCE_LIST = "resourceList";

    @ExternalResource(key = RES_RESOURCE_LIST)
    List<ResourceWithAssert> resourceList;

    public static List<ResourceWithAssert> resources = new ArrayList<ResourceWithAssert>();

    @Override
    public void doAsserts() {
      assertNotNull("Resource array is null", resourceList);
      assertEquals(2, resourceList.size());
      assertTrue("Resource array element 0 is not a MultiValuedResourceAE",
              resourceList.get(0) instanceof ResourceWithAssert);
      assertTrue("Resource array element 1 is not a MultiValuedResourceAE",
              resourceList.get(1) instanceof ResourceWithAssert);
      assertTrue(resourceList.get(0) != resourceList.get(1));

      resources.add(resourceList.get(0));
      resources.add(resourceList.get(1));

      System.out.printf("Element object 0: %d%n", resourceList.get(0).hashCode());
      System.out.printf("Element object 1: %d%n", resourceList.get(1).hashCode());

      for (ResourceWithAssert res : resourceList) {
        res.doAsserts();
      }
    }
  }

  /**
   * Example annotator that uses the share model object. In the process() we only test if the model
   * was properly initialized by uimaFIT
   */
  public static class MultiBindAE extends org.apache.uima.fit.component.JCasAnnotator_ImplBase {
    static int prevHashCode = -1;

    static final String RES_KEY = "Res";

    @ExternalResource(key = RES_KEY)
    ResourceWithAssert res;

    @Override
    public void process(JCas aJCas) throws AnalysisEngineProcessException {
      if (prevHashCode == -1) {
        prevHashCode = res.hashCode();
      } else {
        assertEquals(prevHashCode, res.hashCode());
      }

      System.out.println(getClass().getSimpleName() + ": " + res);
    }

    public static void reset() {
      prevHashCode = -1;
    }
  }

  public static class ResourceWithAssert extends Resource_ImplBase {
    public void doAsserts() {
      // Nothing by default
    }
  }

  public static final class AnnotatedDataResource extends Resource_ImplBase implements DataResource {
    public static final String PARAM_URI = "Uri";

    @ConfigurationParameter(name = PARAM_URI, mandatory = true)
    private String uri;

    public static final String PARAM_EXTENSION = "Extension";

    @ConfigurationParameter(name = PARAM_EXTENSION, mandatory = true)
    private String extension;

    public InputStream getInputStream() throws IOException {
      return null;
    }

    public URI getUri() {
      return URI.create(uri + extension);
    }

    public URL getUrl() {
      return null;
    }
  }

  public static final class AnnotatedParametrizedDataResource extends Resource_ImplBase implements
          ParameterizedDataResource {
    public static final String PARAM_EXTENSION = "Extension";

    @ConfigurationParameter(name = PARAM_EXTENSION, mandatory = true)
    private String extension;

    public DataResource getDataResource(String[] aParams) throws ResourceInitializationException {
      List<String> params = new ArrayList<String>(Arrays.asList(aParams));
      params.add(AnnotatedDataResource.PARAM_EXTENSION);
      params.add(extension);
      ExternalResourceDescription desc = ExternalResourceFactory.createExternalResourceDescription(
              null, AnnotatedDataResource.class, params.toArray(new String[params.size()]));
      return (DataResource) UIMAFramework.produceResource(desc.getResourceSpecifier(), null);
    }
  }
}


text:
layout: post
title: weekend getaway
categories:
- Musing
---

Guess where i was this weekend!

![](/img/seaside_764350782421.jpg)

The sun, the sea, the sand... and loads of water sports with 8 good friends. Snorkeling, jet ski, banana boat, floating in water, high speed boat rides and basically a lot of crazy water splashes all for just 100 bucks! And finally, what an end to an amazing adventurous race... came home at 7 o'clock today morning and rushed for the half day work and basically spent the entire day sleeping ... uuuuuhhh and now i'm just in time to usher in the New Years!

Something tells me that next year is gonna be the most exciting year yet to come in my life... Bring it on 2008!!


text:
package org.apache.causeway.security.spring.webmodule;

import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import org.apache.causeway.applib.annotation.PriorityPrecedence;
import org.apache.causeway.applib.services.inject.ServiceInjector;
import org.apache.causeway.commons.collections.Can;
import org.apache.causeway.core.webapp.modules.WebModuleAbstract;

import lombok.Getter;

/**
 * WebModule to enable support for Spring Security.
 *
 * @since 2.0 {@index}
 */
@Service
@Named("causeway.security.WebModuleSpringSecurity")
@javax.annotation.Priority(PriorityPrecedence.FIRST + 100)
@Qualifier("Spring")
public final class WebModuleSpringSecurity extends WebModuleAbstract {

    @Getter
    private final String name = "Spring Security Integration";

    @Inject
    public WebModuleSpringSecurity(ServiceInjector serviceInjector) {
        super(serviceInjector);
    }

    @Override
    public Can<ServletContextListener> init(ServletContext ctx) throws ServletException {

        registerFilter(ctx, "SpringSecurityFilter", SpringSecurityFilter.class)
            .ifPresent(filterReg -> {
                filterReg.addMappingForUrlPatterns(
                        null,
                        true, // filter is not forced first
                        "/*");

            });

        return Can.empty(); // registers no listeners
    }

}


text:
package com.mapswithme.maps.settings;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Environment;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.mapswithme.maps.BuildConfig;
import com.mapswithme.maps.Framework;
import com.mapswithme.maps.R;
import com.mapswithme.maps.downloader.MapManager;
import com.mapswithme.util.Config;
import com.mapswithme.maps.dialog.DialogUtils;
import com.mapswithme.util.concurrency.ThreadPool;
import com.mapswithme.util.concurrency.UiThread;
import com.mapswithme.util.log.Logger;
import com.mapswithme.util.log.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class StoragePathManager
{
  private static final Logger LOGGER = LoggerFactory.INSTANCE.getLogger(LoggerFactory.Type.STORAGE);
  private static final String[] MOVABLE_EXTS = Framework.nativeGetMovableFilesExts();
  static final FilenameFilter MOVABLE_FILES_FILTER = new FilenameFilter()
  {
    @Override
    public boolean accept(File dir, String filename)
    {
      for (String ext : MOVABLE_EXTS)
        if (filename.endsWith(ext))
          return true;

      return false;
    }
  };

  interface MoveFilesListener
  {
    void moveFilesFinished(String newPath);

    void moveFilesFailed(int errorCode);
  }

  interface OnStorageListChangedListener
  {
    void onStorageListChanged(List<StorageItem> storageItems, int currentStorageIndex);
  }

  public static final int NO_ERROR = 0;
  public static final int UNKNOWN_LITE_PRO_ERROR = 1;
  public static final int IOEXCEPTION_ERROR = 2;
  public static final int NULL_ERROR = 4;
  public static final int NOT_A_DIR_ERROR = 5;
  public static final int UNKNOWN_KITKAT_ERROR = 6;

  static final String TAG = StoragePathManager.class.getName();

  private OnStorageListChangedListener mStoragesChangedListener;
  private MoveFilesListener mMoveFilesListener;

  private BroadcastReceiver mInternalReceiver;
  private Activity mActivity;
  private final List<StorageItem> mItems = new ArrayList<>();
  private int mCurrentStorageIndex = -1;

  /**
   * Observes status of connected media and retrieves list of available external storages.
   */
  void startExternalStorageWatching(Activity activity, final @Nullable OnStorageListChangedListener storagesChangedListener, @Nullable MoveFilesListener moveFilesListener)
  {
    mActivity = activity;
    mStoragesChangedListener = storagesChangedListener;
    mMoveFilesListener = moveFilesListener;
    mInternalReceiver = new BroadcastReceiver()
    {
      @Override
      public void onReceive(Context context, Intent intent)
      {
        updateExternalStorages();

        if (mStoragesChangedListener != null)
          mStoragesChangedListener.onStorageListChanged(mItems, mCurrentStorageIndex);
      }
    };

    mActivity.registerReceiver(mInternalReceiver, getMediaChangesIntentFilter());
    updateExternalStorages();
  }

  private static IntentFilter getMediaChangesIntentFilter()
  {
    final IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_REMOVED);
    filter.addAction(Intent.ACTION_MEDIA_EJECT);
    filter.addAction(Intent.ACTION_MEDIA_SHARED);
    filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
    filter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
    filter.addAction(Intent.ACTION_MEDIA_CHECKING);
    filter.addAction(Intent.ACTION_MEDIA_NOFS);
    filter.addDataScheme(ContentResolver.SCHEME_FILE);

    return filter;
  }

  void stopExternalStorageWatching()
  {
    if (mInternalReceiver != null)
    {
      mActivity.unregisterReceiver(mInternalReceiver);
      mInternalReceiver = null;
      mStoragesChangedListener = null;
    }
  }

  boolean hasMoreThanOneStorage()
  {
    return mItems.size() > 1;
  }

  List<StorageItem> getStorageItems()
  {
    return mItems;
  }

  int getCurrentStorageIndex()
  {
    return mCurrentStorageIndex;
  }

  private void updateExternalStorages()
  {
    updateExternalStorages(StorageUtils.getWritableDirRoot());
  }

  private void updateExternalStorages(String writableDir)
  {
    Set<String> pathsFromConfig = new HashSet<>();

    StorageUtils.parseStorages(pathsFromConfig);

    mItems.clear();

    final StorageItem currentStorage = buildStorageItem(writableDir);
    addStorageItem(currentStorage);
    addStorageItem(buildStorageItem(Environment.getExternalStorageDirectory().getAbsolutePath()));
    for (String path : pathsFromConfig)
      addStorageItem(buildStorageItem(path));

    mCurrentStorageIndex = mItems.indexOf(currentStorage);

    if (mCurrentStorageIndex == -1)
    {
      LOGGER.w(TAG, "Unrecognized current path : " + currentStorage);
      LOGGER.w(TAG, "Parsed paths : ");
      for (StorageItem item : mItems)
        LOGGER.w(TAG, item.toString());
    }
  }

  private void addStorageItem(StorageItem item)
  {
    if (item != null && !mItems.contains(item))
      mItems.add(item);
  }

  private static StorageItem buildStorageItem(String path)
  {
    try
    {
      final File f = new File(path + "/");
      if (f.exists() && f.isDirectory() && f.canWrite() && StorageUtils.isDirWritable(path))
      {
        final long freeSize = StorageUtils.getFreeBytesAtPath(path);
        if (freeSize > 0)
        {
          LOGGER.i(TAG, "Storage found : " + path + ", size : " + freeSize);
          return new StorageItem(path, freeSize);
        }
      }
    } catch (final IllegalArgumentException ex)
    {
      LOGGER.e(TAG, "Can't build storage for path : " + path, ex);
    }

    return null;
  }

  void changeStorage(int newIndex)
  {
    final StorageItem oldItem = (mCurrentStorageIndex != -1) ? mItems.get(mCurrentStorageIndex) : null;
    final StorageItem item = mItems.get(newIndex);
    final String path = item.getFullPath();

    final File f = new File(path);
    if (!f.exists() && !f.mkdirs())
    {
      LOGGER.e(TAG, "Can't create directory: " + path);
      return;
    }

    new AlertDialog.Builder(mActivity)
        .setCancelable(false)
        .setTitle(R.string.move_maps)
        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
        {
          @Override
          public void onClick(DialogInterface dlg, int which)
          {
            setStoragePath(mActivity, new MoveFilesListener()
            {
              @Override
              public void moveFilesFinished(String newPath)
              {
                updateExternalStorages();
                if (mMoveFilesListener != null)
                  mMoveFilesListener.moveFilesFinished(newPath);
              }

              @Override
              public void moveFilesFailed(int errorCode)
              {
                updateExternalStorages();
                if (mMoveFilesListener != null)
                  mMoveFilesListener.moveFilesFailed(errorCode);
              }
            }, item, oldItem, R.string.wait_several_minutes);
          }
        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
        {
          @Override
          public void onClick(DialogInterface dlg, int which)
          {
            dlg.dismiss();
          }
        }).create().show();
  }

  /**
   * Checks whether current directory is actually writable on Kitkat devices. On earlier versions of android ( < 4.4 ) the root of external
   * storages was writable, but on Kitkat it isn't, so we should move our maps to other directory.
   * http://www.doubleencore.com/2014/03/android-external-storage/ check that link for explanations
   *

   * TODO : use SAF framework to allow custom sdcard folder selections on Lollipop+ devices.
   * https://developer.android.com/guide/topics/providers/document-provider.html#client
   * https://code.google.com/p/android/issues/detail?id=103249
   */
  public void checkKitkatMigration(@NonNull final Activity activity)
  {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT ||
        Config.isKitKatMigrationComplete())
      return;

    checkExternalStoragePathOnKitkat(activity, new MoveFilesListener()
    {
      @Override
      public void moveFilesFinished(String newPath)
      {
        Config.setKitKatMigrationComplete();
        DialogUtils.showAlertDialog(activity, R.string.kitkat_migrate_ok);
      }

      @Override
      public void moveFilesFailed(int errorCode)
      {
        DialogUtils.showAlertDialog(activity, R.string.kitkat_migrate_failed);
      }
    });
  }

  /**
   * Dumb way to determine whether the storage contains Maps.me data.
   *
The algorithm is quite simple:
   *

   *
Find all writable storages;

   *
For each storage list sub-dirs under "MapsWithMe" dir;

   *
If there is a directory with version-like name (e.g. "160602")…

   *
…and it is not empty…

   *
…we got it!

   *

   */
  private static boolean containsMapData(String storagePath)
  {
    File path = new File(storagePath);
    File[] candidates = path.listFiles(new FileFilter()
    {
      @Override
      public boolean accept(File pathname)
      {
        if (!pathname.isDirectory())
          return false;

        try
        {
          String name = pathname.getName();
          if (name.length() != 6)
            return false;

          int version = Integer.valueOf(name);
          return (version > 120000 && version <= 999999);
        } catch (NumberFormatException ignored) {}

        return false;
      }
    });

    return (candidates != null && candidates.length > 0 &&
            candidates[0].list().length > 0);
  }

  public String findMapsMeStorage(String settingsPath)
  {
    updateExternalStorages(settingsPath);
    List<StorageItem> items = getStorageItems();

    for (StorageItem item : items)
    {
      if (containsMapData(item.mPath))
        return item.mPath;
    }

    return settingsPath;
  }

  private void checkExternalStoragePathOnKitkat(@NonNull Activity context, MoveFilesListener listener)
  {
    final String settingsDir = Framework.nativeGetSettingsDir();
    final String writableDir = Framework.nativeGetWritableDir();

    if (settingsDir.equals(writableDir) || StorageUtils.isDirWritable(writableDir))
      return;

    final long size = StorageUtils.getWritableDirSize();
    updateExternalStorages();
    for (StorageItem item : mItems)
    {
      if (item.mFreeSize > size)
      {
        setStoragePath(context, listener, item, new StorageItem(StorageUtils.getWritableDirRoot(), 0),
                       R.string.kitkat_optimization_in_progress);
        return;
      }
    }

    listener.moveFilesFailed(UNKNOWN_KITKAT_ERROR);
  }

  private void setStoragePath(@NonNull final Activity context,
                              @NonNull final MoveFilesListener listener,
                              @NonNull final StorageItem newStorage,
                              @Nullable final StorageItem oldStorage, final int messageId)
  {
    final ProgressDialog dialog = DialogUtils.createModalProgressDialog(context, messageId);
    dialog.show();

    ThreadPool.getStorage().execute(new Runnable()
    {
      @Override
      public void run()
      {
        final int result = changeStorage(newStorage, oldStorage);

        UiThread.run(new Runnable()
        {
          @Override
          public void run()
          {
            if (dialog.isShowing())
              dialog.dismiss();

            if (result == NO_ERROR)
              listener.moveFilesFinished(newStorage.mPath);
            else
              listener.moveFilesFailed(result);

            updateExternalStorages();
          }
        });
      }
    });
  }

  @SuppressWarnings("ResultOfMethodCallIgnored")
  private static int changeStorage(StorageItem newStorage, StorageItem oldStorage)
  {
    final String fullNewPath = newStorage.getFullPath();

    // According to changeStorage code above, oldStorage can be null.
    if (oldStorage == null)
    {
      LOGGER.w(TAG, "Old storage path is null. New path is: " + fullNewPath);
      return NULL_ERROR;
    }

    final File oldDir = new File(oldStorage.getFullPath());
    final File newDir = new File(fullNewPath);
    if (!newDir.exists())
      newDir.mkdir();

    if (BuildConfig.DEBUG)
    {
      if (!newDir.isDirectory())
        throw new IllegalStateException("Cannot move maps. New path is not a directory. New path : " + newDir);
      if (!oldDir.isDirectory())
        throw new IllegalStateException("Cannot move maps. Old path is not a directory. Old path : " + oldDir);
      if (!StorageUtils.isDirWritable(fullNewPath))
        throw new IllegalStateException("Cannot move maps. New path is not writable. New path : " + fullNewPath);
    }

    ArrayList<String> relPaths = new ArrayList<>();
    StorageUtils.listFilesRecursively(oldDir, "", MOVABLE_FILES_FILTER, relPaths);

    File[] oldFiles = new File[relPaths.size()];
    File[] newFiles = new File[relPaths.size()];
    for (int i = 0; i < relPaths.size(); ++i)
    {
      oldFiles[i] = new File(oldDir.getAbsolutePath() + File.separator + relPaths.get(i));
      newFiles[i] = new File(newDir.getAbsolutePath() + File.separator + relPaths.get(i));
    }

    try
    {
      for (int i = 0; i < oldFiles.length; ++i)
      {
        if (MapManager.nativeMoveFile(oldFiles[i].getAbsolutePath(), newFiles[i].getAbsolutePath()))
        {
          // No need to delete oldFiles[i] because it was moved to newFiles[i].
          oldFiles[i] = null;
        } else
        {
          File parent = newFiles[i].getParentFile();
          if (parent != null)
            parent.mkdirs();
          StorageUtils.copyFile(oldFiles[i], newFiles[i]);
        }
      }
    } catch (IOException e)
    {
      e.printStackTrace();
      // In the case of failure delete all new files.  Old files will
      // be lost if new files were just moved from old locations.
      StorageUtils.removeFilesInDirectory(newDir, newFiles);
      return IOEXCEPTION_ERROR;
    }

    UiThread.run(new Runnable()
    {
      @Override
      public void run()
      {
        Framework.nativeSetWritableDir(fullNewPath);
      }
    });

    // Delete old files because new files were successfully created.
    StorageUtils.removeFilesInDirectory(oldDir, oldFiles);
    return NO_ERROR;
  }
}


text:
using namespace angle;

class BlendMinMaxTest : public ANGLETest
{
  protected:
    BlendMinMaxTest()
    {
        setWindowWidth(128);
        setWindowHeight(128);
        setConfigRedBits(8);
        setConfigGreenBits(8);
        setConfigBlueBits(8);
        setConfigAlphaBits(8);
        setConfigDepthBits(24);

        mProgram           = 0;
        mColorLocation     = -1;
        mFramebuffer       = 0;
        mColorRenderbuffer = 0;
    }

    struct Color
    {
        float values[4];
    };

    static float getExpected(bool blendMin, float curColor, float prevColor)
    {
        return blendMin ? std::min(curColor, prevColor) : std::max(curColor, prevColor);
    }

    void runTest(GLenum colorFormat, GLenum type)
    {
        ANGLE_SKIP_TEST_IF(getClientMajorVersion() < 3 &&
                           !IsGLExtensionEnabled("GL_EXT_blend_minmax"));

        SetUpFramebuffer(colorFormat);

        int minValue = 0;
        int maxValue = 1;
        if (type == GL_FLOAT)
        {
            minValue = -1024;
            maxValue = 1024;
        }

        const size_t colorCount = 128;
        Color colors[colorCount];
        for (size_t i = 0; i < colorCount; i++)
        {
            for (size_t j = 0; j < 4; j++)
            {
                colors[i].values[j] =
                    static_cast<float>(minValue + (rand() % (maxValue - minValue)));
            }
        }

        float prevColor[4];
        for (size_t i = 0; i < colorCount; i++)
        {
            const Color &color = colors[i];
            glUseProgram(mProgram);
            glUniform4f(mColorLocation, color.values[0], color.values[1], color.values[2],
                        color.values[3]);

            bool blendMin = (rand() % 2 == 0);
            glBlendEquation(blendMin ? GL_MIN : GL_MAX);

            drawQuad(mProgram, essl1_shaders::PositionAttrib(), 0.5f);

            float pixel[4];
            if (type == GL_UNSIGNED_BYTE)
            {
                GLubyte ubytePixel[4];
                glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, ubytePixel);
                for (size_t componentIdx = 0; componentIdx < ArraySize(pixel); componentIdx++)
                {
                    pixel[componentIdx] = ubytePixel[componentIdx] / 255.0f;
                }
            }
            else if (type == GL_FLOAT)
            {
                glReadPixels(0, 0, 1, 1, GL_RGBA, GL_FLOAT, pixel);
            }
            else
            {
                FAIL() << "Unexpected pixel type";
            }

            if (i > 0)
            {
                const float errorRange = 1.0f / 255.0f;
                for (size_t componentIdx = 0; componentIdx < ArraySize(pixel); componentIdx++)
                {
                    EXPECT_NEAR(
                        getExpected(blendMin, color.values[componentIdx], prevColor[componentIdx]),
                        pixel[componentIdx], errorRange)
                        << " blendMin=" << blendMin << " componentIdx=" << componentIdx << std::endl
                        << " color.values[0]=" << color.values[0]
                        << " prevColor[0]=" << prevColor[0] << std::endl
                        << " color.values[1]=" << color.values[1]
                        << " prevColor[1]=" << prevColor[1] << std::endl
                        << " color.values[2]=" << color.values[2]
                        << " prevColor[2]=" << prevColor[2] << std::endl
                        << " color.values[3]=" << color.values[3]
                        << " prevColor[3]=" << prevColor[3];
                }
            }

            memcpy(prevColor, pixel, sizeof(pixel));
        }
    }

    void testSetUp() override
    {
        mProgram = CompileProgram(essl1_shaders::vs::Simple(), essl1_shaders::fs::UniformColor());
        if (mProgram == 0)
        {
            FAIL() << "shader compilation failed.";
        }

        mColorLocation = glGetUniformLocation(mProgram, essl1_shaders::ColorUniform());

        glUseProgram(mProgram);

        glClearColor(0, 0, 0, 0);
        glClearDepthf(0.0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glEnable(GL_BLEND);
        glDisable(GL_DEPTH_TEST);
    }

    void SetUpFramebuffer(GLenum colorFormat)
    {
        glGenFramebuffers(1, &mFramebuffer);
        glBindFramebuffer(GL_FRAMEBUFFER, mFramebuffer);

        glGenRenderbuffers(1, &mColorRenderbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, mColorRenderbuffer);
        glRenderbufferStorage(GL_RENDERBUFFER, colorFormat, getWindowWidth(), getWindowHeight());
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER,
                                  mColorRenderbuffer);

        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        ASSERT_GL_NO_ERROR();
    }

    void testTearDown() override
    {
        glDeleteProgram(mProgram);
        glDeleteFramebuffers(1, &mFramebuffer);
        glDeleteRenderbuffers(1, &mColorRenderbuffer);
    }

    GLuint mProgram;
    GLint mColorLocation;

    GLuint mFramebuffer;
    GLuint mColorRenderbuffer;
};

TEST_P(BlendMinMaxTest, RGBA8)
{
    runTest(GL_RGBA8, GL_UNSIGNED_BYTE);
}

TEST_P(BlendMinMaxTest, RGBA32F)
{
    ANGLE_SKIP_TEST_IF(getClientMajorVersion() < 3 || !IsGLExtensionEnabled("GL_EXT_float_blend") ||
                       !IsGLExtensionEnabled("GL_EXT_color_buffer_float"));

    // Ignore SDK layers messages on D3D11 FL 9.3 (http://anglebug.com/1284)
    ANGLE_SKIP_TEST_IF(IsD3D11_FL93());

    runTest(GL_RGBA32F, GL_FLOAT);
}

TEST_P(BlendMinMaxTest, RGBA16F)
{
    ANGLE_SKIP_TEST_IF(getClientMajorVersion() < 3 &&
                       !IsGLExtensionEnabled("GL_EXT_color_buffer_half_float"));
    // http://anglebug.com/4092
    ANGLE_SKIP_TEST_IF((IsAndroid() && IsVulkan()) || isSwiftshader());

    // http://anglebug.com/4185
    ANGLE_SKIP_TEST_IF(IsMetal());

    // TODO(anglebug.com/5491) Context.cpp disallows GL_EXT_color_buffer_half_float on iOS because
    // it doesn't support GL_EXT_color_buffer_float.
    ANGLE_SKIP_TEST_IF(IsIOS() && IsOpenGLES());

    runTest(GL_RGBA16F, GL_FLOAT);
}

// Use this to select which configurations (e.g. which renderer, which GLES major version) these
// tests should be run against.
ANGLE_INSTANTIATE_TEST_ES2_AND_ES3(BlendMinMaxTest);


text:
import { EC } from "../../test/integration/expected-conditions";

export class NavbarPage {
    readonly timeout: number = 5000;

    logoutButton = element(by.className('logout-button'));
    loginTag = element(by.tagName('login'));

    get() {
        browser.get('/admin');
    }

    isPresentLogoutButton() {
        browser.wait(EC.presenceOf(this.logoutButton), this.timeout);
        return this.logoutButton.isPresent();
    }

    isPresentLoginTag() {
        browser.wait(EC.presenceOf(this.loginTag), this.timeout);
        return this.loginTag.isPresent();
    }

    clickOnLogoutButton() {
        browser.wait(EC.elementToBeClickable(this.logoutButton), this.timeout);
        this.logoutButton.click();
    }
}