text:
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections;
using System.IO;

using Mono.Security.X509.Extensions;

namespace Mono.Security.X509 {

#if INSIDE_CORLIB
	internal
#else
	public
#endif
	sealed class X509StoreManager {

		static private string _userPath;
		static private string _localMachinePath;
		static private string _newUserPath;
		static private string _newLocalMachinePath;
		static private X509Stores _userStore;
		static private X509Stores _machineStore;
		static private X509Stores _newUserStore;
		static private X509Stores _newMachineStore;

		private X509StoreManager ()
		{
		}

		internal static string CurrentUserPath {
			get {
				if (_userPath == null) {
					_userPath = Path.Combine (
							Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData),
							".mono");
					_userPath = Path.Combine (_userPath, "certs");
				}
				return _userPath;
			}
		}

		internal static string LocalMachinePath {
			get {
				if (_localMachinePath == null) {
					_localMachinePath = Path.Combine (
						Environment.GetFolderPath (Environment.SpecialFolder.CommonApplicationData),
						".mono");
					_localMachinePath = Path.Combine (_localMachinePath, "certs");
				}
				return _localMachinePath;
			}
		}

		internal static string NewCurrentUserPath {
			get {
				if (_newUserPath == null) {
					_newUserPath = Path.Combine (
							Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData),
							".mono");
					_newUserPath = Path.Combine (_newUserPath, "new-certs");
				}
				return _newUserPath;
			}
		}

		internal static string NewLocalMachinePath {
			get {
				if (_newLocalMachinePath == null) {
					_newLocalMachinePath = Path.Combine (
						Environment.GetFolderPath (Environment.SpecialFolder.CommonApplicationData),
						".mono");
					_newLocalMachinePath = Path.Combine (_newLocalMachinePath, "new-certs");
				}
				return _newLocalMachinePath;
			}
		}

		static public X509Stores CurrentUser {
			get {
				if (_userStore == null)
					_userStore = new X509Stores (CurrentUserPath, false);

				return _userStore;
			}
		}

		static public X509Stores LocalMachine {
			get {
				if (_machineStore == null)
					_machineStore = new X509Stores (LocalMachinePath, false);

				return _machineStore;
			}
		}

		static public X509Stores NewCurrentUser {
			get {
				if (_newUserStore == null)
					_newUserStore = new X509Stores (NewCurrentUserPath, true);

				return _newUserStore;
			}
		}

		static public X509Stores NewLocalMachine {
			get {
				if (_newMachineStore == null)
					_newMachineStore = new X509Stores (NewLocalMachinePath, true);

				return _newMachineStore;
			}
		}

		// Merged stores collections
		// we need to look at both the user and the machine (entreprise)
		// certificates/CRLs when building/validating a chain

		static public X509CertificateCollection IntermediateCACertificates {
			get {
				X509CertificateCollection intermediateCerts = new X509CertificateCollection ();
				intermediateCerts.AddRange (CurrentUser.IntermediateCA.Certificates);
				intermediateCerts.AddRange (LocalMachine.IntermediateCA.Certificates);
				return intermediateCerts;
			}
		}

		static public ArrayList IntermediateCACrls {
			get {
				ArrayList intermediateCRLs = new ArrayList ();
				intermediateCRLs.AddRange (CurrentUser.IntermediateCA.Crls);
				intermediateCRLs.AddRange (LocalMachine.IntermediateCA.Crls);
				return intermediateCRLs;
			}
		}

		static public X509CertificateCollection TrustedRootCertificates {
			get {
				X509CertificateCollection trustedCerts = new X509CertificateCollection ();
				trustedCerts.AddRange (CurrentUser.TrustedRoot.Certificates);
				trustedCerts.AddRange (LocalMachine.TrustedRoot.Certificates);
				return trustedCerts;
			}
		}

		static public ArrayList TrustedRootCACrls {
			get {
				ArrayList trustedCRLs = new ArrayList ();
				trustedCRLs.AddRange (CurrentUser.TrustedRoot.Crls);
				trustedCRLs.AddRange (LocalMachine.TrustedRoot.Crls);
				return trustedCRLs;
			}
		}

		static public X509CertificateCollection UntrustedCertificates {
			get {
				X509CertificateCollection untrustedCerts = new X509CertificateCollection ();
				untrustedCerts.AddRange (CurrentUser.Untrusted.Certificates);
				untrustedCerts.AddRange (LocalMachine.Untrusted.Certificates);
				return untrustedCerts;
			}
		}
	}
}


text:
#pragma once
#ifndef OGLPLUS_NATIVE_COMMON_GLX_1404232057_HPP
#define OGLPLUS_NATIVE_COMMON_GLX_1404232057_HPP

namespace oglplus {
namespace native {

void HandleNoGLXDisplay(void);
void HandleNoGLXContext(void);
void HandleNoGLXDrawable(void);

} // namespace native
} // namespace oglplus

#if !OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)
#include <oglplus/native/common_glx.ipp>
#endif // OGLPLUS_LINK_LIBRARY

#endif // include guard

redpajama_set_name: RedPajamaGithub


text:
package org.orekit.estimation.measurements.modifiers;

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

import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.stat.descriptive.DescriptiveStatistics;
import org.junit.Assert;
import org.junit.Test;
import org.orekit.attitudes.LofOffset;
import org.orekit.estimation.Context;
import org.orekit.estimation.EstimationTestUtils;
import org.orekit.estimation.measurements.EstimatedMeasurement;
import org.orekit.estimation.measurements.EstimationModifier;
import org.orekit.estimation.measurements.InterSatellitesRange;
import org.orekit.estimation.measurements.InterSatellitesRangeMeasurementCreator;
import org.orekit.estimation.measurements.ObservedMeasurement;
import org.orekit.frames.LOFType;
import org.orekit.orbits.CartesianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.OrbitType;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.BoundedPropagator;
import org.orekit.propagation.EphemerisGenerator;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.conversion.NumericalPropagatorBuilder;
import org.orekit.utils.TimeStampedPVCoordinates;

public class ShapiroInterSatelliteRangeModifierTest {

    @Test
    public void testShapiroOneWay() {
        doTestShapiro(false, 0.000047764, 0.000086953, 0.000164659);
    }

    @Test
    public void testShapiroTwoWay() {
        doTestShapiro(true, 0.000047764, 0.000086952, 0.000164656);
    }

    private void doTestShapiro(final boolean twoWay,
                               final double expectedMin, final double expectedMean, final double expectedMax) {

        Context context = EstimationTestUtils.eccentricContext("regular-data:potential:tides");

        final NumericalPropagatorBuilder propagatorBuilder =
                        context.createBuilder(OrbitType.KEPLERIAN, PositionAngle.TRUE, true,
                                              1.0e-6, 60.0, 0.001);
        propagatorBuilder.setAttitudeProvider(new LofOffset(propagatorBuilder.getFrame(), LOFType.LVLH));

        // create perfect inter-satellites range measurements without antenna offset
        final TimeStampedPVCoordinates original = context.initialOrbit.getPVCoordinates();
        final Orbit closeOrbit = new CartesianOrbit(new TimeStampedPVCoordinates(context.initialOrbit.getDate(),
                                                                                original.getPosition().add(new Vector3D(1000, 2000, 3000)),
                                                                                original.getVelocity().add(new Vector3D(-0.03, 0.01, 0.02))),
                                                    context.initialOrbit.getFrame(),
                                                    context.initialOrbit.getMu());
        final Propagator closePropagator = EstimationTestUtils.createPropagator(closeOrbit,
                                                                                propagatorBuilder);
        final EphemerisGenerator generator = closePropagator.getEphemerisGenerator();
        closePropagator.propagate(context.initialOrbit.getDate().shiftedBy(3.5 * closeOrbit.getKeplerianPeriod()));
        final BoundedPropagator ephemeris = generator.getGeneratedEphemeris();
        final Propagator p1 = EstimationTestUtils.createPropagator(context.initialOrbit,
                                                                           propagatorBuilder);
        final double localClockOffset  = 0.137e-6;
        final double remoteClockOffset = 469.0e-6;
        List<ObservedMeasurement<?>> measurements =
                        EstimationTestUtils.createMeasurements(p1,
                                                               new InterSatellitesRangeMeasurementCreator(ephemeris,
                                                                                localClockOffset,
                                                                                remoteClockOffset,
                                                                                Vector3D.ZERO,
                                                                                Vector3D.ZERO),
                                                               1.0, 3.0, 300.0);
        if (!twoWay) {
            // convert default two way measurements to one way measurements
            final List<ObservedMeasurement<?>> converted = new ArrayList<>();
            for (final ObservedMeasurement<?> m : measurements) {
                final InterSatellitesRange sr = (InterSatellitesRange) m;
                converted.add(new InterSatellitesRange(sr.getSatellites().get(0), sr.getSatellites().get(1),
                                                       false, sr.getDate(),
                                                       sr.getObservedValue()[0],
                                                       sr.getTheoreticalStandardDeviation()[0],
                                                       sr.getBaseWeight()[0]));
            }
            measurements = converted;
        }

        final ShapiroInterSatelliteRangeModifier modifier = new ShapiroInterSatelliteRangeModifier(context.initialOrbit.getMu());
        final Propagator p3 = EstimationTestUtils.createPropagator(context.initialOrbit,
                                                                   propagatorBuilder);
        DescriptiveStatistics stat = new DescriptiveStatistics();
        for (int i = 0; i < measurements.size(); ++i) {
            InterSatellitesRange sr = (InterSatellitesRange) measurements.get(i);
            SpacecraftState[] states = new SpacecraftState[] {
                p3.propagate(sr.getDate()),
                ephemeris.propagate(sr.getDate())
            };
            EstimatedMeasurement<InterSatellitesRange> evalNoMod = sr.estimate(0, 0, states);

            // add modifier
            sr.addModifier(modifier);
            boolean found = false;
            for (final EstimationModifier<InterSatellitesRange> existing : sr.getModifiers()) {
                found = found || existing == modifier;
            }
            Assert.assertTrue(found);
            EstimatedMeasurement<InterSatellitesRange> eval = sr.estimate(0, 0, states);

            stat.addValue(eval.getEstimatedValue()[0] - evalNoMod.getEstimatedValue()[0]);

        }

        Assert.assertEquals(expectedMin,  stat.getMin(),  1.0e-9);
        Assert.assertEquals(expectedMean, stat.getMean(), 1.0e-9);
        Assert.assertEquals(expectedMax,  stat.getMax(),  1.0e-9);

    }

}


text:
select * from {{ ref('my_model_pass') }}
UNION ALL
select null as id


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

using System;
using System.Management.Automation;
using System.Security.Permissions;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.WindowsAzure.Commands.Utilities.Common.XmlSchema.ServiceConfigurationSchema;
using Microsoft.WindowsAzure.Commands.Utilities.Properties;

namespace Microsoft.WindowsAzure.Commands.Utilities.CloudService
{
    /// <summary>
    /// Creates basic scaffolding structure for azure web/worker role.
    /// </summary>
    public abstract class AddRole : AzurePSCmdlet
    {
        private string successMessage;

        private bool isWebRole;

        protected string Scaffolding { set; get; }

        public string RootPath { set; get; }

        [Parameter(Position = 0, HelpMessage = "Role name")]
        [Alias("n")]
        public string Name { get; set; }

        [Parameter(Position = 1, HelpMessage = "Instances count")]
        [Alias("i")]
        public int Instances { get; set; }

        /// <summary>
        /// Constructs new AddRole instance.
        /// </summary>
        /// <param name="scaffolding">The scaffolding path</param>
        /// <param name="successMessage">The verbose message to emit when the cmdlet succeed</param>
        /// <param name="isWebRole">Flag that indicates role is web or worker</param>
        /// <param name="rootPath">The service root path</param>
        public AddRole(string scaffolding, string successMessage, bool isWebRole)
        {
            this.Scaffolding = scaffolding;
            this.isWebRole = isWebRole;
            this.successMessage = successMessage;
            this.Instances = 1;
        }

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public override void ExecuteCmdlet()
        {
            RootPath = RootPath ?? CommonUtilities.GetServiceRootPath(CurrentPath());
            CloudServiceProject service = new CloudServiceProject(RootPath, null);
            RoleInfo roleInfo = null;

            if (isWebRole)
            {
                roleInfo = service.AddWebRole(Scaffolding, Name, Instances);
            }
            else
            {
                roleInfo = service.AddWorkerRole(Scaffolding, Name, Instances);
            }

            OnProcessing(roleInfo);

            try
            {
                service.ChangeRolePermissions(roleInfo);
                SafeWriteOutputPSObject(typeof(RoleSettings).FullName, Parameters.RoleName, roleInfo.Name);
                WriteVerbose(string.Format(successMessage, RootPath, roleInfo.Name));
            }
            catch (UnauthorizedAccessException)
            {
                WriteWarning(Resources.AddRoleMessageInsufficientPermissions);
            }
        }

        protected virtual void OnProcessing(RoleInfo roleInfo)
        {
            // Placeholder for work to do after adding the role scaffolding.
        }
    }
}


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

namespace RequestReduce.Reducer
{
    public struct Position
    {
        public PositionMode PositionMode { get; set; }
        public int Offset { get; set; }
        public Direction Direction { get; set; }
    }
}


text:
class MainMenuRenderer
{
public:
	MainMenuRenderer();
	void RenderMainMenu();

	boost::signals2::signal<void()> m_newFileSignal;
	boost::signals2::signal<void()> m_openFileSignal;
	boost::signals2::signal<void()> m_saveFileSignal;
	boost::signals2::signal<void()> m_saveAsFileSignal;
	boost::signals2::signal<void()> m_closeSignal;
	boost::signals2::signal<void()> m_showMeshViewOptions;
	boost::signals2::signal<void()> m_showJobView;
	boost::signals2::signal<void(int)> m_openExampleSignal;

private:
	void ShowMenuFile();
	void ShowMenuWindow();
};


text:
package net.jsunit.model;

import junit.framework.TestCase;
import net.jsunit.utility.XmlUtility;

public class TestRunResultBuilderTest extends TestCase {

    public void testSimple() throws Exception {
        TestRunResultBuilder builder = new TestRunResultBuilder();
        TestRunResult result = builder.build(XmlUtility.asXmlDocument(fullValidResult()));
        assertEquals(ResultType.SUCCESS, result._getResultType());
        assertEquals(2, result.getChildren().size());
        assertEquals("my cool os", result.getOsName());
        assertEquals("127.0.0.1", result.getIpAddress());
        assertEquals("machine.example.com", result.getHostname());
    }

    private String fullValidResult() {
        return
                "<testRunResult>" +
                        "<properties>" +
                        "<property name=\"os\" value=\"my cool os\"></property>" +
                        "<property name=\"ipAddress\" value=\"127.0.0.1\"></property>" +
                        "<property name=\"hostname\" value=\"machine.example.com\"></property>" +
                        "</properties>" +
                        successResult().asXmlFragment() +
                        successResult().asXmlFragment() +
                        "</testRunResult>";
    }

    private BrowserResult successResult() {
        return new DummyBrowserResult(true, 0, 0);
    }

}


text:
package org.apache.hadoop.fs;

import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;

import java.io.IOException;

import org.apache.hadoop.fs.FileSystemTestHelper.MockFileSystem;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

public class TestFileSystemTokens {
  private static String renewer = "renewer!";

  @Test
  public void testFsWithNoToken() throws Exception {
    MockFileSystem fs = createFileSystemForServiceName(null);
    Credentials credentials = new Credentials();

    fs.addDelegationTokens(renewer, credentials);
    verifyTokenFetch(fs, false);
    assertEquals(0, credentials.numberOfTokens());
  }

  @Test
  public void testFsWithToken() throws Exception {
    Text service = new Text("singleTokenFs");
    MockFileSystem fs = createFileSystemForServiceName(service);
    Credentials credentials = new Credentials();

    fs.addDelegationTokens(renewer, credentials);
    verifyTokenFetch(fs, true);

    assertEquals(1, credentials.numberOfTokens());
    assertNotNull(credentials.getToken(service));
  }

  @Test
  public void testFsWithTokenExists() throws Exception {
    Credentials credentials = new Credentials();
    Text service = new Text("singleTokenFs");
    MockFileSystem fs = createFileSystemForServiceName(service);
    Token<?> token = mock(Token.class);
    credentials.addToken(service, token);

    fs.addDelegationTokens(renewer, credentials);
    verifyTokenFetch(fs, false);

    assertEquals(1, credentials.numberOfTokens());
    assertSame(token, credentials.getToken(service));
  }

  @Test
  public void testFsWithChildTokens() throws Exception {
    Credentials credentials = new Credentials();
    Text service1 = new Text("singleTokenFs1");
    Text service2 = new Text("singleTokenFs2");

    MockFileSystem fs1 = createFileSystemForServiceName(service1);
    MockFileSystem fs2 = createFileSystemForServiceName(service2);
    MockFileSystem fs3 = createFileSystemForServiceName(null);
    MockFileSystem multiFs =
        createFileSystemForServiceName(null, fs1, fs2, fs3);

    multiFs.addDelegationTokens(renewer, credentials);
    verifyTokenFetch(multiFs, false); // has no tokens of own, only child tokens
    verifyTokenFetch(fs1, true);
    verifyTokenFetch(fs2, true);
    verifyTokenFetch(fs3, false);

    assertEquals(2, credentials.numberOfTokens());
    assertNotNull(credentials.getToken(service1));
    assertNotNull(credentials.getToken(service2));
  }

  @Test
  public void testFsWithDuplicateChildren() throws Exception {
    Credentials credentials = new Credentials();
    Text service = new Text("singleTokenFs1");

    MockFileSystem fs = createFileSystemForServiceName(service);
    MockFileSystem multiFs =
        createFileSystemForServiceName(null, fs, new FilterFileSystem(fs));

    multiFs.addDelegationTokens(renewer, credentials);
    verifyTokenFetch(multiFs, false);
    verifyTokenFetch(fs, true);

    assertEquals(1, credentials.numberOfTokens());
    assertNotNull(credentials.getToken(service));
  }

  @Test
  public void testFsWithDuplicateChildrenTokenExists() throws Exception {
    Credentials credentials = new Credentials();
    Text service = new Text("singleTokenFs1");
    Token<?> token = mock(Token.class);
    credentials.addToken(service, token);

    MockFileSystem fs = createFileSystemForServiceName(service);
    MockFileSystem multiFs =
        createFileSystemForServiceName(null, fs, new FilterFileSystem(fs));

    multiFs.addDelegationTokens(renewer, credentials);
    verifyTokenFetch(multiFs, false);
    verifyTokenFetch(fs, false);

    assertEquals(1, credentials.numberOfTokens());
    assertSame(token, credentials.getToken(service));
  }

  @Test
  public void testFsWithChildTokensOneExists() throws Exception {
    Credentials credentials = new Credentials();
    Text service1 = new Text("singleTokenFs1");
    Text service2 = new Text("singleTokenFs2");
    Token<?> token = mock(Token.class);
    credentials.addToken(service2, token);

    MockFileSystem fs1 = createFileSystemForServiceName(service1);
    MockFileSystem fs2 = createFileSystemForServiceName(service2);
    MockFileSystem fs3 = createFileSystemForServiceName(null);
    MockFileSystem multiFs = createFileSystemForServiceName(null, fs1, fs2, fs3);

    multiFs.addDelegationTokens(renewer, credentials);
    verifyTokenFetch(multiFs, false);
    verifyTokenFetch(fs1, true);
    verifyTokenFetch(fs2, false); // we had added its token to credentials
    verifyTokenFetch(fs3, false);

    assertEquals(2, credentials.numberOfTokens());
    assertNotNull(credentials.getToken(service1));
    assertSame(token, credentials.getToken(service2));
  }

  @Test
  public void testFsWithMyOwnAndChildTokens() throws Exception {
    Credentials credentials = new Credentials();
    Text service1 = new Text("singleTokenFs1");
    Text service2 = new Text("singleTokenFs2");
    Text myService = new Text("multiTokenFs");
    Token<?> token = mock(Token.class);
    credentials.addToken(service2, token);

    MockFileSystem fs1 = createFileSystemForServiceName(service1);
    MockFileSystem fs2 = createFileSystemForServiceName(service2);
    MockFileSystem multiFs = createFileSystemForServiceName(myService, fs1, fs2);

    multiFs.addDelegationTokens(renewer, credentials);
    verifyTokenFetch(multiFs, true); // its own token and also of its children
    verifyTokenFetch(fs1, true);
    verifyTokenFetch(fs2, false);  // we had added its token to credentials

    assertEquals(3, credentials.numberOfTokens());
    assertNotNull(credentials.getToken(myService));
    assertNotNull(credentials.getToken(service1));
    assertNotNull(credentials.getToken(service2));
  }

  @Test
  public void testFsWithMyOwnExistsAndChildTokens() throws Exception {
    Credentials credentials = new Credentials();
    Text service1 = new Text("singleTokenFs1");
    Text service2 = new Text("singleTokenFs2");
    Text myService = new Text("multiTokenFs");
    Token<?> token = mock(Token.class);
    credentials.addToken(myService, token);

    MockFileSystem fs1 = createFileSystemForServiceName(service1);
    MockFileSystem fs2 = createFileSystemForServiceName(service2);
    MockFileSystem multiFs = createFileSystemForServiceName(myService, fs1, fs2);

    multiFs.addDelegationTokens(renewer, credentials);
    verifyTokenFetch(multiFs, false);  // we had added its token to credentials
    verifyTokenFetch(fs1, true);
    verifyTokenFetch(fs2, true);

    assertEquals(3, credentials.numberOfTokens());
    assertSame(token, credentials.getToken(myService));
    assertNotNull(credentials.getToken(service1));
    assertNotNull(credentials.getToken(service2));
  }

  @Test
  public void testFsWithNestedDuplicatesChildren() throws Exception {
    Credentials credentials = new Credentials();
    Text service1 = new Text("singleTokenFs1");
    Text service2 = new Text("singleTokenFs2");
    Text service4 = new Text("singleTokenFs4");
    Text multiService = new Text("multiTokenFs");
    Token<?> token2 = mock(Token.class);
    credentials.addToken(service2, token2);

    MockFileSystem fs1 = createFileSystemForServiceName(service1);
    MockFileSystem fs1B = createFileSystemForServiceName(service1);
    MockFileSystem fs2 = createFileSystemForServiceName(service2);
    MockFileSystem fs3 = createFileSystemForServiceName(null);
    MockFileSystem fs4 = createFileSystemForServiceName(service4);
    // now let's get dirty!  ensure dup tokens aren't fetched even when
    // repeated and dupped in a nested fs.  fs4 is a real test of the drill
    // down: multi-filter-multi-filter-filter-fs4.
    MockFileSystem multiFs = createFileSystemForServiceName(multiService,
        fs1, fs1B, fs2, fs2, new FilterFileSystem(fs3),
        new FilterFileSystem(new FilterFileSystem(fs4)));
    MockFileSystem superMultiFs = createFileSystemForServiceName(null,
        fs1, fs1B, fs1, new FilterFileSystem(fs3), new FilterFileSystem(multiFs));
    superMultiFs.addDelegationTokens(renewer, credentials);
    verifyTokenFetch(superMultiFs, false); // does not have its own token
    verifyTokenFetch(multiFs, true); // has its own token
    verifyTokenFetch(fs1, true);
    verifyTokenFetch(fs2, false); // we had added its token to credentials
    verifyTokenFetch(fs3, false); // has no tokens
    verifyTokenFetch(fs4, true);

    assertEquals(4, credentials.numberOfTokens()); //fs1+fs2+fs4+multifs (fs3=0)
    assertNotNull(credentials.getToken(service1));
    assertNotNull(credentials.getToken(service2));
    assertSame(token2, credentials.getToken(service2));
    assertNotNull(credentials.getToken(multiService));
    assertNotNull(credentials.getToken(service4));
  }

  public static MockFileSystem createFileSystemForServiceName(
      final Text service, final FileSystem... children) throws IOException {
    final MockFileSystem fs = new MockFileSystem();
    final MockFileSystem mockFs = fs.getRawFileSystem();
    if (service != null) {
      when(mockFs.getCanonicalServiceName()).thenReturn(service.toString());
      when(mockFs.getDelegationToken(any(String.class))).thenAnswer(
        new Answer<Token<?>>() {
          @Override
          public Token<?> answer(InvocationOnMock invocation) throws Throwable {
            Token<?> token = new Token<TokenIdentifier>();
            token.setService(service);
            return token;
          }
        });
    }
    when(mockFs.getChildFileSystems()).thenReturn(children);
    return fs;
  }

  // check that canonical name was requested, if renewer is not null that
  // a token was requested, and that child fs was invoked
  private void verifyTokenFetch(MockFileSystem fs, boolean expected) throws IOException {
    verify(fs.getRawFileSystem(), atLeast(1)).getCanonicalServiceName();
    if (expected) {
      verify(fs.getRawFileSystem()).getDelegationToken(renewer);
    } else {
      verify(fs.getRawFileSystem(), never()).getDelegationToken(any(String.class));
    }
    verify(fs.getRawFileSystem(), atLeast(1)).getChildFileSystems();
  }
}


text:
'use strict';
var $ = require('../internals/export');
var requireObjectCoercible = require('../internals/require-object-coercible');
var isCallable = require('../internals/is-callable');
var isRegExp = require('../internals/is-regexp');
var toString = require('../internals/to-string');
var getMethod = require('../internals/get-method');
var getRegExpFlags = require('../internals/regexp-flags');
var getSubstitution = require('../internals/get-substitution');
var wellKnownSymbol = require('../internals/well-known-symbol');
var IS_PURE = require('../internals/is-pure');

var REPLACE = wellKnownSymbol('replace');
var RegExpPrototype = RegExp.prototype;
var max = Math.max;

var stringIndexOf = function (string, searchValue, fromIndex) {
  if (fromIndex > string.length) return -1;
  if (searchValue === '') return fromIndex;
  return string.indexOf(searchValue, fromIndex);
};

// `String.prototype.replaceAll` method
// https://tc39.es/ecma262/#sec-string.prototype.replaceall
$({ target: 'String', proto: true }, {
  replaceAll: function replaceAll(searchValue, replaceValue) {
    var O = requireObjectCoercible(this);
    var IS_REG_EXP, flags, replacer, string, searchString, functionalReplace, searchLength, advanceBy, replacement;
    var position = 0;
    var endOfLastMatch = 0;
    var result = '';
    if (searchValue != null) {
      IS_REG_EXP = isRegExp(searchValue);
      if (IS_REG_EXP) {
        flags = toString(requireObjectCoercible('flags' in RegExpPrototype
          ? searchValue.flags
          : getRegExpFlags.call(searchValue)
        ));
        if (!~flags.indexOf('g')) throw TypeError('`.replaceAll` does not allow non-global regexes');
      }
      replacer = getMethod(searchValue, REPLACE);
      if (replacer) {
        return replacer.call(searchValue, O, replaceValue);
      } else if (IS_PURE && IS_REG_EXP) {
        return toString(O).replace(searchValue, replaceValue);
      }
    }
    string = toString(O);
    searchString = toString(searchValue);
    functionalReplace = isCallable(replaceValue);
    if (!functionalReplace) replaceValue = toString(replaceValue);
    searchLength = searchString.length;
    advanceBy = max(1, searchLength);
    position = stringIndexOf(string, searchString, 0);
    while (position !== -1) {
      if (functionalReplace) {
        replacement = toString(replaceValue(searchString, position, string));
      } else {
        replacement = getSubstitution(searchString, string, position, [], undefined, replaceValue);
      }
      result += string.slice(endOfLastMatch, position) + replacement;
      endOfLastMatch = position + searchLength;
      position = stringIndexOf(string, searchString, position + advanceBy);
    }
    if (endOfLastMatch < string.length) {
      result += string.slice(endOfLastMatch);
    }
    return result;
  }
});


text:
import { EventDispatcher } from '../core/EventDispatcher';
import { Texture } from '../textures/Texture';
import { LinearFilter } from '../Constants';
import { Vector4 } from '../math/Vector4';
import { MathTool } from '../math/MathTool';

export class WebGLRenderTarget extends EventDispatcher {

  public uuid: string;
  public width: number;
  public height: number;

  public scissor: Vector4;
  public scissorTest: boolean;

  public viewport: Vector4;

  public texture: Texture;

  public depthBuffer: boolean;
  public stencilBuffer: boolean;

  public depthTexture;

  public isWebGLRenderTarget: boolean;

  constructor(width: number, height: number, options?) {
    super();

    this.uuid = MathTool.generateUUID();

    this.width = width;
    this.height = height;

    this.scissor = new Vector4(0, 0, width, height);
    this.scissorTest = false;

    this.viewport = new Vector4(0, 0, width, height);

    options = options || {};

    if (options.minFilter === undefined) {
      options.minFilter = LinearFilter;
    }

    this.texture = new Texture(undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);

    this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
    this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
    this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  }

  public setSize(width: number, height: number) {
    if (this.width !== width || this.height !== height) {
      this.width = width;
      this.height = height;

      this.dispose();
    }
    this.viewport.set(0, 0, width, height);
    this.scissor.set(0, 0, width, height);
  }

  public clone() {
    return new WebGLRenderTarget(this.width, this.height).copy(this);
  }

  public copy(source: WebGLRenderTarget) {
    this.width = source.width;
    this.height = source.height;

    this.viewport.copy(source.viewport);

    this.texture = source.texture.clone();

    this.depthBuffer = source.depthBuffer;
    this.stencilBuffer = source.stencilBuffer;
    this.depthTexture = source.depthTexture;

    return this;
  }

  public dispose() {
    this.dispatchEvent({ type: 'dispose' });
  }
}


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SimpleAuth.Providers {
	public class DropBoxApi : OAuthApi {
		public DropBoxApi (string identifier, string client_id, string client_secret, string redirectUrl = "http://localhost", HttpMessageHandler handler = null)
			: base (identifier, client_id, client_secret, handler)
		{
			this.ScopesRequired = false;
			this.TokenUrl = "https://api.dropbox.com/oauth2/token";
			BaseAddress = new Uri ("https://api.dropbox.com");
			RedirectUrl = new Uri (redirectUrl);
		}

		public Uri RedirectUrl { get; private set; }

		protected override WebAuthenticator CreateAuthenticator ()
		{
			return new DropBoxAuthenticator {
				ClientId = ClientId,
				RedirectUrl = RedirectUrl,
			};
		}

		protected override Task<OAuthAccount> GetAccountFromAuthCode (WebAuthenticator authenticator, string identifier)
		{
			var author = (DropBoxAuthenticator)authenticator;
			var account = new OAuthAccount () {
				ExpiresIn = -1,
				Created = DateTime.UtcNow,
				RefreshToken = null,
				Scope = new string [0],
				TokenType = author.TokenType,
				Token = author.Token,
				ClientId = ClientId,
				Identifier = identifier,
			};
			account.UserData ["Uid"] = author.Uid;
			return Task.FromResult (account);
		}
	}

	public class DropBoxAuthenticator : OAuthAuthenticator {
		public DropBoxAuthenticator ()
		{
			BaseUrl = "https://www.dropbox.com/oauth2/authorize";
		}

		///Up to 500 bytes of arbitrary data that will be passed back to <paramref name="redirectUri"/>
		public string State { get; set; }

		public override bool CheckUrl (Uri url, Cookie [] cookies)
		{
			try {
				if (url == null)
					return false;
				if (url.Host != RedirectUrl.Host || url.Fragment == null || url.Fragment.Length < 1)
					return false;
				var parts = HttpUtility.ParseQueryString (url.Fragment.Substring (1));
				var code = parts ["access_token"];
				if (!string.IsNullOrWhiteSpace (code) && TokenTask != null) {
					Token = code;
					TokenType = parts ["token_type"];
					Uid = parts ["uid"];
					FoundAuthCode (code);
					return true;
				}
			} catch (Exception ex) {
				System.Diagnostics.Debug.WriteLine (ex);
			}
			return false;
		}
		public string Token { get; private set; }
		public string TokenType { get; private set; }
		public string Uid { get; private set; }

		public override async Task<Uri> GetInitialUrl ()
		{
			var result = await base.GetInitialUrl ();
			return result;
		}

		public override Dictionary<string, string> GetInitialUrlQueryParameters ()
		{
			var result = new Dictionary<string, string> ()
			{
				{"client_id", ClientId},
				{"response_type","token"},
				{"redirect_uri",RedirectUrl.OriginalString},
			};
			if (string.IsNullOrEmpty (State))
				result ["state"] = State;
			return result;
		}
	}
}


text:
package org.mellowtech.core.collections.impl;

import org.mellowtech.core.codec.BCodec;
import org.mellowtech.core.collections.BTree;
import org.mellowtech.core.collections.KeyValue;
import org.mellowtech.core.collections.TreePosition;
import org.mellowtech.core.io.RecordFileBuilder;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;

import static java.nio.file.StandardOpenOption.*;

/**
 * A BPTreeImp that allows for large values
 * Date: 2013-03-22
 * Time: 07:52
 *
 * @author Martin Svensson
 */
@SuppressWarnings("unchecked")
public class BTreeBlobImp<A,B> implements BTree<A,B> {

  private final FileChannel blobs;
  private final BTreeImp <A,BlobPointer> tree;
  private final BCodec<B> valueCodec;

  public BTreeBlobImp(Path dir, String name, BCodec<A> keyCodec, BCodec<B> valueCodec,
                      int indexBlockSize, int maxIndexBlocks, RecordFileBuilder valueFileBuilder) throws Exception {
    tree = new BTreeImp <> (dir, name, keyCodec, new BlobPointerCodec(),
        indexBlockSize, maxIndexBlocks, valueFileBuilder);
    this.valueCodec = valueCodec;
    blobs = FileChannel.open(blobPath(), CREATE, WRITE, READ);
    if(tree.isEmpty() && blobs.size() > 0){
      blobs.truncate(0);
    }
  }

  private Path blobPath(){
    return tree.dir.resolve(tree.name+".blb");
  }

  @Override
  public void save() throws IOException {
    tree.save();
    blobs.force(true);
  }

  @Override
  public void close() throws IOException {
    tree.close();
    blobs.close();
  }

  @Override
  public void delete() throws IOException {
    tree.delete();
    blobs.close();
    Files.delete(blobPath());
  }

  @Override
  public void truncate() throws IOException {
    tree.truncate();
    blobs.truncate(0);
  }

  @Override
  public int size() throws IOException {
    return tree.size();
  }

  @Override
  public boolean isEmpty() throws IOException {
    return tree.isEmpty();
  }

  @Override
  public boolean containsKey(A key) throws IOException {
    return tree.containsKey(key);
  }

  @Override
  public void put(A key, B value) throws IOException {
    ByteBuffer bb = valueCodec.to(value);
    long fpos = blobs.size();
    BlobPointer bp = new BlobPointer(fpos, bb.capacity());
    bb.flip();
    tree.put(key, bp);
    blobs.write(bb, fpos);
  }

  @Override
  public void putIfNotExists(A key, B value) throws IOException {
    if(containsKey(key)) return;
    put(key, value);
  }

  @Override
  public B remove(A key) throws IOException{
    BlobPointer bp = tree.remove(key);
    return bp != null ? getValue(bp) : null;
  }

  @Override
  public B get(A key) throws IOException {
    BlobPointer bp = tree.get(key);
    return bp != null ? getValue(bp) : null;
  }

  @Override
  public A getKey(int position) throws IOException {
    return tree.getKey(position);
  }

  @Override
  public KeyValue<A,B> getKeyValue(A key) throws IOException {
    BlobPointer tmp = tree.get(key);
    if(tmp != null){
      return new KeyValue<>(key, getValue(tmp));
    } else
      return null;
  }

  @Override
  public TreePosition getPosition(A key) throws IOException {
    return tree.getPosition(key);
  }

  @Override
  public TreePosition getPositionWithMissing(A key) throws IOException {
    return tree.getPositionWithMissing(key);
  }

  @Override
  public Iterator<KeyValue<A,B>> iterator(boolean descending, A from, boolean inclusive,
                                          A to, boolean toInclusive) {
    return new BPBlobIterator(descending, from, inclusive, to, toInclusive);
  }

  @Override
  public void compact() throws IOException {
    tree.compact();
  }

  private B getValue(BlobPointer bp) throws IOException{
    ByteBuffer bb = ByteBuffer.allocate(bp.bSize);
    blobs.read(bb, bp.fPointer);
    bb.flip();
    return valueCodec.from(bb);
  }

  private class BPBlobIterator implements Iterator <KeyValue <A,B>>{

    Iterator <KeyValue <A, BlobPointer>> iter;

    BPBlobIterator(boolean descending, A from, boolean inclusive,
                   A to, boolean toInclusive){
      iter = tree.iterator(descending, from, inclusive, to, toInclusive);
    }

    @Override
    public boolean hasNext() {
      return iter.hasNext();
    }

    @Override
    public KeyValue<A,B> next() {
      KeyValue <A, BlobPointer> next = iter.next();
      if(next == null) return null;
      KeyValue <A,B> toRet = new KeyValue<>(next.getKey());
      if(next.getValue() != null){
        try{
          toRet.setValue(getValue(next.getValue()));
        }
        catch(IOException e){
          throw new Error("could not iterate", e);

        }
      }
      return toRet;
    }

    @Override
    public void remove() throws UnsupportedOperationException{
      throw new UnsupportedOperationException();
    }
  }

  @Override
  public void rebuildIndex() throws IOException {
    tree.rebuildIndex();
  }

  @Override
  public void createTree(Iterator<KeyValue<A,B>> iterator) throws IOException {
    blobs.truncate(0);
    BlobMapCreateIterator <A,B> iter = new BlobMapCreateIterator <> (iterator,blobs, valueCodec);
    tree.createTree(iter);
  }

}


text:
[![Build Status](https://travis-ci.org/Maaarcocr/closestmatch-rs.svg?branch=master)](https://travis-ci.org/Maaarcocr/closestmatch-rs)
# closestmatch-rs
This library fuzzy matches an input string to a list of target strings.

## Why this library
Let's say that you have a collections of words, call it a dictionary of known words, such as ["hello","good","rust"]. You also have a word, such as "hllo" and you want to find the closest match from the dictionary. This is the main functionality of this library.

## How it works
The library is based on the concept of bags of words and it calculate the similarity splitting strings in substrings.
The developer using this library can specify how long the bags of words are.

## Documentation
You can find the documentation [here](https://maaarcocr.github.io/closestmatch-rs/)

## Example

```rust
let known_words = ["hello".to_string(), "rust".to_string(), "hello world".to_string()].to_vec();
//The second parameter specify that strings will be splitted in bags of words of length 2 and 3.
let cm = ClosestMatch::new(known_words,[2, 3].to_vec());
let closest = cm.get_closest("hlo".to_string());
println!("{}", closest)
```

This will print ```Some("hello")```.


text:
    DEVICE ZXSPECTRUM48
    BPLIST "dir_setbp.exp" zesarux  ; valid breakpoints file

    SETBP 0x1234
    setbp 0xBCDE
    ORG $2345
    SETBP       ; default = "$"

    BPLIST "dir_setbp.exp" unreal

    ; value truncating warnings
    .SETBP 0x10000
    .setbp -1

    ; syntax error test
    SETBP &


text:
package com.asakusafw.operator.model;

import java.util.Objects;

import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.ExecutableElement;

/**
 * Represents an operator method/constructor.
 */
public class OperatorElement {

    private final AnnotationMirror annotation;

    private final ExecutableElement declaration;

    private final OperatorDescription description;

    /**
     * Creates a new instance.
     * @param annotation target annotation
     * @param declaration method/constructor that declares this operator element
     * @param description description of this operator (nullable)
     * @throws IllegalArgumentException if some parameters were {@code null}
     */
    public OperatorElement(
            AnnotationMirror annotation,
            ExecutableElement declaration,
            OperatorDescription description) {
        this.annotation = Objects.requireNonNull(annotation, "annotation must not be null"); //$NON-NLS-1$
        this.declaration = Objects.requireNonNull(declaration, "declaration must not be null"); //$NON-NLS-1$
        this.description = description;
    }

    /**
     * Returns the annotation of target operator/flow-part.
     * @return the annotation
     */
    public AnnotationMirror getAnnotation() {
        return annotation;
    }

    /**
     * Returns the method/constructor declaration of this operator.
     * @return the method/constructor declaration
     */
    public ExecutableElement getDeclaration() {
        return declaration;
    }

    /**
     * Returns the description of this operator element.
     * @return the description, or {@code null} if it is not described
     */
    public OperatorDescription getDescription() {
        return description;
    }
}


text:
layout: post
status: publish
published: true
title: Jagger écrirait un film
author: mick
author_login: mick
author_email: mickael@flochlay.com
wordpress_id: 19
wordpress_url: http://88.191.132.16/mc/?p=19
date: 2011-04-10 09:43:16.000000000 +02:00
categories:
- Cinéma
- Musique
tags: ["mick jagger"]
comments: []
---

> Mick Jagger is finally ready to shoot a comedy film he's been writing with David Bowie
> over the past 15 years, according to a report.

Update : Bowie a démenti depuis.

via [Mick Jagger and David Bowie working on rock'n'roll comedy film][1]

[1]: http://www.nme.com/news/tabloid-hell/56007


text:
package mux

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"sync"
	"time"
)

// Mux represents a multiplexer for a net.Listener.
type Mux struct {
	ln   net.Listener
	once sync.Once
	wg   sync.WaitGroup

	handlers map[byte]*handler

	Timeout   time.Duration
	LogOutput io.Writer
}

// New returns a new instance of Mux.
func New(ln net.Listener) *Mux {
	return &Mux{
		ln:        ln,
		handlers:  make(map[byte]*handler),
		Timeout:   30 * time.Second,
		LogOutput: os.Stderr,
	}
}

// Close closes the underlying listener.
func (mux *Mux) Close() (err error) {
	mux.once.Do(func() {
		// Close underlying listener.
		if mux.ln != nil {
			err = mux.ln.Close()
		}

		// Wait for open connections to close and then close handlers.
		mux.wg.Wait()
		for _, h := range mux.handlers {
			h.Close()
		}
	})
	return
}

// Serve handles connections from ln and multiplexes then across registered listener.
func (mux *Mux) Serve() error {
	logger := log.New(mux.LogOutput, "", log.LstdFlags)

	for {
		// Handle incoming connections. Retry temporary errors.
		conn, err := mux.ln.Accept()
		if err, ok := err.(interface {
			Temporary() bool
		}); ok && err.Temporary() {
			logger.Printf("tcp.Mux: temporary error: %s", err)
			continue
		}

		// Other errors should close the muxer and wait for outstanding conns.
		if err != nil {
			mux.Close()
			return err
		}

		// Hand off connection to a separate goroutine.
		mux.wg.Add(1)
		go func(conn net.Conn) {
			defer mux.wg.Done()
			if err := mux.handleConn(conn); err != nil {
				conn.Close()
				logger.Printf("tcp.Mux: %s", err)
			}
		}(conn)
	}
}

func (mux *Mux) handleConn(conn net.Conn) error {
	// Wrap in a buffered connection in order to peek at the first byte.
	bufConn := newBufConn(conn)

	// Set a read deadline so connections with no data timeout.
	if err := conn.SetReadDeadline(time.Now().Add(mux.Timeout)); err != nil {
		return fmt.Errorf("set read deadline: %s", err)
	}

	// Peek at first byte from connection to determine handler.
	typ, err := bufConn.r.ReadByte()
	if err != nil {
		return fmt.Errorf("read header byte: %s", err)
	} else if err = bufConn.r.UnreadByte(); err != nil {
		return fmt.Errorf("unread header byte: %s", err)
	}

	// Reset read deadline and let the listener handle that.
	if err := conn.SetReadDeadline(time.Time{}); err != nil {
		return fmt.Errorf("reset set read deadline: %s", err)
	}

	// Lookup handler.
	h := mux.handlers[typ]
	if h == nil {
		return fmt.Errorf("unregistered header byte: 0x%02x", typ)
	}

	// Hand off connection to handler.
	h.c <- bufConn
	return nil
}

// Listen returns a listener that receives connections from any byte in hdrs.
// Re-registering hdr bytes will overwrite existing handlers.
func (mux *Mux) Listen(hdrs []byte) net.Listener {
	// Create new handler.
	h := mux.handler()

	// Register each header byte.
	for _, hdr := range hdrs {
		// Create a new listener and assign it.
		mux.handlers[hdr] = h
	}

	return h
}

// handler returns a new instance of handler.
func (mux *Mux) handler() *handler {
	return &handler{
		mux: mux,
		c:   make(chan net.Conn),
	}
}

// handler is a receiver for connections received by Mux. Implements net.Listener.
type handler struct {
	mux  *Mux
	c    chan net.Conn
	once sync.Once
}

// Accept waits for and returns the next connection.
func (h *handler) Accept() (c net.Conn, err error) {
	conn, ok := <-h.c
	if !ok {
		return nil, errors.New("network connection closed")
	}
	return conn, nil
}

// Close closes the original listener.
func (h *handler) Close() error {
	h.once.Do(func() { close(h.c) })
	return nil
}

// Addr returns the address of the original listener.
func (h *handler) Addr() net.Addr { return h.mux.ln.Addr() }

// bufConn represents a buffered connection.
type bufConn struct {
	conn net.Conn
	r    *bufio.Reader
}

// newBufConn returns a new instance of bufConn.
func newBufConn(conn net.Conn) *bufConn {
	return &bufConn{
		conn: conn,
		r:    bufio.NewReader(conn),
	}
}

func (c *bufConn) Read(b []byte) (n int, err error)   { return c.r.Read(b) }
func (c *bufConn) Write(b []byte) (n int, err error)  { return c.conn.Write(b) }
func (c *bufConn) Close() error                       { return c.conn.Close() }
func (c *bufConn) LocalAddr() net.Addr                { return c.conn.LocalAddr() }
func (c *bufConn) RemoteAddr() net.Addr               { return c.conn.RemoteAddr() }
func (c *bufConn) SetDeadline(t time.Time) error      { return c.conn.SetDeadline(t) }
func (c *bufConn) SetReadDeadline(t time.Time) error  { return c.conn.SetReadDeadline(t) }
func (c *bufConn) SetWriteDeadline(t time.Time) error { return c.conn.SetWriteDeadline(t) }


text:
@interface SGASScreenRecorderUIManager : NSObject

@property (nonatomic, assign, getter=isEnabled) BOOL enabled;

- (instancetype)initWithScreenCorner:(UIRectCorner)screenCorner
                   overlayWindowSize:(CGSize)overlayWindowSize
               activationTapAreaSize:(CGSize)activationTapAreaSize
              screenRecorderSettings:(SGASScreenRecorderSettings *)settings NS_DESIGNATED_INITIALIZER;

- (instancetype)initWithScreenCorner:(UIRectCorner)screenCorner
              screenRecorderSettings:(SGASScreenRecorderSettings *)settings;

@end


text:
/* @file
 * Implementation of a L-TAGE branch predictor. TAGE is a global-history based
 * branch predictor. It features a PC-indexed bimodal predictor and N
 * partially tagged tables, indexed with a hash of the PC and the global
 * branch history. The different lengths of global branch history used to
 * index the partially tagged tables grow geometrically. A small path history
 * is also used in the hash. L-TAGE also features a loop predictor that records
 * iteration count of loops and predicts accordingly.
 *
 * All TAGE tables are accessed in parallel, and the one using the longest
 * history that matches provides the prediction (some exceptions apply).
 * Entries are allocated in components using a longer history than the
 * one that predicted when the prediction is incorrect.
 */

#ifndef __CPU_PRED_LTAGE
#define __CPU_PRED_LTAGE

#include <vector>

#include "base/types.hh"
#include "cpu/pred/bpred_unit.hh"
#include "params/LTAGE.hh"

class LTAGE: public BPredUnit
{
  public:
    LTAGE(const LTAGEParams *params);

    // Base class methods.
    void uncondBranch(ThreadID tid, Addr br_pc, void* &bp_history) override;
    bool lookup(ThreadID tid, Addr branch_addr, void* &bp_history) override;
    void btbUpdate(ThreadID tid, Addr branch_addr, void* &bp_history) override;
    void update(ThreadID tid, Addr branch_addr, bool taken, void *bp_history,
                bool squashed) override;
    void squash(ThreadID tid, void *bp_history) override;
    unsigned getGHR(ThreadID tid, void *bp_history) const override;

  private:
    // Prediction Structures
    // Loop Predictor Entry
    struct LoopEntry
    {
        uint16_t numIter;
        uint16_t currentIter;
        uint16_t currentIterSpec;
        uint8_t confidence;
        uint16_t tag;
        uint8_t age;
        bool dir;

        LoopEntry() : numIter(0), currentIter(0), currentIterSpec(0),
                      confidence(0), tag(0), age(0), dir(0) { }
    };

    // Bimodal Predictor Entry
    struct BimodalEntry
    {
        uint8_t pred;
        uint8_t hyst;

        BimodalEntry() : pred(0), hyst(1) { }
    };

    // Tage Entry
    struct TageEntry
    {
        int8_t ctr;
        uint16_t tag;
        int8_t u;
        TageEntry() : ctr(0), tag(0), u(0) { }
    };

    // Folded History Table - compressed history
    // to mix with instruction PC to index partially
    // tagged tables.
    struct FoldedHistory
    {
        unsigned comp;
        int compLength;
        int origLength;
        int outpoint;

        void init(int original_length, int compressed_length)
        {
            comp = 0;
            origLength = original_length;
            compLength = compressed_length;
            outpoint = original_length % compressed_length;
        }

        void update(uint8_t * h)
        {
            comp = (comp << 1) | h[0];
            comp ^= h[origLength] << outpoint;
            comp ^= (comp >> compLength);
            comp &= (ULL(1) << compLength) - 1;
        }
    };

    // Primary branch history entry
    struct BranchInfo
    {
        int pathHist;
        int ptGhist;
        int hitBank;
        int hitBankIndex;
        int altBank;
        int altBankIndex;
        int bimodalIndex;
        int loopTag;
        uint16_t currentIter;

        bool tagePred;
        bool altTaken;
        bool loopPred;
        bool loopPredValid;
        int  loopIndex;
        int loopHit;
        bool condBranch;
        bool longestMatchPred;
        bool pseudoNewAlloc;
        Addr branchPC;

        // Pointer to dynamically allocated storage
        // to save table indices and folded histories.
        // To do one call to new instead of five.
        int *storage;

        // Pointers to actual saved array within the dynamically
        // allocated storage.
        int *tableIndices;
        int *tableTags;
        int *ci;
        int *ct0;
        int *ct1;

        BranchInfo(int sz)
            : pathHist(0), ptGhist(0),
              hitBank(0), hitBankIndex(0),
              altBank(0), altBankIndex(0),
              bimodalIndex(0), loopTag(0), currentIter(0),
              tagePred(false), altTaken(false), loopPred(false),
              loopPredValid(false), loopIndex(0), loopHit(0),
              condBranch(false), longestMatchPred(false),
              pseudoNewAlloc(false), branchPC(0)
        {
            storage = new int [sz * 5];
            tableIndices = storage;
            tableTags = storage + sz;
            ci = tableTags + sz;
            ct0 = ci + sz;
            ct1 = ct0 + sz;
        }

        ~BranchInfo()
        {
            delete[] storage;
        }
    };

    /**
     * Computes the index used to access the
     * bimodal table.
     * @param pc_in The unshifted branch PC.
     */
    int bindex(Addr pc_in) const;

    /**
     * Computes the index used to access the
     * loop predictor.
     * @param pc_in The unshifted branch PC.
     */
    int lindex(Addr pc_in) const;

    /**
     * Computes the index used to access a
     * partially tagged table.
     * @param tid The thread ID used to select the
     * global histories to use.
     * @param pc The unshifted branch PC.
     * @param bank The partially tagged table to access.
     */
    inline int gindex(ThreadID tid, Addr pc, int bank) const;

    /**
     * Utility function to shuffle the path history
     * depending on which tagged table we are accessing.
     * @param phist The path history.
     * @param size Number of path history bits to use.
     * @param bank The partially tagged table to access.
     */
    int F(int phist, int size, int bank) const;

    /**
     * Computes the partial tag of a tagged table.
     * @param tid the thread ID used to select the
     * global histories to use.
     * @param pc The unshifted branch PC.
     * @param bank The partially tagged table to access.
     */
    inline uint16_t gtag(ThreadID tid, Addr pc, int bank) const;

    /**
     * Updates a direction counter based on the actual
     * branch outcome.
     * @param ctr Reference to counter to update.
     * @param taken Actual branch outcome.
     * @param nbits Counter width.
     */
    void ctrUpdate(int8_t & ctr, bool taken, int nbits);

    /**
     * Get a branch prediction from the bimodal
     * predictor.
     * @param pc The unshifted branch PC.
     * @param bi Pointer to information on the
     * prediction.
     */
    bool getBimodePred(Addr pc, BranchInfo* bi) const;

    /**
     * Updates the bimodal predictor.
     * @param pc The unshifted branch PC.
     * @param taken The actual branch outcome.
     * @param bi Pointer to information on the prediction
     * recorded at prediction time.
     */
    void baseUpdate(Addr pc, bool taken, BranchInfo* bi);

    /**
     * Get a branch prediction from the loop
     * predictor.
     * @param pc The unshifted branch PC.
     * @param bi Pointer to information on the
     * prediction.
     */
    bool getLoop(Addr pc, BranchInfo* bi) const;

   /**
    * Updates the loop predictor.
    * @param pc The unshifted branch PC.
    * @param taken The actual branch outcome.
    * @param bi Pointer to information on the
    * prediction recorded at prediction time.
    */
    void loopUpdate(Addr pc, bool Taken, BranchInfo* bi);

   /**
    * (Speculatively) updates the global branch history.
    * @param h Reference to pointer to global branch history.
    * @param dir (Predicted) outcome to update the histories
    * with.
    * @param tab
    * @param PT Reference to path history.
    */
    void updateGHist(uint8_t * &h, bool dir, uint8_t * tab, int &PT);

    /**
     * Get a branch prediction from L-TAGE. *NOT* an override of
     * BpredUnit::predict().
     * @param tid The thread ID to select the global
     * histories to use.
     * @param branch_pc The unshifted branch PC.
     * @param cond_branch True if the branch is conditional.
     * @param b Reference to wrapping pointer to allow storing
     * derived class prediction information in the base class.
     */
    bool predict(ThreadID tid, Addr branch_pc, bool cond_branch, void* &b);

    /**
     * Update L-TAGE. Called at execute to repair histories on a misprediction
     * and at commit to update the tables.
     * @param tid The thread ID to select the global
     * histories to use.
     * @param branch_pc The unshifted branch PC.
     * @param taken Actual branch outcome.
     * @param bi Pointer to information on the prediction
     * recorded at prediction time.
     */
    void update(ThreadID tid, Addr branch_pc, bool taken, BranchInfo* bi);

   /**
    * (Speculatively) updates global histories (path and direction).
    * Also recomputes compressed (folded) histories based on the
    * branch direction.
    * @param tid The thread ID to select the histories
    * to update.
    * @param branch_pc The unshifted branch PC.
    * @param taken (Predicted) branch direction.
    * @param b Wrapping pointer to BranchInfo (to allow
    * storing derived class prediction information in the
    * base class).
    */
    void updateHistories(ThreadID tid, Addr branch_pc, bool taken, void* b);

    /**
     * Restores speculatively updated path and direction histories.
     * Also recomputes compressed (folded) histories based on the
     * correct branch outcome.
     * This version of squash() is called once on a branch misprediction.
     * @param tid The Thread ID to select the histories to rollback.
     * @param taken The correct branch outcome.
     * @param bp_history Wrapping pointer to BranchInfo (to allow
     * storing derived class prediction information in the
     * base class).
     * @post bp_history points to valid memory.
     */
    void squash(ThreadID tid, bool taken, void *bp_history);

    /**
     * Speculatively updates the loop predictor
     * iteration count.
     * @param pc The unshifted branch PC.
     * @param taken The predicted branch outcome.
     * @param bi Pointer to information on the prediction
     * recorded at prediction time.
     */
    void specLoopUpdate(Addr pc, bool taken, BranchInfo* bi);

    const unsigned logSizeBiMP;
    const unsigned logSizeTagTables;
    const unsigned logSizeLoopPred;
    const unsigned nHistoryTables;
    const unsigned tagTableCounterBits;
    const unsigned histBufferSize;
    const unsigned minHist;
    const unsigned maxHist;
    const unsigned minTagWidth;

    BimodalEntry *btable;
    TageEntry **gtable;
    LoopEntry *ltable;

    // Keep per-thread histories to
    // support SMT.
    struct ThreadHistory {
        // Speculative path history
        // (LSB of branch address)
        int pathHist;

        // Speculative branch direction
        // history (circular buffer)
        // @TODO Convert to std::vector<bool>
        uint8_t *globalHistory;

        // Pointer to most recent branch outcome
        uint8_t* gHist;

        // Index to most recent branch outcome
        int ptGhist;

        // Speculative folded histories.
        FoldedHistory *computeIndices;
        FoldedHistory *computeTags[2];
    };

    std::vector<ThreadHistory> threadHistory;

    int tagWidths[15];
    int tagTableSizes[15];
    int *histLengths;
    int *tableIndices;
    int *tableTags;

    int8_t loopUseCounter;
    int8_t useAltPredForNewlyAllocated;
    int tCounter;
    int logTick;
};

#endif // __CPU_PRED_LTAGE


text:
package de.garbereder.util;

/**
 * @author gerritgarbereder
 * @version 1.0
 */
public class DefectClass {
    protected int i;

    public int getI() {
        return i;
    }

    public void setI(int i) {
    }
}


text:
/**
 *  Author:strive
 *  Date: 2016/1/13
 */
function json2url(json){
    json.t=Math.random();

    var arr=[];
    for(var name in json){
        arr.push(name+'='+json[name]);
    }
    return arr.join('&');
}
function ajax(json){
    json=json || {};
    if(!json.url)return;
    json.data=json.data || {};
    json.type=json.type || 'get';

    var timer=null;

    if(window.XMLHttpRequest){
        var oAjax=new XMLHttpRequest();
    }else{
        var oAjax=new ActiveXObject('Microsoft.XMLHTTP');
    }

    switch(json.type){
        case 'get':
            oAjax.open('GET',json.url+'?'+json2url(json.data),true);
            oAjax.send();
            break;
        case 'post':
            oAjax.open('POST',json.url,true);
            oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            oAjax.send(json2url(json.data));
            break;
    }

    oAjax.onreadystatechange=function(){
        if(oAjax.readyState==4){
            clearTimeout(timer);
            if(oAjax.status>=200 && oAjax.status<300 || oAjax.status==304){
                json.success && json.success(oAjax.responseText);
            }else{
                json.error && json.error(oAjax.status);
            }
        }
    };
}


text:
#include "modelTimer.h"

using namespace twoDModel::model;

ModelTimer::ModelTimer(const Timeline *timeline)
	: mTimeline(timeline)
	, mTimeToWait(0)
	, mListening(false)
	, mTimePast(0)
	, mInterval(0)
	, mRepeatable(false)
{
	connect(timeline, SIGNAL(tick()), this, SLOT(onTick()));
}

bool ModelTimer::isTicking() const
{
	return mListening;
}

void ModelTimer::start()
{
	start(mInterval);
}

void ModelTimer::start(int ms)
{
	mInterval = ms;
	mTimeToWait = ms;
	mTimePast = 0;
	mListening = true;
}

void ModelTimer::stop()
{
	mTimeToWait = 0;
	mTimePast = 0;
	mListening = false;
}

void ModelTimer::onTick()
{
	if (!mListening) {
		return;
	}

	mTimePast += Timeline::timeInterval;
	if (mTimePast >= mTimeToWait) {
		mListening = false;
		onTimeout();
	}
}

void ModelTimer::setInterval(int ms)
{
	mInterval = ms;
}

void ModelTimer::setRepeatable(bool repeatable)
{
	mRepeatable = repeatable;
}

void ModelTimer::onTimeout()
{
	AbstractTimer::onTimeout();
	if (mRepeatable) {
		start();
	}
}


text:
<?php

/**
 * Filter to authorize only certain users.
 * See docs directory.
 *
 * @author Ernesto Revilla, Yaco Sistemas SL.
 * @package simpleSAMLphp
 * @version $Id$
 */
class sspmod_authorize_Auth_Process_Authorize extends SimpleSAML_Auth_ProcessingFilter {

	/**
	 * Array of valid users. Each element is a regular expression. You should
	 * user \ to escape special chars, like '.' etc.
	 *
	 */
	private $valid_attribute_values = array();

	/**
	 * Initialize this filter.
	 * Validate configuration parameters.
	 *
	 * @param array $config  Configuration information about this filter.
	 * @param mixed $reserved  For future use.
	 */
	public function __construct($config, $reserved) {
		parent::__construct($config, $reserved);

		assert('is_array($config)');

		foreach ($config as $attribute => $values) {
			if (is_string($values))
				$values = array($values);
			if (!is_array($values))
				throw new Exception('Filter Authorize: Attribute values is neither string nor array: ' . var_export($attribute, TRUE));
			foreach ($values as $value){
				if(!is_string($value)) {
					throw new Exception('Filter Authorize: Each value should be a string for attribute: ' . var_export($attribute, TRUE) . ' value: ' . var_export($value, TRUE) . ' Config is: ' . var_export($config, TRUE));
				}
			}
			$this->valid_attribute_values[$attribute] = $values;
		}
	}

	/**
	 * Apply filter to validate attributes.
	 *
	 * @param array &$request  The current request
	 */
	public function process(&$request) {
		$authorize = FALSE;
		assert('is_array($request)');
		assert('array_key_exists("Attributes", $request)');

		$attributes =& $request['Attributes'];

		foreach ($this->valid_attribute_values as $name => $patterns) {
			if(array_key_exists($name, $attributes)) {
				foreach ($patterns as $pattern){
					$values = $attributes[$name];
					if (!is_array($values))
						$values = array($values);
					foreach ($values as $value){
						if(preg_match($pattern, $value)) {
							$authorize = TRUE;
							break 3;
						}
					}
				}
			}
		}
		if (!$authorize){
			/* Save state and redirect to 403 page. */
			$id = SimpleSAML_Auth_State::saveState($request,
				'authorize:Authorize');
			$url = SimpleSAML_Module::getModuleURL(
				'authorize/authorize_403.php');
			SimpleSAML_Utilities::redirect($url, array('StateId' => $id));
		}
	}
}

?>


text:
require 'rails_helper'

describe 'New User On-boarding', js: true do

  def fill_in_form
    fill_in "First Name",            with: "Phil"
    fill_in "Last Name",             with: "Monroe"
    fill_in "Email",                 with: "test@example.com"
    fill_in "Password",              with: "passworD1"
    fill_in "Password Confirmation", with: "passworD1"
    fill_in "Mobile Phone",          with: "1-800-867-5309"
    fill_in "City",                  with: "San Francisco"
    fill_in "State",                 with: "CA"
    fill_in "Postal Code",           with: "94109"
    check   "Accept Terms and Conditions"
  end

  context 'circle membership requires admin approval' do

    let!(:circle) { submit_form(:circle_create_form, must_activate_users: true).result }

    it 'works' do

      # New User
      # - opens registration page
      # - fills form
      # - submits
      visit root_path
      click_on t('layouts.public.header.sign-up')
      fill_in_form
      click_on "Continue"
      expect(page).to have_content(t('public.circles.index.title'))

      # - chooses a circle which requires admin approval
      fill_in "user[location]", with: circle.address.location.geocode_query
      sleep 1
      find('.circle-marker .button.submit').click

      # - sees the "pending" message
      expect(page).to have_content(t('public.circles.membership_inactive.pending.title'))

      # - circle admin is notified by email
      expect(last_email.to.first).to eq(circle.admin.email)
      expect(last_email.subject).to eq("[Lale] #{t('mailers.subject.user_mailer.account_activation')}")
    end
  end

  context "admin approves new user" do

    let!(:circle) { submit_form(:circle_create_form, must_activate_users: true).result }
    let!(:new_member) { create(:circle_role_volunteer, circle: circle, status: :pending).user }

    before do
      circle.update_attribute :must_activate_users, true
    end

    it "works" do
      # verify setup
      expect(circle.volunteers).to include(new_member)

      # circle admin goes to manage users page
      visit circle_path(circle, as: circle.admin)
      click_on t('layouts.internal.sidebar.admin')
      click_on t('circle.admins.nav.invite-volunteers')

      # ensure we are on track. This also waits for the page to load
      expect(page).to have_content(t('circle.admins.invite.pending_members_headline'))
      expect(page).to have_content(new_member.name)

      # ensure admin action is properly indicated
      expect(page).to have_css('#admin_link .badge')
      expect(page).to have_css('.tab-nav .invite .before-icon')

      # circle admin clicks on Accept
      click_on t('circle.admins.inactive_members_list.activate')

      # user disappears
      expect(page).not_to have_content(new_member.name)

      # admin action indicators disappear
      expect(page).not_to have_css('#admin_link .badge')
      expect(page).not_to have_css('.tab-nav .invite .before-icon')

      # new user is notified
      expect(last_email.to.first).to eq(new_member.email)
      expect(last_email.subject).to eq("[Lale] #{t('mailers.subject.user_mailer.account_activated')}")

      # user appears in helper list
      click_on t('circle.members.index.directory')
      expect(page).to have_content(new_member.name)
    end
  end

  context "User joins second circle" do

    let!(:circle_1) { submit_form(:circle_create_form, must_activate_users: true).result }
    let!(:circle_2) { submit_form(:circle_create_form, must_activate_users: true).result }
    let!(:circle_1_role) { create(:circle_role_volunteer, circle: circle_1, status: :active) }
    let!(:user) { circle_1_role.user }
    let!(:circle_2_role) { create(:circle_role_volunteer, circle: circle_2, user: user, status: :pending) }

    it "is still active on first circle, pending on the second" do

      visit circle_path(circle_1, as: user)
      expect(page).to have_content(t('circles.show.dashboard_title', name: circle_1.name))

      visit circle_path(circle_2, as: user)
      expect(page).to have_content(t('public.circles.membership_inactive.pending.title'))
    end
  end

end


text:
package com.zzn.aenote.http.sqlmap;

/**
 * linzz
 */

public class SqlMapItem {
	private String itemID;
	private String prapID;
	private boolean isEmpty;
	private String condit;
	public String getItemID() {
		return itemID;
	}
	public void setItemID(String itemID) {
		this.itemID = itemID;
	}
	public boolean isEmpty() {
		return isEmpty;
	}
	public void setEmpty(boolean isEmpty) {
		this.isEmpty = isEmpty;
	}
	public String getCondit() {
		return condit;
	}
	public void setCondit(String condit) {
		this.condit = condit;
	}
	public String getPrapID() {
		return prapID;
	}
	public void setPrapID(String prapID) {
		this.prapID = prapID;
	}
}


text:
package org.apache.jackrabbit.oak.plugins.blob;

import org.apache.jackrabbit.oak.api.Blob;

/**
 * Exposes the blob along with the Node id from which referenced
 */
public class ReferencedBlob {
    private Blob blob;

    private String id;

    public ReferencedBlob(Blob blob, String id) {
        this.setBlob(blob);
        this.setId(id);
    }

    public Blob getBlob() {
        return blob;
    }

    public void setBlob(Blob blob) {
        this.blob = blob;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "ReferencedBlob{" +
                   "blob=" + blob +
                   ", id='" + id + '\'' +
                   '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        ReferencedBlob that = (ReferencedBlob) o;

        if (!getBlob().equals(that.getBlob())) {
            return false;
        }
        return !(getId() != null ? !getId().equals(that.getId()) : that.getId() != null);

    }

    @Override
    public int hashCode() {
        int result = getBlob().hashCode();
        result = 31 * result + (getId() != null ? getId().hashCode() : 0);
        return result;
    }
}


text:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, FormArray } from '@angular/forms';
import { Message } from '../database/message';
import { SocketService } from '../../chat/socket.service';
import { UserDetails } from '../database/user-details';
import { SecurityService } from '../services/security.service';

/**
 * CheckBoxMessageComponent to display check box options
 * @export
 * @class CheckBoxMessageComponent
 * @implements {OnInit}
 * @implements {OnDestroy}
 */
@Component({
    selector: 'mm-checkbox-message',
    template: `

{{header}}

            <input type="checkbox" class="custom-control-input" id="{{option}}"
                name="{{option}}"
                value="{{option}}"
                (change)="onSelectionChange($event, option)">
            {{option}}

        <button type="button" [disabled]="!enable" class="btn btn-secondary" (click)="submit()">Submit</button>
    `
})

export class CheckBoxMessageComponent implements OnInit {

    @Input() message: Message;
    @Input() index: number;
    @Input() public selectedOption: string[] = [];
    @Output() public onNewEntryAdded = new EventEmitter();
    header: string = '';
    options: string[];
    selectedUser: UserDetails;
    enable = true;

    constructor(private socketService: SocketService, private securityService: SecurityService) {
    }

    ngOnInit() {
        this.options = this.message.contentData.data;
        this.header = this.message.text;
        this.selectedUser = JSON.parse(this.securityService.getCookie('userDetails'));
        if (this.selectedUser.id === this.message.senderId) {
            this.enable = false;
        } else {
            this.enable = true;
        }
    }

    onSelectionChange(event: any, option: any) {
        if (event.target.checked) {
            this.selectedOption.push(option);
        } else {
            let updateItem = this.selectedOption.find(this.findIndexToUpdate, option);
            let index = this.selectedOption.indexOf(updateItem);
            this.selectedOption.splice(index, 1);
        }
    }

    findIndexToUpdate(option: any) {
        return option === this;
    }

    submit() {
        this.message.contentType = 'text';
        this.message.text = this.header + this.message.contentData.data;
        this.message.responseData.data = this.options;
        this.message.createdBy = this.message.senderId;
        this.message.updatedBy = this.message.senderId;
        this.edit(this.message);
        this.addNewEntry();
    }

    addNewEntry(): void {
        this.onNewEntryAdded.emit({
            value: 'Option chosen: ' + this.selectedOption
        });
    }

    edit(message: Message): void {
        let result = JSON.stringify(message);
        if (!result) {
            return;
        }
        this.socketService.updateMessage(message, this.index);
    }
}


text:
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using SharpCrop.Models;
using SharpCrop.Services;

namespace SharpCrop.Forms
{
    /// <summary>
    /// CropForm helps the user to select a rectangle which gonna be captured and uploaded.
    /// </summary>
    public class CropForm : Form
    {
        private readonly Controller controller;
        private readonly Rectangle screen;

        private MouseButtons mouseButtonUsed = MouseButtons.Left;
        private Point mouseMovePoint = Point.Empty;
        private Point mouseDownPoint = Point.Empty;
        private Point mouseUpPoint = Point.Empty;
        private bool isMouseDown;
        private Rectangle lastRegion;

        /// <summary>
        /// Construct a new CropForm with the given provider.
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="screen">Screen bounds</param>
        public CropForm(Controller controller, Rectangle screen)
        {
            this.controller = controller;
            this.screen = screen;

            InitializeComponent();

            Location = screen.Location;
            ClientSize = Size = screen.Size;

            RefreshBackground();
            MakeClickable();
        }

        private void InitializeComponent()
        {
            SuspendLayout();

            AutoScaleDimensions = new SizeF(96F, 96F);
            AutoScaleMode = AutoScaleMode.Dpi;
            FormBorderStyle = FormBorderStyle.Sizable;
            StartPosition = FormStartPosition.Manual;
            WindowState = FormWindowState.Maximized;
            BackColor = Color.Black;
            DoubleBuffered = true;
            Opacity = 0.25D;
            Text = "SharpCrop";
            TopMost = false;
        }

        /// <summary>
        /// Reset the mouse position.
        /// </summary>
        private void ResetMouse()
        {
            mouseMovePoint = mouseDownPoint = mouseUpPoint = Point.Empty;
            isMouseDown = false;
        }

        /// <summary>
        /// When CropForm shown.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            RefreshBackground();
            MakeClickable();
            ResetMouse();

            if(FormService.CropForms.Count == 1)
            {
                Focus();
            }
        }

        /// <summary>
        /// When CropForm lose focus.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLostFocus(EventArgs e)
        {
            base.OnLostFocus(e);

            RefreshBackground();
            MakeClickable();
            ResetMouse();

            if (FormService.CropForms.Count == 1)
            {
                Focus();
            }
        }

        /// <summary>
        /// Construct a new ConfigForm and hide CropForm.
        /// </summary>
        private void ShowConfig()
        {
            FormService.HideCropForms();
            FormService.ConfigForm.Show();
        }

        /// <summary>
        /// Listen for key presses.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);

            switch (e.KeyCode)
            {
                case Keys.Escape:
                    Close();
                    break;
                case Keys.F1:
                    ShowConfig();
                    break;
            }
        }

        /// <summary>
        /// Listen for mouse up event and proceed to upload.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            MakeClickable();

            if(!isMouseDown)
            {
                return;
            }

            mouseUpPoint = mouseMovePoint = e.Location;
            mouseButtonUsed = e.Button;
            isMouseDown = false;

            // IMPORTANT: Convert the local (window) points to absolute (screen) points
            var region = CaptureService.GetRectangle(
                PointToScreen(mouseDownPoint),
                PointToScreen(mouseUpPoint));

            if (region.Width < 1 || region.Height < 1)
            {
                return;
            }

            FormService.HideCropForms();
            Application.DoEvents();

            // Wait the form to be hidden
            Thread.Sleep(200);

            switch (e.Button)
            {
                case MouseButtons.Left:
                    controller.CaptureImage(region);
                    break;
                case MouseButtons.Right:
                    controller.CaptureVideo(region);
                    break;
            }
        }

        /// <summary>
        /// Listen for mouse down events and save the coords.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            MakeInvisible();

            mouseUpPoint = mouseMovePoint = mouseDownPoint = e.Location;
            mouseButtonUsed = e.Button;
            isMouseDown = true;
        }

        /// <summary>
        /// Request repaint as the mouse moves.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);

            mouseMovePoint = e.Location;
            mouseButtonUsed = e.Button;

            Invalidate();
        }

        /// <summary>
        /// Draw the select rectangle on the screen.
        /// It uses the lastRegion variable to repaint only the difference.
        /// </summary>
        /// <param name="gfx"></param>
        /// <param name="color"></param>
        /// <param name="r"></param>
        private void DrawSelectRectangle(Graphics gfx, Brush color, Rectangle r)
        {
            if (SettingsService.Current.NoTransparency)
            {

                var path = new[]
                {
                    new Point { X = r.X, Y = r.Y },
                    new Point { X = r.X + r.Width , Y = r.Y },
                    new Point { X = r.X + r.Width , Y = r.Y + r.Height },
                    new Point { X = r.X , Y = r.Y + r.Height },
                    new Point { X = r.X, Y = r.Y }
                };

                gfx.DrawLines(new Pen(color, Config.PenWidth), path);

                return;
            }

            var old = lastRegion;
            var b = new SolidBrush(BackColor);

            if (old.X < r.X)
            {
                gfx.FillRectangle(b, old.X, old.Y, r.X - old.X, old.Height);
            }

            if (old.Y < r.Y)
            {
                gfx.FillRectangle(b, old.X, old.Y, old.Width, r.Y - old.Y);
            }

            if (old.Y + old.Height > r.Y + r.Height)
            {
                gfx.FillRectangle(b, old.X, r.Y + r.Height, old.Width, old.Y + old.Height - (r.Y + r.Height));
            }

            if (old.X + old.Width > r.X + r.Width)
            {
                gfx.FillRectangle(b, r.X + r.Width, old.Y, old.X + old.Width - (r.X + r.Width), old.Height);
            }

            gfx.FillRectangle(color, r.X, r.Y, r.Width, r.Height);
        }

        /// <summary>
        /// Paint the rectangle if the mouse button is down.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            if (!isMouseDown)
            {
                return;
            }

            var region = CaptureService.GetRectangle(mouseDownPoint, mouseMovePoint);

            if (mouseButtonUsed == MouseButtons.Left)
            {
                DrawSelectRectangle(e.Graphics, Config.LeftColor, region);
            }
            else if (mouseButtonUsed == MouseButtons.Right)
            {
                DrawSelectRectangle(e.Graphics, Config.RightColor, region);
            }

            lastRegion = region;
        }

        /// <summary>
        /// Refresh the background if transparency is disabled.
        /// </summary>
        private void RefreshBackground()
        {
            if (!SettingsService.Current.NoTransparency)
            {
                return;
            }

            var bitmap = CaptureService.CaptureBitmap(new Rectangle(PointToScreen(Location), ClientSize));

            BackgroundImage = bitmap;
            Opacity = 1.0D;
        }

        /// <summary>
        /// Make the form invisible and enable clicking.
        /// </summary>
        private void MakeClickable()
        {
            if(VersionService.GetPlatform() != PlatformType.Windows || SettingsService.Current.NoTransparency)
            {
                return;
            }

            TransparencyKey = Color.White;
            Opacity = 0.005D;
        }

        /// <summary>
        /// Make the background invisible (not the selecting rectangle) and disable clicking.
        /// </summary>
        private void MakeInvisible()
        {
            if (VersionService.GetPlatform() != PlatformType.Windows || SettingsService.Current.NoTransparency)
            {
                return;
            }

            TransparencyKey = Color.Black;
            Opacity = 0.75D;
        }
    }
}


text:
<?php
  wp_reset_query();
?>
<?php
  $response = '';

  function gen_response($type, $uzi){
    if($type == 'success') {
      return $response = '

'.$uzi.'

';
    } else {
      return $response = '

'.$uzi.'

';
    }
  }

  $not_human       = 'Authentication failed';
  $missing_content = 'Missing fields are required';
  $email_invalid   = 'Invalid e-mail address';
  $message_unsent  = 'Error message';
  $message_sent    = 'Melding er sendt.
Vi vil ta kontakt med deg så raskt som mulig. Ha en fin dag';

  //user posted variables
  $name = $_POST['contact_name'];
  $email = $_POST['contact_email'];
  $tel = $_POST['contact_tel'];
  $message = $_POST['contact_message'];
  $human = $_POST['contact_human'];
  $type = $_POST['contact_type'];

  $submitted = $_POST['submitted'];

  $addr = $_POST['contact_gateaddresse'];
  $po = $_POST['contact_postnummer'];
  $poststed = $_POST['contact_poststed'];
  $mnummer = $_POST['contact_mnummer'];
  $mobil = $_POST['contact_mobil'];
  $prosjekt = $_POST['contact_prosjekt'];
  $tfork = $_POST['contact_tfork'];

  //php mailer variables
  //$to = get_option('admin_email');
  $to = 'Annette.kleven@vestbo.no';
  //$to = 'szabogabi@gmail.com';

  $subject = $type.": Hesjaholtet Park";

  $headers = "From: " . strip_tags($email) . "\r\n";
  $headers .= "Reply-To: ". strip_tags($email) . "\r\n";
  //$headers .= "CC: szabogabi@gmail.com\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

  if ($submitted == 1) {
    // Simple contact to Anette
    $to = 'Annette.kleven@vestbo.no';
    $message='Name: '.$name.'
'.'Tel: '.$tel.'
'.'Message:
'.$message;

  } else {
    // Frorkj message to vestbo
    $to = 'forkjopsrett@vestbo.no';
    $message='Prosjekt: Brl Hesjaholtet Park
'.
             'Navn: '.$name.'
'.
             'Gateadresse: '.$addr.'
'.
             'Postnummer: '.$po.'
'.
             'Poststed: '.$poststed.'
'.
             'Medlemsnummer: '.$mnummer.'
'.
             'Tel: '.$tel.'
'.
             'Mobil: '.$mobil.'
'.
             'E-post: '.$email.'
'.
             'Type forkj.: '.$tfork.'
';
    $message_sent    = 'Melding er sendt.
Takk for din påmelding. Ha en fin dag';
  }

  //$to='szabogabi@gmail.com';

if(!$human == 0){
    if($human != 2) gen_response('error', $not_human); //not human!
    else {

      //validate email
      if(!filter_var($email, FILTER_VALIDATE_EMAIL))
        $response = gen_response('error', $email_invalid);
      else //email is valid
      {
        //validate presence of name and email
        if(empty($name) || empty($email)){
          $response = gen_response('error', $missing_content);
        }
        else //ready to go!
        {

          $sent = wp_mail($to, $subject, $message, $headers);
            if($sent) {
              $sent = wp_mail($email, $subject, $message, $headers);
              $response = gen_response('success', $message_sent); //message sent!
            } else {
                $response = gen_response('error', $message_unsent); //message wasn't sent
              }

        }
      }
    }
  }
  else
    if ($_POST['submitted']) { $response = gen_response('error', $missing_content);}

?>

<?php if ( !is_archive() && !is_page_template('template-chooser.php') ) : ?>
<?php echo $response; ?>
<aside id="contactblock" class="footer--contactblock is_light <?php echo is_singular('apartment')?'collapse':''; ?>">

        Meld interesse |
        Meld forkjøpsrett

          <form action="<?php the_permalink(); ?>#contacresponse" method="post">

              <input required placeholder="ditt navn (obligatorisk)" type="text" id="contact_name" name="contact_name">

              <input required placeholder="e-post (obligatorisk)" type="email" id="contact_email" name="contact_email">

              <input placeholder="telefonnummer" type="tel" id="contact_tel" name="contact_tel">

              <textarea name="contact_message" placeholder="melding" id="contact_message" cols="30" rows="6"></textarea>

              <input id="contact_type" type="hidden" name="contact_type" value="Interesse">
              <input type="hidden" name="contact_human" value="2">
              <input type="hidden" name="submitted" value="1">
              <input type="submit" class="btn" value="Send">

          </form>

          <form action="<?php the_permalink(); ?>#contacresponse" method="post">

              <input required disabled="disabled" placeholder="Prosjekt" type="text" id="contact_prosjekt" name="contact_prosjekt" value="Prosjekt: Brl Hesjaholtet Park">

              <input required placeholder="Navn (obligatorisk)" type="text" id="contact_name" name="contact_name">

              <input required placeholder="Gateadresse (obligatorisk)" type="text" id="contact_gateaddresse" name="contact_gateaddresse">

              <input required placeholder="Postnummer (obligatorisk)" type="text" id="contact_postnummer" name="contact_postnummer">

              <input required placeholder="Poststed (obligatorisk)" type="text" id="contact_poststed" name="contact_poststed">

              <input required placeholder="Medlemsnummer i Vestbo (obligatorisk)" type="text" id="contact_mnummer" name="contact_mnummer">

              <input placeholder="Mobilnummer" type="tel" id="contact_mobil" name="contact_mobil">

              <input placeholder="Telefonnummer" type="tel" id="contact_tel" name="contact_tel">

              <input required placeholder="E-post (obligatorisk)" type="email" id="contact_email" name="contact_email">

Type forkjøpsrett (obligatorisk)

              <input required type="radio" name="contact_tfork" value=">Intern forkjøsrett, boende i leilighet nr" /> Intern forkjøsrett, boende i leilighet nr

              <input required type="radio" name="contact_tfork" value="Medlemskap i Vestbo, medlemsnummer" /> Medlemskap i Vestbo, medlemsnummer

              <input id="contact_type" type="hidden" name="contact_type" value="Forkjøpsrett">
              <input type="hidden" name="contact_human" value="2">
              <input type="hidden" name="submitted" value="2">
              <input type="submit" class="btn" value="Send">

          </form>

<?php endif; ?>


text:
# disallow empty character classes in regular expressions (no-empty-character-class)

Because empty character classes in regular expressions do not match anything, they might be typing mistakes.

```js
var foo = /^abc[]/;
```

## Rule Details

This rule disallows empty character classes in regular expressions.

Examples of **incorrect** code for this rule:

```js
/*eslint no-empty-character-class: "error"*/

/^abc[]/.test("abcdefg"); // false
"abcdefg".match(/^abc[]/); // null
```

Examples of **correct** code for this rule:

```js
/*eslint no-empty-character-class: "error"*/

/^abc/.test("abcdefg"); // true
"abcdefg".match(/^abc/); // ["abc"]

/^abc[a-z]/.test("abcdefg"); // true
"abcdefg".match(/^abc[a-z]/); // ["abcd"]
```

## Known Limitations

This rule does not report empty character classes in the string argument of calls to the `RegExp` constructor.

Example of a *false negative* when this rule reports correct code:

```js
/*eslint no-empty-character-class: "error"*/

var abcNeverMatches = new RegExp("^abc[]");
```


text:
const {Mixin} = require('../..')
const $$skippingRebound = Symbol('skippingRebound')

const DifferenceMixin = Mixin('DifferenceMixin')
  .method('$fork', function () {
    let forked = this.$clone(this.$isNew)
    let original = this

    forked.$startTracking()
    original.$startTracking()

    Object.defineProperties(forked, {
      $original: {
        get () { return original }
      },
      $forked: {
        get () { return original != null }
      }
    })

    let applyDeltaFn = function (changeset) {
      if (original != null && changeset.$size > 0 && forked[$$skippingRebound] !== true) {
        forked.$difference.$applyToInitial(changeset)
      }
    }

    this.$on('update', applyDeltaFn)

    forked.$on('destroy', function () {
      original = null
      this.$off('update', applyDeltaFn)
    })

    return forked
  })
  .method('$commitChanges', function (mixin, applyToInitial = false) {
    if (this.$original != null || !this.$isPristine) {
      let changeset = this.$difference.$getChangeSet()
      if (changeset.$size > 0) {
        this[$$skippingRebound] = true
        if (applyToInitial) {
          this.$original.$difference.$applyToInitial(changeset)
        } else {
          changeset.$applyToObject(this.$original)
        }
        delete this[$$skippingRebound]
      }
      this.$difference.$setPristine()
    }
    return this
  })

module.exports = DifferenceMixin


text:
package com.nowellpoint.console.entity;

import java.io.Serializable;
import java.util.Date;

public class Contact implements Serializable {

	private static final long serialVersionUID = 7757768228776544041L;

	public String firstName;

	public String lastName;

	public String email;

	public String phone;

	public Date addedOn;

	public Date updatedOn;

	public Contact() {

	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Date getAddedOn() {
		return addedOn;
	}

	public void setAddedOn(Date addedOn) {
		this.addedOn = addedOn;
	}

	public Date getUpdatedOn() {
		return updatedOn;
	}

	public void setUpdatedOn(Date updatedOn) {
		this.updatedOn = updatedOn;
	}
}


text:
public class Message {
	public enum Msgtype {
		ERROR, INNERSUCCESS, MESSAGE,OUTTERSUCCESS
	};

	Msgtype type=Msgtype.MESSAGE;
	String msg=null;

	public Message() {

	}

	public Message(Msgtype type, String msg) {
		this.type = type;
		this.msg = msg;
	}
}