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

package com.google.api.services.dlp.v2.model;

/**
 * Apply transformation to the selected info_types.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Data Loss Prevention (DLP) API. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

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

  /**
   * Required. InfoTypes to apply the transformation to. Required. Provided InfoType must be unique
   * within the ImageTransformations message.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<GooglePrivacyDlpV2InfoType> infoTypes;

  static {
    // hack to force ProGuard to consider GooglePrivacyDlpV2InfoType used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(GooglePrivacyDlpV2InfoType.class);
  }

  /**
   * Required. InfoTypes to apply the transformation to. Required. Provided InfoType must be unique
   * within the ImageTransformations message.
   * @return value or {@code null} for none
   */
  public java.util.List<GooglePrivacyDlpV2InfoType> getInfoTypes() {
    return infoTypes;
  }

  /**
   * Required. InfoTypes to apply the transformation to. Required. Provided InfoType must be unique
   * within the ImageTransformations message.
   * @param infoTypes infoTypes or {@code null} for none
   */
  public GooglePrivacyDlpV2SelectedInfoTypes setInfoTypes(java.util.List<GooglePrivacyDlpV2InfoType> infoTypes) {
    this.infoTypes = infoTypes;
    return this;
  }

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

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

}


text:
@implementation UIBarButtonItem (Item)
+ (instancetype)itemWithImage:(UIImage *)image highlightImage:(UIImage *)highImage Target:(nullable id)target action:(SEL)action
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:image forState:UIControlStateNormal];
    [btn setImage:highImage forState:UIControlStateHighlighted];
    [btn sizeToFit];
    UIView *contentV = [[UIView alloc] initWithFrame:btn.bounds];
    [contentV addSubview:btn];
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    return [[UIBarButtonItem alloc] initWithCustomView:contentV];
}

+ (instancetype)itemWithImage:(UIImage *)image selImage:(UIImage *)selImage Target:(id)target action:(SEL)action
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:image forState:UIControlStateNormal];
    [btn setImage:selImage forState:UIControlStateSelected];
    [btn sizeToFit];
    UIView *contentV = [[UIView alloc] initWithFrame:btn.bounds];
    [contentV addSubview:btn];
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    return [[UIBarButtonItem alloc] initWithCustomView:contentV];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package org.apache.wss4j.dom.message;

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

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.security.auth.callback.CallbackHandler;

import org.w3c.dom.Document;
import org.apache.wss4j.common.crypto.Crypto;
import org.apache.wss4j.common.crypto.CryptoFactory;
import org.apache.wss4j.common.derivedKey.ConversationConstants;
import org.apache.wss4j.common.util.XMLUtils;
import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.common.CustomHandler;
import org.apache.wss4j.dom.common.KeystoreCallbackHandler;
import org.apache.wss4j.dom.common.SOAPUtil;
import org.apache.wss4j.dom.common.SecretKeyCallbackHandler;
import org.apache.wss4j.dom.common.SecurityTestUtil;
import org.apache.wss4j.dom.engine.WSSConfig;
import org.apache.wss4j.dom.engine.WSSecurityEngine;
import org.apache.wss4j.dom.handler.HandlerAction;
import org.apache.wss4j.dom.handler.RequestData;
import org.apache.wss4j.dom.handler.WSHandlerConstants;
import org.apache.wss4j.dom.handler.WSHandlerResult;
import org.junit.Assert;
import org.junit.Test;

/**
 * A set of tests for using a derived key for encryption/signature using WSHandler actions.
 */
public class DerivedKeyActionTest extends Assert {
    private static final org.slf4j.Logger LOG =
        org.slf4j.LoggerFactory.getLogger(DerivedKeyActionTest.class);
    private CallbackHandler callbackHandler = new KeystoreCallbackHandler();
    private Crypto crypto = null;

    @org.junit.AfterClass
    public static void cleanup() throws Exception {
        SecurityTestUtil.cleanup();
    }

    public DerivedKeyActionTest() throws Exception {
        crypto = CryptoFactory.getInstance("wss40.properties");
        WSSConfig.init();
    }

    @Test
    public void testSignatureThumbprintSHA1() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.SIG_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        HandlerAction action = new HandlerAction(WSConstants.DKT_SIGN);
        handler.send(
            doc,
            reqData,
            Collections.singletonList(action),
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        Assert.assertTrue(outputString.contains(ConversationConstants.WSC_NS_05_12));
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc);
    }

    @Test
    public void testSignatureThumbprintSHA1OldNamespace() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.SIG_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        config.put(WSHandlerConstants.USE_2005_12_NAMESPACE, "false");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        HandlerAction action = new HandlerAction(WSConstants.DKT_SIGN);
        handler.send(
            doc,
            reqData,
            Collections.singletonList(action),
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        Assert.assertTrue(outputString.contains(ConversationConstants.WSC_NS_05_02));
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc);
    }

    @Test
    public void testSignatureThumbprintSHA1StrongDigest() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.SIG_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
        config.put(WSHandlerConstants.SIG_DIGEST_ALGO, WSConstants.SHA256);
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        HandlerAction action = new HandlerAction(WSConstants.DKT_SIGN);
        handler.send(
            doc,
            reqData,
            Collections.singletonList(action),
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc);
    }

    @Test
    public void testSignatureThumbprintDifferentKeyLength() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.SIG_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        config.put(WSHandlerConstants.DERIVED_SIGNATURE_KEY_LENGTH, "16");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        HandlerAction action = new HandlerAction(WSConstants.DKT_SIGN);
        handler.send(
            doc,
            reqData,
            Collections.singletonList(action),
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        Assert.assertTrue(outputString.contains(ConversationConstants.WSC_NS_05_12));
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc);
    }

    @Test
    public void testSignatureSKI() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.SIG_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "SKIKeyIdentifier");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        HandlerAction action = new HandlerAction(WSConstants.DKT_SIGN);
        handler.send(
            doc,
            reqData,
            Collections.singletonList(action),
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc);
    }

    @Test
    public void testSignatureX509() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.SIG_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_REFERENCE, "DirectReference");
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "X509KeyIdentifier");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        HandlerAction action = new HandlerAction(WSConstants.DKT_SIGN);
        handler.send(
            doc,
            reqData,
            Collections.singletonList(action),
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc);
    }

    @Test
    public void testSignatureEncryptedKeyThumbprintSHA1() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.SIG_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_REFERENCE, "EncryptedKey");
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        HandlerAction action = new HandlerAction(WSConstants.DKT_SIGN);
        handler.send(
            doc,
            reqData,
            Collections.singletonList(action),
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc);
    }

    @Test
    public void testSignatureSCT() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);

        // Generate a Key
        SecretKeyCallbackHandler secretKeyCallbackHandler = new SecretKeyCallbackHandler();
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey key = keyGen.generateKey();
        byte[] keyData = key.getEncoded();
        secretKeyCallbackHandler.setOutboundSecret(keyData);

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.PW_CALLBACK_REF, secretKeyCallbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_REFERENCE, "SecurityContextToken");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        HandlerAction action = new HandlerAction(WSConstants.DKT_SIGN);
        handler.send(
            doc,
            reqData,
            Collections.singletonList(action),
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc, secretKeyCallbackHandler);
    }

    @Test
    public void testEncryptionThumbprintSHA1() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.ENC_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_REFERENCE, "EncryptedKey");
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        HandlerAction action = new HandlerAction(WSConstants.DKT_ENCR);
        handler.send(
            doc,
            reqData,
            Collections.singletonList(action),
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        Assert.assertTrue(outputString.contains(ConversationConstants.WSC_NS_05_12));
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc);
    }

    @Test
    public void testEncryptionSCT() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        // Generate a Key
        SecretKeyCallbackHandler secretKeyCallbackHandler = new SecretKeyCallbackHandler();
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey key = keyGen.generateKey();
        byte[] keyData = key.getEncoded();
        secretKeyCallbackHandler.setOutboundSecret(keyData);

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.PW_CALLBACK_REF, secretKeyCallbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_REFERENCE, "SecurityContextToken");
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        HandlerAction action = new HandlerAction(WSConstants.DKT_ENCR);
        handler.send(
            doc,
            reqData,
            Collections.singletonList(action),
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        Assert.assertTrue(outputString.contains(ConversationConstants.WSC_NS_05_12));
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc, secretKeyCallbackHandler);
    }

    @Test
    public void testSignatureEncryptionThumbprintSHA1() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.SIG_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.ENC_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_REFERENCE, "EncryptedKey");
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        List<HandlerAction> actions = new ArrayList<>();
        actions.add(new HandlerAction(WSConstants.DKT_SIGN));
        actions.add(new HandlerAction(WSConstants.DKT_ENCR));
        handler.send(
            doc,
            reqData,
            actions,
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        Assert.assertTrue(outputString.contains(ConversationConstants.WSC_NS_05_12));
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc);
    }

    @Test
    public void testEncryptionSignatureThumbprintSHA1() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.SIG_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.ENC_PROP_FILE, "wss40.properties");
        config.put(WSHandlerConstants.PW_CALLBACK_REF, callbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_REFERENCE, "EncryptedKey");
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        List<HandlerAction> actions = new ArrayList<>();
        actions.add(new HandlerAction(WSConstants.DKT_ENCR));
        actions.add(new HandlerAction(WSConstants.DKT_SIGN));
        handler.send(
            doc,
            reqData,
            actions,
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        Assert.assertTrue(outputString.contains(ConversationConstants.WSC_NS_05_12));
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc);
    }

    @Test
    public void testSignatureEncryptionSecurityContextToken() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        // Generate a Key
        SecretKeyCallbackHandler secretKeyCallbackHandler = new SecretKeyCallbackHandler();
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey key = keyGen.generateKey();
        byte[] keyData = key.getEncoded();
        secretKeyCallbackHandler.setOutboundSecret(keyData);

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.PW_CALLBACK_REF, secretKeyCallbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_REFERENCE, "SecurityContextToken");
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        List<HandlerAction> actions = new ArrayList<>();
        actions.add(new HandlerAction(WSConstants.DKT_SIGN));
        actions.add(new HandlerAction(WSConstants.DKT_ENCR));
        handler.send(
            doc,
            reqData,
            actions,
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        Assert.assertTrue(outputString.contains(ConversationConstants.WSC_NS_05_12));
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc, secretKeyCallbackHandler);
    }

    @Test
    public void testEncryptionSignatureSecurityContextToken() throws Exception {
        final WSSConfig cfg = WSSConfig.getNewInstance();
        final RequestData reqData = new RequestData();
        reqData.setWssConfig(cfg);
        reqData.setUsername("wss40");

        // Generate a Key
        SecretKeyCallbackHandler secretKeyCallbackHandler = new SecretKeyCallbackHandler();
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey key = keyGen.generateKey();
        byte[] keyData = key.getEncoded();
        secretKeyCallbackHandler.setOutboundSecret(keyData);

        java.util.Map<String, Object> config = new java.util.TreeMap<String, Object>();
        config.put(WSHandlerConstants.PW_CALLBACK_REF, secretKeyCallbackHandler);
        config.put(WSHandlerConstants.DERIVED_TOKEN_REFERENCE, "SecurityContextToken");
        config.put(WSHandlerConstants.DERIVED_TOKEN_KEY_ID, "Thumbprint");
        reqData.setMsgContext(config);

        final Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
        CustomHandler handler = new CustomHandler();
        List<HandlerAction> actions = new ArrayList<>();
        actions.add(new HandlerAction(WSConstants.DKT_ENCR));
        actions.add(new HandlerAction(WSConstants.DKT_SIGN));
        handler.send(
            doc,
            reqData,
            actions,
            true
        );
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        Assert.assertTrue(outputString.contains(ConversationConstants.WSC_NS_05_12));
        if (LOG.isDebugEnabled()) {
            LOG.debug(outputString);
        }

        verify(doc, secretKeyCallbackHandler);
    }

    private WSHandlerResult verify(Document doc) throws Exception {
        return verify(doc, callbackHandler);
    }

    private WSHandlerResult verify(Document doc, CallbackHandler cbHandler) throws Exception {
        WSSecurityEngine secEngine = new WSSecurityEngine();
        WSHandlerResult results =
            secEngine.processSecurityHeader(doc, null, cbHandler, crypto);
        String outputString =
            XMLUtils.prettyDocumentToString(doc);
        assertTrue(outputString.indexOf("counter_port_type") > 0 ? true : false);

        return results;
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Crystal SDK for iOS: LeaderboardEntry Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Modules

Classes

Files

Class List

Class Members

Public Attributes

LeaderboardEntry Class Reference

Class describing an entry in a Leaderboard.
More...

List of all members.

Public Attributes

string 	username

string 	position

double 	score

Detailed Description

Class describing an entry in a Leaderboard.

The documentation for this class was generated from the following file:

CrystalUnityBasic.cs

<address class="footer">Generated on Thu Mar 24 2011 11:51:14 for Crystal SDK for iOS by

 1.7.1 </address>


text:
/*
    Area of Circle = PI * radius * radius
*/
define(['./constants', './circle'], function(constants, circle) {
    return function(radius, angleInRadian) {
        return circle(radius) * (angleInRadian / 2 / constants.PI  ) ;
    };
});


text:
using Agrobook.Client.Login;
using Eventing.Client.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace Agrobook.Web.Controllers.Login
{
    [RoutePrefix("app/login")]
    public class LoginController : ApiControllerBase
    {
        private readonly ILoginClient client;

        public LoginController()
        {
            this.client = ServiceLocator
                            .ResolveNewOf<ILoginClient>()
                            .WithTokenProvider(this.TokenProvider);
        }

        [HttpPost]
        [Route("try-login")]
        public async Task<IHttpActionResult> TryLogin([FromBody]dynamic value)
        {
            var result = await this.client.TryLoginAsync(value.usuario.Value, value.password.Value);
            return this.Ok(result);
        }
    }
}


text:
import { BitGoBase, InitiateRecoveryOptions } from '@bitgo/sdk-core';
import * as stellar from 'stellar-sdk';

export function getStellarKeys(bitgo: BitGoBase, params: InitiateRecoveryOptions): stellar.Keypair[] {
  const keys: stellar.Keypair[] = [];
  let userKey = params.userKey;
  let backupKey = params.backupKey;

  // Stellar's Ed25519 public keys start with a G, while private keys start with an S
  const isKrsRecovery = backupKey.startsWith('G') && !userKey.startsWith('G');
  const isUnsignedSweep = backupKey.startsWith('G') && userKey.startsWith('G');

  try {
    if (!userKey.startsWith('S') && !userKey.startsWith('G')) {
      userKey = bitgo.decrypt({
        input: userKey,
        password: params.walletPassphrase,
      });
    }

    const userKeyPair = isUnsignedSweep ? stellar.Keypair.fromPublicKey(userKey) : stellar.Keypair.fromSecret(userKey);
    keys.push(userKeyPair);
  } catch (e) {
    throw new Error('Failed to decrypt user key with passcode - try again!');
  }

  try {
    if (!backupKey.startsWith('S') && !isKrsRecovery && !isUnsignedSweep) {
      backupKey = bitgo.decrypt({
        input: backupKey,
        password: params.walletPassphrase,
      });
    }

    if (isKrsRecovery || isUnsignedSweep) {
      keys.push(stellar.Keypair.fromPublicKey(backupKey));
    } else {
      keys.push(stellar.Keypair.fromSecret(backupKey));
    }
  } catch (e) {
    throw new Error('Failed to decrypt backup key with passcode - try again!');
  }

  return keys;
}


text:
-WTM-Plugin
===========

Plugin for a new Gamemode


text:
package org.tbax.baxshops.internal.text;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.bukkit.inventory.ItemStack;
import org.tbax.baxshops.internal.items.ItemUtil;

public final class HoverEvent
{
    private String event;
    private JsonElement value;

    private HoverEvent(String event, String value)
    {
        this.event = event;
        this.value = new JsonPrimitive(value);
    }

    private HoverEvent(String event, ChatComponent value)
    {
        this.event = event;
        this.value = value.toJsonObject();
    }

    public String getEvent()
    {
        return event;
    }

    public String getValue()
    {
        if (value.isJsonPrimitive()) {
            return value.getAsString();
        }
        else {
            return value.toString();
        }
    }

    public JsonObject toJsonObject()
    {
        JsonObject object = new JsonObject();
        object.addProperty("action", event);
        object.add("value", value);
        return object;
    }

    @Override
    public String toString()
    {
        return toJsonObject().toString();
    }

    public static HoverEvent showText(String text)
    {
        return new HoverEvent("show_text", text);
    }

    public static HoverEvent showText(ChatComponent text)
    {
        return new HoverEvent("show_text", text);
    }

    public static HoverEvent showItem(ItemStack stack)
    {
        return new HoverEvent("show_item", ItemUtil.getNBTTag(stack));
    }
}


text:
"""Command Skeleton."""

import argparse
import datetime
import parsedatetime

class BaseCommand(object):
    """Base command."""

    NAME = ""
    HELP = ""

    def add_arguments(self, parser):
        """Add custom arguments.

        Args:
          parser: argparse.Parser
        """
        pass

    def run(self, accessor, opts):
        """Run the command.

        Args:
          accessor: biggraphite.accessor.Accessor
          opts: argparse.Namespace
        """
        pass

# Following code comes from https://github.com/Clemson-DPA/dpa-pipe.
class ParseDateTimeArg(argparse.Action):
    """argparse.Action subclass. parses natural language cl datetime strings.

    Use this class as an argument to the 'action' argument when calling
    add_argument on an argparse parser. When the command line arguments are
    parsed, the resulting namespace will have a datetime.datetime object
    assigned to the argument's destination.

    If a datetime could not be parsed from the string, a ValueError will be
    raised.

    Examples of parsable human readable datetime strings:
        "now", "yesterday", "2 weeks from now", "3 days ago", etc.
    Note: When the datetime string is more than one word, you should include
    the argument in quotes on the command line.
    """

    def __call__(self, parser, namespace, datetime_str, option_string=None):
        """Do the thing."""
        parsed_datetime = date_time_from_str(datetime_str)
        setattr(namespace, self.dest, parsed_datetime)

def date_time_from_str(datetime_str):
    """Parse a humanly readable datetime.

    Args:
      datetime_str: str, humanly readable date time.

    Returns:
      datetime, correctponding datetime object.
    """
    cal = parsedatetime.Calendar()
    parsed_result, date_type = cal.parse(datetime_str)
    parsed_datetime = None

    if date_type == 3:
        # parsed_result is a datetime
        parsed_datetime = parsed_result
    elif date_type in (1, 2):
        # parsed_result is struct_time
        parsed_datetime = datetime.datetime(*parsed_result[:6])
    else:
        # Failed to parse
        raise ValueError("Could not parse date/time string: " + datetime_str)
    return parsed_datetime


text:
Updated Master Project Plan for Sprint I
========================================

* Implementation of the websites GUI using HTML, CSS and Bootstrap with the URL being http://136.145.57.180 , here some description of the website is provided
* SQL was used to implement the communication between the database of the website and the user
* Dummy accounts were created for the website's database to verify how the information was being stored


text:
<?php namespace Codeception\Module\MailTester;

use InvalidArgumentException;
use ReflectionClass;
use RuntimeException;

class MailTesterFactory
{
    /**
     * @param array $moduleConfig
     *
     * @return MailTestable
     */
    public function make(array $moduleConfig)
    {
        $name = $this->getProviderName($moduleConfig);
        $config = $this->getProviderConfig($moduleConfig, $name);
        $class = $this->getProviderClass($name);

        return new $class($config);
    }

    protected function getProviderName($config)
    {
        if (!isset($config['provider']))
        {
            $message = "A mail testing provider must be specified.";

            throw new InvalidArgumentException($message);
        }

        return $config['provider'];
    }

    /**
     * @param string $driver
     *
     * @return string
     */
    protected function getProviderClassName($driver)
    {
        $class = new ReflectionClass($this);
        $namespace = $class->getNamespaceName();

        return "{$namespace}\\Providers\\{$driver}";
    }

    protected function getProviderConfig($config, $provider)
    {
        if (!isset($config[$provider]))
        {
            $message = "Config options for [$provider] must be specified.";

            throw new InvalidArgumentException($message);
        }

        return $config[$provider];
    }

    /**
     * @param string $driver
     *
     * @return string
     */
    protected function getProviderClass($driver)
    {
        $provider = $this->getProviderClassName($driver);

        if (!class_exists($provider))
        {
            $message = "Provider class [$provider] does not exist.";

            throw new RuntimeException($message);
        }

        return $provider;
    }

}


text:
using PlayerIOClient;

namespace BotBits.Events
{
    /// <summary>
    ///     Occurs when a player toggles god mode.
    /// </summary>
    /// <seealso cref="PlayerEvent{T}" />
    [ReceiveEvent("god")]
    public sealed class GodModeEvent : PlayerEvent<GodModeEvent>
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="GodModeEvent" /> class.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="client"></param>
        internal GodModeEvent(BotBitsClient client, Message message)
            : base(client, message)
        {
            this.God = message.GetBoolean(1);
        }

        /// <summary>
        ///     Gets or sets a value indicating whether this player is in god mode.
        /// </summary>
        /// <value><c>true</c> if this player is in god mode; otherwise, <c>false</c>.</value>
        public bool God { get; set; }
    }
}


text:
var plantModel = {};

//遍历plant表
plantModel.findAllPlant = function(callback) {
	connection.query('select * from plant', function (error, results, fields) {
		var resData = {
			code: 0,
			data: {}
		}
		if (error) {
			throw error;
		}else {
			resData.code = 1;
			resData.data = results;
			console.log('The first is: ', results);

		}
		callback(resData);
	});
}

//种植查询
plantModel.findPlantInfoById = function(id, callback) {
	var resData = {
		code: 1,
		data: null
	}
	// var sql = 'select * from seed where seedid = "' + id + '"';
	var sql = 'select * from plant,plantusedrug where plant.plantid = "' + id + '" and plantusedrug.plantid = "' + id + '"';
	//console.log(sql)
	connection.query(sql, function(error, results) {
		if(error) {
			resData.code = 0;
			console.log(error)
		}else {
			resData.data = results;
		}
		callback(resData);
	});
}

module.exports = plantModel;


text:
package io.spring.initializr.web.support;

import java.util.LinkedHashMap;
import java.util.Map;

import io.spring.initializr.metadata.BillOfMaterials;
import io.spring.initializr.metadata.Dependency;
import io.spring.initializr.metadata.DependencyMetadata;
import io.spring.initializr.metadata.DependencyMetadataProvider;
import io.spring.initializr.metadata.InitializrMetadata;
import io.spring.initializr.metadata.Repository;
import io.spring.initializr.util.Version;

import org.springframework.cache.annotation.Cacheable;

/**
 * A default {@link DependencyMetadataProvider} implementation.
 *
 * @author Stephane Nicoll
 */
public class DefaultDependencyMetadataProvider implements DependencyMetadataProvider {

	@Override
	@Cacheable(cacheNames = "initializr.dependency-metadata", key = "#p1")
	public DependencyMetadata get(InitializrMetadata metadata, Version bootVersion) {
		Map<String, Dependency> dependencies = new LinkedHashMap<>();
		for (Dependency d : metadata.getDependencies().getAll()) {
			if (d.match(bootVersion)) {
				dependencies.put(d.getId(), d.resolve(bootVersion));
			}
		}

		Map<String, Repository> repositories = new LinkedHashMap<>();
		for (Dependency d : dependencies.values()) {
			if (d.getRepository() != null) {
				repositories.put(d.getRepository(), metadata.getConfiguration()
						.getEnv().getRepositories().get(d.getRepository()));
			}
		}

		Map<String, BillOfMaterials> boms = new LinkedHashMap<>();
		for (Dependency d : dependencies.values()) {
			if (d.getBom() != null) {
				boms.put(d.getBom(), metadata.getConfiguration().getEnv()
						.getBoms().get(d.getBom()).resolve(bootVersion));
			}
		}
		// Each resolved bom may require additional repositories
		for (BillOfMaterials b : boms.values()) {
			for (String id : b.getRepositories()) {
				repositories.put(id, metadata.getConfiguration().getEnv()
						.getRepositories().get(id));
			}
		}

		return new DependencyMetadata(bootVersion, dependencies, repositories, boms);
	}

}


text:
using System.Collections.Generic;
using System.Linq;
using Cresce.Datasources.Commands;
using Cresce.Datasources.Repositories;
using Cresce.Datasources.Sql.Dapper;
using Cresce.Models;

namespace Cresce.Datasources.Sql
{
    public class SqlUserRepository : IUserRepository
    {

        private readonly ICrudCommands<User> _crudCommands;

        public SqlUserRepository(IDbManagerFactory dbManagerFactory)
        {
            var crudBuilder = Cmd.MakeCrudCommandsBuilder<User>("User", dbManagerFactory);

            crudBuilder.SetIdentifierField("Id");
            crudBuilder.SetField("Name");
            crudBuilder.SetField("Inactive");

            _crudCommands = crudBuilder.Build();
        }

        public User GetById(string userId) => _crudCommands.GetByIdCommand.Execute(userId);
        public bool Exists(string userId) => _crudCommands.ExistsCommand.Execute(userId);
        public IEnumerable<User> GetUsers() => _crudCommands.GetMultipleRecordsCommand.Execute();
        public IEnumerable<User> GetValidUsers() => GetUsers().Where(e => e.Inactive == false);

        public User Save(User user)
        {
            _crudCommands.UpdateOrInsertCommand.Execute(user);

            return user;
        }
    }
}


text:
package org.apache.isis.core.wrapper.internal.util;

import java.util.Arrays;
import java.util.LinkedHashSet;

public final class MethodPrefixFinder {

    // a Linked Hash Set is used to ensure that the ordering is preserved.
    public final static LinkedHashSet<String> ALL_PREFIXES = new LinkedHashSet<String>() {
        private static final long serialVersionUID = 1L;
        {
            // collection prefixes are added first because we want to
            // test validateAddTo and validateRemoveFrom before validate
            addAll(Arrays.asList(Constants.COLLECTION_PREFIXES));
            addAll(Arrays.asList(Constants.PROPERTY_PREFIXES));
            addAll(Arrays.asList(Constants.ACTION_PREFIXES));
        }
    };

    public String findPrefix(final String methodName) {
        for (final String prefix : ALL_PREFIXES) {
            if (methodName.startsWith(prefix)) {
                return prefix;
            }
        }
        return "";
    }

}


text:
/*!
 * \file
 * \brief Android utilities.
 *//*--------------------------------------------------------------------*/

#include "tcuAndroidUtil.hpp"

namespace tcu
{
namespace Android
{

using std::string;

static string getIntentStringExtra (JNIEnv* env, jobject activity, const char* name)
{
	// \todo [2013-05-12 pyry] Clean up references on error.

	jclass	activityCls		= env->GetObjectClass(activity);
	jobject	intent			= env->CallObjectMethod(activity, env->GetMethodID(activityCls, "getIntent", "()Landroid/content/Intent;"));
	TCU_CHECK(intent);

	jstring	extraName		= env->NewStringUTF(name);
	jclass	intentCls		= env->GetObjectClass(intent);
	TCU_CHECK(extraName && intentCls);

	jvalue getExtraArgs[1];
	getExtraArgs[0].l = extraName;
	jstring extraStr = (jstring)env->CallObjectMethodA(intent, env->GetMethodID(intentCls, "getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;"), getExtraArgs);

	env->DeleteLocalRef(extraName);

	if (extraStr)
	{
		const char* ptr = env->GetStringUTFChars(extraStr, DE_NULL);
		string str = string(ptr);
		env->ReleaseStringUTFChars(extraStr, ptr);
		return str;
	}
	else
		return string();
}

string getIntentStringExtra (ANativeActivity* activity, const char* name)
{
	return getIntentStringExtra(activity->env, activity->clazz, name);
}

static void setRequestedOrientation (JNIEnv* env, jobject activity, ScreenOrientation orientation)
{
	jclass		activityCls			= env->GetObjectClass(activity);
	jmethodID	setOrientationId	= env->GetMethodID(activityCls, "setRequestedOrientation", "(I)V");

	env->CallVoidMethod(activity, setOrientationId, (int)orientation);
}

void setRequestedOrientation (ANativeActivity* activity, ScreenOrientation orientation)
{
	setRequestedOrientation(activity->env, activity->clazz, orientation);
}

ScreenOrientation mapScreenRotation (ScreenRotation rotation)
{
	switch (rotation)
	{
		case SCREENROTATION_0:		return SCREEN_ORIENTATION_PORTRAIT;
		case SCREENROTATION_90:		return SCREEN_ORIENTATION_LANDSCAPE;
		case SCREENROTATION_180:	return SCREEN_ORIENTATION_REVERSE_PORTRAIT;
		case SCREENROTATION_270:	return SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
		default:
			print("Warning: Unsupported rotation");
			return SCREEN_ORIENTATION_PORTRAIT;
	}
}

} // Android
} // tcu


text:
package com.planet_ink.coffee_mud.Abilities.Diseases;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Disease_Lockjaw extends Disease
{
	@Override public String ID() { return "Disease_Lockjaw"; }
	private final static String localizedName = CMLib.lang()._("Lockjaw");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang()._("(Lockjaw)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override protected int canAffectCode(){return CAN_MOBS;}
	@Override protected int canTargetCode(){return CAN_MOBS;}
	@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	@Override public boolean putInCommandlist(){return false;}
	@Override public int difficultyLevel(){return 2;}

	@Override protected int DISEASE_TICKS(){return 9999999;}
	@Override protected int DISEASE_DELAY(){return CMProps.getIntVar( CMProps.Int.TICKSPERMUDDAY );}
	@Override protected String DISEASE_DONE(){return "Your lockjaw is cured.";}
	@Override protected String DISEASE_START(){return "^G<S-NAME> get(s) lockjaw!^?";}
	@Override protected String DISEASE_AFFECT(){return "";}
	@Override public int spreadBitmap(){return DiseaseAffect.SPREAD_CONSUMPTION;}

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if(!super.tick(ticking,tickID))	return false;
		if(affected==null) return false;
		if(!(affected instanceof MOB)) return true;

		final MOB mob=(MOB)affected;
		if((!mob.amDead())&&((--diseaseTick)<=0))
		{
			diseaseTick=DISEASE_DELAY();
			if(CMLib.dice().rollPercentage()<mob.charStats().getSave(CharStats.STAT_SAVE_DISEASE))
			{
				unInvoke();
				return false;
			}
			return true;
		}
		return true;
	}
	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(!(affected instanceof MOB))
			return super.okMessage(myHost,msg);

		final MOB mob=(MOB)affected;

		// when this spell is on a MOBs Affected list,
		// it should consistantly prevent the mob
		// from trying to do ANYTHING except sleep
		if((msg.amISource(mob))
		&&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_ALWAYS))
		&&((msg.sourceMinor()==CMMsg.TYP_EAT)||(msg.sourceMinor()==CMMsg.TYP_DRINK)))
		{
			mob.tell(_("You can't open your mouth!"));
			return false;
		}

		return super.okMessage(myHost,msg);
	}

	@Override
	public void affectPhyStats(Physical affected, PhyStats affectableStats)
	{
		if(affected==null) return;
		affectableStats.setSensesMask(affectableStats.sensesMask()|PhyStats.CAN_NOT_SPEAK);
	}
}


text:
/*jshint node:true*/
'use strict';

var Battleship = require('./Battleship');
var GuessValidator = require('./GuessValidator');
var readline = require('readline');
var _ = require('lodash');

function Game(playsNumber, shipsNumber, boardSize) {
    this.playsNumber = playsNumber;
    this.shipsNumber = shipsNumber;
    this.boardSize = boardSize;
    this.guessNumber = 0;
    this.Battleship = new Battleship(shipsNumber, boardSize);
    this.GuessValidator = new GuessValidator(this.Battleship);
}

Game.prototype = {
    constructor : Game,
    playerGuess : function(guess, guessCount) {
        var that = this;
        this._processGuess(guess);
        if(that._isGameOver(guess, guessCount)) {
            return {
                'gameStatus' : 'end',
                'turn' : guessCount
            };
        } else {
            return {
                'gameStatus' : 'continue',
                'turn' : guessCount + 1
            };
        }
    },
    _isGameOver : function(guess, guessCount) {
        // is Game over?
        if(this._isPlayerWin()) {
            this._playerWin();
        } else if(guessCount >= this.playsNumber) {
            this._playerLose();
        }else {
            return false;
        }
        return true;
    },
    _processGuess : function(guess) {
        if(this.GuessValidator.validateGuess(guess)){
            var formatedGuess = this.GuessValidator.formatGuess(guess);
            if(this.Battleship.isBoatHit(formatedGuess)) {
                this.Battleship.markAsHit(formatedGuess);
            } else {
                this.Battleship.markAsMiss(formatedGuess);
            }
        } else {
            console.log('What are you trying to hit?');
        }
    },
    _playerLose : function() {
        console.log('You lose!');
        this.Battleship.markAllNonHitShips();
        this.Battleship.board.prettyPrint();
    },
    _isPlayerWin : function() {
        return this.Battleship.isAllShipsHit();
    },
    _playerWin : function() {
        console.log('You win!');
    }
};

module.exports = Game;


text:
<!DOCTYPE HTML>

<title>com.mxgraph.swing.handler (mxGraph 4.2.2 API Specification)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="dc.created" content="2020-10-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

mxGraph 4.2.2

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Package com.mxgraph.swing.handler

This package contains all classes required for mouse event handling in
  JFC/Swing. The classes implement rubberband selection, mouse tracking,
  creating connections, handling vertices and edges, moving cells, panning
  and keystroke handling.

Class Summary

Class
Description

mxCellHandler

mxCellMarker

Implements a mouse tracker that marks cells under the mouse.

mxCellTracker

Event handler that highlights cells.

mxConnectionHandler

Connection handler creates new connections between cells.

mxConnectPreview

Connection handler creates new connections between cells.

mxEdgeHandler

mxElbowEdgeHandler

mxGraphHandler

mxGraphTransferHandler

mxInsertHandler

mxKeyboardHandler

mxMovePreview

Connection handler creates new connections between cells.

mxPanningHandler

mxRotationHandler

Basic example of implementing a handler for rotation.

mxRubberband

Implements a rubberband selection.

mxSelectionCellsHandler

mxVertexHandler

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

mxGraph 4.2.2

All Classes

JavaScript is disabled on your browser.

Copyright (c) 2010-2017 Gaudenz Alder, JGraph Ltd. All rights reserved.


text:
var appConstants = require('../constants/appConstants');
var axios = require('axios');

var id = "f2e272948565c4ead60e";
var sec = "5e76c6da6e2bc056bbb4d7740c11c3eb909211bc";
var param = "?client_id=" + id + "&client_secret=" + sec;

var githubUtils = {
  getBio: function(username){
    var url = "https://api.github.com/users/" + username + param;
    return axios.get(url);
  },
  getRepos: function(username){
    var url = "https://api.github.com/users/" + username + "/repos" + param;
    return axios.get(url);
  }
};

module.exports = githubUtils;


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="../metro/css/metro-all.css?ver=@@b-version" rel="stylesheet">

    <title>Test Master - Metro 4 :: Popular HTML, CSS and JS library</title>

Master test page

Page 1

Page 2

Page 3

Page 4


text:
class CreateGames < ActiveRecord::Migration[5.1]
  def change
    create_table :games do |t|
      t.integer :total_play_time
      t.references :user, foreign_key: true

      t.timestamps
    end
  end
end


text:
class AddBarcodeColumnToInstrument < ActiveRecord::Migration
  def self.up
    add_column :instruments, :barcode, :string
    add_index :instruments, :barcode
  end

  def self.down
    remove_column :instruments, :barcode
  end
end


text:
.class Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;
.super Ljava/lang/Object;
.source "FingerprintLocationAnimationVideoView.java"

# interfaces
.implements Landroid/view/TextureView$SurfaceTextureListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->onFinishInflate()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field private mTextureToDestroy:Landroid/graphics/SurfaceTexture;

.field final synthetic this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

# direct methods
.method constructor <init>(Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;)V
    .locals 1

    iput-object p1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->mTextureToDestroy:Landroid/graphics/SurfaceTexture;

    return-void
.end method

# virtual methods
.method public onSurfaceTextureAvailable(Landroid/graphics/SurfaceTexture;II)V
    .locals 4

    const/4 v3, 0x0

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    const/4 v2, 0x4

    invoke-virtual {v1, v2}, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->setVisibility(I)V

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    invoke-virtual {v1}, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->getFingerprintLocationAnimation()Landroid/net/Uri;

    move-result-object v0

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v1, v1, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->mMediaPlayer:Landroid/media/MediaPlayer;

    if-eqz v1, :cond_0

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v1, v1, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->mMediaPlayer:Landroid/media/MediaPlayer;

    invoke-virtual {v1}, Landroid/media/MediaPlayer;->release()V

    :cond_0
    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->mTextureToDestroy:Landroid/graphics/SurfaceTexture;

    if-eqz v1, :cond_1

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->mTextureToDestroy:Landroid/graphics/SurfaceTexture;

    invoke-virtual {v1}, Landroid/graphics/SurfaceTexture;->release()V

    iput-object v3, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->mTextureToDestroy:Landroid/graphics/SurfaceTexture;

    :cond_1
    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v2, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v3, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    invoke-static {v3}, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->-get0(Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;)Landroid/content/Context;

    move-result-object v3

    invoke-virtual {v2, v3, v0}, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->createMediaPlayer(Landroid/content/Context;Landroid/net/Uri;)Landroid/media/MediaPlayer;

    move-result-object v2

    iput-object v2, v1, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->mMediaPlayer:Landroid/media/MediaPlayer;

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v1, v1, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->mMediaPlayer:Landroid/media/MediaPlayer;

    if-nez v1, :cond_2

    return-void

    :cond_2
    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v1, v1, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->mMediaPlayer:Landroid/media/MediaPlayer;

    new-instance v2, Landroid/view/Surface;

    invoke-direct {v2, p1}, Landroid/view/Surface;-><init>(Landroid/graphics/SurfaceTexture;)V

    invoke-virtual {v1, v2}, Landroid/media/MediaPlayer;->setSurface(Landroid/view/Surface;)V

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v1, v1, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->mMediaPlayer:Landroid/media/MediaPlayer;

    new-instance v2, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1$1;

    invoke-direct {v2, p0}, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1$1;-><init>(Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;)V

    invoke-virtual {v1, v2}, Landroid/media/MediaPlayer;->setOnPreparedListener(Landroid/media/MediaPlayer$OnPreparedListener;)V

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v1, v1, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->mMediaPlayer:Landroid/media/MediaPlayer;

    new-instance v2, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1$2;

    invoke-direct {v2, p0}, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1$2;-><init>(Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;)V

    invoke-virtual {v1, v2}, Landroid/media/MediaPlayer;->setOnInfoListener(Landroid/media/MediaPlayer$OnInfoListener;)V

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v2, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v2, v2, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->mMediaPlayer:Landroid/media/MediaPlayer;

    invoke-virtual {v2}, Landroid/media/MediaPlayer;->getVideoHeight()I

    move-result v2

    int-to-float v2, v2

    iget-object v3, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    iget-object v3, v3, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->mMediaPlayer:Landroid/media/MediaPlayer;

    invoke-virtual {v3}, Landroid/media/MediaPlayer;->getVideoWidth()I

    move-result v3

    int-to-float v3, v3

    div-float/2addr v2, v3

    iput v2, v1, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->mAspect:F

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    invoke-virtual {v1}, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->requestLayout()V

    iget-object v1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->this$0:Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;

    invoke-virtual {v1}, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView;->startAnimation()V

    return-void
.end method

.method public onSurfaceTextureDestroyed(Landroid/graphics/SurfaceTexture;)Z
    .locals 1

    iput-object p1, p0, Lcom/android/settings/fingerprint/FingerprintLocationAnimationVideoView$1;->mTextureToDestroy:Landroid/graphics/SurfaceTexture;

    const/4 v0, 0x0

    return v0
.end method

.method public onSurfaceTextureSizeChanged(Landroid/graphics/SurfaceTexture;II)V
    .locals 0

    return-void
.end method

.method public onSurfaceTextureUpdated(Landroid/graphics/SurfaceTexture;)V
    .locals 0

    return-void
.end method


text:
import {AfterContentInit, Component, OnInit} from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {RoleService} from "@app/services/role.service";
import {UserService} from "@app/services/user.service";
import {FormBuilder} from "@angular/forms";
import {ToastService} from "@app/services/toast.service";
import {EditBaseComponent} from "@app/modules/shared/edit-base.component";
import {SecurityConfiguration} from "@app/model/security-configuration";
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
import {SecurityService} from "@app/services/security.service";
import {switchMap, tap, withLatestFrom} from 'rxjs/operators';
import {BeanInformation} from "@app/model/bean-information";
import {zip} from "rxjs";
import {ErrorResult} from "@app/model/error-result";

@Component({
  selector: 'app-base-security',
  templateUrl: './base-security.component.html',
  styleUrls: ['./base-security.component.scss']
})
export class BaseSecurityComponent extends EditBaseComponent<SecurityConfiguration> implements OnInit, AfterContentInit  {

  activeUserManagers : BeanInformation[] = [];
  availableUserManagers: BeanInformation[] = [];
  activeRbacManagers: BeanInformation[] = [];
  availableRbacManagers: BeanInformation[] = [];

  submitting: boolean = false;

  rbacInfo: Map<string,BeanInformation> = new Map<string, BeanInformation>();
  userInfo: Map<string,BeanInformation> = new Map<string, BeanInformation>();

  constructor(private route: ActivatedRoute,
              public fb: FormBuilder, private securityService: SecurityService, private toastService: ToastService) {
    super(fb);
    super.init(fb.group({
      user_cache_enabled:[''],
    }, {}));

  }

  drop(event: CdkDragDrop<string[]>) {
    console.log("Drop " + event);
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
          event.container.data,
          event.previousIndex,
          event.currentIndex);
    }
  }

  ngOnInit(): void {
    zip(this.securityService.getRbacManagers(),this.securityService.getUserManagers()).pipe(tap(([rbacInfo,userInfo])=>{
      rbacInfo.forEach(info => this.rbacInfo.set(info.id, info));
      userInfo.forEach(info => this.userInfo.set(info.id, info));
      console.log("Rbac info " + JSON.stringify(this.rbacInfo));
      console.log("User info " + JSON.stringify(this.userInfo));
    }),switchMap(()=>this.securityService.getConfiguration())).subscribe(userConfig=>{
      this.activeRbacManagers=[];
      this.activeUserManagers=[];
      this.availableRbacManagers=[];
      this.availableUserManagers=[];
      this.userForm.get('user_cache_enabled').setValue(userConfig.user_cache_enabled);
      let availableRbacManagers : string[] = Array.from(this.rbacInfo.keys())
      let availableUserManagers : string[] = Array.from(this.userInfo.keys());
      userConfig.active_rbac_managers.forEach(rbacId=>{
        this.activeRbacManagers.push(this.rbacInfo.get(rbacId));
        availableRbacManagers = availableRbacManagers.filter(item => item != rbacId);
      });
      userConfig.active_user_managers.forEach(userId=>{
        this.activeUserManagers.push(this.userInfo.get(userId));
        availableUserManagers = availableUserManagers.filter(item => item != userId);
      });
      availableRbacManagers.forEach(rbacId => this.availableRbacManagers.push(this.rbacInfo.get(rbacId)));
      availableUserManagers.forEach(userId => this.availableUserManagers.push(this.userInfo.get(userId)));
    })
  }

  createEntity(): SecurityConfiguration {
    return undefined;
  }

  onSubmit() {
    if (this.activeUserManagers.length>0 && this.activeRbacManagers.length>0) {
      this.submitting=true;
      let sConfig = new SecurityConfiguration()
      sConfig.active_user_managers = [];
      sConfig.active_user_managers = this.activeUserManagers.map(uInfo => uInfo.id);
      sConfig.active_rbac_managers = this.activeRbacManagers.map(rInfo => rInfo.id);
      sConfig.user_cache_enabled = this.userForm.get('user_cache_enabled').value;
      this.securityService.updateConfiguration(sConfig).subscribe(()=>
          {
            this.toastService.showSuccessByKey('base-security','security.config.base.submit_success')
            this.submitting = false;
          }, ( error :ErrorResult) => {
            this.toastService.showErrorByKey('base-security','security.config.base.submit_error',
                {'error':error.toString()})
            this.submitting = false;
          }
      );
    } else {
      this.toastService.showErrorByKey('base-security','security.config.base.submit_active_empty')
    }

  }

  ngAfterContentInit(): void {
  }

  enableSubmit() : boolean {
    return !this.submitting && this.activeUserManagers.length>0 && this.activeRbacManagers.length>0 && this.userForm.valid;
  }

}


text:
'use strict';

var inherits = require('inherits')
  , EventEmitter = require('events').EventEmitter
  , EventSourceDriver = require('eventsource')
  ;

var debug = function() {};
if (process.env.NODE_ENV !== 'production') {
  debug = require('debug')('sockjs-client:receiver:eventsource');
}

function decodeURISafe(s) {
    return decodeURI(s.replace(/%(?![0-9][0-9a-fA-F]+)/g, '%25'));
}

function EventSourceReceiver(url) {
  debug(url);
  EventEmitter.call(this);

  var self = this;
  var es = this.es = new EventSourceDriver(url);
  es.onmessage = function(e) {
    debug('message', e.data);
    self.emit('message', decodeURISafe(e.data));
  };
  es.onerror = function(e) {
    debug('error', es.readyState, e);
    // ES on reconnection has readyState = 0 or 1.
    // on network error it's CLOSED = 2
    var reason = (es.readyState !== 2 ? 'network' : 'permanent');
    self._cleanup();
    self._close(reason);
  };
}

inherits(EventSourceReceiver, EventEmitter);

EventSourceReceiver.prototype.abort = function() {
  debug('abort');
  this._cleanup();
  this._close('user');
};

EventSourceReceiver.prototype._cleanup = function() {
  debug('cleanup');
  var es = this.es;
  if (es) {
    es.onmessage = es.onerror = null;
    es.close();
    this.es = null;
  }
};

EventSourceReceiver.prototype._close = function(reason) {
  debug('close', reason);
  var self = this;
  // Safari and chrome < 15 crash if we close window before
  // waiting for ES cleanup. See:
  // https://code.google.com/p/chromium/issues/detail?id=89155
  setTimeout(function() {
    self.emit('close', null, reason);
    self.removeAllListeners();
  }, 200);
};

module.exports = EventSourceReceiver;


text:
var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res) {
    var db = req.db;
    db.collection('usercollection').find().toArray(function (err, items) {
        res.render('users/index', {
            "title" : "Users",
            "users" : items
        });
    });
});

/* GET new user form. */
router.get('/new', function(req, res) {
    res.render('users/new', { title: 'New User' });
});

/* POST add user */
router.post('/add', function(req, res){
    var db = req.db;

    db.collection('usercollection').insert(req.body, function(err, result){
        if(err){
            // if it failed return error
            res.send("There was a problem adding the information to the database: " + err);
        }else{
            // if it worked, set the header so the address bar doesn't still say /add
            res.location("/users");
            // and foreward to success page
            res.redirect("/users");
        }
    });

});

/* DELETE delete user */
router.delete('/delete/:id', function(req, res) {
    var db = req.db;
    var userToDelete = req.params.id;

    db.collection('usercollection').removeById(userToDelete, function(err, result) {
        res.send((result === 1) ? { msg: '' } : { msg:'error: ' + err });
    });
});

module.exports = router;


text:
using System;
using NiL.JS.BaseLibrary;
using NiL.JS.Core;
using NiL.JS.Statements;

namespace NiL.JS.Expressions
{
#if !(PORTABLE || NETCORE)
    [Serializable]
#endif
    public sealed class RegExpExpression : Expression
    {
        private string pattern;
        private string flags;

        protected internal override bool ContextIndependent
        {
            get
            {
                return false;
            }
        }

        internal override bool ResultInTempContainer
        {
            get { return false; }
        }

        protected internal override PredictedType ResultType
        {
            get
            {
                return PredictedType.Object;
            }
        }

        public RegExpExpression(string pattern, string flags)
        {
            this.pattern = pattern;
            this.flags = flags;
        }

        public static CodeNode Parse(ParseInfo state, ref int position)
        {
            var i = position;
            if (!Parser.ValidateRegex(state.Code, ref i, false))
                return null;

            string value = state.Code.Substring(position, i - position);
            position = i;

            state.Code = Tools.removeComments(state.SourceCode, i);
            var s = value.LastIndexOf('/') + 1;
            string flags = value.Substring(s);
            try
            {
                return new RegExpExpression(value.Substring(1, s - 2), flags); // объекты должны быть каждый раз разные
            }
            catch (Exception e)
            {
                if (state.message != null)
                    state.message(MessageLevel.Error, CodeCoordinates.FromTextPosition(state.Code, i - value.Length, value.Length), string.Format(Strings.InvalidRegExp, value));
                return new ExpressionWrapper(new Throw(e));
            }
        }

        protected internal override CodeNode[] GetChildsImpl()
        {
            return null;
        }

        public override JSValue Evaluate(Context context)
        {
            return new RegExp(pattern, flags);
        }

        public override T Visit<T>(Visitor<T> visitor)
        {
            return visitor.Visit(this);
        }

        public override string ToString()
        {
            return "/" + pattern + "/" + flags;
        }
    }
}


text:
package org.apache.flink.streaming.connectors.kafka.table;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.connector.source.Boundedness;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.KafkaSourceBuilder;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.connector.kafka.source.reader.deserializer.KafkaRecordDeserializationSchema;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.KafkaDeserializationSchema;
import org.apache.flink.streaming.connectors.kafka.config.StartupMode;
import org.apache.flink.streaming.connectors.kafka.internals.KafkaTopicPartition;
import org.apache.flink.streaming.connectors.kafka.table.DynamicKafkaDeserializationSchema.MetadataConverter;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.connector.ChangelogMode;
import org.apache.flink.table.connector.format.DecodingFormat;
import org.apache.flink.table.connector.source.DataStreamScanProvider;
import org.apache.flink.table.connector.source.DynamicTableSource;
import org.apache.flink.table.connector.source.ScanTableSource;
import org.apache.flink.table.connector.source.abilities.SupportsReadingMetadata;
import org.apache.flink.table.connector.source.abilities.SupportsWatermarkPushDown;
import org.apache.flink.table.data.GenericMapData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.table.data.TimestampData;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.utils.DataTypeUtils;
import org.apache.flink.util.Preconditions;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.header.Header;

import javax.annotation.Nullable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/** A version-agnostic Kafka {@link ScanTableSource}. */
@Internal
public class KafkaDynamicSource
        implements ScanTableSource, SupportsReadingMetadata, SupportsWatermarkPushDown {

    // --------------------------------------------------------------------------------------------
    // Mutable attributes
    // --------------------------------------------------------------------------------------------

    /** Data type that describes the final output of the source. */
    protected DataType producedDataType;

    /** Metadata that is appended at the end of a physical source row. */
    protected List<String> metadataKeys;

    /** Watermark strategy that is used to generate per-partition watermark. */
    protected @Nullable WatermarkStrategy<RowData> watermarkStrategy;

    // --------------------------------------------------------------------------------------------
    // Format attributes
    // --------------------------------------------------------------------------------------------

    private static final String VALUE_METADATA_PREFIX = "value.";

    /** Data type to configure the formats. */
    protected final DataType physicalDataType;

    /** Optional format for decoding keys from Kafka. */
    protected final @Nullable DecodingFormat<DeserializationSchema<RowData>> keyDecodingFormat;

    /** Format for decoding values from Kafka. */
    protected final DecodingFormat<DeserializationSchema<RowData>> valueDecodingFormat;

    /** Indices that determine the key fields and the target position in the produced row. */
    protected final int[] keyProjection;

    /** Indices that determine the value fields and the target position in the produced row. */
    protected final int[] valueProjection;

    /** Prefix that needs to be removed from fields when constructing the physical data type. */
    protected final @Nullable String keyPrefix;

    // --------------------------------------------------------------------------------------------
    // Kafka-specific attributes
    // --------------------------------------------------------------------------------------------

    /** The Kafka topics to consume. */
    protected final List<String> topics;

    /** The Kafka topic pattern to consume. */
    protected final Pattern topicPattern;

    /** Properties for the Kafka consumer. */
    protected final Properties properties;

    /**
     * The startup mode for the contained consumer (default is {@link StartupMode#GROUP_OFFSETS}).
     */
    protected final StartupMode startupMode;

    /**
     * Specific startup offsets; only relevant when startup mode is {@link
     * StartupMode#SPECIFIC_OFFSETS}.
     */
    protected final Map<KafkaTopicPartition, Long> specificStartupOffsets;

    /**
     * The start timestamp to locate partition offsets; only relevant when startup mode is {@link
     * StartupMode#TIMESTAMP}.
     */
    protected final long startupTimestampMillis;

    /** Flag to determine source mode. In upsert mode, it will keep the tombstone message. * */
    protected final boolean upsertMode;

    protected final String tableIdentifier;

    public KafkaDynamicSource(
            DataType physicalDataType,
            @Nullable DecodingFormat<DeserializationSchema<RowData>> keyDecodingFormat,
            DecodingFormat<DeserializationSchema<RowData>> valueDecodingFormat,
            int[] keyProjection,
            int[] valueProjection,
            @Nullable String keyPrefix,
            @Nullable List<String> topics,
            @Nullable Pattern topicPattern,
            Properties properties,
            StartupMode startupMode,
            Map<KafkaTopicPartition, Long> specificStartupOffsets,
            long startupTimestampMillis,
            boolean upsertMode,
            String tableIdentifier) {
        // Format attributes
        this.physicalDataType =
                Preconditions.checkNotNull(
                        physicalDataType, "Physical data type must not be null.");
        this.keyDecodingFormat = keyDecodingFormat;
        this.valueDecodingFormat =
                Preconditions.checkNotNull(
                        valueDecodingFormat, "Value decoding format must not be null.");
        this.keyProjection =
                Preconditions.checkNotNull(keyProjection, "Key projection must not be null.");
        this.valueProjection =
                Preconditions.checkNotNull(valueProjection, "Value projection must not be null.");
        this.keyPrefix = keyPrefix;
        // Mutable attributes
        this.producedDataType = physicalDataType;
        this.metadataKeys = Collections.emptyList();
        this.watermarkStrategy = null;
        // Kafka-specific attributes
        Preconditions.checkArgument(
                (topics != null && topicPattern == null)
                        || (topics == null && topicPattern != null),
                "Either Topic or Topic Pattern must be set for source.");
        this.topics = topics;
        this.topicPattern = topicPattern;
        this.properties = Preconditions.checkNotNull(properties, "Properties must not be null.");
        this.startupMode =
                Preconditions.checkNotNull(startupMode, "Startup mode must not be null.");
        this.specificStartupOffsets =
                Preconditions.checkNotNull(
                        specificStartupOffsets, "Specific offsets must not be null.");
        this.startupTimestampMillis = startupTimestampMillis;
        this.upsertMode = upsertMode;
        this.tableIdentifier = tableIdentifier;
    }

    @Override
    public ChangelogMode getChangelogMode() {
        return valueDecodingFormat.getChangelogMode();
    }

    @Override
    public ScanRuntimeProvider getScanRuntimeProvider(ScanContext context) {
        final DeserializationSchema<RowData> keyDeserialization =
                createDeserialization(context, keyDecodingFormat, keyProjection, keyPrefix);

        final DeserializationSchema<RowData> valueDeserialization =
                createDeserialization(context, valueDecodingFormat, valueProjection, null);

        final TypeInformation<RowData> producedTypeInfo =
                context.createTypeInformation(producedDataType);

        final KafkaSource<RowData> kafkaSource =
                createKafkaSource(keyDeserialization, valueDeserialization, producedTypeInfo);

        return new DataStreamScanProvider() {
            @Override
            public DataStream<RowData> produceDataStream(StreamExecutionEnvironment execEnv) {
                if (watermarkStrategy == null) {
                    watermarkStrategy = WatermarkStrategy.noWatermarks();
                }
                return execEnv.fromSource(
                        kafkaSource, watermarkStrategy, "KafkaSource-" + tableIdentifier);
            }

            @Override
            public boolean isBounded() {
                return kafkaSource.getBoundedness() == Boundedness.BOUNDED;
            }
        };
    }

    @Override
    public Map<String, DataType> listReadableMetadata() {
        final Map<String, DataType> metadataMap = new LinkedHashMap<>();

        // according to convention, the order of the final row must be
        // PHYSICAL + FORMAT METADATA + CONNECTOR METADATA
        // where the format metadata has highest precedence

        // add value format metadata with prefix
        valueDecodingFormat
                .listReadableMetadata()
                .forEach((key, value) -> metadataMap.put(VALUE_METADATA_PREFIX + key, value));

        // add connector metadata
        Stream.of(ReadableMetadata.values())
                .forEachOrdered(m -> metadataMap.putIfAbsent(m.key, m.dataType));

        return metadataMap;
    }

    @Override
    public void applyReadableMetadata(List<String> metadataKeys, DataType producedDataType) {
        // separate connector and format metadata
        final List<String> formatMetadataKeys =
                metadataKeys.stream()
                        .filter(k -> k.startsWith(VALUE_METADATA_PREFIX))
                        .collect(Collectors.toList());
        final List<String> connectorMetadataKeys = new ArrayList<>(metadataKeys);
        connectorMetadataKeys.removeAll(formatMetadataKeys);

        // push down format metadata
        final Map<String, DataType> formatMetadata = valueDecodingFormat.listReadableMetadata();
        if (formatMetadata.size() > 0) {
            final List<String> requestedFormatMetadataKeys =
                    formatMetadataKeys.stream()
                            .map(k -> k.substring(VALUE_METADATA_PREFIX.length()))
                            .collect(Collectors.toList());
            valueDecodingFormat.applyReadableMetadata(requestedFormatMetadataKeys);
        }

        this.metadataKeys = connectorMetadataKeys;
        this.producedDataType = producedDataType;
    }

    @Override
    public boolean supportsMetadataProjection() {
        return false;
    }

    @Override
    public void applyWatermark(WatermarkStrategy<RowData> watermarkStrategy) {
        this.watermarkStrategy = watermarkStrategy;
    }

    @Override
    public DynamicTableSource copy() {
        final KafkaDynamicSource copy =
                new KafkaDynamicSource(
                        physicalDataType,
                        keyDecodingFormat,
                        valueDecodingFormat,
                        keyProjection,
                        valueProjection,
                        keyPrefix,
                        topics,
                        topicPattern,
                        properties,
                        startupMode,
                        specificStartupOffsets,
                        startupTimestampMillis,
                        upsertMode,
                        tableIdentifier);
        copy.producedDataType = producedDataType;
        copy.metadataKeys = metadataKeys;
        copy.watermarkStrategy = watermarkStrategy;
        return copy;
    }

    @Override
    public String asSummaryString() {
        return "Kafka table source";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final KafkaDynamicSource that = (KafkaDynamicSource) o;
        return Objects.equals(producedDataType, that.producedDataType)
                && Objects.equals(metadataKeys, that.metadataKeys)
                && Objects.equals(physicalDataType, that.physicalDataType)
                && Objects.equals(keyDecodingFormat, that.keyDecodingFormat)
                && Objects.equals(valueDecodingFormat, that.valueDecodingFormat)
                && Arrays.equals(keyProjection, that.keyProjection)
                && Arrays.equals(valueProjection, that.valueProjection)
                && Objects.equals(keyPrefix, that.keyPrefix)
                && Objects.equals(topics, that.topics)
                && Objects.equals(String.valueOf(topicPattern), String.valueOf(that.topicPattern))
                && Objects.equals(properties, that.properties)
                && startupMode == that.startupMode
                && Objects.equals(specificStartupOffsets, that.specificStartupOffsets)
                && startupTimestampMillis == that.startupTimestampMillis
                && Objects.equals(upsertMode, that.upsertMode)
                && Objects.equals(tableIdentifier, that.tableIdentifier)
                && Objects.equals(watermarkStrategy, that.watermarkStrategy);
    }

    @Override
    public int hashCode() {
        return Objects.hash(
                producedDataType,
                metadataKeys,
                physicalDataType,
                keyDecodingFormat,
                valueDecodingFormat,
                keyProjection,
                valueProjection,
                keyPrefix,
                topics,
                topicPattern,
                properties,
                startupMode,
                specificStartupOffsets,
                startupTimestampMillis,
                upsertMode,
                tableIdentifier,
                watermarkStrategy);
    }

    // --------------------------------------------------------------------------------------------

    protected KafkaSource<RowData> createKafkaSource(
            DeserializationSchema<RowData> keyDeserialization,
            DeserializationSchema<RowData> valueDeserialization,
            TypeInformation<RowData> producedTypeInfo) {

        final KafkaDeserializationSchema<RowData> kafkaDeserializer =
                createKafkaDeserializationSchema(
                        keyDeserialization, valueDeserialization, producedTypeInfo);

        final KafkaSourceBuilder<RowData> kafkaSourceBuilder = KafkaSource.builder();

        if (topics != null) {
            kafkaSourceBuilder.setTopics(topics);
        } else {
            kafkaSourceBuilder.setTopicPattern(topicPattern);
        }

        switch (startupMode) {
            case EARLIEST:
                kafkaSourceBuilder.setStartingOffsets(OffsetsInitializer.earliest());
                break;
            case LATEST:
                kafkaSourceBuilder.setStartingOffsets(OffsetsInitializer.latest());
                break;
            case GROUP_OFFSETS:
                kafkaSourceBuilder.setStartingOffsets(OffsetsInitializer.committedOffsets());
                break;
            case SPECIFIC_OFFSETS:
                Map<TopicPartition, Long> offsets = new HashMap<>();
                specificStartupOffsets.forEach(
                        (tp, offset) ->
                                offsets.put(
                                        new TopicPartition(tp.getTopic(), tp.getPartition()),
                                        offset));
                kafkaSourceBuilder.setStartingOffsets(OffsetsInitializer.offsets(offsets));
                break;
            case TIMESTAMP:
                kafkaSourceBuilder.setStartingOffsets(
                        OffsetsInitializer.timestamp(startupTimestampMillis));
                break;
        }

        kafkaSourceBuilder
                .setProperties(properties)
                .setDeserializer(KafkaRecordDeserializationSchema.of(kafkaDeserializer));

        return kafkaSourceBuilder.build();
    }

    private KafkaDeserializationSchema<RowData> createKafkaDeserializationSchema(
            DeserializationSchema<RowData> keyDeserialization,
            DeserializationSchema<RowData> valueDeserialization,
            TypeInformation<RowData> producedTypeInfo) {
        final MetadataConverter[] metadataConverters =
                metadataKeys.stream()
                        .map(
                                k ->
                                        Stream.of(ReadableMetadata.values())
                                                .filter(rm -> rm.key.equals(k))
                                                .findFirst()
                                                .orElseThrow(IllegalStateException::new))
                        .map(m -> m.converter)
                        .toArray(MetadataConverter[]::new);

        // check if connector metadata is used at all
        final boolean hasMetadata = metadataKeys.size() > 0;

        // adjust physical arity with value format's metadata
        final int adjustedPhysicalArity =
                DataType.getFieldDataTypes(producedDataType).size() - metadataKeys.size();

        // adjust value format projection to include value format's metadata columns at the end
        final int[] adjustedValueProjection =
                IntStream.concat(
                                IntStream.of(valueProjection),
                                IntStream.range(
                                        keyProjection.length + valueProjection.length,
                                        adjustedPhysicalArity))
                        .toArray();

        return new DynamicKafkaDeserializationSchema(
                adjustedPhysicalArity,
                keyDeserialization,
                keyProjection,
                valueDeserialization,
                adjustedValueProjection,
                hasMetadata,
                metadataConverters,
                producedTypeInfo,
                upsertMode);
    }

    private @Nullable DeserializationSchema<RowData> createDeserialization(
            DynamicTableSource.Context context,
            @Nullable DecodingFormat<DeserializationSchema<RowData>> format,
            int[] projection,
            @Nullable String prefix) {
        if (format == null) {
            return null;
        }
        DataType physicalFormatDataType =
                DataTypeUtils.projectRow(this.physicalDataType, projection);
        if (prefix != null) {
            physicalFormatDataType = DataTypeUtils.stripRowPrefix(physicalFormatDataType, prefix);
        }
        return format.createRuntimeDecoder(context, physicalFormatDataType);
    }

    // --------------------------------------------------------------------------------------------
    // Metadata handling
    // --------------------------------------------------------------------------------------------

    enum ReadableMetadata {
        TOPIC(
                "topic",
                DataTypes.STRING().notNull(),
                new MetadataConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public Object read(ConsumerRecord<?, ?> record) {
                        return StringData.fromString(record.topic());
                    }
                }),

        PARTITION(
                "partition",
                DataTypes.INT().notNull(),
                new MetadataConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public Object read(ConsumerRecord<?, ?> record) {
                        return record.partition();
                    }
                }),

        HEADERS(
                "headers",
                // key and value of the map are nullable to make handling easier in queries
                DataTypes.MAP(DataTypes.STRING().nullable(), DataTypes.BYTES().nullable())
                        .notNull(),
                new MetadataConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public Object read(ConsumerRecord<?, ?> record) {
                        final Map<StringData, byte[]> map = new HashMap<>();
                        for (Header header : record.headers()) {
                            map.put(StringData.fromString(header.key()), header.value());
                        }
                        return new GenericMapData(map);
                    }
                }),

        LEADER_EPOCH(
                "leader-epoch",
                DataTypes.INT().nullable(),
                new MetadataConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public Object read(ConsumerRecord<?, ?> record) {
                        return record.leaderEpoch().orElse(null);
                    }
                }),

        OFFSET(
                "offset",
                DataTypes.BIGINT().notNull(),
                new MetadataConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public Object read(ConsumerRecord<?, ?> record) {
                        return record.offset();
                    }
                }),

        TIMESTAMP(
                "timestamp",
                DataTypes.TIMESTAMP_WITH_LOCAL_TIME_ZONE(3).notNull(),
                new MetadataConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public Object read(ConsumerRecord<?, ?> record) {
                        return TimestampData.fromEpochMillis(record.timestamp());
                    }
                }),

        TIMESTAMP_TYPE(
                "timestamp-type",
                DataTypes.STRING().notNull(),
                new MetadataConverter() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public Object read(ConsumerRecord<?, ?> record) {
                        return StringData.fromString(record.timestampType().toString());
                    }
                });

        final String key;

        final DataType dataType;

        final MetadataConverter converter;

        ReadableMetadata(String key, DataType dataType, MetadataConverter converter) {
            this.key = key;
            this.dataType = dataType;
            this.converter = converter;
        }
    }
}


text:
from msrest.serialization import Model

class ProxyResource(Model):
    """The Resource model definition.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :ivar id: Resource Id.
    :vartype id: str
    :ivar name: Resource name.
    :vartype name: str
    :ivar type: Resource type.
    :vartype type: str
    :param e_tag: eTag of the resource. To handle concurrent update scenarion,
     this field will be used to determine whether the user is updating the
     latest version or not.
    :type e_tag: str
    """

    _validation = {
        'id': {'readonly': True},
        'name': {'readonly': True},
        'type': {'readonly': True},
    }

    _attribute_map = {
        'id': {'key': 'id', 'type': 'str'},
        'name': {'key': 'name', 'type': 'str'},
        'type': {'key': 'type', 'type': 'str'},
        'e_tag': {'key': 'eTag', 'type': 'str'},
    }

    def __init__(self, e_tag=None):
        super(ProxyResource, self).__init__()
        self.id = None
        self.name = None
        self.type = None
        self.e_tag = e_tag


text:
require_relative "../integration_test_helper"
require "gds_api/test_helpers/account_api"
require "gds_api/test_helpers/email_alert_api"
require "gds_api/test_helpers/content_store"

class SessionsTest < ActionDispatch::IntegrationTest
  include GdsApi::TestHelpers::AccountApi
  include GdsApi::TestHelpers::EmailAlertApi
  include GovukPersonalisation::TestHelpers::Features

  context "Given a signing in user" do
    should "Log the user in and redirect them to manage their account" do
      given_a_successful_login_attempt
      get new_govuk_session_callback_path(code: "code", state: "state")
      # initial redirect to /account/home which redirects on to the manage page
      assert_response :redirect
      follow_redirect!
      assert response.location = GovukPersonalisation::Urls.manage
    end

    context "With a redirect path" do
      setup do
        @redirect_path = "/email/subscriptions/account/confirm?frequency=immediately&return_to_url=true&topic_id=some-page-with-notifications"
        given_a_successful_login_attempt
      end

      should "Log the user in and send them to the redirect path" do
        ClimateControl.modify GOVUK_PERSONALISATION_MANAGE_URI: "https://account.gov.uk/manage-your-account" do
          assert_this_redirects_me { when_i_return_from_digital_identity }
        end
      end
    end
  end

  def given_a_successful_login_attempt
    @govuk_account_session = "session-id"

    stub_account_api_validates_auth_response(
      govuk_account_session: @govuk_account_session,
      redirect_path: @redirect_path,
    )

    @stub_user_info = stub_account_api_user_info(new_govuk_account_session: @govuk_account_session)
    stub_email_alert_api_authenticate_subscriber_by_govuk_account(@govuk_account_session, "subscriber-id", "email@example.com")
    stub_email_alert_api_has_subscriber_subscriptions("subscriber-id", "example@example.com")
  end

  def when_i_return_from_digital_identity
    visit new_govuk_session_callback_path(code: "code", state: "state")
  end

  def assert_this_redirects_me
    # the /email/... redirect path isn't in this app so ignore a 404
    yield
    assert_current_url account_home_path
  rescue ActionController::RoutingError
    assert_current_url @redirect_path
  end
end