/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.orc;

import org.apache.orc.impl.ReaderImpl;
import org.apache.orc.impl.SchemaEvolution;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.apache.hadoop.util.StringUtils.COMMA_STR;

public class OrcUtils {

  /**
   * Returns selected columns as a boolean array with true value set for specified column names.
   * The result will contain number of elements equal to flattened number of columns.
   * For example:
   * selectedColumns - a,b,c
   * allColumns - a,b,c,d
   * If column c is a complex type, say list<string> and other types are
   * primitives then result will
   * be [false, true, true, true, true, true, false]
   * Index 0 is the root element of the struct which is set to false by default, index 1,2
   * corresponds to columns a and b. Index 3,4 correspond to column c which is list<string> and
   * index 5 correspond to column d. After flattening list<string> gets 2 columns.
   *
   * Column names that aren't found are ignored.
   * @param selectedColumns - comma separated list of selected column names
   * @param schema       - object schema
   * @return - boolean array with true value set for the specified column names
   */
  public static boolean[] includeColumns(String selectedColumns,
                                         TypeDescription schema) {
    int numFlattenedCols = schema.getMaximumId();
    boolean[] results = new boolean[numFlattenedCols + 1];
    if ("*".equals(selectedColumns)) {
      Arrays.fill(results, true);
      return results;
    }
    TypeDescription baseSchema = SchemaEvolution.checkAcidSchema(schema) ?
        SchemaEvolution.getBaseRow(schema) : schema;

    if (selectedColumns != null &&
        baseSchema.getCategory() == TypeDescription.Category.STRUCT) {

      for (String columnName : selectedColumns.split(COMMA_STR)) {
        TypeDescription column = findColumn(baseSchema, columnName.trim());
        if (column != null) {
          for (int i = column.getId(); i <= column.getMaximumId(); ++i) {
            results[i] = true;
          }
        }
      }
    }
    return results;
  }

  private static TypeDescription findColumn(TypeDescription schema, String column) {
    TypeDescription result = schema;
    String[] columnMatcher = column.split("\\.");

    int index = 0;
    while (index < columnMatcher.length &&
        result.getCategory() == TypeDescription.Category.STRUCT) {

      String columnName = columnMatcher[index];
      int prevIndex = index;

      List<TypeDescription> fields = result.getChildren();
      List<String> fieldNames = result.getFieldNames();

      for (int i = 0; i < fields.size(); i++) {
        if (columnName.equalsIgnoreCase(fieldNames.get(i))) {
          result = fields.get(i);
          index++;

          break;
        }
      }
      if (prevIndex == index) {
        return null;
      }
    }
    return result;
  }

  public static List<OrcProto.Type> getOrcTypes(TypeDescription typeDescr) {
    List<OrcProto.Type> result = new ArrayList<>();
    appendOrcTypes(result, typeDescr);
    return result;
  }

  private static void appendOrcTypes(List<OrcProto.Type> result, TypeDescription typeDescr) {
    OrcProto.Type.Builder type = OrcProto.Type.newBuilder();
    List<TypeDescription> children = typeDescr.getChildren();
    // save the attributes
    for(String key: typeDescr.getAttributeNames()) {
      type.addAttributes(
          OrcProto.StringPair.newBuilder()
              .setKey(key).setValue(typeDescr.getAttributeValue(key))
              .build());
    }
    switch (typeDescr.getCategory()) {
    case BOOLEAN:
      type.setKind(OrcProto.Type.Kind.BOOLEAN);
      break;
    case BYTE:
      type.setKind(OrcProto.Type.Kind.BYTE);
      break;
    case SHORT:
      type.setKind(OrcProto.Type.Kind.SHORT);
      break;
    case INT:
      type.setKind(OrcProto.Type.Kind.INT);
      break;
    case LONG:
      type.setKind(OrcProto.Type.Kind.LONG);
      break;
    case FLOAT:
      type.setKind(OrcProto.Type.Kind.FLOAT);
      break;
    case DOUBLE:
      type.setKind(OrcProto.Type.Kind.DOUBLE);
      break;
    case STRING:
      type.setKind(OrcProto.Type.Kind.STRING);
      break;
    case CHAR:
      type.setKind(OrcProto.Type.Kind.CHAR);
      type.setMaximumLength(typeDescr.getMaxLength());
      break;
    case VARCHAR:
      type.setKind(OrcProto.Type.Kind.VARCHAR);
      type.setMaximumLength(typeDescr.getMaxLength());
      break;
    case BINARY:
      type.setKind(OrcProto.Type.Kind.BINARY);
      break;
    case TIMESTAMP:
      type.setKind(OrcProto.Type.Kind.TIMESTAMP);
      break;
    case TIMESTAMP_INSTANT:
        type.setKind(OrcProto.Type.Kind.TIMESTAMP_INSTANT);
        break;
    case DATE:
      type.setKind(OrcProto.Type.Kind.DATE);
      break;
    case DECIMAL:
      type.setKind(OrcProto.Type.Kind.DECIMAL);
      type.setPrecision(typeDescr.getPrecision());
      type.setScale(typeDescr.getScale());
      break;
    case LIST:
      type.setKind(OrcProto.Type.Kind.LIST);
      type.addSubtypes(children.get(0).getId());
      break;
    case MAP:
      type.setKind(OrcProto.Type.Kind.MAP);
      for(TypeDescription t: children) {
        type.addSubtypes(t.getId());
      }
      break;
    case STRUCT:
      type.setKind(OrcProto.Type.Kind.STRUCT);
      for(TypeDescription t: children) {
        type.addSubtypes(t.getId());
      }
      for(String field: typeDescr.getFieldNames()) {
        type.addFieldNames(field);
      }
      break;
    case UNION:
      type.setKind(OrcProto.Type.Kind.UNION);
      for(TypeDescription t: children) {
        type.addSubtypes(t.getId());
      }
      break;
    default:
      throw new IllegalArgumentException("Unknown category: " +
          typeDescr.getCategory());
    }
    result.add(type.build());
    if (children != null) {
      for(TypeDescription child: children) {
        appendOrcTypes(result, child);
      }
    }
  }

  /**
   * Checks whether the list of protobuf types from the file are valid or not.
   * @param types the list of types from the protobuf
   * @param root the top of the tree to check
   * @return the next available id
   * @throws java.io.IOException if the tree is invalid
   */
  public static int isValidTypeTree(List<OrcProto.Type> types,
                                    int root) throws IOException  {
    if (root < 0 || root >= types.size()) {
      throw new IOException("Illegal type id " + root +
          ". The valid range is 0 to " + (types.size() - 1));
    }
    OrcProto.Type rootType = types.get(root);
    int current = root+1;
    List<Integer> children = rootType.getSubtypesList();
    if (!rootType.hasKind()) {
      throw new IOException("Type " + root + " has an unknown kind.");
    }
    // ensure that we have the right number of children
    switch(rootType.getKind()) {
      case LIST:
        if (children == null || children.size() != 1) {
          throw new IOException("Wrong number of type children in list " + root);
        }
        break;
      case MAP:
        if (children == null || children.size() != 2) {
          throw new IOException("Wrong number of type children in map " + root);
        }
        break;
      case UNION:
      case STRUCT:
        break;
      default:
        if (children != null && children.size() != 0) {
          throw new IOException("Type children under primitive type " + root);
        }
    }
    // ensure the children are also correct
    if (children != null) {
      for(int child: children) {
        if (child != current) {
          throw new IOException("Unexpected child type id " + child + " when " +
              current + " was expected.");
        }
        current = isValidTypeTree(types, current);
      }
    }
    return current;
  }
  /**
   * Translate the given rootColumn from the list of types to a TypeDescription.
   * @param types all of the types
   * @param rootColumn translate this type
   * @return a new TypeDescription that matches the given rootColumn
   */
  public static
        TypeDescription convertTypeFromProtobuf(List<OrcProto.Type> types,
                                                int rootColumn)
          throws FileFormatException {
    OrcProto.Type type = types.get(rootColumn);
    TypeDescription result;
    switch (type.getKind()) {
      case BOOLEAN:
        result = TypeDescription.createBoolean();
        break;
      case BYTE:
        result = TypeDescription.createByte();
        break;
      case SHORT:
        result = TypeDescription.createShort();
        break;
      case INT:
        result = TypeDescription.createInt();
        break;
      case LONG:
        result = TypeDescription.createLong();
        break;
      case FLOAT:
        result = TypeDescription.createFloat();
        break;
      case DOUBLE:
        result = TypeDescription.createDouble();
        break;
      case STRING:
        result = TypeDescription.createString();
        break;
      case CHAR:
      case VARCHAR: {
          result = type.getKind() == OrcProto.Type.Kind.CHAR ?
              TypeDescription.createChar() : TypeDescription.createVarchar();
          if (type.hasMaximumLength()) {
            result.withMaxLength(type.getMaximumLength());
          }
        }
        break;
      case BINARY:
        result = TypeDescription.createBinary();
        break;
      case TIMESTAMP:
        result = TypeDescription.createTimestamp();
        break;
      case TIMESTAMP_INSTANT:
        result = TypeDescription.createTimestampInstant();
        break;
      case DATE:
        result = TypeDescription.createDate();
        break;
      case DECIMAL: {
          result = TypeDescription.createDecimal();
          if (type.hasScale()) {
            result.withScale(type.getScale());
          }
          if (type.hasPrecision()) {
            result.withPrecision(type.getPrecision());
          }
        }
        break;
      case LIST:
        if (type.getSubtypesCount() != 1) {
          throw new FileFormatException("LIST type should contain exactly " +
                  "one subtype but has " + type.getSubtypesCount());
        }
        result = TypeDescription.createList(
            convertTypeFromProtobuf(types, type.getSubtypes(0)));
        break;
      case MAP:
        if (type.getSubtypesCount() != 2) {
          throw new FileFormatException("MAP type should contain exactly " +
                  "two subtypes but has " + type.getSubtypesCount());
        }
        result = TypeDescription.createMap(
            convertTypeFromProtobuf(types, type.getSubtypes(0)),
            convertTypeFromProtobuf(types, type.getSubtypes(1)));
        break;
      case STRUCT: {
          result = TypeDescription.createStruct();
          for(int f=0; f < type.getSubtypesCount(); ++f) {
            result.addField(type.getFieldNames(f),
                convertTypeFromProtobuf(types, type.getSubtypes(f)));
          }
        }
        break;
      case UNION: {
          if (type.getSubtypesCount() == 0) {
            throw new FileFormatException("UNION type should contain at least" +
                  " one subtype but has none");
          }
          result = TypeDescription.createUnion();
          for(int f=0; f < type.getSubtypesCount(); ++f) {
            result.addUnionChild(
                convertTypeFromProtobuf(types, type.getSubtypes(f)));
          }
        }
        break;
      default:
        throw new IllegalArgumentException("Unknown ORC type " + type.getKind());
    }
    for(int i = 0; i < type.getAttributesCount(); ++i) {
      OrcProto.StringPair pair = type.getAttributes(i);
      result.setAttribute(pair.getKey(), pair.getValue());
    }
    return result;
  }

  public static List<StripeInformation> convertProtoStripesToStripes(
      List<OrcProto.StripeInformation> stripes) {
    List<StripeInformation> result = new ArrayList<>(stripes.size());
    long previousStripeId = 0;
    byte[][] previousKeys = null;
    long stripeId = 0;
    for (OrcProto.StripeInformation stripeProto: stripes) {
      ReaderImpl.StripeInformationImpl stripe =
          new ReaderImpl.StripeInformationImpl(stripeProto, stripeId++,
              previousStripeId, previousKeys);
      result.add(stripe);
      previousStripeId = stripe.getEncryptionStripeId();
      previousKeys = stripe.getEncryptedLocalKeys();
    }
    return result;
  }
}


var mkdirp = require('../').mkdirp;
var path = require('path');
var fs = require('fs');
var test = require('tap').test;

test('race', function (t) {
    t.plan(4);
    var ps = [ '', 'tmp' ];

    for (var i = 0; i < 25; i++) {
        var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
        ps.push(dir);
    }
    var file = ps.join('/');

    var res = 2;
    mk(file, function () {
        if (--res === 0) t.end();
    });

    mk(file, function () {
        if (--res === 0) t.end();
    });

    function mk (file, cb) {
        mkdirp(file, 0755, function (err) {
            if (err) t.fail(err);
            else path.exists(file, function (ex) {
                if (!ex) t.fail('file not created')
                else fs.stat(file, function (err, stat) {
                    if (err) t.fail(err)
                    else {
                        t.equal(stat.mode & 0777, 0755);
                        t.ok(stat.isDirectory(), 'target not a directory');
                        if (cb) cb();
                    }
                })
            })
        });
    }
});


module CommonCrypto [system] [extern_c] {
  umbrella header "CommonCrypto.h"
  export *
  module * { export * }

  module Error {
      header "CommonCryptoError.h"
      export *
  }

  module Random {
      header "CommonRandom.h"
      export *
  }
}


#!./perl

BEGIN {
    chdir 't' if -d 't';
    require "./test.pl";
    set_up_inc(qw(. ../lib));
}

plan( tests => 47 );

$x = 10000;
cmp_ok(0 + ++$x - 1,'==',10000,'scalar ++x - 1');
cmp_ok(0 + $x-- - 1,'==',10000,'scalar x-- - 1');
cmp_ok(1 * $x,      '==',10000,'scalar 1 * x');
cmp_ok(0 + $x-- - 0,'==',10000,'scalar x-- - 0');
cmp_ok(1 + $x,      '==',10000,'scalar 1 + x');
cmp_ok(1 + $x++,    '==',10000,'scalar 1 + x++');
cmp_ok(0 + $x,      '==',10000,'scalar x');
cmp_ok(0 + --$x + 1,'==',10000,'scalar --x + 1');
cmp_ok(0 + ++$x + 0,'==',10000,'scalar ++x + 0');
cmp_ok($x,          '==',10000,'scalar x final');

$x[0] = 10000;
cmp_ok(0 + ++$x[0] - 1,'==',10000,'aelem ++x - 1');
cmp_ok(0 + $x[0]-- - 1,'==',10000,'aelem x-- - 1');
cmp_ok(1 * $x[0],      '==',10000,'aelem 1 * x');
cmp_ok(0 + $x[0]-- - 0,'==',10000,'aelem x-- - 0');
cmp_ok(1 + $x[0],      '==',10000,'aelem 1 + x');
cmp_ok(1 + $x[0]++,    '==',10000,'aelem 1 + x++');
cmp_ok(0 + $x[0],      '==',10000,'aelem x');
cmp_ok(0 + --$x[0] + 1,'==',10000,'aelem --x + 1');
cmp_ok(0 + ++$x[0] + 0,'==',10000,'aelem ++x + 0');
cmp_ok($x[0],          '==',10000,'aelem x final');

$x{0} = 10000;
cmp_ok(0 + ++$x{0} - 1,'==',10000,'helem ++x - 1');
cmp_ok(0 + $x{0}-- - 1,'==',10000,'helem x-- - 1');
cmp_ok(1 * $x{0},      '==',10000,'helem 1 * x');
cmp_ok(0 + $x{0}-- - 0,'==',10000,'helem x-- - 0');
cmp_ok(1 + $x{0},      '==',10000,'helem 1 + x');
cmp_ok(1 + $x{0}++,    '==',10000,'helem 1 + x++');
cmp_ok(0 + $x{0},      '==',10000,'helem x');
cmp_ok(0 + --$x{0} + 1,'==',10000,'helem --x + 1');
cmp_ok(0 + ++$x{0} + 0,'==',10000,'helem ++x + 0');
cmp_ok($x{0},          '==',10000,'helem x final');

# test magical autoincrement

cmp_ok(++($foo = '99'), 'eq','100','99 incr 100');
cmp_ok(++($foo = "99a"), 'eq','100','99a incr 100');
cmp_ok(++($foo = "99\0a"), 'eq','100','99\0a incr 100');
cmp_ok(++($foo = 'a0'), 'eq','a1','a0 incr a1');
cmp_ok(++($foo = 'Az'), 'eq','Ba','Az incr Ba');
cmp_ok(++($foo = 'zz'), 'eq','aaa','zzz incr aaa');
cmp_ok(++($foo = 'A99'),'eq','B00','A99 incr B00');
cmp_ok(++($foo = 'zi'), 'eq','zj','zi incr zj (EBCDIC i,j non-contiguous check)');
cmp_ok(++($foo = 'zr'), 'eq','zs','zr incr zs (EBCDIC r,s non-contiguous check)');

# test with glob copies

for(qw '$x++ ++$x $x-- --$x') {
  my $x = *foo;
  ok eval "$_; 1", "$_ does not die on a glob copy";
  is $x, /-/ ? -1 : 1, "result of $_ on a glob copy";
}


#! /bin/luavar
-- SPDX-License-Identifier: GPL-2.0-or-later

lineno = 0;
rc = 0;

while true do
	local line = io.read("*line");
	if (line == nil) then
		if (lineno == 0) then
			io.stderr:write("Missing requests\n");
			os.exit(2);
		end
		break;
	end
	lineno = lineno + 1;
	local varname, query = string.match(line, "(.*)=(.*)");
	if (varname ~= nil and query ~= nil) then
		if (string.find(query, "%(.*%)") == nil) then
			local single_res = box.query(query);
			if (single_res == nil) then
				print(varname.."=\"***no result***\"");
				rc = 1;
			else
				print(varname.."=\""..single_res.."\"");
			end
		else
			local columns = {};
			local first, last = string.find(query, "%(.*%)");
			local list = string.sub(query, first + 1, last - 1);
			for col in string.gmatch(list, "[^,]+") do
				table.insert(columns, col);
			end
			if (string.find(query, "listwindow%(.*%)") ~= nil) then
				table.remove(columns, 1);
				table.remove(columns, 1);
			end
			local result = box.multiquery(query);
			local index = 0;
			for i, entry in ipairs(result) do
				for j, value in ipairs(entry) do
					j = j - 1;
					if (j > 0) then
						colname = columns[j];
					else
						colname = "index";
					end
					print(varname.."_"..i.."_"..colname.."=\""..value.."\"");
				end
				index = i;
			end
			print(varname.."_count="..index);
		end
	else
		io.stderr:write("Malformed request at line ",lineno,"\n");
		rc = 127;
-- die folgende Zeile aktivieren (-- am Beginn entfernen), um bei falscher Eingabe die Verarbeitung abzubrechen
--		break;
	end
end

os.exit(rc);


// Static assertions

// C++03 provides two methods to test assertions: the macro assert and the preprocessor directive #error.
// However, neither is appropriate for use in templates: the macro tests the assertion at execution-time,
// while the preprocessor directive tests the assertion during preprocessing, which happens before
// instantiation of templates. Neither is appropriate for testing properties that are dependent on
// template parameters.

// The new utility introduces a new way to test assertions at compile-time, using the new keyword
// static_assert. The declaration assumes the following form:

// static_assert (constant-expression, error-message);

#include<type_traits>

// Here are some examples of how static_assert can be used:

const int GREEKPI = 4;

// static_assert((GREEKPI > 3.14) && (GREEKPI < 3.15), "GREEKPI is inaccurate!");
static_assert((GREEKPI > 2) && (GREEKPI < 5), "GREEKPI is inaccurate!");

template<class T>
struct Check  {
    static_assert(sizeof(int) <= sizeof(T), "T is not big enough!");
};

template<class Integral>
Integral foo(Integral x, Integral y) {
    static_assert(std::is_integral<Integral>::value, "foo() parameter must be an integral type.");
}

// When the constant expression is false the compiler produces an error message. The first example
// represents an alternative to the preprocessor directive #error, in contrast in the second example
// the assertion is checked at every instantiation of the template class Check.

// Static assertions are useful outside of templates as well. For instance, a particular implementation
// of an algorithm might depend on the size of a long long being larger than an int, something the
// standard does not guarantee. Such an assumption is valid on most systems and compilers, but not all.


#begin document (wb/sel/89/sel_8977); part 000
wb/sel/89/sel_8977   -1    0    [WORD]     XX   (TOP*         -   -   -   -   *   -
wb/sel/89/sel_8977   -1    1    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1    2    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1    3    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1    4    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1    5    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1    6    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1    7    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1    8    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1    9    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   10    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   11    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   12    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   13    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   14    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   15    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   16    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   17    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   18    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   19    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   20    [WORD]   VERB       *      rerun  -   1   -   *   -
wb/sel/89/sel_8977   -1   21    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   22    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   23    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   24    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   25    [WORD]     XX       *         -   -   -   -   *   -
wb/sel/89/sel_8977   -1   26    [WORD]     XX       *)        -   -   -   -   *   -

#end document


// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef IOS_CHROME_BROWSER_UI_CONTEXT_MENU_CONTEXT_MENU_COORDINATOR_H_
#define IOS_CHROME_BROWSER_UI_CONTEXT_MENU_CONTEXT_MENU_COORDINATOR_H_

#import <UIKit/UIKit.h>

#include "base/ios/block_types.h"

namespace web {
struct ContextMenuParams;
}

// Abstracts displaying context menus for all device form factors. Will show a
// sheet on the phone and use a popover on a tablet.
@interface ContextMenuCoordinator : NSObject

// Whether the context menu is visible. This will be true after |-start| is
// called until a subsequent |-stop|.
@property(nonatomic, readonly, getter=isVisible) BOOL visible;

// Initializes with details provided in |params|. Context menu will be presented
// from |viewController|.
- (instancetype)initWithViewController:(UIViewController*)viewController
                                params:(const web::ContextMenuParams&)params;

// Adds an item at the end of the menu if |visible| is false.
- (void)addItemWithTitle:(NSString*)title action:(ProceduralBlock)action;

// Displays the context menu.
- (void)start;
// Dismisses the context menu. Any menu items which have been added will be
// cleared after this call.
- (void)stop;

@end

#endif  // IOS_CHROME_BROWSER_UI_CONTEXT_MENU_CONTEXT_MENU_COORDINATOR_H_


/*
 * Copyright (C) 2020. by onlymash <im@fiepi.me>, All rights reserved
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

package onlymash.flexbooru.data.repository.favorite

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import onlymash.flexbooru.app.App
import onlymash.flexbooru.R
import onlymash.flexbooru.app.Values.BOORU_TYPE_DAN
import onlymash.flexbooru.app.Values.BOORU_TYPE_DAN1
import onlymash.flexbooru.app.Values.BOORU_TYPE_GEL
import onlymash.flexbooru.app.Values.BOORU_TYPE_MOE
import onlymash.flexbooru.data.action.ActionVote
import onlymash.flexbooru.data.api.BooruApis
import onlymash.flexbooru.data.database.dao.PostDao
import onlymash.flexbooru.extension.NetResult
import retrofit2.HttpException

class VoteRepositoryImpl(
    private val booruApis: BooruApis,
    private val postDao: PostDao
): VoteRepository {

    override suspend fun addFav(action: ActionVote): NetResult<Boolean> {
        return when (action.booru.type) {
            BOORU_TYPE_DAN -> addDanFav(action)
            BOORU_TYPE_DAN1 -> addDan1Fav(action)
            BOORU_TYPE_MOE -> voteMoePost(action, 3)
            BOORU_TYPE_GEL -> addGelFav(action)
            else -> addSankakuFav(action)
        }
    }

    override suspend fun removeFav(action: ActionVote): NetResult<Boolean> {
        return when (action.booru.type) {
            BOORU_TYPE_DAN -> removeDanFav(action)
            BOORU_TYPE_DAN1 -> removeDan1Fav(action)
            BOORU_TYPE_MOE -> voteMoePost(action, 0)
            BOORU_TYPE_GEL -> removeGelFav()
            else -> removeSankakuFav(action)
        }
    }

    private suspend fun addGelFav(action: ActionVote): NetResult<Boolean> {
        return withContext(Dispatchers.IO) {
            try {
                val response = booruApis.gelApi.favPost(
                    cookie = action.booru.user?.gelCookie,
                    httpUrl = action.getGelAddFavUrl()
                )
                if (response.isSuccessful) {
                    postDao.updateFav(booruUid = action.booru.uid, postId = action.postId, isFavored = true)
                    NetResult.Success(true)
                } else {
                    NetResult.Error("code: ${response.code()}")
                }
            } catch (e: Exception) {
                NetResult.Error(e.message.toString())
            }
        }
    }

    private fun removeGelFav(): NetResult<Boolean> {
        return NetResult.Error("Not supported")
    }

    private suspend fun voteMoePost(action: ActionVote, score: Int): NetResult<Boolean> {
        return withContext(Dispatchers.IO) {
            try {
                val response = booruApis.moeApi.votePost(
                    url = action.getMoeVoteUrl(),
                    id = action.postId,
                    score = score,
                    username = action.booru.user?.name ?: "",
                    passwordHash = action.booru.user?.token ?: ""
                )
                if (response.isSuccessful) {
                    postDao.updateFav(booruUid = action.booru.uid, postId = action.postId, isFavored = score != 0)
                    NetResult.Success(true)
                } else {
                    NetResult.Error("code: ${response.code()}")
                }
            } catch (e: Exception) {
                if (e is HttpException) {
                    val code = e.code()
                    if (code == 403) {
                        NetResult.Error(App.app.getString(R.string.msg_password_or_hash_salt_wrong))
                    } else {
                        NetResult.Error("code: $code")
                    }
                } else NetResult.Error(e.message.toString())
            }
        }
    }

    private suspend fun addDanFav(action: ActionVote): NetResult<Boolean> {
        return withContext(Dispatchers.IO) {
            try {
                val response = booruApis.danApi.favPost(
                    url = action.getDanAddFavUrl(),
                    id = action.postId,
                    username = action.booru.user?.name ?: "",
                    apiKey = action.booru.user?.token ?: ""
                )
                if (response.isSuccessful) {
                    postDao.updateFav(booruUid = action.booru.uid, postId = action.postId, isFavored = true)
                    NetResult.Success(true)
                } else {
                    NetResult.Error("code: ${response.code()}")
                }
            } catch (e: Exception) {
                if (e is HttpException) {
                    val code = e.code()
                    if (code == 500) {
                        postDao.updateFav(booruUid = action.booru.uid, postId = action.postId, isFavored = true)
                        NetResult.Success(true)
                    } else NetResult.Error("code: ${e.code()}")
                } else NetResult.Error(e.message.toString())
            }
        }
    }

    private suspend fun removeDanFav(action: ActionVote): NetResult<Boolean> {
        return withContext(Dispatchers.IO) {
            try {
                val response = booruApis.danApi.removeFavPost(action.getDanRemoveFavUrl())
                if (response.isSuccessful) {
                    postDao.updateFav(booruUid = action.booru.uid, postId = action.postId, isFavored = false)
                    NetResult.Success(true)
                } else {
                    NetResult.Error("code: ${response.code()}")
                }
            } catch (e: Exception) {
                if (e is HttpException)
                    NetResult.Error("code: ${e.code()}")
                else
                    NetResult.Error(e.message.toString())
            }
        }
    }

    private suspend fun addDan1Fav(action: ActionVote): NetResult<Boolean> {
        return withContext(Dispatchers.IO) {
            try {
                val response = booruApis.dan1Api.favPost(
                    url = action.getDan1RemoveFavUrl(),
                    id = action.postId,
                    username = action.booru.user?.name ?: "",
                    passwordHash = action.booru.user?.token ?: ""
                )
                if (response.isSuccessful) {
                    postDao.updateFav(booruUid = action.booru.uid, postId = action.postId, isFavored = true)
                    NetResult.Success(true)
                } else {
                    NetResult.Error("code: ${response.code()}")
                }
            } catch (e: Exception) {
                if (e is HttpException)
                    NetResult.Error("code: ${e.code()}")
                else
                    NetResult.Error(e.message.toString())
            }
        }
    }

    private suspend fun removeDan1Fav(action: ActionVote): NetResult<Boolean> {
        return withContext(Dispatchers.IO) {
            try {
                val response = booruApis.dan1Api.removeFavPost(
                    url = action.getDan1RemoveFavUrl(),
                    postId = action.postId,
                    username = action.booru.user?.name ?: "",
                    passwordHash = action.booru.user?.token ?: ""
                )
                if (response.isSuccessful) {
                    postDao.updateFav(booruUid = action.booru.uid, postId = action.postId, isFavored = false)
                    NetResult.Success(true)
                } else {
                    NetResult.Error("code: ${response.code()}")
                }
            } catch (e: Exception) {
                if (e is HttpException)
                    NetResult.Error("code: ${e.code()}")
                else
                    NetResult.Error(e.message.toString())
            }
        }
    }

    private suspend fun addSankakuFav(action: ActionVote): NetResult<Boolean> {
        return withContext(Dispatchers.IO) {
            try {
                val response = booruApis.sankakuApi.favPost(
                    url = action.getSankakuAddFavUrl(),
                    postId = action.postId,
                    username = action.booru.user?.name ?: "",
                    passwordHash = action.booru.user?.token ?: ""
                )
                if (response.isSuccessful || response.code() == 423) {
                    postDao.updateFav(booruUid = action.booru.uid, postId = action.postId, isFavored = true)
                    NetResult.Success(true)
                } else {
                    NetResult.Error("code: ${response.code()}")
                }
            } catch (e: Exception) {
                if (e is HttpException)
                    NetResult.Error("code: ${e.code()}")
                else
                    NetResult.Error(e.message.toString())
            }
        }
    }

    private suspend fun removeSankakuFav(action: ActionVote): NetResult<Boolean> {
        return withContext(Dispatchers.IO) {
            try {
                val response = booruApis.sankakuApi.removeFavPost(
                    url = action.getSankakuRemoveFavUrl(),
                    postId = action.postId,
                    username = action.booru.user?.name ?: "",
                    passwordHash = action.booru.user?.token ?: ""
                )
                if (response.isSuccessful) {
                    postDao.updateFav(booruUid = action.booru.uid, postId = action.postId, isFavored = false)
                    NetResult.Success(true)
                } else {
                    NetResult.Error("code: ${response.code()}")
                }
            } catch (e: Exception) {
                if (e is HttpException)
                    NetResult.Error("code: ${e.code()}")
                else
                    NetResult.Error(e.message.toString())
            }
        }
    }
}


#include "trick/rand_generator.h"


<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
<title>SSL/TLS Strong Encryption: How-To - Apache HTTP Server Version 2.4</title>
<link href="../style/css/manual-zip.css" rel="stylesheet" media="all" type="text/css" title="Main stylesheet" />
<link href="../style/css/manual-zip-100pc.css" rel="alternate stylesheet" media="all" type="text/css" title="No Sidebar - Default font size" />
<link href="../style/css/manual-print.css" rel="stylesheet" media="print" type="text/css" /><link rel="stylesheet" type="text/css" href="../style/css/prettify.css" />

Modules | Directives | FAQ | Glossary | Sitemap

Apache HTTP Server Version 2.4

Apache > HTTP Server > Documentation > Version 2.4 > SSL/TLS

SSL/TLS Strong Encryption: How-To

This documented is intended to get you started, and get a few things
working. You are strongly encouraged to read the rest of the SSL
documentation, and arrive at a deeper understanding of the material,
before progressing to the advanced techniques.

 Basic Configuration Example

 Cipher Suites and Enforcing Strong Security

 OCSP Stapling

 Client Authentication and Access Control

 Logging

Basic Configuration Example

Your SSL configuration will need to contain, at minimum, the
following directives.

LoadModule ssl_module modules/mod_ssl.so

Listen 443
<VirtualHost *:443>
    ServerName www.example.com
    SSLEngine on
    SSLCertificateFile /path/to/www.example.com.cert
    SSLCertificateKeyFile /path/to/www.example.com.key
</VirtualHost>

Cipher Suites and Enforcing Strong Security

How can I create an SSL server which accepts strong encryption only?

How can I create an SSL server which accepts all types of ciphers in general, but
requires a strong cipher for access to a particular URL?

How can I create an SSL server which accepts strong encryption
only?

The following enables only the strongest ciphers:

SSLCipherSuite HIGH:!aNULL:!MD5

While with the following configuration you specify a preference
    for specific speed-optimized ciphers (which will be selected by
    mod_ssl, provided that they are supported by the client):

SSLCipherSuite RC4-SHA:AES128-SHA:HIGH:!aNULL:!MD5
SSLHonorCipherOrder on

How can I create an SSL server which accepts all types of ciphers
in general, but requires a strong ciphers for access to a particular
URL?

Obviously, a server-wide SSLCipherSuite which restricts
    ciphers to the strong variants, isn't the answer here. However,
    mod_ssl can be reconfigured within Location
    blocks, to give a per-directory solution, and can automatically force
    a renegotiation of the SSL parameters to meet the new configuration.
    This can be done as follows:

# be liberal in general
SSLCipherSuite ALL:!aNULL:RC4+RSA:+HIGH:+MEDIUM:+LOW:+EXP:+eNULL

<Location /strong/area>
# but https://hostname/strong/area/ and below
# requires strong ciphers
SSLCipherSuite HIGH:!aNULL:!MD5
</Location>

OCSP Stapling

The Online Certificate Status Protocol (OCSP) is a mechanism for
determining whether or not a server certificate has been revoked, and OCSP
Stapling is a special form of this in which the server, such as httpd and
mod_ssl, maintains current OCSP responses for its certificates and sends
them to clients which communicate with the server.  Most certificates
contain the address of an OCSP responder maintained by the issuing
Certificate Authority, and mod_ssl can communicate with that responder to
obtain a signed response that can be sent to clients communicating with
the server.

Because the client can obtain the certificate revocation status from
the server, without requiring an extra connection from the client to the
Certificate Authority, OCSP Stapling is the preferred way for the
revocation status to be obtained.  Other benefits of eliminating the
communication between clients and the Certificate Authority are that the
client browsing history is not exposed to the Certificate Authority and
obtaining status is more reliable by not depending on potentially heavily
loaded Certificate Authority servers.

Because the response obtained by the server can be reused for all clients
using the same certificate during the time that the response is valid, the
overhead for the server is minimal.

Once general SSL support has been configured properly, enabling OCSP
Stapling generally requires only very minor modifications to the httpd
configuration — the addition of these two directives:

SSLUseStapling On
SSLStaplingCache "shmcb:logs/ssl_stapling(32768)"

These directives are placed at global scope (i.e., not within a virtual
host definition) wherever other global SSL configuration directives are
placed, such as in conf/extra/httpd-ssl.conf for normal
open source builds of httpd, /etc/apache2/mods-enabled/ssl.conf
for the Ubuntu or Debian-bundled httpd, etc.

The path on the SSLStaplingCache directive
(e.g., logs/) should match the one on the
SSLSessionCache directive.  This path is relative
to ServerRoot.

This particular SSLStaplingCache directive requires
mod_socache_shmcb (from the shmcb prefix on the
directive's argument).  This module is usually enabled already for
SSLSessionCache or on behalf of some module other than
mod_ssl.  If you enabled an SSL session cache using a
mechanism other than mod_socache_shmcb, use that alternative
mechanism for SSLStaplingCache as well.  For example:

SSLSessionCache "dbm:logs/ssl_scache"
SSLStaplingCache "dbm:logs/ssl_stapling"

You can use the openssl command-line program to verify that an OCSP response
is sent by your server:

$ openssl s_client -connect www.example.com:443 -status -servername www.example.com
...
OCSP response:
======================================
OCSP Response Data:
    OCSP Response Status: successful (0x0)
    Response Type: Basic OCSP Response
...
    Cert Status: Good
...

The following sections highlight the most common situations which require
further modification to the configuration.  Refer also to the
mod_ssl reference manual.

If more than a few SSL certificates are used for the server

OCSP responses are stored in the SSL stapling cache.  While the responses
are typically a few hundred to a few thousand bytes in size, mod_ssl
supports OCSP responses up to around 10K bytes in size.  With more than a
few certificates, the stapling cache size (32768 bytes in the example above)
may need to be increased.  Error message AH01929 will be logged in case of
an error storing a response.

If the certificate does not point to an OCSP responder, or if a
different address must be used

Refer to the
SSLStaplingForceURL directive.

You can confirm that a server certificate points to an OCSP responder
using the openssl command-line program, as follows:

$ openssl x509 -in ./www.example.com.crt -text | grep 'OCSP.*http'
OCSP - URI:http://ocsp.example.com

If the OCSP URI is provided and the web server can communicate to it
directly without using a proxy, no configuration is required.  Note that
firewall rules that control outbound connections from the web server may
need to be adjusted.

If no OCSP URI is provided, contact your Certificate Authority to
determine if one is available; if so, configure it with
SSLStaplingForceURL in the virtual
host that uses the certificate.

If multiple SSL-enabled virtual hosts are configured and OCSP
Stapling should be disabled for some

Add SSLUseStapling Off to the virtual hosts for which OCSP
Stapling should be disabled.

If the OCSP responder is slow or unreliable

Several directives are available to handle timeouts and errors.  Refer
to the documentation for the
SSLStaplingFakeTryLater,
SSLStaplingResponderTimeout, and
SSLStaplingReturnResponderErrors
directives.

If mod_ssl logs error AH02217

AH02217: ssl_stapling_init_cert: Can't retrieve issuer certificate!

In order to support OCSP Stapling when a particular server certificate is
used, the certificate chain for that certificate must be configured.  If it
was not configured as part of enabling SSL, the AH02217 error will be issued
when stapling is enabled, and an OCSP response will not be provided for clients
using the certificate.

Refer to the SSLCertificateChainFile
and SSLCertificateFile for instructions
for configuring the certificate chain.

Client Authentication and Access Control

How can I force clients to authenticate using certificates?

How can I force clients to authenticate using certificates for a
        particular URL, but still allow arbitrary clients to access the rest of the server?

How can I allow only clients who have certificates to access a
        particular URL, but allow all clients to access the rest of the server?

How can I require HTTPS with strong ciphers, and either
basic authentication or client certificates, for access to part of the
Intranet website, for clients coming from the Internet?

How can I force clients to authenticate using certificates?

When you know all of your users (eg, as is often the case on a corporate
    Intranet), you can require plain certificate authentication. All you
    need to do is to create client certificates signed by your own CA
    certificate (ca.crt) and then verify the clients against this
    certificate.

# require a client certificate which has to be directly
# signed by our CA certificate in ca.crt
SSLVerifyClient require
SSLVerifyDepth 1
SSLCACertificateFile conf/ssl.crt/ca.crt

How can I force clients to authenticate using certificates for a
  particular URL, but still allow arbitrary clients to access the rest of the server?

To force clients to authenticate using certificates for a particular URL,
    you can use the per-directory reconfiguration features of
    mod_ssl:

SSLVerifyClient none
SSLCACertificateFile conf/ssl.crt/ca.crt

<Location /secure/area>
SSLVerifyClient require
SSLVerifyDepth 1
</Location>

How can I allow only clients who have certificates to access a
  particular URL, but allow all clients to access the rest of the server?

The key to doing this is checking that part of the client certificate
    matches what you expect. Usually this means checking all or part of the
    Distinguished Name (DN), to see if it contains some known string.
    There are two ways to do this, using either mod_auth_basic or
    SSLRequire.

The mod_auth_basic method is generally required when
    the certificates are completely arbitrary, or when their DNs have
    no common fields (usually the organisation, etc.). In this case,
    you should establish a password database containing all
    clients allowed, as follows:

SSLVerifyClient      none
SSLCACertificateFile conf/ssl.crt/ca.crt
SSLCACertificatePath conf/ssl.crt

<Directory /usr/local/apache2/htdocs/secure/area>
    SSLVerifyClient      require
    SSLVerifyDepth       5
    SSLOptions           +FakeBasicAuth
    SSLRequireSSL
    AuthName             "Snake Oil Authentication"
    AuthType             Basic
    AuthBasicProvider    file
    AuthUserFile         /usr/local/apache2/conf/httpd.passwd
    Require              valid-user
</Directory>

The password used in this example is the DES encrypted string "password".
    See the SSLOptions docs for more
    information.

httpd.passwd

/C=DE/L=Munich/O=Snake Oil, Ltd./OU=Staff/CN=Foo:xxj31ZMTZzkVA
/C=US/L=S.F./O=Snake Oil, Ltd./OU=CA/CN=Bar:xxj31ZMTZzkVA
/C=US/L=L.A./O=Snake Oil, Ltd./OU=Dev/CN=Quux:xxj31ZMTZzkVA

When your clients are all part of a common hierarchy, which is encoded
    into the DN, you can match them more easily using SSLRequire, as follows:

SSLVerifyClient      none
SSLCACertificateFile conf/ssl.crt/ca.crt
SSLCACertificatePath conf/ssl.crt

<Directory /usr/local/apache2/htdocs/secure/area>
  SSLVerifyClient      require
  SSLVerifyDepth       5
  SSLOptions           +FakeBasicAuth
  SSLRequireSSL
  SSLRequire       %{SSL_CLIENT_S_DN_O}  eq "Snake Oil, Ltd." \
               and %{SSL_CLIENT_S_DN_OU} in {"Staff", "CA", "Dev"}
</Directory>

How can I require HTTPS with strong ciphers, and either basic
authentication or client certificates, for access to part of the
Intranet website, for clients coming from the Internet? I still want to allow
plain HTTP access for clients on the Intranet.

These examples presume that clients on the Intranet have IPs in the range
   192.168.1.0/24, and that the part of the Intranet website you want to allow
   internet access to is /usr/local/apache2/htdocs/subarea.
   This configuration should remain outside of your HTTPS virtual host, so
   that it applies to both HTTPS and HTTP.

SSLCACertificateFile conf/ssl.crt/company-ca.crt

<Directory /usr/local/apache2/htdocs>
    #   Outside the subarea only Intranet access is granted
    Require              ip 192.168.1.0/24
</Directory>

<Directory /usr/local/apache2/htdocs/subarea>
    #   Inside the subarea any Intranet access is allowed
    #   but from the Internet only HTTPS + Strong-Cipher + Password
    #   or the alternative HTTPS + Strong-Cipher + Client-Certificate

    #   If HTTPS is used, make sure a strong cipher is used.
    #   Additionally allow client certs as alternative to basic auth.
    SSLVerifyClient      optional
    SSLVerifyDepth       1
    SSLOptions           +FakeBasicAuth +StrictRequire
    SSLRequire           %{SSL_CIPHER_USEKEYSIZE} >= 128

    #   Force clients from the Internet to use HTTPS
    RewriteEngine        on
    RewriteCond          %{REMOTE_ADDR} !^192\.168\.1\.[0-9]+$
    RewriteCond          %{HTTPS} !=on
    RewriteRule          . - [F]

    #   Allow Network Access and/or Basic Auth
    Satisfy              any

    #   Network Access Control
    Require              ip 192.168.1.0/24

    #   HTTP Basic Authentication
    AuthType             basic
    AuthName             "Protected Intranet Area"
    AuthBasicProvider    file
    AuthUserFile         conf/protected.passwd
    Require              valid-user
</Directory>

Logging

mod_ssl can log extremely verbose debugging information
    to the error log, when its LogLevel is
    set to the higher trace levels. On the other hand, on a very busy server,
    level info may already be too much. Remember that you can
    configure the LogLevel per module to
    suite your needs.

Copyright 2015 The Apache Software Foundation.
Licensed under the Apache License, Version 2.0.

Modules | Directives | FAQ | Glossary | Sitemap


// code: 1
typedef int INT; typedef INT i;
         i main() { return 1; }


// This file is a part of Julia. License is MIT: https://julialang.org/license

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "dtypes.h"

#if defined(_OS_WINDOWS_)
#include <malloc.h>
#include <sys/timeb.h>
#include <windows.h>
#else
#include <sys/time.h>
#include <sys/poll.h>
#include <unistd.h>
#endif

#include "timefuncs.h"

#ifdef __cplusplus
extern "C" {
#endif

JL_DLLEXPORT int jl_gettimeofday(struct jl_timeval *jtv)
{
#if defined(_OS_WINDOWS_)
    struct __timeb64 tb;
    errno_t code = _ftime64_s(&tb);
    jtv->sec = tb.time;
    jtv->usec = tb.millitm * 1000;
#else
    struct timeval tv;
    int code = gettimeofday(&tv, NULL);
    jtv->sec = tv.tv_sec;
    jtv->usec = tv.tv_usec;
#endif
    return code;
}

JL_DLLEXPORT double jl_clock_now(void)
{
    struct jl_timeval now;
    jl_gettimeofday(&now);
    return now.sec + now.usec * 1e-6;
}

void sleep_ms(int ms)
{
    if (ms == 0)
        return;

#if defined(_OS_WINDOWS_)
    Sleep(ms);
#else
    struct timeval timeout;

    timeout.tv_sec = ms / 1000;
    timeout.tv_usec = (ms % 1000) * 1000;

    select(0, NULL, NULL, NULL, &timeout);
#endif
}

#ifdef __cplusplus
}
#endif


-----------------------------------
-- Area: Cloister of Gales
-- BCNM: Trial-size Trial by Wind
-----------------------------------
local ID = require("scripts/zones/Cloister_of_Gales/IDs")
require("scripts/globals/battlefield")
require("scripts/globals/quests")
-----------------------------------

function onBattlefieldTick(battlefield, tick)
    dsp.battlefield.onBattlefieldTick(battlefield, tick)
end

function onBattlefieldRegister(player, battlefield)
end

function onBattlefieldEnter(player, battlefield)
end

function onBattlefieldLeave(player, battlefield, leavecode)
    if leavecode == dsp.battlefield.leaveCode.WON then
        local name, clearTime, partySize = battlefield:getRecord()
        local arg8 = (player:getQuestStatus(OUTLANDS, dsp.quest.id.outlands.TRIAL_SIZE_TRIAL_BY_WIND) == QUEST_COMPLETED) and 1 or 0
        player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
    elseif leavecode == dsp.battlefield.leaveCode.LOST then
        player:setCharVar("TrialSizeWind_date", tonumber(os.date("%j"))) -- If you lose, you need to wait 1 real day
        player:startEvent(32002)
    end
end

function onEventUpdate(player, csid, option)
end

function onEventFinish(player, csid, option)
    if csid == 32001 then
        if not player:hasSpell(301) then
            player:addSpell(301)
            player:messageSpecial(ID.text.GARUDA_UNLOCKED, 0, 0, 3)
        end
        if not player:hasItem(4181) then
            player:addItem(4181) -- Scroll of instant warp
            player:messageSpecial(ID.text.ITEM_OBTAINED, 4181)
        end
        player:setCharVar("TrialSizeWind_date", 0)
        player:addFame(RABAO, 30)
        player:completeQuest(OUTLANDS, dsp.quest.id.outlands.TRIAL_SIZE_TRIAL_BY_WIND)
    end
end


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

package sinks

import (
	"fmt"
	"github.com/AliyunContainerService/kube-eventer/common/flags"
	"github.com/AliyunContainerService/kube-eventer/core"
	"github.com/AliyunContainerService/kube-eventer/sinks/dingtalk"
	"github.com/AliyunContainerService/kube-eventer/sinks/elasticsearch"
	"github.com/AliyunContainerService/kube-eventer/sinks/honeycomb"
	"github.com/AliyunContainerService/kube-eventer/sinks/influxdb"
	"github.com/AliyunContainerService/kube-eventer/sinks/kafka"
	"github.com/AliyunContainerService/kube-eventer/sinks/log"
	"github.com/AliyunContainerService/kube-eventer/sinks/mysql"
	"github.com/AliyunContainerService/kube-eventer/sinks/riemann"
	"github.com/AliyunContainerService/kube-eventer/sinks/sls"
	"github.com/AliyunContainerService/kube-eventer/sinks/webhook"
	"github.com/AliyunContainerService/kube-eventer/sinks/wechat"
	"k8s.io/klog"
)

type SinkFactory struct {
}

func (this *SinkFactory) Build(uri flags.Uri) (core.EventSink, error) {
	switch uri.Key {
	case "log":
		return logsink.CreateLogSink()
	case "influxdb":
		return influxdb.CreateInfluxdbSink(&uri.Val)
	case "mysql":
		return mysql.CreateMysqlSink(&uri.Val)
	case "elasticsearch":
		return elasticsearch.NewElasticSearchSink(&uri.Val)
	case "kafka":
		return kafka.NewKafkaSink(&uri.Val)
	case "riemann":
		return riemann.CreateRiemannSink(&uri.Val)
	case "honeycomb":
		return honeycomb.NewHoneycombSink(&uri.Val)
	case "dingtalk":
		return dingtalk.NewDingTalkSink(&uri.Val)
	case "sls":
		return sls.NewSLSSink(&uri.Val)
	case "wechat":
		return wechat.NewWechatSink(&uri.Val)
	case "webhook":
		return webhook.NewWebHookSink(&uri.Val)
	default:
		return nil, fmt.Errorf("Sink not recognized: %s", uri.Key)
	}
}

func (this *SinkFactory) BuildAll(uris flags.Uris) []core.EventSink {
	result := make([]core.EventSink, 0, len(uris))
	for _, uri := range uris {
		sink, err := this.Build(uri)
		if err != nil {
			klog.Errorf("Failed to create %v sink: %v", uri, err)
			continue
		}
		result = append(result, sink)
	}
	return result
}

func NewSinkFactory() *SinkFactory {
	return &SinkFactory{}
}


/* Copyright 2009-2020 David Hadka
 *
 * This file is part of the MOEA Framework.
 *
 * The MOEA Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * The MOEA Framework is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the MOEA Framework.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.moeaframework.algorithm;

import org.moeaframework.core.Initialization;
import org.moeaframework.core.NondominatedSortingPopulation;
import org.moeaframework.core.Population;
import org.moeaframework.core.Problem;
import org.moeaframework.core.Solution;
import org.moeaframework.core.comparator.DominanceComparator;
import org.moeaframework.core.operator.real.DifferentialEvolutionVariation;
import org.moeaframework.core.operator.real.DifferentialEvolutionSelection;

/**
 * Implementation of the Generalized Differential Evolution (GDE3) algorithm.
 *

 * References:
 *

 *
Kukkonen and Lampinen (2005). "GDE3: The Third Evolution Step of
 * Generalized Differential Evolution." KanGAL Report Number 2005013.
 *

 */
public class GDE3 extends AbstractEvolutionaryAlgorithm {

	/**
	 * The dominance comparator used to determine if offspring survive until
	 * the non-dominated sorting step.
	 */
	private final DominanceComparator comparator;

	/**
	 * The selection operator.
	 */
	private final DifferentialEvolutionSelection selection;

	/**
	 * The variation operator.
	 */
	private final DifferentialEvolutionVariation variation;

	/**
	 * Constructs the GDE3 algorithm with the specified components.
	 *
	 * @param problem the problem being solved
	 * @param population the population used to store solutions
	 * @param comparator the dominance comparator used to determine if offspring
	 *        survive until the non-dominated sorting step
	 * @param selection the selection operator
	 * @param variation the variation operator
	 * @param initialization the initialization method
	 */
	public GDE3(Problem problem, NondominatedSortingPopulation population,
			DominanceComparator comparator,
			DifferentialEvolutionSelection selection,
			DifferentialEvolutionVariation variation, Initialization initialization) {
		super(problem, population, null, initialization);
		this.comparator = comparator;
		this.selection = selection;
		this.variation = variation;
	}

	@Override
	public void iterate() {
		NondominatedSortingPopulation population = getPopulation();
		Population children = new Population();
		int populationSize = population.size();

		//generate children
		for (int i = 0; i < populationSize; i++) {
			selection.setCurrentIndex(i);

			Solution[] parents = selection.select(variation.getArity(),
					population);
			children.add(variation.evolve(parents)[0]);
		}

		//evaluate children
		evaluateAll(children);

		//determine composition of next population
		Population offspring = new Population();

		for (int i = 0; i < populationSize; i++) {
			int result = comparator.compare(children.get(i), population.get(i));

			if (result < 0) {
				offspring.add(children.get(i));
			} else if (result > 0) {
				offspring.add(population.get(i));
			} else {
				offspring.add(children.get(i));
				offspring.add(population.get(i));
			}
		}

		population.clear();
		population.addAll(offspring);
		population.prune(populationSize);
	}

	@Override
	public NondominatedSortingPopulation getPopulation() {
		return (NondominatedSortingPopulation)super.getPopulation();
	}

}


FUNCTION MULTINT(X,Y)
INTEGER MULTINT, X, Y
MULTINT = X * Y
END


//  (C) Copyright John Maddock 2018.
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).
//
//  See http://www.boost.org/libs/type_traits for most recent version including documentation.

#ifndef BOOST_TT_IS_FUNCTION_MSVC10_FIX_HPP_INCLUDED
#define BOOST_TT_IS_FUNCTION_MSVC10_FIX_HPP_INCLUDED

namespace boost {

template <class R> struct is_function<R(&&)()> : public false_type {};
template <class R> struct is_function<R(&&)(...)> : public false_type {};
template <class R, class Arg1> struct is_function<R(&&)(Arg1)> : public false_type {};
template <class R, class Arg1> struct is_function<R(&&)(Arg1, ...)> : public false_type {};
template <class R, class Arg1, class Arg2> struct is_function<R(&&)(Arg1, Arg2)> : public false_type {};
template <class R, class Arg1, class Arg2> struct is_function<R(&&)(Arg1, Arg2, ...)> : public false_type {};
template <class R, class Arg1, class Arg2, class Arg3> struct is_function<R(&&)(Arg1, Arg2, Arg3)> : public false_type {};
template <class R, class Arg1, class Arg2, class Arg3> struct is_function<R(&&)(Arg1, Arg2, Arg3, ...)> : public false_type {};
template <class R, class Arg1, class Arg2, class Arg3, class Arg4> struct is_function<R(&&)(Arg1, Arg2, Arg3, Arg4)> : public false_type {};
template <class R, class Arg1, class Arg2, class Arg3, class Arg4> struct is_function<R(&&)(Arg1, Arg2, Arg3, Arg4, ...)> : public false_type {};
template <class R, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5> struct is_function<R(&&)(Arg1, Arg2, Arg3, Arg4, Arg5)> : public false_type {};
template <class R, class Arg1, class Arg2, class Arg3, class Arg4, class Arg5> struct is_function<R(&&)(Arg1, Arg2, Arg3, Arg4, Arg5, ...)> : public false_type {};

} // namespace boost

#endif // BOOST_TT_IS_REFERENCE_HPP_INCLUDED


/* Copyright (c) 2010 Michael Lidgren

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Diagnostics;
using System.Net;

namespace Lidgren.Network
{
	public partial class NetBuffer
	{
		/// <summary>
		/// Gets the internal data buffer
		/// </summary>
		public byte[] PeekDataBuffer() { return m_data; }

		//
		// 1 bit
		//
		/// <summary>
		/// Reads a 1-bit Boolean without advancing the read pointer
		/// </summary>
		public bool PeekBoolean()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 1, c_readOverflowError);
			byte retval = NetBitWriter.ReadByte(m_data, 1, m_readPosition);
			return (retval > 0 ? true : false);
		}

		//
		// 8 bit
		//
		/// <summary>
		/// Reads a Byte without advancing the read pointer
		/// </summary>
		public byte PeekByte()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 8, c_readOverflowError);
			byte retval = NetBitWriter.ReadByte(m_data, 8, m_readPosition);
			return retval;
		}

		/// <summary>
		/// Reads an SByte without advancing the read pointer
		/// </summary>
		[CLSCompliant(false)]
		public sbyte PeekSByte()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 8, c_readOverflowError);
			byte retval = NetBitWriter.ReadByte(m_data, 8, m_readPosition);
			return (sbyte)retval;
		}

		/// <summary>
		/// Reads the specified number of bits into a Byte without advancing the read pointer
		/// </summary>
		public byte PeekByte(int numberOfBits)
		{
			byte retval = NetBitWriter.ReadByte(m_data, numberOfBits, m_readPosition);
			return retval;
		}

		/// <summary>
		/// Reads the specified number of bytes without advancing the read pointer
		/// </summary>
		public byte[] PeekBytes(int numberOfBytes)
		{
			NetException.Assert(m_bitLength - m_readPosition >= (numberOfBytes * 8), c_readOverflowError);

			byte[] retval = new byte[numberOfBytes];
			NetBitWriter.ReadBytes(m_data, numberOfBytes, m_readPosition, retval, 0);
			return retval;
		}

		/// <summary>
		/// Reads the specified number of bytes without advancing the read pointer
		/// </summary>
		public void PeekBytes(byte[] into, int offset, int numberOfBytes)
		{
			NetException.Assert(m_bitLength - m_readPosition >= (numberOfBytes * 8), c_readOverflowError);
			NetException.Assert(offset + numberOfBytes <= into.Length);

			NetBitWriter.ReadBytes(m_data, numberOfBytes, m_readPosition, into, offset);
			return;
		}

		//
		// 16 bit
		//
		/// <summary>
		/// Reads an Int16 without advancing the read pointer
		/// </summary>
		public Int16 PeekInt16()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 16, c_readOverflowError);
			uint retval = NetBitWriter.ReadUInt16(m_data, 16, m_readPosition);
			return (short)retval;
		}

		/// <summary>
		/// Reads a UInt16 without advancing the read pointer
		/// </summary>
		[CLSCompliant(false)]
		public UInt16 PeekUInt16()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 16, c_readOverflowError);
			uint retval = NetBitWriter.ReadUInt16(m_data, 16, m_readPosition);
			return (ushort)retval;
		}

		//
		// 32 bit
		//
		/// <summary>
		/// Reads an Int32 without advancing the read pointer
		/// </summary>
		public Int32 PeekInt32()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 32, c_readOverflowError);
			uint retval = NetBitWriter.ReadUInt32(m_data, 32, m_readPosition);
			return (Int32)retval;
		}

		/// <summary>
		/// Reads the specified number of bits into an Int32 without advancing the read pointer
		/// </summary>
		public Int32 PeekInt32(int numberOfBits)
		{
			NetException.Assert((numberOfBits > 0 && numberOfBits <= 32), "ReadInt() can only read between 1 and 32 bits");
			NetException.Assert(m_bitLength - m_readPosition >= numberOfBits, c_readOverflowError);

			uint retval = NetBitWriter.ReadUInt32(m_data, numberOfBits, m_readPosition);

			if (numberOfBits == 32)
				return (int)retval;

			int signBit = 1 << (numberOfBits - 1);
			if ((retval & signBit) == 0)
				return (int)retval; // positive

			// negative
			unchecked
			{
				uint mask = ((uint)-1) >> (33 - numberOfBits);
				uint tmp = (retval & mask) + 1;
				return -((int)tmp);
			}
		}

		/// <summary>
		/// Reads a UInt32 without advancing the read pointer
		/// </summary>
		[CLSCompliant(false)]
		public UInt32 PeekUInt32()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 32, c_readOverflowError);
			uint retval = NetBitWriter.ReadUInt32(m_data, 32, m_readPosition);
			return retval;
		}

		/// <summary>
		/// Reads the specified number of bits into a UInt32 without advancing the read pointer
		/// </summary>
		[CLSCompliant(false)]
		public UInt32 PeekUInt32(int numberOfBits)
		{
			NetException.Assert((numberOfBits > 0 && numberOfBits <= 32), "ReadUInt() can only read between 1 and 32 bits");
			//NetException.Assert(m_bitLength - m_readBitPtr >= numberOfBits, "tried to read past buffer size");

			UInt32 retval = NetBitWriter.ReadUInt32(m_data, numberOfBits, m_readPosition);
			return retval;
		}

		//
		// 64 bit
		//
		/// <summary>
		/// Reads a UInt64 without advancing the read pointer
		/// </summary>
		[CLSCompliant(false)]
		public UInt64 PeekUInt64()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 64, c_readOverflowError);

			ulong low = NetBitWriter.ReadUInt32(m_data, 32, m_readPosition);
			ulong high = NetBitWriter.ReadUInt32(m_data, 32, m_readPosition + 32);

			ulong retval = low + (high << 32);

			return retval;
		}

		/// <summary>
		/// Reads an Int64 without advancing the read pointer
		/// </summary>
		public Int64 PeekInt64()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 64, c_readOverflowError);
			unchecked
			{
				ulong retval = PeekUInt64();
				long longRetval = (long)retval;
				return longRetval;
			}
		}

		/// <summary>
		/// Reads the specified number of bits into an UInt64 without advancing the read pointer
		/// </summary>
		[CLSCompliant(false)]
		public UInt64 PeekUInt64(int numberOfBits)
		{
			NetException.Assert((numberOfBits > 0 && numberOfBits <= 64), "ReadUInt() can only read between 1 and 64 bits");
			NetException.Assert(m_bitLength - m_readPosition >= numberOfBits, c_readOverflowError);

			ulong retval;
			if (numberOfBits <= 32)
			{
				retval = (ulong)NetBitWriter.ReadUInt32(m_data, numberOfBits, m_readPosition);
			}
			else
			{
				retval = NetBitWriter.ReadUInt32(m_data, 32, m_readPosition);
				retval |= (UInt64)NetBitWriter.ReadUInt32(m_data, numberOfBits - 32, m_readPosition + 32) << 32;
			}
			return retval;
		}

		/// <summary>
		/// Reads the specified number of bits into an Int64 without advancing the read pointer
		/// </summary>
		public Int64 PeekInt64(int numberOfBits)
		{
			NetException.Assert(((numberOfBits > 0) && (numberOfBits < 65)), "ReadInt64(bits) can only read between 1 and 64 bits");
			return (long)PeekUInt64(numberOfBits);
		}

		//
		// Floating point
		//
		/// <summary>
		/// Reads a 32-bit Single without advancing the read pointer
		/// </summary>
		public float PeekFloat()
		{
			return PeekSingle();
		}

		/// <summary>
		/// Reads a 32-bit Single without advancing the read pointer
		/// </summary>
		public float PeekSingle()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 32, c_readOverflowError);

			if ((m_readPosition & 7) == 0) // read directly
			{
				float retval = BitConverter.ToSingle(m_data, m_readPosition >> 3);
				return retval;
			}

			byte[] bytes = PeekBytes(4);
			return BitConverter.ToSingle(bytes, 0);
		}

		/// <summary>
		/// Reads a 64-bit Double without advancing the read pointer
		/// </summary>
		public double PeekDouble()
		{
			NetException.Assert(m_bitLength - m_readPosition >= 64, c_readOverflowError);

			if ((m_readPosition & 7) == 0) // read directly
			{
				// read directly
				double retval = BitConverter.ToDouble(m_data, m_readPosition >> 3);
				return retval;
			}

			byte[] bytes = PeekBytes(8);
			return BitConverter.ToDouble(bytes, 0);
		}

		/// <summary>
		/// Reads a string without advancing the read pointer
		/// </summary>
		public string PeekString()
		{
			int wasReadPosition = m_readPosition;
			string retval = ReadString();
			m_readPosition = wasReadPosition;
			return retval;
		}
	}
}


<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

    <link rel="stylesheet" type="text/css" href="other-outermost-sheet.css"
          media="print" />
    <link rel="stylesheet" type="text/css" href="outermost-sheet.css"
          media="screen" />

purple

blue

yellow


<?xml version='1.0' encoding='UTF-8'?>
<resources>
  <string name="tutorial_overview">我們在這兒！我已經根據你的興趣給你添加了幾個任務~也試試自己添加幾個吧！你還可以點擊任務標題來修改它們。</string>
  <string name="tutorial_habits_1">首先是習慣。它們可以是你想養成的好習慣，也可以是你想戒掉的壞習慣。</string>
  <string name="tutorial_habits_2">每當你完成一次好的習慣，點擊習慣前的加號，就可以獲得經驗和金幣啦！</string>
  <string name="tutorial_habits_3">如果你一不留神完成了一次壞習慣，點擊減號，這會減少角色的生命值來幫助你戒掉壞習慣。</string>
  <string name="tutorial_habits_4">試試看吧！你可以在下方導航列中發掘更多任務類型。</string>
  <string name="tutorial_dailies_1">有一定規律的、或是時間緊迫的任務，可以將其新增至每日任務。</string>
  <string name="tutorial_dailies_2">小心 - 如果你沒有完成，你的角色會在一夜之間受到傷害！</string>
  <string name="tutorial_todos_1">待辦事項是只需要執行一次的任務。</string>
  <string name="tutorial_todos_2">如果您的待辦事項必須在特定時間內完成，請設置截止日期！</string>
  <string name="tutorial_rewards_1">用金幣為你的角色添購裝備吧！</string>
  <string name="tutorial_rewards_2">你也可以自定義獎勵。</string>
  <string name="tutorial_tasks_complete">目前為止就這樣了。如果您想了解更多，請查看FAQ部分。</string>
    <string name="tutorial_skills">技能是有強大作用的特殊能力！點擊技能使用。使用技能需要消耗魔法值(藍色條)，魔力可由每日打卡和完成現實任務來獲得。更多信息請查詢FAQ！</string>
  <string name="tutorial_party">在這裡，你和你的朋友可以互相激勵完成目標並通過完成任務組團打BOSS！</string>
  <string name="tutorial_tavern">歡迎來到酒館，這裡是一個公開的不分年齡的聊天室！這裡，可以聊聊心得，問問問題。祝您玩的愉快！</string>
    <string name="tutorial_stats">按灰色的按鈕可以把所有的能力點用於一次升級某項能力，或是按箭頭以批次分配能力點。</string>
</resources>


readable-stream

Streams3, a user-land copy of the stream library from Node.js v0.11.x


/****************************************************************************
 *
 * Copyright 2018 Samsung Electronics All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 *
 ****************************************************************************/
//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <iterator>

// template <InputIterator Iter>
//   Iter::difference_type
//   distance(Iter first, Iter last);
//
// template <RandomAccessIterator Iter>
//   Iter::difference_type
//   distance(Iter first, Iter last);

#include <iterator>
#include <cassert>
#include "test_macros.h"
#include "libcxx_tc_common.h"

#include "test_iterators.h"

template <class It>
static int
test(It first, It last, typename std::iterator_traits<It>::difference_type x)
{
    TC_ASSERT_EXPR(std::distance(first, last) == x);
    return 0;
}

#if TEST_STD_VER > 14
template <class It>
constexpr bool
constexpr_test(It first, It last, typename std::iterator_traits<It>::difference_type x)
{
    return std::distance(first, last) == x;
    return 0;
}
#endif

int tc_libcxx_iterators_iterator_operations_distance(void)
{
    {
    const char* s = "1234567890";
    TC_ASSERT_FUNC((test(input_iterator<const char*>(s), input_iterator<const char*>(s+10), 10)));
    TC_ASSERT_FUNC((test(forward_iterator<const char*>(s), forward_iterator<const char*>(s+10), 10)));
    TC_ASSERT_FUNC((test(bidirectional_iterator<const char*>(s), bidirectional_iterator<const char*>(s+10), 10)));
    TC_ASSERT_FUNC((test(random_access_iterator<const char*>(s), random_access_iterator<const char*>(s+10), 10)));
    TC_ASSERT_FUNC((test(s, s+10, 10)));
    }
#if TEST_STD_VER > 14
    {
    constexpr const char* s = "1234567890";
    static_assert( constexpr_test(input_iterator<const char*>(s), input_iterator<const char*>(s+10), 10), "");
    static_assert( constexpr_test(forward_iterator<const char*>(s), forward_iterator<const char*>(s+10), 10), "");
    static_assert( constexpr_test(bidirectional_iterator<const char*>(s), bidirectional_iterator<const char*>(s+10), 10), "");
    static_assert( constexpr_test(random_access_iterator<const char*>(s), random_access_iterator<const char*>(s+10), 10), "");
    static_assert( constexpr_test(s, s+10, 10), "");
    }
#endif
    TC_SUCCESS_RESULT();
    return 0;
}


// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing

extension Array {
{
}
init {
let a {
func d {
for {
deinit {
class
case ,


// Copyright 2018, The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE.md file.

// +build !purego

package value

import (
	"reflect"
	"unsafe"
)

// Pointer is an opaque typed pointer and is guaranteed to be comparable.
type Pointer struct {
	p unsafe.Pointer
	t reflect.Type
}

// PointerOf returns a Pointer from v, which must be a
// reflect.Ptr, reflect.Slice, or reflect.Map.
func PointerOf(v reflect.Value) Pointer {
	// The proper representation of a pointer is unsafe.Pointer,
	// which is necessary if the GC ever uses a moving collector.
	return Pointer{unsafe.Pointer(v.Pointer()), v.Type()}
}


/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.spring.boot.starter.configuration.id;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.assertj.core.api.Assertions.assertThat;

public class PrefixedUuidGeneratorTest {

  @Rule
  public final ExpectedException thrown = ExpectedException.none();

  @Test
  public void prefixed_uuid() throws Exception {

    final String id = new PrefixedUuidGenerator("foo").getNextId();
    assertThat(id).startsWith("foo-");
    assertThat(id.split("-")).hasSize(6);
  }

  @Test
  public void fails_on_null() throws Exception {
    thrown.expect(NullPointerException.class);
    thrown.expectMessage("spring.application.name");

    new PrefixedUuidGenerator(null);
  }
}


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `angular-cli.json`.

export const environment = {
    production: false
};


var passed = this === self;
onconnect = function(e) {
  e.ports[0].postMessage(passed);
}


{{- if .Values.host }}
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: {{ template "ethereum.fullname" . }}
  labels:
    app: {{ template "ethereum.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
  annotations:
    kubernetes.io/ingress.class: nginx-ingress
    kubernetes.io/tls-acme: "true"
    cert-manager.io/cluster-issuer: "letsencrypt-prod"
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/rewrite-target: /
    nginx.ingress.kubernetes.io/limit-rps: "50"
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-methods: "GET, POST, OPTIONS"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"

spec:
  tls:
    - secretName: {{ .Values.host }}
      hosts:
        - {{ .Values.host }}
  rules:
  - host: {{ .Values.host }}
    http:
      paths:
      - path: /
        backend:
          serviceName: {{ template "ethereum.fullname" . }}-ethstats
          servicePort: 80
      - path: /rpc
        backend:
          serviceName: {{ template "ethereum.fullname" . }}
          servicePort: 8545
      # TODO use separate ingress and adjust for websocket
      - path: /ws
        backend:
          serviceName: {{ template "ethereum.fullname" . }}
          servicePort: 8546
{{- end }}


.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #999988; font-style: italic } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { font-weight: bold } /* Keyword */
.highlight .o { font-weight: bold } /* Operator */
.highlight .cm { color: #999988; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #999999; font-weight: bold } /* Comment.Preproc */
.highlight .c1 { color: #999988; font-style: italic } /* Comment.Single */
.highlight .cs { color: #999999; font-weight: bold; font-style: italic } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #999999 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #aaaaaa } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { font-weight: bold } /* Keyword.Constant */
.highlight .kd { font-weight: bold } /* Keyword.Declaration */
.highlight .kn { font-weight: bold } /* Keyword.Namespace */
.highlight .kp { font-weight: bold } /* Keyword.Pseudo */
.highlight .kr { font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #445588; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #009999 } /* Literal.Number */
.highlight .s { color: #bb8844 } /* Literal.String */
.highlight .na { color: #008080 } /* Name.Attribute */
.highlight .nb { color: #999999 } /* Name.Builtin */
.highlight .nc { color: #445588; font-weight: bold } /* Name.Class */
.highlight .no { color: #008080 } /* Name.Constant */
.highlight .ni { color: #800080 } /* Name.Entity */
.highlight .ne { color: #990000; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #990000; font-weight: bold } /* Name.Function */
.highlight .nn { color: #555555 } /* Name.Namespace */
.highlight .nt { color: #000080 } /* Name.Tag */
.highlight .nv { color: #008080 } /* Name.Variable */
.highlight .ow { font-weight: bold } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mf { color: #009999 } /* Literal.Number.Float */
.highlight .mh { color: #009999 } /* Literal.Number.Hex */
.highlight .mi { color: #009999 } /* Literal.Number.Integer */
.highlight .mo { color: #009999 } /* Literal.Number.Oct */
.highlight .sb { color: #bb8844 } /* Literal.String.Backtick */
.highlight .sc { color: #bb8844 } /* Literal.String.Char */
.highlight .sd { color: #bb8844 } /* Literal.String.Doc */
.highlight .s2 { color: #bb8844 } /* Literal.String.Double */
.highlight .se { color: #bb8844 } /* Literal.String.Escape */
.highlight .sh { color: #bb8844 } /* Literal.String.Heredoc */
.highlight .si { color: #bb8844 } /* Literal.String.Interpol */
.highlight .sx { color: #bb8844 } /* Literal.String.Other */
.highlight .sr { color: #808000 } /* Literal.String.Regex */
.highlight .s1 { color: #bb8844 } /* Literal.String.Single */
.highlight .ss { color: #bb8844 } /* Literal.String.Symbol */
.highlight .bp { color: #999999 } /* Name.Builtin.Pseudo */
.highlight .vc { color: #008080 } /* Name.Variable.Class */
.highlight .vg { color: #008080 } /* Name.Variable.Global */
.highlight .vi { color: #008080 } /* Name.Variable.Instance */
.highlight .il { color: #009999 } /* Literal.Number.Integer.Long */


//
//  QBMulticastDelegate.h
//
//  Created by QuickBlox team
//  Copyright (c) 2017 QuickBlox. All rights reserved.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface QBMulticastDelegate : NSObject

/**
 *  Adds the given delegate implementation to the list of observers.
 *
 *  @param delegate delegate to add
 *
 *  @notes All delegates are called on the main thread asynchronously.
 */
- (void)addDelegate:(id)delegate;

/**
 *  Removes the given delegate implementation from the list of observers.
 *
 *  @param delegate delegate to remove
 */
- (void)removeDelegate:(id)delegate;

/**
 *  Removes all delegates.
 */
- (void)removeAllDelegates;

/**
 *  Hashtable of all delegates.
 */
- (NSHashTable *)delegates;

@end

NS_ASSUME_NONNULL_END


@ECHO OFF
REM Simple check of a stateful encoding.
REM Usage: check-stateful.bat SRCDIR CHARSET

if not exist %1\%2-snippet.alt goto ENDIF_1
  ..\src\iconv_no_i18n -f %2 -t UTF-8 < %1\%2-snippet.alt > tmp-snippet
  fc %1\%2-snippet.UTF-8 tmp-snippet
:ENDIF_1

..\src\iconv_no_i18n -f %2 -t UTF-8 < %1\%2-snippet > tmp-snippet
fc %1\%2-snippet.UTF-8 tmp-snippet
..\src\iconv_no_i18n -f UTF-8 -t %2 < %1\%2-snippet.UTF-8 > tmp-snippet
fc %1\%2-snippet tmp-snippet
del tmp-snippet


var convert = require('./convert'),
    func = convert('min', require('../min'), require('./_falseOptions'));

func.placeholder = require('./placeholder');
module.exports = func;