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
 *
 *   https://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.
 */

package org.apache.pdfbox.pdmodel.encryption;

import java.nio.CharBuffer;
import java.text.Normalizer;

/**
 * Copied from https://github.com/tombentley/saslprep/blob/master/src/main/java/SaslPrep.java on
 * 30.5.2019, commit 2e30daa.
 *
 * @author Tom Bentley
 */
class SaslPrep
{

    private SaslPrep()
    {
    }

    /**
     * Return the {@code SASLPrep}-canonicalised version of the given {@code str} for use as a query
     * string. This implements the {@code SASLPrep} algorithm defined in
     * RFC 4013.
     *
     * @param str The string to canonicalise.
     * @return The canonicalised string.
     * @throws IllegalArgumentException if the string contained prohibited codepoints, or broke the
     * requirements for bidirectional character handling.
     * @see RFC 3454, Section 7 for
     * discussion of what a query string is.
     */
    static String saslPrepQuery(String str)
    {
        return saslPrep(str, true);
    }

    /**
     * Return the {@code SASLPrep}-canonicalised version of the given
     * @code str} for use as a stored string. This implements the {@code SASLPrep} algorithm defined
     * in
     * RFC 4013.
     *
     * @param str The string to canonicalise.
     * @return The canonicalised string.
     * @throws IllegalArgumentException if the string contained prohibited codepoints, or broke the
     * requirements for bidirectional character handling.
     * @see RFC 3454, Section 7 for
     * discussion of what a stored string is.
     */
    static String saslPrepStored(String str)
    {
        return saslPrep(str, false);
    }

    private static String saslPrep(String str, boolean allowUnassigned)
    {
        char[] chars = str.toCharArray();

        // 1. Map
        // non-ASCII space chars mapped to space
        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if (nonAsciiSpace(ch))
            {
                chars[i] = ' ';
            }
        }

        int length = 0;
        for (int i = 0; i < str.length(); i++)
        {
            char ch = chars[i];
            if (!mappedToNothing(ch))
            {
                chars[length++] = ch;
            }
        }

        // 2. Normalize
        String normalized = Normalizer.normalize(CharBuffer.wrap(chars, 0, length), Normalizer.Form.NFKC);

        boolean containsRandALCat = false;
        boolean containsLCat = false;
        boolean initialRandALCat = false;
        int i = 0;
        while (i < normalized.length())
        {
            final int codepoint = normalized.codePointAt(i);
            // 3. Prohibit
            if (prohibited(codepoint))
            {
                throw new IllegalArgumentException("Prohibited character '" +
                        Character.getName(codepoint) + "' at position " + i);
            }

            // 4. Check bidi
            final byte directionality = Character.getDirectionality(codepoint);
            final boolean isRandALcat = directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT
                    || directionality == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC;
            containsRandALCat |= isRandALcat;
            containsLCat |= directionality == Character.DIRECTIONALITY_LEFT_TO_RIGHT;

            initialRandALCat |= i == 0 && isRandALcat;
            if (!allowUnassigned && !Character.isDefined(codepoint))
            {
                throw new IllegalArgumentException("Character at position " + i + " is unassigned");
            }

            i += Character.charCount(codepoint);

            if (initialRandALCat && i >= normalized.length() && !isRandALcat)
            {
                throw new IllegalArgumentException("First character is RandALCat, but last character is not");
            }
        }
        if (containsRandALCat && containsLCat)
        {
            throw new IllegalArgumentException("Contains both RandALCat characters and LCat characters");
        }
        return normalized;
    }

    /**
     * Return true if the given {@code codepoint} is a prohibited character
     * as defined by
     * RFC 4013,
     * Section 2.3.
     */
    static boolean prohibited(int codepoint)
    {
        return nonAsciiSpace((char)codepoint)
                || asciiControl((char)codepoint)
                || nonAsciiControl(codepoint)
                || privateUse(codepoint)
                || nonCharacterCodePoint(codepoint)
                || surrogateCodePoint(codepoint)
                || inappropriateForPlainText(codepoint)
                || inappropriateForCanonical(codepoint)
                || changeDisplayProperties(codepoint)
                || tagging(codepoint);
    }

    /**
     * Return true if the given {@code codepoint} is a tagging character
     * as defined by
     * RFC 3454,
     * Appendix C.9.
     */
    private static boolean tagging(int codepoint)
    {
        return codepoint == 0xE0001
                || 0xE0020 <= codepoint && codepoint <= 0xE007F;
    }

    /**
     * Return true if the given {@code codepoint} is change display properties
     * or deprecated characters as defined by
     * RFC 3454,
     * Appendix C.8.
     */
    private static boolean changeDisplayProperties(int codepoint)
    {
        return codepoint == 0x0340
                || codepoint == 0x0341
                || codepoint == 0x200E
                || codepoint == 0x200F
                || codepoint == 0x202A
                || codepoint == 0x202B
                || codepoint == 0x202C
                || codepoint == 0x202D
                || codepoint == 0x202E
                || codepoint == 0x206A
                || codepoint == 0x206B
                || codepoint == 0x206C
                || codepoint == 0x206D
                || codepoint == 0x206E
                || codepoint == 0x206F
                ;
    }

    /**
     * Return true if the given {@code codepoint} is inappropriate for
     * canonical representation characters as defined by
     * RFC 3454,
     * Appendix C.7.
     */
    private static boolean inappropriateForCanonical(int codepoint)
    {
        return 0x2FF0 <= codepoint && codepoint <= 0x2FFB;
    }

    /**
     * Return true if the given {@code codepoint} is inappropriate for plain
     * text characters as defined by
     * RFC 3454,
     * Appendix C.6.
     */
    private static boolean inappropriateForPlainText(int codepoint)
    {
        return codepoint == 0xFFF9
                || codepoint == 0xFFFA
                || codepoint == 0xFFFB
                || codepoint == 0xFFFC
                || codepoint == 0xFFFD
                ;
    }

    /**
     * Return true if the given {@code codepoint} is a surrogate
     * code point as defined by
     * RFC 3454,
     * Appendix C.5.
     */
    private static boolean surrogateCodePoint(int codepoint)
    {
        return 0xD800 <= codepoint && codepoint <= 0xDFFF;
    }

    /**
     * Return true if the given {@code codepoint} is a non-character
     * code point as defined by
     * RFC 3454,
     * Appendix C.4.
     */
    private static boolean nonCharacterCodePoint(int codepoint)
    {
        return 0xFDD0 <= codepoint && codepoint <= 0xFDEF
                || 0xFFFE <= codepoint && codepoint <= 0xFFFF
                || 0x1FFFE <= codepoint && codepoint <= 0x1FFFF
                || 0x2FFFE <= codepoint && codepoint <= 0x2FFFF
                || 0x3FFFE <= codepoint && codepoint <= 0x3FFFF
                || 0x4FFFE <= codepoint && codepoint <= 0x4FFFF
                || 0x5FFFE <= codepoint && codepoint <= 0x5FFFF
                || 0x6FFFE <= codepoint && codepoint <= 0x6FFFF
                || 0x7FFFE <= codepoint && codepoint <= 0x7FFFF
                || 0x8FFFE <= codepoint && codepoint <= 0x8FFFF
                || 0x9FFFE <= codepoint && codepoint <= 0x9FFFF
                || 0xAFFFE <= codepoint && codepoint <= 0xAFFFF
                || 0xBFFFE <= codepoint && codepoint <= 0xBFFFF
                || 0xCFFFE <= codepoint && codepoint <= 0xCFFFF
                || 0xDFFFE <= codepoint && codepoint <= 0xDFFFF
                || 0xEFFFE <= codepoint && codepoint <= 0xEFFFF
                || 0xFFFFE <= codepoint && codepoint <= 0xFFFFF
                || 0x10FFFE <= codepoint && codepoint <= 0x10FFFF
                ;
    }

    /**
     * Return true if the given {@code codepoint} is a private use character
     * as defined by RFC 3454,
     * Appendix C.3.
     */
    private static boolean privateUse(int codepoint)
    {
        return 0xE000 <= codepoint && codepoint <= 0xF8FF
                || 0xF0000 <= codepoint && codepoint <= 0xFFFFD
                || 0x100000 <= codepoint && codepoint <= 0x10FFFD;
    }

    /**
     * Return true if the given {@code ch} is a non-ASCII control character
     * as defined by RFC 3454,
     * Appendix C.2.2.
     */
    private static boolean nonAsciiControl(int codepoint)
    {
        return 0x0080 <= codepoint && codepoint <= 0x009F
                || codepoint == 0x06DD
                || codepoint == 0x070F
                || codepoint == 0x180E
                || codepoint == 0x200C
                || codepoint == 0x200D
                || codepoint == 0x2028
                || codepoint == 0x2029
                || codepoint == 0x2060
                || codepoint == 0x2061
                || codepoint == 0x2062
                || codepoint == 0x2063
                || 0x206A <= codepoint && codepoint <= 0x206F
                || codepoint == 0xFEFF
                || 0xFFF9 <= codepoint && codepoint <= 0xFFFC
                || 0x1D173 <= codepoint && codepoint <= 0x1D17A;
    }

    /**
     * Return true if the given {@code ch} is an ASCII control character
     * as defined by RFC 3454,
     * Appendix C.2.1.
     */
    private static boolean asciiControl(char ch)
    {
        return '\u0000' <= ch && ch <= '\u001F' || ch == '\u007F';
    }

    /**
     * Return true if the given {@code ch} is a non-ASCII space character
     * as defined by RFC 3454,
     * Appendix C.1.2.
     */
    private static boolean nonAsciiSpace(char ch)
    {
        return ch == '\u00A0'
                || ch == '\u1680'
                || '\u2000' <= ch && ch <= '\u200B'
                || ch == '\u202F'
                || ch == '\u205F'
                || ch == '\u3000';
    }

    /**
     * Return true if the given {@code ch} is a "commonly mapped to nothing" character
     * as defined by RFC 3454,
     * Appendix B.1.
     */
    private static boolean mappedToNothing(char ch)
    {
        return ch == '\u00AD'
                || ch == '\u034F'
                || ch == '\u1806'
                || ch == '\u180B'
                || ch == '\u180C'
                || ch == '\u180D'
                || ch == '\u200B'
                || ch == '\u200C'
                || ch == '\u200D'
                || ch == '\u2060'
                || '\uFE00' <= ch && ch <= '\uFE0F'
                || ch == '\uFEFF';
    }
}


text:
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

static const CString strRegEntryName = _T("Mouse");
static const CString strMouseProfile = _T("BCGMouseManager");

CBCGMouseManager* g_pMouseManager = NULL;

IMPLEMENT_SERIAL(CBCGMouseManager, CObject, 1)

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CBCGMouseManager::CBCGMouseManager()
{
	ASSERT (g_pMouseManager == NULL);
	g_pMouseManager = this;
}
//************************************************************************************************
CBCGMouseManager::~CBCGMouseManager()
{
	g_pMouseManager = NULL;
}
//************************************************************************************************
BOOL CBCGMouseManager::AddView (int iViewId, UINT uiViewNameResId, UINT uiIconId)
{
	CString strViewName;
	strViewName.LoadString (uiViewNameResId);

	return AddView (iViewId, strViewName, uiIconId);
}
//************************************************************************************************
BOOL CBCGMouseManager::AddView (int iViewId, LPCTSTR lpszViewName, UINT uiIconId)
{
	ASSERT (lpszViewName != NULL);

	int iId;
	if (m_ViewsNames.Lookup (lpszViewName, iId))	// Already exist
	{
		return FALSE;
	}

	m_ViewsNames.SetAt (lpszViewName, iViewId);

	if (uiIconId != 0)
	{
		m_ViewsToIcons.SetAt (iViewId, uiIconId);
	}

	return TRUE;
}
//************************************************************************************************
UINT CBCGMouseManager::GetViewDblClickCommand (int iId) const
{
	UINT uiCmd;

	if (!m_ViewsToCommands.Lookup (iId, uiCmd))
	{
		return 0;
	}

	return uiCmd;
}
//************************************************************************************************
void CBCGMouseManager::GetViewNames (CStringList& listOfNames) const
{
	listOfNames.RemoveAll ();

	for (POSITION pos = m_ViewsNames.GetStartPosition (); pos != NULL;)
	{
		CString strName;
		int iId;

		m_ViewsNames.GetNextAssoc (pos, strName, iId);
		listOfNames.AddTail (strName);
	}
}
//************************************************************************************************
int CBCGMouseManager::GetViewIdByName (LPCTSTR lpszName) const
{
	ASSERT (lpszName != NULL);

	int iId;

	if (!m_ViewsNames.Lookup (lpszName, iId))
	{
		return -1;
	}

	return iId;
}
//************************************************************************************************
BOOL CBCGMouseManager::LoadState (LPCTSTR lpszProfileName)
{
	CString strProfileName = ::BCGGetRegPath (strMouseProfile, lpszProfileName);

	BOOL bResult = FALSE;

	LPBYTE	lpbData = NULL;
	UINT	uiDataSize;

	CBCGRegistrySP regSP;
	CBCGRegistry& reg = regSP.Create (FALSE, TRUE);

	if (!reg.Open (strProfileName))
	{
		TRACE(_T("CBCGMouseManager::LoadState: Can't open registry %s!\n"), strProfileName);
		return FALSE;
	}

	if (!reg.Read (strRegEntryName, &lpbData, &uiDataSize))
	{
		TRACE(_T("CBCGMouseManager::LoadState: Can't load registry data %s!\n"), strProfileName);
		return FALSE;
	}

	try
	{
		CMemFile file (lpbData, uiDataSize);
		CArchive ar (&file, CArchive::load);

		Serialize (ar);
		bResult = TRUE;
	}
	catch (CMemoryException* pEx)
	{
		pEx->Delete ();
		TRACE(_T("Memory exception in CBCGMouseManager::LoadState ()!\n"));
	}
	catch (CArchiveException* pEx)
	{
		pEx->Delete ();
		TRACE(_T("CArchiveException exception in CBCGMouseManager::LoadState ()!\n"));
	}

	if (lpbData != NULL)
	{
		delete lpbData;
	}

	return bResult;
}
//************************************************************************************************
BOOL CBCGMouseManager::SaveState (LPCTSTR lpszProfileName)
{
	CString strProfileName = ::BCGGetRegPath (strMouseProfile, lpszProfileName);

	BOOL bResult = FALSE;

	try
	{
		CMemFile file;

		{
			CArchive ar (&file, CArchive::store);

			Serialize (ar);
			ar.Flush ();
		}

		UINT uiDataSize = (UINT) file.GetLength ();
		LPBYTE lpbData = file.Detach ();

		if (lpbData != NULL)
		{
			CBCGRegistrySP regSP;
			CBCGRegistry& reg = regSP.Create (FALSE, FALSE);

			if (reg.CreateKey (strProfileName))
			{
				bResult = reg.Write (strRegEntryName, lpbData, uiDataSize);
			}

			free (lpbData);
		}
	}
	catch (CMemoryException* pEx)
	{
		pEx->Delete ();
		TRACE(_T("Memory exception in CBCGMouseManager::SaveState ()!\n"));
	}
	catch (CArchiveException* pEx)
	{
		pEx->Delete ();
		TRACE(_T("CArchiveException exception in CBCGMouseManager::SaveState ()!\n"));
	}

	return bResult;
}
//************************************************************************************************
void CBCGMouseManager::Serialize (CArchive& ar)
{
	CObject::Serialize (ar);

	if (ar.IsLoading ())
	{
		m_ViewsToCommands.RemoveAll ();

		int iCount;
		ar >> iCount;

		for (int i = 0; i < iCount; i ++)
		{
			int iViewId;
			ar >> iViewId;

			UINT uiCmd;
			ar >> uiCmd;

			m_ViewsToCommands.SetAt (iViewId, uiCmd);
		}
	}
	else
	{
		int iCount = (int) m_ViewsToCommands.GetCount ();
		ar << iCount;

		for (POSITION pos = m_ViewsToCommands.GetStartPosition (); pos != NULL;)
		{
			int iViewId;
			UINT uiCmd;

			m_ViewsToCommands.GetNextAssoc (pos, iViewId, uiCmd);

			ar << iViewId;
			ar << uiCmd;
		}
	}
}
//************************************************************************************************
void CBCGMouseManager::SetCommandForDblClick (int iViewId, UINT uiCmd)
{
	if (uiCmd > 0)
	{
		m_ViewsToCommands.SetAt (iViewId, uiCmd);
	}
	else
	{
		m_ViewsToCommands.RemoveKey (iViewId);
	}
}
//************************************************************************************************
UINT CBCGMouseManager::GetViewIconId (int iViewId) const
{
	UINT uiIconId;
	if (!m_ViewsToIcons.Lookup (iViewId, uiIconId))
	{
		return 0;
	}

	return uiIconId;
}

redpajama_set_name: RedPajamaGithub


text:
<!-- jQuery -->
<script src="js/jquery.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>

<?php
  // This function must be the very last executed
  ob_end_flush(); //End the preparation of the page, and sends it to client

 ?>


text:
package bio.terra.app.utils;

import bio.terra.model.PolicyModel;
import bio.terra.model.ResourcePolicyModel;
import bio.terra.model.SamPolicyModel;
import java.util.List;
import java.util.stream.Collectors;

public class PolicyUtils {

  public static List<PolicyModel> samToTdrPolicyModels(List<SamPolicyModel> samPolicyModels) {
    return samPolicyModels.stream()
        .map(spm -> new PolicyModel().name(spm.getName()).members(spm.getMembers()))
        .collect(Collectors.toList());
  }

  public static List<PolicyModel> resourcePolicyToPolicyModel(
      List<ResourcePolicyModel> resourcePolicyModels) {
    return resourcePolicyModels.stream()
        .map(
            rpm ->
                new PolicyModel().name(rpm.getPolicyName()).members(List.of(rpm.getPolicyEmail())))
        .collect(Collectors.toList());
  }
}


text:
freeze("$(PORT_DIR)/modules")
freeze("$(MPY_DIR)/drivers/onewire")
freeze("$(MPY_DIR)/drivers/dht", "dht.py")
include("$(MPY_DIR)/extmod/uasyncio/manifest.py")


text:
Greenpeace.configure(Rails.env) do |env|
  env.requires :secret_key_base,
    doc: "Rails secret key base used to sign cookies",
    defaults: { development: "supersecret", test: "supersecret" }

  env.requires :default_host,
    doc: "Default host for links inside mails",
    defaults: { development: "localhost:3000", test: "localhost:3000" }

  env.requires :mailtrap_username,
    doc: "Username for the mailtrap email sending service",
    defaults: { development: "mailtrap", test: "mailtrap" }

  env.requires :mailtrap_password,
    doc: "Password for the mailtrap email sending service",
    defaults: { development: "mailtrap", test: "mailtrap" }

  env.requires :parse_app_id,
    doc: "Application ID of the parse account used to send push notifications to the devices",
    defaults: { development: "", test: "" }

  env.requires :parse_app_key,
    doc: "REST API key of the parse account used to send push notifications to the devices",
    defaults: { development: "", test: "" }
end


text:
import Node from '../Node.js';
import minifyPropertyKey from './shared/minifyPropertyKey.js';

export default class MethodDefinition extends Node {
	initialise ( program, scope ) {
		if ( !this.computed ) program.addWord( this.key.name );
		super.initialise( program, scope );
	}

	minify ( code, chars ) {
		minifyPropertyKey( code, chars, this, false );
		this.value.minify( code, chars );
	}
}


text:
from django.conf.urls import url
from payments import views

urlpatterns = [
    url(r'^stripe/charge', views.stripe_charge_view, name='stripe'),
    url(r'^paypal/success', views.paypal_success_view, name='paypal_success'),
    url(r'^paypal/cancel', views.paypal_cancel_view, name='paypal_cancel'),
]


text:
#include <limits.h>
#include <math.h>

#include "vp9/encoder/vp9_aq_complexity.h"
#include "vp9/encoder/vp9_aq_variance.h"
#include "vp9/encoder/vp9_encodeframe.h"
#include "vp9/common/vp9_seg_common.h"
#include "vp9/encoder/vp9_segmentation.h"

#define AQ_C_SEGMENTS  5
#define DEFAULT_AQ2_SEG 3   // Neutral Q segment
#define AQ_C_STRENGTHS 3
static const double aq_c_q_adj_factor[AQ_C_STRENGTHS][AQ_C_SEGMENTS] =
  { {1.75, 1.25, 1.05, 1.00, 0.90},
    {2.00, 1.50, 1.15, 1.00, 0.85},
    {2.50, 1.75, 1.25, 1.00, 0.80} };
static const double aq_c_transitions[AQ_C_STRENGTHS][AQ_C_SEGMENTS] =
  { {0.15, 0.30, 0.55, 2.00, 100.0},
    {0.20, 0.40, 0.65, 2.00, 100.0},
    {0.25, 0.50, 0.75, 2.00, 100.0} };
static const double aq_c_var_thresholds[AQ_C_STRENGTHS][AQ_C_SEGMENTS] =
  { {-4.0, -3.0, -2.0, 100.00, 100.0},
    {-3.5, -2.5, -1.5, 100.00, 100.0},
    {-3.0, -2.0, -1.0, 100.00, 100.0} };

#define DEFAULT_COMPLEXITY 64

static int get_aq_c_strength(int q_index, vpx_bit_depth_t bit_depth) {
  // Approximate base quatizer (truncated to int)
  const int base_quant = vp9_ac_quant(q_index, 0, bit_depth) / 4;
  return (base_quant > 10) + (base_quant > 25);
}

void vp9_setup_in_frame_q_adj(VP9_COMP *cpi) {
  VP9_COMMON *const cm = &cpi->common;
  struct segmentation *const seg = &cm->seg;

  // Make SURE use of floating point in this function is safe.
  vp9_clear_system_state();

  if (cm->frame_type == KEY_FRAME ||
      cpi->refresh_alt_ref_frame ||
      (cpi->refresh_golden_frame && !cpi->rc.is_src_frame_alt_ref)) {
    int segment;
    const int aq_strength = get_aq_c_strength(cm->base_qindex, cm->bit_depth);

    // Clear down the segment map.
    memset(cpi->segmentation_map, DEFAULT_AQ2_SEG, cm->mi_rows * cm->mi_cols);

    vp9_clearall_segfeatures(seg);

    // Segmentation only makes sense if the target bits per SB is above a
    // threshold. Below this the overheads will usually outweigh any benefit.
    if (cpi->rc.sb64_target_rate < 256) {
      vp9_disable_segmentation(seg);
      return;
    }

    vp9_enable_segmentation(seg);

    // Select delta coding method.
    seg->abs_delta = SEGMENT_DELTADATA;

    // Default segment "Q" feature is disabled so it defaults to the baseline Q.
    vp9_disable_segfeature(seg, DEFAULT_AQ2_SEG, SEG_LVL_ALT_Q);

    // Use some of the segments for in frame Q adjustment.
    for (segment = 0; segment < AQ_C_SEGMENTS; ++segment) {
      int qindex_delta;

      if (segment == DEFAULT_AQ2_SEG)
        continue;

      qindex_delta =
        vp9_compute_qdelta_by_rate(&cpi->rc, cm->frame_type, cm->base_qindex,
                                   aq_c_q_adj_factor[aq_strength][segment],
                                   cm->bit_depth);

      // For AQ complexity mode, we dont allow Q0 in a segment if the base
      // Q is not 0. Q0 (lossless) implies 4x4 only and in AQ mode 2 a segment
      // Q delta is sometimes applied without going back around the rd loop.
      // This could lead to an illegal combination of partition size and q.
      if ((cm->base_qindex != 0) && ((cm->base_qindex + qindex_delta) == 0)) {
        qindex_delta = -cm->base_qindex + 1;
      }
      if ((cm->base_qindex + qindex_delta) > 0) {
        vp9_enable_segfeature(seg, segment, SEG_LVL_ALT_Q);
        vp9_set_segdata(seg, segment, SEG_LVL_ALT_Q, qindex_delta);
      }
    }
  }
}

#define DEFAULT_LV_THRESH 10.0
#define MIN_DEFAULT_LV_THRESH 8.0
#define VAR_STRENGTH_STEP 0.25
// Select a segment for the current block.
// The choice of segment for a block depends on the ratio of the projected
// bits for the block vs a target average and its spatial complexity.
void vp9_caq_select_segment(VP9_COMP *cpi, MACROBLOCK *mb, BLOCK_SIZE bs,
                            int mi_row, int mi_col, int projected_rate) {
  VP9_COMMON *const cm = &cpi->common;

  const int mi_offset = mi_row * cm->mi_cols + mi_col;
  const int bw = num_8x8_blocks_wide_lookup[BLOCK_64X64];
  const int bh = num_8x8_blocks_high_lookup[BLOCK_64X64];
  const int xmis = MIN(cm->mi_cols - mi_col, num_8x8_blocks_wide_lookup[bs]);
  const int ymis = MIN(cm->mi_rows - mi_row, num_8x8_blocks_high_lookup[bs]);
  int x, y;
  int i;
  unsigned char segment;

  if (0) {
    segment = DEFAULT_AQ2_SEG;
  } else {
    // Rate depends on fraction of a SB64 in frame (xmis * ymis / bw * bh).
    // It is converted to bits * 256 units.
    const int target_rate = (cpi->rc.sb64_target_rate * xmis * ymis * 256) /
                            (bw * bh);
    double logvar;
    double low_var_thresh;
    const int aq_strength = get_aq_c_strength(cm->base_qindex, cm->bit_depth);

    vp9_clear_system_state();
    low_var_thresh = (cpi->oxcf.pass == 2)
      ? MAX(cpi->twopass.mb_av_energy, MIN_DEFAULT_LV_THRESH)
      : DEFAULT_LV_THRESH;

    vp9_setup_src_planes(mb, cpi->Source, mi_row, mi_col);
    logvar = vp9_log_block_var(cpi, mb, bs);

    segment = AQ_C_SEGMENTS - 1;    // Just in case no break out below.
    for (i = 0; i < AQ_C_SEGMENTS; ++i) {
      // Test rate against a threshold value and variance against a threshold.
      // Increasing segment number (higher variance and complexity) = higher Q.
      if ((projected_rate <
           target_rate * aq_c_transitions[aq_strength][i]) &&
          (logvar < (low_var_thresh + aq_c_var_thresholds[aq_strength][i]))) {
        segment = i;
        break;
      }
    }
  }

  // Fill in the entires in the segment map corresponding to this SB64.
  for (y = 0; y < ymis; y++) {
    for (x = 0; x < xmis; x++) {
      cpi->segmentation_map[mi_offset + y * cm->mi_cols + x] = segment;
    }
  }
}


text:
(function (angular) {
  "use strict";

  // when $routeProvider.whenAuthenticated() is called, the path is stored in this list
  // to be used by authRequired() in the services below
  var securedRoutes = [];

  angular.module('app.security', ['ngRoute', 'firebase.auth', 'app.config'])

    .config(['$routeProvider', 'loginRedirectPath', function ($routeProvider, loginRedirectPath) {
      // routes which are not in our map are redirected to /home
      $routeProvider.otherwise({redirectTo: loginRedirectPath});
    }])

  /**
   * Adds a special `whenAuthenticated` method onto $routeProvider. This special method,
   * when called, waits for auth status to be resolved asynchronously, and then fails/redirects
   * if the user is not properly authenticated.
   *
   * The promise either resolves to the authenticated user object and makes it available to
   * dependency injection (see AuthCtrl), or rejects the promise if user is not logged in,
   * forcing a redirect to the /login page
   */
    .config(['$routeProvider', function ($routeProvider) {
      // credits for this idea: https://groups.google.com/forum/#!msg/angular/dPr9BpIZID0/MgWVluo_Tg8J
      // unfortunately, a decorator cannot be use here because they are not applied until after
      // the .config calls resolve, so they can't be used during route configuration, so we have
      // to hack it directly onto the $routeProvider object
      $routeProvider.whenAuthenticated = function (path, route) {
        securedRoutes.push(path); // store all secured routes for use with authRequired() below
        route.resolve = route.resolve || {};
        route.resolve.user = ['Auth', function (Auth) {
          return Auth.$requireAuth();
        }];
        $routeProvider.when(path, route);
        return this;
      }
    }])

  /**
   * Apply some route security. Any route's resolve method can reject the promise with
   * { authRequired: true } to force a redirect. This method enforces that and also watches
   * for changes in auth status which might require us to navigate away from a path
   * that we can no longer view.
   */
    .run(['$rootScope', '$location', 'Auth', 'loginRedirectPath',
      function ($rootScope, $location, Auth, loginRedirectPath) {
        // watch for login status changes and redirect if appropriate
        Auth.$onAuth(check);

        // some of our routes may reject resolve promises with the special {authRequired: true} error
        // this redirects to the login page whenever that is encountered
        $rootScope.$on("$routeChangeError", function (e, next, prev, err) {
          if (err === "AUTH_REQUIRED") {
            $location.path(loginRedirectPath);
          }
        });

        function check(user) {
          if (!user && authRequired($location.path())) {
            //console.log('check failed', user, $location.path()); //debug
            $location.path(loginRedirectPath);
          }
        }

        function authRequired(path) {
          //console.log('authRequired?', path, securedRoutes.indexOf(path)); //debug
          return securedRoutes.indexOf(path) !== -1;
        }
      }
    ]);

})(angular);


text:
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;

public class BuySellStockTwiceTest {
    private List<Integer> prices;
    private int maxProfit;

    @Test
    public void buySellStockTwice1() {
        prices = Arrays.asList(310, 315, 275, 295, 260, 270, 290, 230, 255, 250);
        maxProfit = 55;

        test(prices, maxProfit);
    }

    @Test
    public void buySellStockTwice2() {
        prices = Arrays.asList(100, 200);
        maxProfit = 100;

        test(prices, maxProfit);
    }

    @Test
    public void buySellStockTwice3() {
        prices = Arrays.asList(200, 100);
        maxProfit = 0;

        test(prices, maxProfit);
    }

    @Test
    public void buySellStockTwice4() {
        prices = Arrays.asList(2, 4, 2, 6, 3, 0, 5);
        maxProfit = 9;

        test(prices, maxProfit);
    }

    private void test(List<Integer> prices, int maxProfit) {
        assertEquals(maxProfit, BuySellStockTwice.buySellStockTwice(prices));
    }

}


text:
<link rel="import" href="../polymer/polymer.html">
<dom-module name="orov-serial-monitor">
  <style>
  </style>
  <template>
    <input id='sendbox' type='text'>{{sendData}}</input><button on-click='send'>{{__('Send')}}</button>
    <textarea id="serialMonitorList">
    </textarea>
    <button on-click='start'>{{__('Start')}}</button>
    <button on-click='stop'>{{__('Stop')}}</button>

  </template>
  <script>
    (function() {
      Polymer({
        is: "orov-serial-monitor",
        properties: {
          maxLines: {type: Number, value: 500},
          autoScroll: {type: Boolean, value: true},
          sendData: {type: String}
        },
        behaviors: [namespace('behaviors').oROVStandard],
        registerEmitterHanlders: function(emitter){
          var self = this;
          emitter.on('plugin.serial-monitor.serial-received',function(data){
            var list = self.$.serialMonitorList;
            var text = self.tail(self.maxLines, list.value.trim() + data);
            list.value = text;
            if (self.autoScroll){
              list.scrollTop = list.scrollHeight;
            }
          });
        },
        send: function(){
          if(this.eventEmitter!==undefined){
            this.eventEmitter.emit('plugin.serial-monitor.serial-sent',this.$.sendbox.value);
          }
        },
        countNewlines: function countNewlines(haystack) {
          return this.count('\n', haystack);
        },
        count: function count(needle, haystack) {
          var num = 0, len = haystack.length;
          for (var i = 0; i < len; i++) {
            if (haystack.charAt(i) === needle) {
              num++;
            }
          }
          return num;
        },
        tail: function tail(limit, haystack) {
          var lines = this.countNewlines(haystack) + 1;
          if (lines > limit) {
            return haystack.split('\n').slice(-limit).join('\n');
          }
          return haystack;
        },
        start: function start(){
          if (this.eventEmitter !== undefined){
            this.eventEmitter.emit('plugin.serial-monitor.start');
          }
        },
        stop: function stop(){
          if (this.eventEmitter !== undefined){
            this.eventEmitter.emit('plugin.serial-monitor.stop');
          }
        }

      })
    })();
  </script>

</dom-module>


text:
@interface PodsDummy_NasahUtils : NSObject
@end
@implementation PodsDummy_NasahUtils
@end


text:
title: "Nomad Service Discovery"
description: "Learn how to use Nomad as a provider for configuration discovery in Traefik Proxy. Read the technical documentation."
---

# Traefik & Nomad Service Discovery

A Story of Tags, Services & Nomads
{: .subtitle }

![Nomad Service Discovery](../assets/img/providers/nomad.png)

Attach tags to your Nomad services and let Traefik do the rest!

## Configuration Examples

??? example "Configuring Nomad & Deploying Services"

    Enabling the nomad provider

    ```yaml tab="File (YAML)"
    providers:
      nomad: {}
    ```

    ```toml tab="File (TOML)"
    [providers.nomad]
    ```

    ```bash tab="CLI"
    --providers.nomad=true
    ```

    Attaching tags to services:

    ```
    ...
    service {
      name = "myService"
      tags = [
        "traefik.http.routers.my-router.rule=Host(`example.com`)",
      ]
    }
    ...
    ```

## Routing Configuration

See the dedicated section in [routing](../routing/providers/nomad.md).

## Provider Configuration

### `refreshInterval`

_Optional, Default=15s_

Defines the polling interval.

```yaml tab="File (YAML)"
providers:
  nomad:
    refreshInterval: 30s
    # ...
```

```toml tab="File (TOML)"
[providers.nomad]
  refreshInterval = "30s"
  # ...
```

```bash tab="CLI"
--providers.nomad.refreshInterval=30s
# ...
```

### `prefix`

_required, Default="traefik"_

The prefix for Nomad service tags defining Traefik labels.

```yaml tab="File (YAML)"
providers:
  nomad:
    prefix: test
    # ...
```

```toml tab="File (TOML)"
[providers.nomad]
  prefix = "test"
  # ...
```

```bash tab="CLI"
--providers.nomad.prefix=test
# ...
```

### `stale`

_Optional, Default=false_

Use stale consistency for Nomad service API reads.

!!! note ""

    This makes reads very fast and scalable at the cost of a higher likelihood of stale values.

    For more information, see the Nomad [documentation on consistency](https://www.nomadproject.io/api-docs#consistency-modes).

```yaml tab="File (YAML)"
providers:
  nomad:
    stale: true
    # ...
```

```toml tab="File (TOML)"
[providers.nomad]
  stale = true
  # ...
```

```bash tab="CLI"
--providers.nomad.stale=true
# ...
```

### `endpoint`

Defines the Nomad server endpoint.

#### `address`

Defines the address of the Nomad server.

_Optional, Default="http://127.0.0.1:4646"_

```yaml tab="File (YAML)"
providers:
  nomad:
    endpoint:
      address: http://127.0.0.1:4646
    # ...
```

```toml tab="File (TOML)"
[providers.nomad]
  [providers.nomad.endpoint]
    address = "http://127.0.0.1:4646"
    # ...
```

```bash tab="CLI"
--providers.nomad.endpoint.address=http://127.0.0.1:4646
# ...
```

#### `token`

_Optional, Default=""_

Token is used to provide a per-request ACL token, if Nomad ACLs are enabled.

```yaml tab="File (YAML)"
providers:
  nomad:
    endpoint:
      token: test
    # ...
```

```toml tab="File (TOML)"
[providers.nomad]
  [providers.nomad.endpoint]
    token = "test"
    # ...
```

```bash tab="CLI"
--providers.nomad.endpoint.token=test
# ...
```

#### `endpointWaitTime`

_Optional, Default=""_

Limits the duration for which a Watch can block.
If not provided, the agent default values will be used.

```yaml tab="File (YAML)"
providers:
  nomad:
    endpoint:
      endpointWaitTime: 15s
    # ...
```

```toml tab="File (TOML)"
[providers.nomad]
  [providers.nomad.endpoint]
    endpointWaitTime = "15s"
    # ...
```

```bash tab="CLI"
--providers.nomad.endpoint.endpointwaittime=15s
# ...
```

#### `tls`

_Optional_

Defines the TLS configuration used for the secure connection to the Nomad API.

##### `ca`

_Optional_

`ca` is the path to the certificate authority used for the secure connection to Nomad,
it defaults to the system bundle.

```yaml tab="File (YAML)"
providers:
  nomad:
    endpoint:
      tls:
        ca: path/to/ca.crt
```

```toml tab="File (TOML)"
[providers.nomad.endpoint.tls]
  ca = "path/to/ca.crt"
```

```bash tab="CLI"
--providers.nomad.endpoint.tls.ca=path/to/ca.crt
```

##### `cert`

_Optional_

`cert` is the path to the public certificate used for the secure connection to the Nomad API.
When using this option, setting the `key` option is required.

```yaml tab="File (YAML)"
providers:
  nomad:
    endpoint:
      tls:
        cert: path/to/foo.cert
        key: path/to/foo.key
```

```toml tab="File (TOML)"
[providers.nomad.endpoint.tls]
  cert = "path/to/foo.cert"
  key = "path/to/foo.key"
```

```bash tab="CLI"
--providers.nomad.endpoint.tls.cert=path/to/foo.cert
--providers.nomad.endpoint.tls.key=path/to/foo.key
```

##### `key`

_Optional_

`key` is the path to the private key used for the secure connection to the Nomad API.
When using this option, setting the `cert` option is required.

```yaml tab="File (YAML)"
providers:
  nomad:
    endpoint:
      tls:
        cert: path/to/foo.cert
        key: path/to/foo.key
```

```toml tab="File (TOML)"
[providers.nomad.endpoint.tls]
  cert = "path/to/foo.cert"
  key = "path/to/foo.key"
```

```bash tab="CLI"
--providers.nomad.endpoint.tls.cert=path/to/foo.cert
--providers.nomad.endpoint.tls.key=path/to/foo.key
```

##### `insecureSkipVerify`

_Optional, Default=false_

If `insecureSkipVerify` is `true`, the TLS connection to Nomad accepts any certificate presented by the server regardless of the hostnames it covers.

```yaml tab="File (YAML)"
providers:
  nomad:
    endpoint:
      tls:
        insecureSkipVerify: true
```

```toml tab="File (TOML)"
[providers.nomad.endpoint.tls]
  insecureSkipVerify = true
```

```bash tab="CLI"
--providers.nomad.endpoint.tls.insecureskipverify=true
```

### `exposedByDefault`

_Optional, Default=true_

Expose Nomad services by default in Traefik.
If set to `false`, services that do not have a `traefik.enable=true` tag will be ignored from the resulting routing configuration.

For additional information, refer to [Restrict the Scope of Service Discovery](./overview.md#restrict-the-scope-of-service-discovery).

```yaml tab="File (YAML)"
providers:
  nomad:
    exposedByDefault: false
    # ...
```

```toml tab="File (TOML)"
[providers.nomad]
  exposedByDefault = false
  # ...
```

```bash tab="CLI"
--providers.nomad.exposedByDefault=false
# ...
```

### `defaultRule`

_Optional, Default=```Host(`{{ normalize .Name }}`)```_

The default host rule for all services.

For a given service, if no routing rule was defined by a tag, it is defined by this `defaultRule` instead.
The `defaultRule` must be set to a valid [Go template](https://pkg.go.dev/text/template/),
and can include [sprig template functions](https://masterminds.github.io/sprig/).
The service name can be accessed with the `Name` identifier,
and the template has access to all the labels (i.e. tags beginning with the `prefix`) defined on this service.

The option can be overridden on an instance basis with the `traefik.http.routers.{name-of-your-choice}.rule` tag.

```yaml tab="File (YAML)"
providers:
  nomad:
    defaultRule: "Host(`{{ .Name }}.{{ index .Labels \"customLabel\"}}`)"
    # ...
```

```toml tab="File (TOML)"
[providers.nomad]
  defaultRule = "Host(`{{ .Name }}.{{ index .Labels \"customLabel\"}}`)"
  # ...
```

```bash tab="CLI"
--providers.nomad.defaultRule="Host(`{{ .Name }}.{{ index .Labels \"customLabel\"}}`)"
# ...
```

### `constraints`

_Optional, Default=""_

The `constraints` option can be set to an expression that Traefik matches against the service tags to determine whether
to create any route for that service. If none of the service tags match the expression, no route for that service is
created. If the expression is empty, all detected services are included.

The expression syntax is based on the ```Tag(`tag`)```, and ```TagRegex(`tag`)``` functions,
as well as the usual boolean logic, as shown in examples below.

??? example "Constraints Expression Examples"

    ```toml
    # Includes only services having the tag `a.tag.name=foo`
    constraints = "Tag(`a.tag.name=foo`)"
    ```

    ```toml
    # Excludes services having any tag `a.tag.name=foo`
    constraints = "!Tag(`a.tag.name=foo`)"
    ```

    ```toml
    # With logical AND.
    constraints = "Tag(`a.tag.name`) && Tag(`another.tag.name`)"
    ```

    ```toml
    # With logical OR.
    constraints = "Tag(`a.tag.name`) || Tag(`another.tag.name`)"
    ```

    ```toml
    # With logical AND and OR, with precedence set by parentheses.
    constraints = "Tag(`a.tag.name`) && (Tag(`another.tag.name`) || Tag(`yet.another.tag.name`))"
    ```

    ```toml
    # Includes only services having a tag matching the `a\.tag\.t.+` regular expression.
    constraints = "TagRegex(`a\.tag\.t.+`)"
    ```

```yaml tab="File (YAML)"
providers:
  nomad:
    constraints: "Tag(`a.tag.name`)"
    # ...
```

```toml tab="File (TOML)"
[providers.nomad]
  constraints = "Tag(`a.tag.name`)"
  # ...
```

```bash tab="CLI"
--providers.nomad.constraints="Tag(`a.tag.name`)"
# ...
```

For additional information, refer to [Restrict the Scope of Service Discovery](./overview.md#restrict-the-scope-of-service-discovery).

### `namespace`

??? warning "Deprecated in favor of the [`namespaces`](#namespaces) option."

    _Optional, Default=""_

    The `namespace` option defines the namespace in which the Nomad services will be discovered.

    !!! warning

        One should only define either the `namespaces` option or the `namespace` option.

    ```yaml tab="File (YAML)"
    providers:
      nomad:
        namespace: "production"
        # ...
    ```

    ```toml tab="File (TOML)"
    [providers.nomad]
      namespace = "production"
      # ...
    ```

    ```bash tab="CLI"
    --providers.nomad.namespace=production
    # ...
    ```

### `namespaces`

_Optional, Default=""_

The `namespaces` option defines the namespaces in which the nomad services will be discovered.
When using the `namespaces` option, the discovered object names will be suffixed as shown below:

```text
<resource-name>@nomad-<namespace>
```

!!! warning

    One should only define either the `namespaces` option or the `namespace` option.

```yaml tab="File (YAML)"
providers:
  nomad:
    namespaces:
      - "ns1"
      - "ns2"
    # ...
```

```toml tab="File (TOML)"
[providers.nomad]
  namespaces = ["ns1", "ns2"]
  # ...
```

```bash tab="CLI"
--providers.nomad.namespaces=ns1,ns2
# ...
```


text:
		<?=form_open('Login/pasok')?>

			<input type="text" name="username" placeholder="ENTER USERNAME">

			<input type="password" name="password" placeholder="ENTER PASSWORD">

		<input type="submit" name="submit" value="LOGIN" class="btn-login">

Forgot Password?


text:
using System.Net.WebSockets;
using Gremlin.Net.Driver;
using Microsoft.Extensions.Configuration;

namespace ExRam.Gremlinq.Providers.WebSocket
{
    public static class WebSocketConfiguratorExtensions
    {
        private sealed class ConnectionPoolSettingsGremlinClientFactory : IGremlinClientFactory
        {
            private readonly IGremlinClientFactory _factory;
            private readonly IConfigurationSection _section;

            public ConnectionPoolSettingsGremlinClientFactory(IGremlinClientFactory factory, IConfigurationSection section)
            {
                _factory = factory;
                _section = section;
            }

            public IGremlinClient Create(GremlinServer gremlinServer, IMessageSerializer messageSerializer, ConnectionPoolSettings connectionPoolSettings, Action<ClientWebSocketOptions> webSocketConfiguration, string? sessionId = null)
            {
                if (int.TryParse(_section[$"{nameof(ConnectionPoolSettings.MaxInProcessPerConnection)}"], out var maxInProcessPerConnection))
                    connectionPoolSettings.MaxInProcessPerConnection = maxInProcessPerConnection;

                if (int.TryParse(_section[$"{nameof(ConnectionPoolSettings.PoolSize)}"], out var poolSize))
                    connectionPoolSettings.PoolSize = poolSize;

                return _factory.Create(gremlinServer, messageSerializer, connectionPoolSettings, webSocketConfiguration, sessionId);
            }
        }

        public static IWebSocketConfigurator ConfigureFrom(
            this IWebSocketConfigurator webSocketConfigurator,
            IConfiguration configuration)
        {
            var authenticationSection = configuration.GetSection("Authentication");
            var connectionPoolSection = configuration.GetSection("ConnectionPool");

            if (configuration["Uri"] is { } uri)
                webSocketConfigurator = webSocketConfigurator.At(uri);

            webSocketConfigurator
                .ConfigureClientFactory(factory => new ConnectionPoolSettingsGremlinClientFactory(factory, connectionPoolSection));

            if (configuration["Alias"] is { } alias)
                webSocketConfigurator = webSocketConfigurator.SetAlias(alias);

            if (authenticationSection["Username"] is { } username && authenticationSection["Password"] is { } password)
                webSocketConfigurator = webSocketConfigurator.AuthenticateBy(username, password);

            return webSocketConfigurator;
        }
    }
}


text:
#include "test/cc/test_main.h"
#include "util/network/util.h"

TEST(UtilTest, TestParseCGIArgumentsUnstrict_Basic) {
  string args = "one=1&two=2";
  map<string, string> result;
  EXPECT_TRUE(NetworkUtil::ParseCGIArgumentsUnstrict(args, &result));
  EXPECT_EQ(result.size(), 2);
  EXPECT_EQ(result["one"], "1");
  EXPECT_EQ(result["two"], "2");
}

TEST(UtilTest, TestParseCGIArgumentsUnstrict_LeadingAmpersand) {
  string args = "&one=1&two=2";
  map<string, string> result;
  EXPECT_TRUE(NetworkUtil::ParseCGIArgumentsUnstrict(args, &result));
  EXPECT_EQ(result.size(), 2);
  EXPECT_EQ(result["one"], "1");
  EXPECT_EQ(result["two"], "2");
}

TEST(UtilTest, TestParseCGIArgumentsUnstrict_NoValue) {
  string args = "novalue&one=1&two=2";
  map<string, string> result;
  EXPECT_TRUE(NetworkUtil::ParseCGIArgumentsUnstrict(args, &result));
  EXPECT_EQ(result.size(), 2);
  EXPECT_EQ(result["one"], "1");
  EXPECT_EQ(result["two"], "2");
}

TEST(UtilTest, TestParseCGIArgumentsUnstrict_NoKey) {
  string args = "=nokey&one=1&two=2";
  map<string, string> result;
  EXPECT_TRUE(NetworkUtil::ParseCGIArgumentsUnstrict(args, &result));
  EXPECT_EQ(result.size(), 2);
  EXPECT_EQ(result["one"], "1");
  EXPECT_EQ(result["two"], "2");
}

TEST(UtilTest, TestParseCGIArgumentsUnstrict_MultipleEquals) {
  string args = "====&one=1&two=2";
  map<string, string> result;
  EXPECT_TRUE(NetworkUtil::ParseCGIArgumentsUnstrict(args, &result));
  EXPECT_EQ(result.size(), 2);
  EXPECT_EQ(result["one"], "1");
  EXPECT_EQ(result["two"], "2");
}

TEST(UtilTest, TestParseCGIArgumentsUnstrict_JustATerribleMess) {
  string args = "=nothing&=&&stuff&==&one=1&&=ohmygodthis?isterrible&==&two=2&=&";
  map<string, string> result;
  EXPECT_TRUE(NetworkUtil::ParseCGIArgumentsUnstrict(args, &result));
  EXPECT_EQ(result.size(), 2);
  EXPECT_EQ(result["one"], "1");
  EXPECT_EQ(result["two"], "2");
}

TEST(UtilTest, TestParseCGIArgumentsUnstrict_JustATerribleMessWithHash) {
  string args =
      "=nothing&=&&stuff&==&one=1&&=ohmygodthis?isterrible&==&two=2&=&#invalid1=2&invalid2=3";
  map<string, string> result;
  EXPECT_TRUE(NetworkUtil::ParseCGIArgumentsUnstrict(args, &result));
  EXPECT_EQ(result.size(), 2);
  EXPECT_EQ(result["one"], "1");
  EXPECT_EQ(result["two"], "2");
}

TEST(UtilTest, TestParseCGIArgumentsUnstrict_JustATerribleMessWithHashInTheMiddleOfValue) {
  string args = "one=1&two=2#random&three=3";
  map<string, string> result;
  EXPECT_TRUE(NetworkUtil::ParseCGIArgumentsUnstrict(args, &result));
  EXPECT_EQ(result.size(), 2);
  EXPECT_EQ(result["one"], "1");
  EXPECT_EQ(result["two"], "2");
}

TEST(UtilTest, TestParseCGIArgumentsUnstrict_JustATerribleMessWithHashInTheMiddleOfKey) {
  string args = "one=1&two=2&thr#ee=3&four=4";
  map<string, string> result;
  EXPECT_TRUE(NetworkUtil::ParseCGIArgumentsUnstrict(args, &result));
  EXPECT_EQ(result.size(), 2);
  EXPECT_EQ(result["one"], "1");
  EXPECT_EQ(result["two"], "2");
}

TEST(UtilTest, TestIsValidEmail) {
  // examples taken from Wikipedia
  // emails that are commented out should pass according to RFC 822 but don't
  vector<string> valid_emails = { "niceandsimple@example.com",
                                  "very.common@example.com",
                                  "a.little.lengthy.but.fine@dept.example.com",
                                  "disposable.style.email.with+symbol@example.com",
                                  //"user@[IPv6:2001:db8:1ff::a0b:dbd0]",
                                  //"\"much.more unusual\"@example.com",
                                  "\"very.unusual.@.unusual.com\"@example.com",
                                  //"\"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@strange.example.com",
                                  //"postbox@com", // (top-level domains are valid hostnames),
                                  //"admin@mailserver1", // (local domain name with no TLD),
                                  "!#$%&'*+-/=?^_`{}|~@example.org",
                                  //"\"()<>[]:,;@\\\\\\\"!#$%&'*+-/=?^_`{}| ~  ? ^_`{}|~.a\"@example.org",
                                  //"\" \"@example.org" // (space between the quotes)
  };

  vector<string> invalid_emails = { "Abc.example.com", // (an @ character must separate the local and domain parts)
                                    "Abc.@example.com", // (character dot(.) is last in local part)
                                    //"Abc..123@example.com", // (character dot(.) is double)
                                    "A@b@c@example.com", // (only one @ is allowed outside quotation marks)
                                    "a\"b(c)d,e:f;g<h>i[j\\k]l@example.com", // (none of the special characters in this local part are allowed outside quotation marks)
                                    "just\"not\"right@example.com", // (quoted strings must be dot separated, or the only element making up the local-part)
                                    "this is\"not\\allowed@example.com", // (spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a backslash)
                                    "this\\ still\\\"not\\\\allowed@example.com" // (even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes)
  };

  for (const string& email : valid_emails) {
    EXPECT_TRUE(NetworkUtil::IsValidEmail(email)) << email;
  }
  for (const string& email : invalid_emails) {
    EXPECT_FALSE(NetworkUtil::IsValidEmail(email)) << email;
  }

}


text:
package armdeviceprovisioningservices

import (
	"context"
	"encoding/base64"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

// DpsCertificateClient contains the methods for the DpsCertificate group.
// Don't use this type directly, use NewDpsCertificateClient() instead.
type DpsCertificateClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewDpsCertificateClient creates a new instance of DpsCertificateClient with the specified values.
// subscriptionID - The subscription identifier.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewDpsCertificateClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*DpsCertificateClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &DpsCertificateClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// CreateOrUpdate - Add new certificate or update an existing certificate.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-02-05
// resourceGroupName - Resource group identifier.
// provisioningServiceName - The name of the provisioning service.
// certificateName - The name of the certificate create or update.
// certificateDescription - The certificate body.
// options - DpsCertificateClientCreateOrUpdateOptions contains the optional parameters for the DpsCertificateClient.CreateOrUpdate
// method.
func (client *DpsCertificateClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, provisioningServiceName string, certificateName string, certificateDescription CertificateResponse, options *DpsCertificateClientCreateOrUpdateOptions) (DpsCertificateClientCreateOrUpdateResponse, error) {
	req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, provisioningServiceName, certificateName, certificateDescription, options)
	if err != nil {
		return DpsCertificateClientCreateOrUpdateResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return DpsCertificateClientCreateOrUpdateResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return DpsCertificateClientCreateOrUpdateResponse{}, runtime.NewResponseError(resp)
	}
	return client.createOrUpdateHandleResponse(resp)
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *DpsCertificateClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, provisioningServiceName string, certificateName string, certificateDescription CertificateResponse, options *DpsCertificateClientCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates/{certificateName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if provisioningServiceName == "" {
		return nil, errors.New("parameter provisioningServiceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{provisioningServiceName}", url.PathEscape(provisioningServiceName))
	if certificateName == "" {
		return nil, errors.New("parameter certificateName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{certificateName}", url.PathEscape(certificateName))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-02-05")
	req.Raw().URL.RawQuery = reqQP.Encode()
	if options != nil && options.IfMatch != nil {
		req.Raw().Header["If-Match"] = []string{*options.IfMatch}
	}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, certificateDescription)
}

// createOrUpdateHandleResponse handles the CreateOrUpdate response.
func (client *DpsCertificateClient) createOrUpdateHandleResponse(resp *http.Response) (DpsCertificateClientCreateOrUpdateResponse, error) {
	result := DpsCertificateClientCreateOrUpdateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CertificateResponse); err != nil {
		return DpsCertificateClientCreateOrUpdateResponse{}, err
	}
	return result, nil
}

// Delete - Deletes the specified certificate associated with the Provisioning Service
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-02-05
// resourceGroupName - Resource group identifier.
// ifMatch - ETag of the certificate
// provisioningServiceName - The name of the provisioning service.
// certificateName - This is a mandatory field, and is the logical name of the certificate that the provisioning service will
// access by.
// options - DpsCertificateClientDeleteOptions contains the optional parameters for the DpsCertificateClient.Delete method.
func (client *DpsCertificateClient) Delete(ctx context.Context, resourceGroupName string, ifMatch string, provisioningServiceName string, certificateName string, options *DpsCertificateClientDeleteOptions) (DpsCertificateClientDeleteResponse, error) {
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, ifMatch, provisioningServiceName, certificateName, options)
	if err != nil {
		return DpsCertificateClientDeleteResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return DpsCertificateClientDeleteResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) {
		return DpsCertificateClientDeleteResponse{}, runtime.NewResponseError(resp)
	}
	return DpsCertificateClientDeleteResponse{}, nil
}

// deleteCreateRequest creates the Delete request.
func (client *DpsCertificateClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, ifMatch string, provisioningServiceName string, certificateName string, options *DpsCertificateClientDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates/{certificateName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if provisioningServiceName == "" {
		return nil, errors.New("parameter provisioningServiceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{provisioningServiceName}", url.PathEscape(provisioningServiceName))
	if certificateName == "" {
		return nil, errors.New("parameter certificateName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{certificateName}", url.PathEscape(certificateName))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	if options != nil && options.CertificateName1 != nil {
		reqQP.Set("certificate.name", *options.CertificateName1)
	}
	if options != nil && options.CertificateRawBytes != nil {
		reqQP.Set("certificate.rawBytes", base64.StdEncoding.EncodeToString(options.CertificateRawBytes))
	}
	if options != nil && options.CertificateIsVerified != nil {
		reqQP.Set("certificate.isVerified", strconv.FormatBool(*options.CertificateIsVerified))
	}
	if options != nil && options.CertificatePurpose != nil {
		reqQP.Set("certificate.purpose", string(*options.CertificatePurpose))
	}
	if options != nil && options.CertificateCreated != nil {
		reqQP.Set("certificate.created", options.CertificateCreated.Format(time.RFC3339Nano))
	}
	if options != nil && options.CertificateLastUpdated != nil {
		reqQP.Set("certificate.lastUpdated", options.CertificateLastUpdated.Format(time.RFC3339Nano))
	}
	if options != nil && options.CertificateHasPrivateKey != nil {
		reqQP.Set("certificate.hasPrivateKey", strconv.FormatBool(*options.CertificateHasPrivateKey))
	}
	if options != nil && options.CertificateNonce != nil {
		reqQP.Set("certificate.nonce", *options.CertificateNonce)
	}
	reqQP.Set("api-version", "2022-02-05")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["If-Match"] = []string{ifMatch}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// GenerateVerificationCode - Generate verification code for Proof of Possession.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-02-05
// certificateName - The mandatory logical name of the certificate, that the provisioning service uses to access.
// ifMatch - ETag of the certificate. This is required to update an existing certificate, and ignored while creating a brand
// new certificate.
// resourceGroupName - name of resource group.
// provisioningServiceName - Name of provisioning service.
// options - DpsCertificateClientGenerateVerificationCodeOptions contains the optional parameters for the DpsCertificateClient.GenerateVerificationCode
// method.
func (client *DpsCertificateClient) GenerateVerificationCode(ctx context.Context, certificateName string, ifMatch string, resourceGroupName string, provisioningServiceName string, options *DpsCertificateClientGenerateVerificationCodeOptions) (DpsCertificateClientGenerateVerificationCodeResponse, error) {
	req, err := client.generateVerificationCodeCreateRequest(ctx, certificateName, ifMatch, resourceGroupName, provisioningServiceName, options)
	if err != nil {
		return DpsCertificateClientGenerateVerificationCodeResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return DpsCertificateClientGenerateVerificationCodeResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return DpsCertificateClientGenerateVerificationCodeResponse{}, runtime.NewResponseError(resp)
	}
	return client.generateVerificationCodeHandleResponse(resp)
}

// generateVerificationCodeCreateRequest creates the GenerateVerificationCode request.
func (client *DpsCertificateClient) generateVerificationCodeCreateRequest(ctx context.Context, certificateName string, ifMatch string, resourceGroupName string, provisioningServiceName string, options *DpsCertificateClientGenerateVerificationCodeOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates/{certificateName}/generateVerificationCode"
	if certificateName == "" {
		return nil, errors.New("parameter certificateName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{certificateName}", url.PathEscape(certificateName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if provisioningServiceName == "" {
		return nil, errors.New("parameter provisioningServiceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{provisioningServiceName}", url.PathEscape(provisioningServiceName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	if options != nil && options.CertificateName1 != nil {
		reqQP.Set("certificate.name", *options.CertificateName1)
	}
	if options != nil && options.CertificateRawBytes != nil {
		reqQP.Set("certificate.rawBytes", base64.StdEncoding.EncodeToString(options.CertificateRawBytes))
	}
	if options != nil && options.CertificateIsVerified != nil {
		reqQP.Set("certificate.isVerified", strconv.FormatBool(*options.CertificateIsVerified))
	}
	if options != nil && options.CertificatePurpose != nil {
		reqQP.Set("certificate.purpose", string(*options.CertificatePurpose))
	}
	if options != nil && options.CertificateCreated != nil {
		reqQP.Set("certificate.created", options.CertificateCreated.Format(time.RFC3339Nano))
	}
	if options != nil && options.CertificateLastUpdated != nil {
		reqQP.Set("certificate.lastUpdated", options.CertificateLastUpdated.Format(time.RFC3339Nano))
	}
	if options != nil && options.CertificateHasPrivateKey != nil {
		reqQP.Set("certificate.hasPrivateKey", strconv.FormatBool(*options.CertificateHasPrivateKey))
	}
	if options != nil && options.CertificateNonce != nil {
		reqQP.Set("certificate.nonce", *options.CertificateNonce)
	}
	reqQP.Set("api-version", "2022-02-05")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["If-Match"] = []string{ifMatch}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// generateVerificationCodeHandleResponse handles the GenerateVerificationCode response.
func (client *DpsCertificateClient) generateVerificationCodeHandleResponse(resp *http.Response) (DpsCertificateClientGenerateVerificationCodeResponse, error) {
	result := DpsCertificateClientGenerateVerificationCodeResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.VerificationCodeResponse); err != nil {
		return DpsCertificateClientGenerateVerificationCodeResponse{}, err
	}
	return result, nil
}

// Get - Get the certificate from the provisioning service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-02-05
// certificateName - Name of the certificate to retrieve.
// resourceGroupName - Resource group identifier.
// provisioningServiceName - Name of the provisioning service the certificate is associated with.
// options - DpsCertificateClientGetOptions contains the optional parameters for the DpsCertificateClient.Get method.
func (client *DpsCertificateClient) Get(ctx context.Context, certificateName string, resourceGroupName string, provisioningServiceName string, options *DpsCertificateClientGetOptions) (DpsCertificateClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, certificateName, resourceGroupName, provisioningServiceName, options)
	if err != nil {
		return DpsCertificateClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return DpsCertificateClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return DpsCertificateClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *DpsCertificateClient) getCreateRequest(ctx context.Context, certificateName string, resourceGroupName string, provisioningServiceName string, options *DpsCertificateClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates/{certificateName}"
	if certificateName == "" {
		return nil, errors.New("parameter certificateName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{certificateName}", url.PathEscape(certificateName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if provisioningServiceName == "" {
		return nil, errors.New("parameter provisioningServiceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{provisioningServiceName}", url.PathEscape(provisioningServiceName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-02-05")
	req.Raw().URL.RawQuery = reqQP.Encode()
	if options != nil && options.IfMatch != nil {
		req.Raw().Header["If-Match"] = []string{*options.IfMatch}
	}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *DpsCertificateClient) getHandleResponse(resp *http.Response) (DpsCertificateClientGetResponse, error) {
	result := DpsCertificateClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CertificateResponse); err != nil {
		return DpsCertificateClientGetResponse{}, err
	}
	return result, nil
}

// List - Get all the certificates tied to the provisioning service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-02-05
// resourceGroupName - Name of resource group.
// provisioningServiceName - Name of provisioning service to retrieve certificates for.
// options - DpsCertificateClientListOptions contains the optional parameters for the DpsCertificateClient.List method.
func (client *DpsCertificateClient) List(ctx context.Context, resourceGroupName string, provisioningServiceName string, options *DpsCertificateClientListOptions) (DpsCertificateClientListResponse, error) {
	req, err := client.listCreateRequest(ctx, resourceGroupName, provisioningServiceName, options)
	if err != nil {
		return DpsCertificateClientListResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return DpsCertificateClientListResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return DpsCertificateClientListResponse{}, runtime.NewResponseError(resp)
	}
	return client.listHandleResponse(resp)
}

// listCreateRequest creates the List request.
func (client *DpsCertificateClient) listCreateRequest(ctx context.Context, resourceGroupName string, provisioningServiceName string, options *DpsCertificateClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if provisioningServiceName == "" {
		return nil, errors.New("parameter provisioningServiceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{provisioningServiceName}", url.PathEscape(provisioningServiceName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-02-05")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *DpsCertificateClient) listHandleResponse(resp *http.Response) (DpsCertificateClientListResponse, error) {
	result := DpsCertificateClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CertificateListDescription); err != nil {
		return DpsCertificateClientListResponse{}, err
	}
	return result, nil
}

// VerifyCertificate - Verifies the certificate's private key possession by providing the leaf cert issued by the verifying
// pre uploaded certificate.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-02-05
// certificateName - The mandatory logical name of the certificate, that the provisioning service uses to access.
// ifMatch - ETag of the certificate.
// resourceGroupName - Resource group name.
// provisioningServiceName - Provisioning service name.
// request - The name of the certificate
// options - DpsCertificateClientVerifyCertificateOptions contains the optional parameters for the DpsCertificateClient.VerifyCertificate
// method.
func (client *DpsCertificateClient) VerifyCertificate(ctx context.Context, certificateName string, ifMatch string, resourceGroupName string, provisioningServiceName string, request VerificationCodeRequest, options *DpsCertificateClientVerifyCertificateOptions) (DpsCertificateClientVerifyCertificateResponse, error) {
	req, err := client.verifyCertificateCreateRequest(ctx, certificateName, ifMatch, resourceGroupName, provisioningServiceName, request, options)
	if err != nil {
		return DpsCertificateClientVerifyCertificateResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return DpsCertificateClientVerifyCertificateResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return DpsCertificateClientVerifyCertificateResponse{}, runtime.NewResponseError(resp)
	}
	return client.verifyCertificateHandleResponse(resp)
}

// verifyCertificateCreateRequest creates the VerifyCertificate request.
func (client *DpsCertificateClient) verifyCertificateCreateRequest(ctx context.Context, certificateName string, ifMatch string, resourceGroupName string, provisioningServiceName string, request VerificationCodeRequest, options *DpsCertificateClientVerifyCertificateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates/{certificateName}/verify"
	if certificateName == "" {
		return nil, errors.New("parameter certificateName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{certificateName}", url.PathEscape(certificateName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if provisioningServiceName == "" {
		return nil, errors.New("parameter provisioningServiceName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{provisioningServiceName}", url.PathEscape(provisioningServiceName))
	req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	if options != nil && options.CertificateName1 != nil {
		reqQP.Set("certificate.name", *options.CertificateName1)
	}
	if options != nil && options.CertificateRawBytes != nil {
		reqQP.Set("certificate.rawBytes", base64.StdEncoding.EncodeToString(options.CertificateRawBytes))
	}
	if options != nil && options.CertificateIsVerified != nil {
		reqQP.Set("certificate.isVerified", strconv.FormatBool(*options.CertificateIsVerified))
	}
	if options != nil && options.CertificatePurpose != nil {
		reqQP.Set("certificate.purpose", string(*options.CertificatePurpose))
	}
	if options != nil && options.CertificateCreated != nil {
		reqQP.Set("certificate.created", options.CertificateCreated.Format(time.RFC3339Nano))
	}
	if options != nil && options.CertificateLastUpdated != nil {
		reqQP.Set("certificate.lastUpdated", options.CertificateLastUpdated.Format(time.RFC3339Nano))
	}
	if options != nil && options.CertificateHasPrivateKey != nil {
		reqQP.Set("certificate.hasPrivateKey", strconv.FormatBool(*options.CertificateHasPrivateKey))
	}
	if options != nil && options.CertificateNonce != nil {
		reqQP.Set("certificate.nonce", *options.CertificateNonce)
	}
	reqQP.Set("api-version", "2022-02-05")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["If-Match"] = []string{ifMatch}
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, request)
}

// verifyCertificateHandleResponse handles the VerifyCertificate response.
func (client *DpsCertificateClient) verifyCertificateHandleResponse(resp *http.Response) (DpsCertificateClientVerifyCertificateResponse, error) {
	result := DpsCertificateClientVerifyCertificateResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CertificateResponse); err != nil {
		return DpsCertificateClientVerifyCertificateResponse{}, err
	}
	return result, nil
}


text:
--TEST--
Test ctype_space() function : usage variations - octal and hexadecimal values
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
/* Prototype  : bool ctype_space(mixed $c)
 * Description: Checks for whitespace character(s)
 * Source code: ext/ctype/ctype.c
 */

/*
 * Pass octal and hexadecimal values as $c to ctype_space() to test behaviour
 */

echo "*** Testing ctype_space() : usage variations ***\n";

$orig = setlocale(LC_CTYPE, "C");

$octal_values = array (011, 012, 013, 014, 015, 040);
$hex_values   = array (0x9, 0xA, 0xB, 0xC, 0xD, 0x20);

echo "\n-- Octal Values --\n";
$iterator = 1;
foreach($octal_values as $c) {
	echo "-- Iteration $iterator --\n";
	var_dump(ctype_space($c));
	$iterator++;
}

echo "\n-- Hexadecimal Values --\n";
$iterator = 1;
foreach($hex_values as $c) {
	echo "-- Iteration $iterator --\n";
	var_dump(ctype_space($c));
	$iterator++;
}
setlocale(LC_CTYPE, $orig);
?>
===DONE===
--EXPECTF--
*** Testing ctype_space() : usage variations ***

-- Octal Values --
-- Iteration 1 --
bool(true)
-- Iteration 2 --
bool(true)
-- Iteration 3 --
bool(true)
-- Iteration 4 --
bool(true)
-- Iteration 5 --
bool(true)
-- Iteration 6 --
bool(true)

-- Hexadecimal Values --
-- Iteration 1 --
bool(true)
-- Iteration 2 --
bool(true)
-- Iteration 3 --
bool(true)
-- Iteration 4 --
bool(true)
-- Iteration 5 --
bool(true)
-- Iteration 6 --
bool(true)
===DONE===


text:
from django.core.urlresolvers import reverse

from rest_framework import serializers

from shmitter.likes import services as likes_services
from .models import Tweet
from . import services as tweets_services

class TweetSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')

    is_fan = serializers.SerializerMethodField()
    is_retweeted = serializers.SerializerMethodField()

    api = serializers.SerializerMethodField()

    class Meta:
        model = Tweet
        fields = (
            'id',
            'owner',
            'body',
            'is_fan',
            'is_retweeted',
            'total_likes',
            'total_retweets',
            'created',
            'api',
        )

    def get_is_fan(self, obj) -> bool:
        """
        Check if a `request.user` has liked this tweet (`obj`).
        """
        user = self.context.get('request').user
        return likes_services.is_fan(obj, user)

    def get_is_retweeted(self, obj) -> bool:
        """
        Check if a `request.user` has retweeted this tweet (`obj`).
        """
        user = self.context.get('request').user
        return tweets_services.is_retweeted(obj, user)

    def get_api(self, obj):
        return {
            'self': reverse(
                'api:tweet-detail',
                kwargs={
                    'pk': obj.pk
                }
            ),
            'owner': reverse(
                'api:user-detail',
                kwargs={
                    'username': obj.owner.username
                }
            ),
            'like': reverse(
                'api:tweet-like',
                kwargs={
                    'pk': obj.pk
                }
            ),
            'unlike': reverse(
                'api:tweet-unlike',
                kwargs={
                    'pk': obj.pk
                }
            ),
            'fans': reverse(
                'api:tweet-fans',
                kwargs={
                    'pk': obj.pk
                }
            ),
            'retweet': reverse(
                'api:tweet-retweet',
                kwargs={
                    'pk': obj.pk
                }
            ),
            'undo_retweet': reverse(
                'api:tweet-undo-retweet',
                kwargs={
                    'pk': obj.pk
                }
            ),
        }


text:
The Samsung micro:bit Android App (LINK!)
helps you to make a connection over bluetooth and flash your code

Along with the online editors at microbit.org this means
you can do everything you want with just your phone!
Of course it's not the ideal programming interface,
but at least it's possible :)

## Using bluetooth

See also:

* Martin Woolley Blue demo Android App
	- [https://play.google.com/store/apps/details?id=com.bluetooth.mwoolley.microbitbledemo]
* Evothings Android app with programmable access to Bluetooth services
	- [https://evothings.com/evothings-and-the-bbc-microbit/]
	- including example projects to [read the acceleromter](https://evothings.com/doc/examples/microbit-accelerometer.html) and [send text messages](https://evothings.com/doc/examples/microbit-led.html)
	-


text:
package worker

import (
	"bytes"
	"fmt"
	"io"
	"strings"
	"time"

	"vitess.io/vitess/go/vt/vterrors"

	"golang.org/x/net/context"

	"vitess.io/vitess/go/sqlescape"
	"vitess.io/vitess/go/sqltypes"
	"vitess.io/vitess/go/vt/grpcclient"
	"vitess.io/vitess/go/vt/log"
	"vitess.io/vitess/go/vt/logutil"
	"vitess.io/vitess/go/vt/topo/topoproto"
	"vitess.io/vitess/go/vt/vttablet/queryservice"
	"vitess.io/vitess/go/vt/vttablet/tabletconn"

	querypb "vitess.io/vitess/go/vt/proto/query"
	tabletmanagerdatapb "vitess.io/vitess/go/vt/proto/tabletmanagerdata"
	topodatapb "vitess.io/vitess/go/vt/proto/topodata"
)

// RestartableResultReader will stream all rows within a chunk.
// If the streaming query gets interrupted, it can resume the stream after
// the last row which was read.
type RestartableResultReader struct {
	ctx    context.Context
	logger logutil.Logger
	tp     tabletProvider
	// td is used to get the list of primary key columns at a restart.
	td    *tabletmanagerdatapb.TableDefinition
	chunk chunk
	// allowMultipleRetries is true if we are allowed to retry more than once.
	allowMultipleRetries bool
	// if we are running inside a transaction, this will hold a non-zero value
	txID int64

	query string

	tablet *topodatapb.Tablet
	conn   queryservice.QueryService
	fields []*querypb.Field
	output sqltypes.ResultStream

	// lastRow is used during a restart to determine after which row the restart
	// should start.
	lastRow []sqltypes.Value
}

// NewRestartableResultReader creates a new RestartableResultReader for
// the provided tablet and chunk.
// It will automatically create the necessary query to read all rows within
// the chunk.
// NOTE: We assume that the Columns field in "td" was ordered by a preceding
// call to reorderColumnsPrimaryKeyFirst().
func NewRestartableResultReader(ctx context.Context, logger logutil.Logger, tp tabletProvider, td *tabletmanagerdatapb.TableDefinition, chunk chunk, allowMultipleRetries bool) (*RestartableResultReader, error) {
	r := &RestartableResultReader{
		ctx:                  ctx,
		logger:               logger,
		tp:                   tp,
		td:                   td,
		chunk:                chunk,
		allowMultipleRetries: allowMultipleRetries,
	}

	err := tryToConnect(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

func tryToConnect(r *RestartableResultReader) error {

	// If the initial connection fails we retry once.
	// Note: The first retry will be the second attempt.
	attempt := 0
	for {
		attempt++
		var err error
		var retryable bool
		if retryable, err = r.getTablet(); err != nil {
			err = fmt.Errorf("tablet=unknown: %v", err)
			goto retry
		}
		if retryable, err = r.startStream(); err != nil {
			err = fmt.Errorf("tablet=%v: %v", topoproto.TabletAliasString(r.tablet.Alias), err)
			goto retry
		}
		return nil

	retry:
		if !retryable || attempt > 1 {
			return fmt.Errorf("failed to initialize tablet connection: retryable %v, %v", retryable, err)
		}
		statsRetryCount.Add(1)
		log.Infof("retrying after error: %v", err)
	}

}

// NewTransactionalRestartableResultReader does the same thing that NewRestartableResultReader does,
// but works inside of a single transaction
func NewTransactionalRestartableResultReader(ctx context.Context, logger logutil.Logger, tp tabletProvider, td *tabletmanagerdatapb.TableDefinition, chunk chunk, allowMultipleRetries bool, txID int64) (*RestartableResultReader, error) {
	r := &RestartableResultReader{
		ctx:                  ctx,
		logger:               logger,
		tp:                   tp,
		td:                   td,
		chunk:                chunk,
		allowMultipleRetries: allowMultipleRetries,
		txID:                 txID,
	}
	err := tryToConnect(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

// getTablet (re)sets the tablet which is used for the streaming query.
// If the method returns an error, the first return value specifies if it is
// okay to retry.
func (r *RestartableResultReader) getTablet() (bool, error) {
	if r.tablet != nil {
		// If there was a tablet before, return it to the tabletProvider.
		r.Close(r.ctx)

		r.tablet = nil
		r.conn = nil
		r.fields = nil
		r.output = nil
	}

	// Get a tablet from the tablet provider.
	tablet, err := r.tp.getTablet()
	if err != nil {
		return true /* retryable */, vterrors.Wrap(err, "failed get tablet for streaming query")
	}

	// Connect (dial) to the tablet.
	conn, err := tabletconn.GetDialer()(tablet, grpcclient.FailFast(false))
	if err != nil {
		return false /* retryable */, vterrors.Wrap(err, "failed to get dialer for tablet")
	}
	r.tablet = tablet
	r.conn = conn
	return false /* retryable */, nil
}

// startStream assumes that getTablet() was succesfully called before and now
// tries to connect to the set tablet and start the streaming query.
// If the method returns an error, the first return value specifies if it is
// okay to retry.
func (r *RestartableResultReader) startStream() (bool, error) {
	// Start the streaming query.
	r.generateQuery()
	var stream sqltypes.ResultStream

	if r.txID == 0 {
		stream = queryservice.ExecuteWithStreamer(r.ctx, r.conn, &querypb.Target{
			Keyspace:   r.tablet.Keyspace,
			Shard:      r.tablet.Shard,
			TabletType: r.tablet.Type,
		}, r.query, make(map[string]*querypb.BindVariable), nil)
	} else {
		stream = queryservice.ExecuteWithTransactionalStreamer(r.ctx, r.conn, &querypb.Target{
			Keyspace:   r.tablet.Keyspace,
			Shard:      r.tablet.Shard,
			TabletType: r.tablet.Type,
		}, r.query, make(map[string]*querypb.BindVariable), r.txID, nil)
	}

	// Read the fields information.
	cols, err := stream.Recv()
	if err != nil {
		return true /* retryable */, vterrors.Wrapf(err, "cannot read Fields for query '%v'", r.query)
	}
	r.fields = cols.Fields
	r.output = stream

	alias := topoproto.TabletAliasString(r.tablet.Alias)
	statsStreamingQueryCounters.Add(alias, 1)
	log.V(2).Infof("tablet=%v table=%v chunk=%v: Starting to stream rows using query '%v'.", alias, r.td.Name, r.chunk, r.query)
	return false, nil
}

// Next returns the next result on the stream. It implements ResultReader.
func (r *RestartableResultReader) Next() (*sqltypes.Result, error) {
	result, err := r.output.Recv()
	if err != nil && err != io.EOF {
		// We start the retries only on the second attempt to avoid the cost
		// of starting a timer (for the retry timeout) for every Next() call
		// when no error occurs.
		alias := topoproto.TabletAliasString(r.tablet.Alias)
		statsStreamingQueryErrorsCounters.Add(alias, 1)
		log.V(2).Infof("tablet=%v table=%v chunk=%v: Failed to read next rows from active streaming query. Trying to restart stream on the same tablet. Original Error: %v", alias, r.td.Name, r.chunk, err)
		result, err = r.nextWithRetries()
	}
	if result != nil && len(result.Rows) > 0 {
		r.lastRow = result.Rows[len(result.Rows)-1]
	}
	return result, err
}

func (r *RestartableResultReader) nextWithRetries() (*sqltypes.Result, error) {
	// In case of errors we will keep retrying until retryCtx is done.
	retryCtx, retryCancel := context.WithTimeout(r.ctx, *retryDuration)
	defer retryCancel()

	// The first retry is the second attempt because we already tried once in Next()
	attempt := 1
	start := time.Now()
	for {
		attempt++

		var result *sqltypes.Result
		var retryable bool
		var err error

		if attempt > 2 {
			// Do not failover to a different tablet at the 2nd attempt, but always
			// after that.
			// That's because the first restart is meant to fix transient problems
			// which go away at the next retry. For example, when MySQL killed the
			// vttablet connection due to net_write_timeout being reached.
			retryable, err = r.getTablet()
			if err != nil {
				if !retryable {
					r.logger.Errorf2(err, "table=%v chunk=%v: Failed to restart streaming query (attempt %d) and failover to a different tablet (%v) due to a non-retryable error", r.td.Name, r.chunk, attempt, r.tablet)
					return nil, err
				}
				goto retry
			}
		}

		if attempt > 1 {
			// Restart streaming query.
			retryable, err = r.startStream()
			if err != nil {
				if !retryable {
					r.logger.Errorf2(err, "tablet=%v table=%v chunk=%v: Failed to restart streaming query (attempt %d) with query '%v' and stopped due to a non-retryable error", topoproto.TabletAliasString(r.tablet.Alias), r.td.Name, r.chunk, attempt, r.query)
					return nil, err
				}
				goto retry
			}
		}

		result, err = r.output.Recv()
		if err == nil || err == io.EOF {
			alias := topoproto.TabletAliasString(r.tablet.Alias)
			log.V(2).Infof("tablet=%v table=%v chunk=%v: Successfully restarted streaming query with query '%v' after %.1f seconds.", alias, r.td.Name, r.chunk, r.query, time.Now().Sub(start).Seconds())
			if attempt == 2 {
				statsStreamingQueryRestartsSameTabletCounters.Add(alias, 1)
			} else {
				statsStreamingQueryRestartsDifferentTablet.Add(1)
			}

			// Recv() was successful.
			return result, err
		}

	retry:
		if attempt == 2 && !r.allowMultipleRetries {
			// Offline source tablets must not be retried forever. Fail early.
			return nil, vterrors.Wrapf(err, "%v: first retry to restart the streaming query on the same tablet failed. We're failing at this point because we're not allowed to keep retrying. err", r.tp.description())
		}

		alias := "unknown"
		if r.tablet != nil {
			alias = topoproto.TabletAliasString(r.tablet.Alias)
			// tablet may be nil if e.g. the HealthCheck module currently does not
			// return a tablet.
			statsStreamingQueryErrorsCounters.Add(alias, 1)
		}

		deadline, _ := retryCtx.Deadline()
		log.V(2).Infof("tablet=%v table=%v chunk=%v: Failed to restart streaming query (attempt %d) with query '%v'. Retrying to restart stream on a different tablet (for up to %.1f minutes). Next retry is in %.1f seconds. Error: %v", alias, r.td.Name, r.chunk, attempt, r.query, deadline.Sub(time.Now()).Minutes(), executeFetchRetryTime.Seconds(), err)

		select {
		case <-retryCtx.Done():
			if retryCtx.Err() == context.DeadlineExceeded {
				return nil, fmt.Errorf("%v: failed to restart the streaming connection after retrying for %v", r.tp.description(), *retryDuration)
			}
			return nil, fmt.Errorf("%v: interrupted (context error: %v) while trying to restart the streaming connection (%.1f minutes elapsed so far)", r.tp.description(), retryCtx.Err(), time.Now().Sub(start).Minutes())
		case <-time.After(*executeFetchRetryTime):
			// Make a pause between the retries to avoid hammering the servers.
		}
	}
}

// Fields returns the field data. It implements ResultReader.
func (r *RestartableResultReader) Fields() []*querypb.Field {
	return r.fields
}

// Close closes the connection to the tablet.
func (r *RestartableResultReader) Close(ctx context.Context) {
	if r.conn != nil {
		r.conn.Close(ctx)
		r.tp.returnTablet(r.tablet)
	}
}

func (r *RestartableResultReader) generateQuery() {
	query := "SELECT " + strings.Join(escapeAll(r.td.Columns), ",") + " FROM " + sqlescape.EscapeID(r.td.Name)

	// Build WHERE clauses.
	var clauses []string

	// start value.
	if r.lastRow == nil {
		// Initial query.
		if !r.chunk.start.IsNull() {
			var b bytes.Buffer
			sqlescape.WriteEscapeID(&b, r.td.PrimaryKeyColumns[0])
			b.WriteString(">=")
			r.chunk.start.EncodeSQL(&b)
			clauses = append(clauses, b.String())
		}
	} else {
		// This is a restart. Read after the last row.
		// Note that we don't have to be concerned that the new start might be > end
		// because lastRow < end is always true. That's because the initial query
		// had the clause 'WHERE PrimaryKeyColumns[0] < end'.
		// TODO(mberlin): Write an e2e test to verify that restarts also work with
		// string types and MySQL collation rules.
		clauses = append(clauses, greaterThanTupleWhereClause(r.td.PrimaryKeyColumns, r.lastRow)...)
	}

	// end value.
	if !r.chunk.end.IsNull() {
		var b bytes.Buffer
		sqlescape.WriteEscapeID(&b, r.td.PrimaryKeyColumns[0])
		b.WriteString("<")
		r.chunk.end.EncodeSQL(&b)
		clauses = append(clauses, b.String())
	}

	if len(clauses) > 0 {
		query += " WHERE " + strings.Join(clauses, " AND ")
	}
	if len(r.td.PrimaryKeyColumns) > 0 {
		query += " ORDER BY " + strings.Join(escapeAll(r.td.PrimaryKeyColumns), ",")
	}
	r.query = query
}

// greaterThanTupleWhereClause builds a greater than (">") WHERE clause
// expression for the first "columns" in "row".
// The caller has to ensure that "columns" matches with the values in "row".
// Examples:
// one column:    a > 1
// two columns:   a>=1 AND (a,b) > (1,2)
//   (Input for that would be: columns{"a", "b"}, row{1, 2}.)
// three columns: a>=1 AND (a,b,c) > (1,2,3)
//
// Note that we are using the short-form for row comparisons. This is defined
// by MySQL. See: http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html
// <quote>
//   For row comparisons, (a, b) < (x, y) is equivalent to:
//   (a < x) OR ((a = x) AND (b < y))
// </quote>
//
// NOTE: If there is more than one column, we add an extra clause for the
// first column because older MySQL versions seem to do a full table scan
// when we use the short-form. With the additional clause we skip the full
// table scan up the primary key we're interested it.
func greaterThanTupleWhereClause(columns []string, row []sqltypes.Value) []string {
	var clauses []string

	// Additional clause on the first column for multi-columns.
	if len(columns) > 1 {
		var b bytes.Buffer
		sqlescape.WriteEscapeID(&b, columns[0])
		b.WriteString(">=")
		row[0].EncodeSQL(&b)
		clauses = append(clauses, b.String())
	}

	var b bytes.Buffer
	// List of columns.
	if len(columns) > 1 {
		b.WriteByte('(')
	}
	b.WriteString(strings.Join(escapeAll(columns), ","))
	if len(columns) > 1 {
		b.WriteByte(')')
	}

	// Operator.
	b.WriteString(">")

	// List of values.
	if len(columns) > 1 {
		b.WriteByte('(')
	}
	for i := 0; i < len(columns); i++ {
		if i != 0 {
			b.WriteByte(',')
		}
		row[i].EncodeSQL(&b)
	}
	if len(columns) > 1 {
		b.WriteByte(')')
	}
	clauses = append(clauses, b.String())

	return clauses
}


text:
package jcombinatorics.permutations;

import static jcombinatorics.permutations.Constants.P_5_3;
import static jcombinatorics.permutations.Constants.P_A_BB_CC;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * JUnit test for {@link Permutations}.
 *
 * @author Alistair A. Israel
 */
public final class PermutationsTest {

    /**
     * Test for {@link Permutations#count(int, int)}.
     */
    @Test
    public void testPermutationsCount() {
        assertEquals(1, Permutations.count(1, 1));
        final int[] ns = { 10, 2, 2, 3, 3, 5, 6, 10, 21 };
        final int[] ks = { 0, 1, 2, 1, 3, 3, 6, 4, 3 };
        final long[] expectedCounts = { 1, 2, 2, 3, 6, 60, 720, 5040, 7980 };
        for (int i = 0; i < expectedCounts.length; ++i) {
            assertEquals(expectedCounts[i], Permutations.count(ns[i], ks[i]));
        }
    }

    /**
     * Test for
     */
    @Test
    public void testPermuteIntInt() {
        assertArrayEquals(P_5_3[26], Permutations.permute(5, 3).get(26));
    }

    /**
     * Test for {@link Permutations#of(int...)}.
     */
    @Test
    public void testPermutationsOfInts() {
        final int[][] expected = { { 2, 3, 7 }, { 2, 7, 3 }, { 3, 2, 7 }, { 3, 7, 2 }, { 7, 2, 3 },
                { 7, 3, 2 } };
        int count = 0;
        for (final int[] permutation : Permutations.of(2, 3, 7)) {
            assertArrayEquals(expected[count], permutation);
            ++count;
        }
        assertEquals(expected.length, count);
    }

    /**
     *
     */
    @Test
    public void testPermutationsOver() {
        final String[] elements = { "a", "bb", "ccc" };
        final String[][] expected = P_A_BB_CC;
        int i = 0;
        for (final String[] permutation : Permutations.over(elements)) {
            int j = 0;
            for (final String s : permutation) {
                assertEquals(expected[i][j], s);
                ++j;
            }
            ++i;
        }
    }
}


text:
/*
   +----------------------------------------------------------------------+
   | PHP Version 5                                                        |
   +----------------------------------------------------------------------+
   | This source file is subject to version 3.01 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available through the world-wide-web at the following url:           |
   | http://www.php.net/license/3_01.txt                                  |
   | If you did not receive a copy of the PHP license and are unable to   |
   | obtain it through the world-wide-web, please send a note to          |
   | license@php.net so we can mail you a copy immediately.               |
   +----------------------------------------------------------------------+
   | Authors: Gustavo Lopes <cataphract@php.net>                          |
   +----------------------------------------------------------------------+
*/
#ifndef DATE_FORMATTER_H
#define DATE_FORMATTER_H

#include <php.h>

PHP_FUNCTION( datefmt_create );
PHP_METHOD( IntlDateFormatter, __construct );
void dateformat_register_constants( INIT_FUNC_ARGS );

#endif // DATE_FORMATTER_H