@@ -41,6 +41,21 @@ public class GoDiscoveryContext extends DiscoveryContext implements GoContext {
           .put(Field.Kind.TYPE_DOUBLE, "0.0")
           .build();

+  @Override
+  protected String arrayTypeName(String elementName) {
+    return String.format("%sArray", elementName);
+  }
+
+  @Override
+  protected String mapTypeName(String keyName, String valueName) {
+    return String.format("%sTo%sMap", keyName, valueName);
+  }
+
+  @Override
+  protected String objectTypeName(String typeName) {
+    return upperCamelToLowerCamel(typeName);
+  }
+
   public String typeDefaultValue(Type type, Field field) {
     if (field.getCardinality() == Field.Cardinality.CARDINALITY_REPEATED) {
       return typeName(type, field) + "{}";

/* Copyright 2016 Google Inc
 *
 * 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 com.google.api.codegen.go;

import com.google.api.codegen.ApiaryConfig;
import com.google.api.codegen.DiscoveryContext;
import com.google.api.codegen.DiscoveryImporter;
import com.google.api.Service;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableTable;
import com.google.protobuf.Field;
import com.google.protobuf.Method;
import com.google.protobuf.Type;

public class GoDiscoveryContext extends DiscoveryContext implements GoContext {
  public GoDiscoveryContext(Service service, ApiaryConfig apiaryConfig) {
    super(service, apiaryConfig);
  }

  private static final ImmutableMap<Field.Kind, String> DEFAULT_VALUES =
      ImmutableMap.<Field.Kind, String>builder()
          .put(Field.Kind.TYPE_BOOL, "false")
          .put(Field.Kind.TYPE_INT32, "int64(0)")
          .put(Field.Kind.TYPE_UINT32, "uint64(0)")
          .put(Field.Kind.TYPE_INT64, "int64(0)")
          .put(Field.Kind.TYPE_UINT64, "uint64(0)")
          .put(Field.Kind.TYPE_FLOAT, "float32(0.0)")
          .put(Field.Kind.TYPE_DOUBLE, "0.0")
          .build();

  public String typeDefaultValue(Type type, Field field) {
    if (field.getCardinality() == Field.Cardinality.CARDINALITY_REPEATED) {
      return typeName(type, field) + "{}";
    }
    if (DEFAULT_VALUES.containsKey(field.getKind())) {
      return DEFAULT_VALUES.get(field.getKind());
    }
    if (field.getKind() == Field.Kind.TYPE_STRING || field.getKind() == Field.Kind.TYPE_ENUM) {
      return getDefaultString(type, field);
    }
    throw new IllegalArgumentException(
        String.format("not implemented: typeDefaultValue(%s, %s)", type, field));
  }

  @Override
  public String lineEnding(String value) {
    return value;
  }

  private static final ImmutableMap<Field.Kind, String> PRIMITIVE_TYPE =
      ImmutableMap.<Field.Kind, String>builder()
          .put(Field.Kind.TYPE_BOOL, "bool")
          .put(Field.Kind.TYPE_INT32, "int64")
          .put(Field.Kind.TYPE_UINT32, "uint64")
          .put(Field.Kind.TYPE_INT64, "int64")
          .put(Field.Kind.TYPE_UINT64, "uint64")
          .put(Field.Kind.TYPE_FLOAT, "float32")
          .put(Field.Kind.TYPE_DOUBLE, "float64")
          .put(Field.Kind.TYPE_STRING, "string")
          .put(Field.Kind.TYPE_ENUM, "string")
          .build();

  /**
   * Returns the Go representation of a type's field's type.
   */
  private String typeName(Type type, Field field) {
    String fieldName = field.getName();
    String fieldTypeName = field.getTypeUrl();
    String arrayPrefix = "";

    if (field.getCardinality() == Field.Cardinality.CARDINALITY_REPEATED) {
      Type items = this.getApiaryConfig().getType(fieldTypeName);
      if (isMapField(type, fieldName)) {
        return String.format(
            "map[%s]%s",
            typeName(items, this.getField(items, "key")),
            typeName(items, this.getField(items, "value")));
      }
      Field elements = this.getField(items, "elements");
      if (elements != null) {
        return "[]" + typeName(items, elements);
      }
      arrayPrefix = "[]";
    }
    if (field.getKind() == Field.Kind.TYPE_MESSAGE) {
      return arrayPrefix + fieldTypeName;
    }
    if (PRIMITIVE_TYPE.containsKey(field.getKind())) {
      return arrayPrefix + PRIMITIVE_TYPE.get(field.getKind());
    }
    throw new IllegalArgumentException(
        String.format("cannot find suitable type for %s %s", type.getName(), field.getName()));
  }

  @Override
  /**
   * Most languages ignore return type "Empty". However, Go cannot since the client library will
   * return an empty struct, and we have to assign it to something. Consequently, the only time the
   * response is truly "empty" for Go is when DiscoveryImporter says EMPTY_TYPE_NAME, which
   * signifies complete absence of return value.
   */
  public boolean isResponseEmpty(Method method) {
    return method.getResponseTypeUrl().equals(DiscoveryImporter.EMPTY_TYPE_NAME);
  }

  @Override
  public boolean isPageStreaming(Method method) {
    if (isResponseEmpty(method) || hasRequestField(method)) {
      return false;
    }
    boolean hasNextPageToken = false;
    for (Field field : getApiaryConfig().getType(method.getResponseTypeUrl()).getFieldsList()) {
      if (field.getName().equals("nextPageToken")) {
        hasNextPageToken = true;
        break;
      }
    }

    boolean hasPageToken = false;
    for (Field field : getApiaryConfig().getType(method.getRequestTypeUrl()).getFieldsList()) {
      if (field.getName().equals("pageToken")) {
        hasPageToken = true;
        break;
      }
    }
    return hasPageToken && hasNextPageToken;
  }

  private static final ImmutableTable<String, String, String> API_VERSION_RENAME =
      ImmutableTable.<String, String, String>builder()
          .put("clouduseraccounts", "beta", "v0.beta")
          .build();

  /**
   * We need this because in some cases there is a mismatch between discovery doc and import path
   * version numbers. API_VERSION_RENAME is a table of API name and versions as found in discovery
   * doc to the renamed versions as found in the import path.
   *
   * TODO(pongad): Find a more sustainable solution to this.
   */
  public String getApiVersion() {
    String rename = API_VERSION_RENAME.get(getApi().getName(), getApi().getVersion());
    return rename == null ? getApi().getVersion() : rename;
  }

  /*
   * Returns an empty or singleton list of auth scopes for the method. If the method has no scope,
   * returns an empty list; otherwise returns the first scope. We return an empty list instead of
   * null to denote absence of scope since the snippet cannot handle null values. If the scope
   * exists, it is stripped to its last path-element and converted to camel case, eg
   * "https://www.googleapis.com/auth/cloud-platform" becomes "CloudPlatform".
   */
  public ImmutableList<String> getAuthScopes(Method method) {
    if (!getApiaryConfig().getAuthScopes().containsKey(method.getName())) {
      return ImmutableList.<String>of();
    }
    String scope = getApiaryConfig().getAuthScopes().get(method.getName()).get(0);
    int slash = scope.lastIndexOf('/');
    if (slash < 0) {
      throw new IllegalArgumentException(
          String.format("malformed scope, cannot find slash: %s", scope));
    }
    scope = scope.substring(slash + 1);
    scope = scope.replace('.', '_');
    scope = scope.replace('-', '_');
    scope = lowerUnderscoreToUpperCamel(scope);
    return ImmutableList.<String>of(scope);
  }
}

Where is this used? Go's array of ints is `[]int` not `intArray`. I also don't see this reflected in baseline test for any language. (I ran git diff and regexp `^\+.*Array`).


@@ -34,7 +34,7 @@ module Selenium
           driver.manage.timeouts.implicit_wait = 6

           driver.find_element(id: 'adder').click
-          driver.find_element(id: 'box0')
+          expect { driver.find_element(id: 'box0') }.not_to raise_error(WebDriver::Error::NoSuchElementError)
         end

         it 'should still fail to find an element with implicit waits enabled' do

# frozen_string_literal: true

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC 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.

require_relative 'spec_helper'

module Selenium
  module WebDriver
    describe Timeouts do
      context 'implicit waits' do
        before do
          driver.manage.timeouts.implicit_wait = 0
          driver.navigate.to url_for('dynamic.html')
        end

        after { driver.manage.timeouts.implicit_wait = 0 }

        it 'should implicitly wait for a single element', except: {browser: :safari_preview} do
          driver.manage.timeouts.implicit_wait = 6

          driver.find_element(id: 'adder').click
          driver.find_element(id: 'box0')
        end

        it 'should still fail to find an element with implicit waits enabled' do
          driver.manage.timeouts.implicit_wait = 0.5
          expect { driver.find_element(id: 'box0') }.to raise_error(WebDriver::Error::NoSuchElementError)
        end

        it 'should return after first attempt to find one after disabling implicit waits' do
          driver.manage.timeouts.implicit_wait = 3
          driver.manage.timeouts.implicit_wait = 0

          expect { driver.find_element(id: 'box0') }.to raise_error(WebDriver::Error::NoSuchElementError)
        end

        it 'should implicitly wait until at least one element is found when searching for many' do
          add = driver.find_element(id: 'adder')

          driver.manage.timeouts.implicit_wait = 6
          add.click
          add.click

          expect(driver.find_elements(class_name: 'redbox')).not_to be_empty
        end

        it 'should still fail to find elements when implicit waits are enabled' do
          driver.manage.timeouts.implicit_wait = 0.5
          expect(driver.find_elements(class_name: 'redbox')).to be_empty
        end

        it 'should return after first attempt to find many after disabling implicit waits', except: {browser: :firefox, platform: :windows} do
          add = driver.find_element(id: 'adder')

          driver.manage.timeouts.implicit_wait = 3
          driver.manage.timeouts.implicit_wait = 0
          add.click

          expect(driver.find_elements(class_name: 'redbox')).to be_empty
        end
      end

      context 'page loads' do
        # w3c default is 300,000
        after { driver.manage.timeouts.page_load = 300000 }

        it 'should be able to set the page load timeout' do
          expect { driver.manage.timeouts.page_load = 2 }.not_to raise_exception
        end
      end
    end
  end # WebDriver
end # Selenium

This should just be `.not_to raise_error` otherwise it potentially hides errors


@@ -78,6 +78,32 @@ public final class TestObjects {
           .build()
   ).stream().map(ApplyTimestampAndDuration::apply).collect(toList());

+
+  // this object simulates
+  public static final List<Span> TRACEWITHSAMEIDANDSAMEPARENTID = asList(
+    Span.builder().traceId(WEB_SPAN_ID+1).id(WEB_SPAN_ID).name("get")
+      .addAnnotation(Annotation.create(TODAY * 1000, SERVER_RECV, WEB_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 350) * 1000, SERVER_SEND, WEB_ENDPOINT))
+      .build(),
+    Span.builder().traceId(WEB_SPAN_ID+1).parentId(WEB_SPAN_ID).id(WEB_SPAN_ID).name("get")
+      .addAnnotation(Annotation.create((TODAY + 50) * 1000, CLIENT_SEND, WEB_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 100) * 1000, SERVER_RECV, APP_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 250) * 1000, SERVER_SEND, APP_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 300) * 1000, CLIENT_RECV, WEB_ENDPOINT))
+      .addBinaryAnnotation(BinaryAnnotation.address(CLIENT_ADDR, WEB_ENDPOINT))
+      .addBinaryAnnotation(BinaryAnnotation.address(SERVER_ADDR, APP_ENDPOINT))
+      .build(),
+    Span.builder().traceId(WEB_SPAN_ID+1).parentId(WEB_SPAN_ID).id(WEB_SPAN_ID).name("query")
+      .addAnnotation(Annotation.create((TODAY + 150) * 1000, CLIENT_SEND, APP_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 200) * 1000, CLIENT_RECV, APP_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 190) * 1000, "⻩", NO_IP_ENDPOINT))
+      .addBinaryAnnotation(BinaryAnnotation.address(CLIENT_ADDR, APP_ENDPOINT))
+      .addBinaryAnnotation(BinaryAnnotation.address(SERVER_ADDR, DB_ENDPOINT))
+      .addBinaryAnnotation(BinaryAnnotation.create(ERROR, "\uD83D\uDCA9", NO_IP_ENDPOINT))
+      .build()
+  ).stream().map(ApplyTimestampAndDuration::apply).collect(toList());
+
+
   public static final List<DependencyLink> LINKS = asList(
       DependencyLink.builder().parent("web").child("app").callCount(1).build(),
       DependencyLink.builder().parent("app").child("db").callCount(1).build()

/**
 * Copyright 2015-2016 The OpenZipkin Authors
 *
 * 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 zipkin;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import zipkin.internal.ApplyTimestampAndDuration;
import zipkin.internal.Dependencies;

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static zipkin.Constants.CLIENT_ADDR;
import static zipkin.Constants.CLIENT_RECV;
import static zipkin.Constants.CLIENT_SEND;
import static zipkin.Constants.ERROR;
import static zipkin.Constants.SERVER_ADDR;
import static zipkin.Constants.SERVER_RECV;
import static zipkin.Constants.SERVER_SEND;
import static zipkin.internal.Util.UTF_8;
import static zipkin.internal.Util.midnightUTC;

public final class TestObjects {

  /** Notably, the cassandra implementation has day granularity */
  public static final long DAY = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS);

  // Use real time, as most span-stores have TTL logic which looks back several days.
  public static final long TODAY = midnightUTC(System.currentTimeMillis());

  public static final Endpoint WEB_ENDPOINT = Endpoint.builder()
      .serviceName("web")
      .ipv4(124 << 24 | 13 << 16 | 90 << 8 | 3)
      // Cheat so we don't have to catch an exception here
      .ipv6(sun.net.util.IPAddressUtil.textToNumericFormatV6("2001:db8::c001"))
      .port((short) 80).build();
  public static final Endpoint APP_ENDPOINT =
      Endpoint.builder().serviceName("app").ipv4(172 << 24 | 17 << 16 | 2).port(8080).build();
  public static final Endpoint DB_ENDPOINT =
      Endpoint.builder().serviceName("db").ipv4(172 << 24 | 17 << 16 | 2).port(3306).build();
  public static final Endpoint NO_IP_ENDPOINT = Endpoint.builder().serviceName("no_ip").build();

  static final long WEB_SPAN_ID = -692101025335252320L;
  static final long APP_SPAN_ID = -7842865617155193778L;
  static final long DB_SPAN_ID = 8207293009014896295L;

  public static final List<Span> TRACE = asList(
      Span.builder().traceId(WEB_SPAN_ID).id(WEB_SPAN_ID).name("get")
          .addAnnotation(Annotation.create(TODAY * 1000, SERVER_RECV, WEB_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 350) * 1000, SERVER_SEND, WEB_ENDPOINT))
          .build(),
      Span.builder().traceId(WEB_SPAN_ID).parentId(WEB_SPAN_ID).id(APP_SPAN_ID).name("get")
          .addAnnotation(Annotation.create((TODAY + 50) * 1000, CLIENT_SEND, WEB_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 100) * 1000, SERVER_RECV, APP_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 250) * 1000, SERVER_SEND, APP_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 300) * 1000, CLIENT_RECV, WEB_ENDPOINT))
          .addBinaryAnnotation(BinaryAnnotation.address(CLIENT_ADDR, WEB_ENDPOINT))
          .addBinaryAnnotation(BinaryAnnotation.address(SERVER_ADDR, APP_ENDPOINT))
          .build(),
      Span.builder().traceId(WEB_SPAN_ID).parentId(APP_SPAN_ID).id(DB_SPAN_ID).name("query")
          .addAnnotation(Annotation.create((TODAY + 150) * 1000, CLIENT_SEND, APP_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 200) * 1000, CLIENT_RECV, APP_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 190) * 1000, "⻩", NO_IP_ENDPOINT))
          .addBinaryAnnotation(BinaryAnnotation.address(CLIENT_ADDR, APP_ENDPOINT))
          .addBinaryAnnotation(BinaryAnnotation.address(SERVER_ADDR, DB_ENDPOINT))
          .addBinaryAnnotation(BinaryAnnotation.create(ERROR, "\uD83D\uDCA9", NO_IP_ENDPOINT))
          .build()
  ).stream().map(ApplyTimestampAndDuration::apply).collect(toList());

  public static final List<DependencyLink> LINKS = asList(
      DependencyLink.builder().parent("web").child("app").callCount(1).build(),
      DependencyLink.builder().parent("app").child("db").callCount(1).build()
  );
  public static final Dependencies DEPENDENCIES = Dependencies.create(TODAY, TODAY + 1000, LINKS);

  static final Span.Builder spanBuilder = spanBuilder();

  /** Reuse a builder as it is significantly slows tests to create 100000 of these! */
  static Span.Builder spanBuilder() {
    Endpoint e = Endpoint.builder().serviceName("service").ipv4(127 << 24 | 1).port(8080).build();
    Annotation sr = Annotation.create(System.currentTimeMillis() * 1000, SERVER_RECV, e);
    Annotation ss = Annotation.create(sr.timestamp + 1000, SERVER_SEND, e);
    BinaryAnnotation ba = BinaryAnnotation.create(TraceKeys.HTTP_METHOD, "GET", e);
    return Span.builder().name("get").addAnnotation(sr).addAnnotation(ss).addBinaryAnnotation(ba);
  }

  /**
   * Zipkin trace ids are random 64bit numbers. This creates a relatively large input to avoid
   * flaking out due to PRNG nuance.
   */
  public static final Span[] LOTS_OF_SPANS =
      new Random().longs(100_000).mapToObj(t -> span(t)).toArray(Span[]::new);

  public static Span span(long traceId) {
    return spanBuilder.traceId(traceId).id(traceId).build();
  }
}

please move this into a local variable in its only caller: DependencyLinkerTest.linksSpansShouldHandleNullSpans() also please don't concatenate words like this as it is not readable. Once a local variable use lower-camel


@@ -16,17 +16,13 @@

 package org.springframework.security.oauth2.server.resource.authentication;

-import java.util.Arrays;
 import java.util.Collection;
-import java.util.Collections;
-import java.util.stream.Collectors;

 import org.springframework.core.convert.converter.Converter;
 import org.springframework.security.authentication.AbstractAuthenticationToken;
 import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
 import org.springframework.security.oauth2.jwt.Jwt;
-import org.springframework.util.StringUtils;
+import org.springframework.util.Assert;

 /**
  * @author Rob Winch

/*
 * Copyright 2002-2018 the original author or authors.
 *
 * 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 org.springframework.security.oauth2.server.resource.authentication;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;

import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.util.StringUtils;

/**
 * @author Rob Winch
 * @author Josh Cummings
 * @since 5.1
 */
public class JwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
	private static final String SCOPE_AUTHORITY_PREFIX = "SCOPE_";

	private static final Collection<String> WELL_KNOWN_SCOPE_ATTRIBUTE_NAMES =
			Arrays.asList("scope", "scp");

	public final AbstractAuthenticationToken convert(Jwt jwt) {
		Collection<GrantedAuthority> authorities = extractAuthorities(jwt);
		return new JwtAuthenticationToken(jwt, authorities);
	}

	protected Collection<GrantedAuthority> extractAuthorities(Jwt jwt) {
		return this.getScopes(jwt)
						.stream()
						.map(authority -> SCOPE_AUTHORITY_PREFIX + authority)
						.map(SimpleGrantedAuthority::new)
						.collect(Collectors.toList());
	}

	private Collection<String> getScopes(Jwt jwt) {
		for ( String attributeName : WELL_KNOWN_SCOPE_ATTRIBUTE_NAMES ) {
			Object scopes = jwt.getClaims().get(attributeName);
			if (scopes instanceof String) {
				if (StringUtils.hasText((String) scopes)) {
					return Arrays.asList(((String) scopes).split(" "));
				} else {
					return Collections.emptyList();
				}
			} else if (scopes instanceof Collection) {
				return (Collection<String>) scopes;
			}
		}

		return Collections.emptyList();
	}
}

Allow injecting the `Converter<Jwt, Collection<GrantedAuthority>>`


@@ -20,4 +20,5 @@ import azkaban.executor.ExecutorManagerException;
 public interface ContainerizedImpl {
   void createContainer(final int executionId) throws ExecutorManagerException;
   void deleteContainer(final int executionId) throws ExecutorManagerException;
+  void logPodDetails(final int execId) throws ExecutorManagerException ;
 }

/*
 * Copyright 2020 LinkedIn Corp.
 *
 * 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 azkaban.executor.container;

import azkaban.executor.ExecutorManagerException;

public interface ContainerizedImpl {
  void createContainer(final int executionId) throws ExecutorManagerException;
  void deleteContainer(final int executionId) throws ExecutorManagerException;
}

Currently this doesn't seem to be invoked anywhere beyond `KubernetesContainerizedImpl`, is that intentional ? (we could get away w/o adding it to the interface then)


@@ -42,7 +42,7 @@ public class Cast extends NoOp {
     } else if (targetDataType instanceof RealType) {
       casted = castToDouble(value);
     } else {
-      throw new UnsupportedOperationException("only support cast to Long, Double and String");
+      casted = value;
     }
     row.set(pos, targetDataType, casted);
   }

/*
 *
 * Copyright 2017 PingCAP, Inc.
 *
 * 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,
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.pingcap.tikv.operation.transformer;

import com.pingcap.tikv.row.Row;
import com.pingcap.tikv.types.*;
import java.math.BigDecimal;

public class Cast extends NoOp {
  public Cast(DataType type) {
    super(type);
  }

  @Override
  public void set(Object value, Row row, int pos) {
    Object casted;
    if (value == null) {
      row.set(pos, targetDataType, null);
      return;
    }
    if (targetDataType instanceof IntegerType) {
      casted = castToLong(value);
    } else if (targetDataType instanceof BytesType) {
      casted = castToString(value);
    } else if (targetDataType instanceof DecimalType) {
      casted = castToDecimal(value);
    } else if (targetDataType instanceof RealType) {
      casted = castToDouble(value);
    } else {
      throw new UnsupportedOperationException("only support cast to Long, Double and String");
    }
    row.set(pos, targetDataType, casted);
  }

  public Double castToDouble(Object obj) {
    if (obj instanceof Number) {
      Number num = (Number) obj;
      return num.doubleValue();
    }
    throw new UnsupportedOperationException("can not cast un-number to double ");
  }

  public BigDecimal castToDecimal(Object obj) {
    if (obj instanceof Number) {
      Number num = (Number) obj;
      return new BigDecimal(num.doubleValue());
    } else if (obj instanceof BigDecimal) {
      return (BigDecimal) obj;
    }
    throw new UnsupportedOperationException(
        "can not cast to BigDecimal: " + obj == null ? "null" : obj.getClass().getSimpleName());
  }

  public Long castToLong(Object obj) {
    if (obj instanceof Number) {
      Number num = (Number) obj;
      return num.longValue();
    }
    throw new UnsupportedOperationException("can not cast un-number to long ");
  }

  public String castToString(Object obj) {
    return obj.toString();
  }
}

Is this covered by regression tests? Also you might make a patch onto refactor branch.


@@ -42,19 +42,26 @@ import org.apache.spark.sql.catalyst.util.MapData;
 import org.apache.spark.sql.types.Decimal;
 import org.apache.spark.unsafe.types.UTF8String;

-
-class SparkOrcValueReaders {
+public class SparkOrcValueReaders {
   private SparkOrcValueReaders() {
   }

-  static OrcValueReader<UTF8String> utf8String() {
+  public static OrcValueReader<UTF8String> utf8String() {
     return StringReader.INSTANCE;
   }

-  static OrcValueReader<?> timestampTzs() {
+  public static OrcValueReader<Long> timestampTzs() {
     return TimestampTzReader.INSTANCE;
   }

+  public static OrcValueReader<Decimal> decimals(int precision, int scale) {
+    if (precision <= Decimal.MAX_LONG_DIGITS()) {
+      return new SparkOrcValueReaders.Decimal18Reader(precision, scale);
+    } else {
+      return new SparkOrcValueReaders.Decimal38Reader(precision, scale);
+    }
+  }
+
   static OrcValueReader<?> struct(
       List<OrcValueReader<?>> readers, Types.StructType struct, Map<Integer, ?> idToConstant) {
     return new StructReader(readers, struct, idToConstant);

/*
 * 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.iceberg.spark.data;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.apache.iceberg.orc.OrcValueReader;
import org.apache.iceberg.orc.OrcValueReaders;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.types.Types;
import org.apache.orc.storage.ql.exec.vector.BytesColumnVector;
import org.apache.orc.storage.ql.exec.vector.ColumnVector;
import org.apache.orc.storage.ql.exec.vector.DecimalColumnVector;
import org.apache.orc.storage.ql.exec.vector.ListColumnVector;
import org.apache.orc.storage.ql.exec.vector.MapColumnVector;
import org.apache.orc.storage.ql.exec.vector.TimestampColumnVector;
import org.apache.orc.storage.serde2.io.HiveDecimalWritable;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.catalyst.expressions.GenericInternalRow;
import org.apache.spark.sql.catalyst.util.ArrayBasedMapData;
import org.apache.spark.sql.catalyst.util.ArrayData;
import org.apache.spark.sql.catalyst.util.GenericArrayData;
import org.apache.spark.sql.catalyst.util.MapData;
import org.apache.spark.sql.types.Decimal;
import org.apache.spark.unsafe.types.UTF8String;

class SparkOrcValueReaders {
  private SparkOrcValueReaders() {
  }

  static OrcValueReader<UTF8String> utf8String() {
    return StringReader.INSTANCE;
  }

  static OrcValueReader<?> timestampTzs() {
    return TimestampTzReader.INSTANCE;
  }

  static OrcValueReader<?> struct(
      List<OrcValueReader<?>> readers, Types.StructType struct, Map<Integer, ?> idToConstant) {
    return new StructReader(readers, struct, idToConstant);
  }

  static OrcValueReader<?> array(OrcValueReader<?> elementReader) {
    return new ArrayReader(elementReader);
  }

  static OrcValueReader<?> map(OrcValueReader<?> keyReader, OrcValueReader<?> valueReader) {
    return new MapReader(keyReader, valueReader);
  }

  private static class ArrayReader implements OrcValueReader<ArrayData> {
    private final OrcValueReader<?> elementReader;

    private ArrayReader(OrcValueReader<?> elementReader) {
      this.elementReader = elementReader;
    }

    @Override
    public ArrayData nonNullRead(ColumnVector vector, int row) {
      ListColumnVector listVector = (ListColumnVector) vector;
      int offset = (int) listVector.offsets[row];
      int length = (int) listVector.lengths[row];
      List<Object> elements = Lists.newArrayListWithExpectedSize(length);
      for (int c = 0; c < length; ++c) {
        elements.add(elementReader.read(listVector.child, offset + c));
      }
      return new GenericArrayData(elements.toArray());
    }
  }

  private static class MapReader implements OrcValueReader<MapData> {
    private final OrcValueReader<?> keyReader;
    private final OrcValueReader<?> valueReader;

    private MapReader(OrcValueReader<?> keyReader, OrcValueReader<?> valueReader) {
      this.keyReader = keyReader;
      this.valueReader = valueReader;
    }

    @Override
    public MapData nonNullRead(ColumnVector vector, int row) {
      MapColumnVector mapVector = (MapColumnVector) vector;
      int offset = (int) mapVector.offsets[row];
      long length = mapVector.lengths[row];
      List<Object> keys = Lists.newArrayListWithExpectedSize((int) length);
      List<Object> values = Lists.newArrayListWithExpectedSize((int) length);
      for (int c = 0; c < length; c++) {
        keys.add(keyReader.read(mapVector.keys, offset + c));
        values.add(valueReader.read(mapVector.values, offset + c));
      }

      return new ArrayBasedMapData(
          new GenericArrayData(keys.toArray()),
          new GenericArrayData(values.toArray()));
    }
  }

  static class StructReader extends OrcValueReaders.StructReader<InternalRow> {
    private final int numFields;

    protected StructReader(List<OrcValueReader<?>> readers, Types.StructType struct, Map<Integer, ?> idToConstant) {
      super(readers, struct, idToConstant);
      this.numFields = struct.fields().size();
    }

    @Override
    protected InternalRow create() {
      return new GenericInternalRow(numFields);
    }

    @Override
    protected void set(InternalRow struct, int pos, Object value) {
      if (value != null) {
        struct.update(pos, value);
      } else {
        struct.setNullAt(pos);
      }
    }
  }

  private static class StringReader implements OrcValueReader<UTF8String> {
    private static final StringReader INSTANCE = new StringReader();

    private StringReader() {
    }

    @Override
    public UTF8String nonNullRead(ColumnVector vector, int row) {
      BytesColumnVector bytesVector = (BytesColumnVector) vector;
      return UTF8String.fromBytes(bytesVector.vector[row], bytesVector.start[row], bytesVector.length[row]);
    }
  }

  private static class TimestampTzReader implements OrcValueReader<Long> {
    private static final TimestampTzReader INSTANCE = new TimestampTzReader();

    private TimestampTzReader() {
    }

    @Override
    public Long nonNullRead(ColumnVector vector, int row) {
      TimestampColumnVector timestampVector = (TimestampColumnVector) vector;
      return (timestampVector.time[row] / 1000) * 1_000_000 + timestampVector.nanos[row] / 1000;
    }
  }

  static class Decimal18Reader implements OrcValueReader<Decimal> {
    //TODO: these are being unused. check for bug
    private final int precision;
    private final int scale;

    Decimal18Reader(int precision, int scale) {
      this.precision = precision;
      this.scale = scale;
    }

    @Override
    public Decimal nonNullRead(ColumnVector vector, int row) {
      HiveDecimalWritable value = ((DecimalColumnVector) vector).vector[row];
      return new Decimal().set(value.serialize64(value.scale()), value.precision(), value.scale());
    }
  }

  static class Decimal38Reader implements OrcValueReader<Decimal> {
    private final int precision;
    private final int scale;

    Decimal38Reader(int precision, int scale) {
      this.precision = precision;
      this.scale = scale;
    }

    @Override
    public Decimal nonNullRead(ColumnVector vector, int row) {
      BigDecimal value = ((DecimalColumnVector) vector).vector[row]
          .getHiveDecimal().bigDecimalValue();
      return new Decimal().set(new scala.math.BigDecimal(value), precision, scale);
    }
  }
}

I like the changes here and in `SparkOrcReader`, but they aren't really needed for this PR and increase the number of files that are touched. In general, I prefer keeping changes like this separate to avoid unnecessary conflicts, and so that we can revert commits without removing unrelated clean-up.


@@ -14,10 +14,15 @@
  */
 package com.google.api.codegen.transformer.nodejs;

+import com.google.api.codegen.config.MethodConfig;
 import com.google.api.codegen.transformer.ApiMethodParamTransformer;
 import com.google.api.codegen.transformer.MethodTransformerContext;
+import com.google.api.codegen.transformer.SurfaceNamer;
+import com.google.api.codegen.util.Name;
 import com.google.api.codegen.viewmodel.DynamicLangDefaultableParamView;
 import com.google.api.codegen.viewmodel.ParamDocView;
+import com.google.api.codegen.viewmodel.SimpleParamDocView;
+import com.google.api.tools.framework.model.Field;
 import com.google.common.collect.ImmutableList;
 import java.util.List;

/* Copyright 2017 Google Inc
 *
 * 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 com.google.api.codegen.transformer.nodejs;

import com.google.api.codegen.transformer.ApiMethodParamTransformer;
import com.google.api.codegen.transformer.MethodTransformerContext;
import com.google.api.codegen.viewmodel.DynamicLangDefaultableParamView;
import com.google.api.codegen.viewmodel.ParamDocView;
import com.google.common.collect.ImmutableList;
import java.util.List;

public class NodeJSApiMethodParamTransformer implements ApiMethodParamTransformer {
  @Override
  public List<DynamicLangDefaultableParamView> generateMethodParams(
      MethodTransformerContext context) {
    // TODO(eoogbe): implement this method when migrating to MVVM
    return ImmutableList.<DynamicLangDefaultableParamView>of();
  }

  @Override
  public List<ParamDocView> generateParamDocs(MethodTransformerContext context) {
    // TODO(eoogbe): implement this method when migrating to MVVM
    return ImmutableList.<ParamDocView>of();
  }
}


@@ -133,7 +133,9 @@ public class RestServerVerticle extends AbstractVerticle {
     serverOptions.setIdleTimeout(TransportConfig.getConnectionIdleTimeoutInSeconds());
     serverOptions.setCompressionSupported(TransportConfig.getCompressed());
     serverOptions.setMaxHeaderSize(TransportConfig.getMaxHeaderSize());
-
+    if (endpointObject.isHttp2Enabled()) {
+      serverOptions.setUseAlpn(true);
+    }
     if (endpointObject.isSslEnabled()) {
       SSLOptionFactory factory =
           SSLOptionFactory.createSSLOptionFactory(SSL_KEY, 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.
 */

package org.apache.servicecomb.transport.rest.vertx;

import java.util.List;

import org.apache.servicecomb.core.Endpoint;
import org.apache.servicecomb.core.transport.AbstractTransport;
import org.apache.servicecomb.foundation.common.net.URIEndpointObject;
import org.apache.servicecomb.foundation.common.utils.SPIServiceUtils;
import org.apache.servicecomb.foundation.ssl.SSLCustom;
import org.apache.servicecomb.foundation.ssl.SSLOption;
import org.apache.servicecomb.foundation.ssl.SSLOptionFactory;
import org.apache.servicecomb.foundation.vertx.VertxTLSBuilder;
import org.apache.servicecomb.transport.rest.vertx.accesslog.AccessLogConfiguration;
import org.apache.servicecomb.transport.rest.vertx.accesslog.impl.AccessLogHandler;
import org.apache.servicecomb.transport.rest.vertx.accesslog.parser.impl.DefaultAccessLogPatternParser;
import org.apache.servicecomb.transport.rest.vertx.trace.TracePrepareHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.ext.web.Router;

public class RestServerVerticle extends AbstractVerticle {
  private static final Logger LOGGER = LoggerFactory.getLogger(RestServerVerticle.class);

  private static final String SSL_KEY = "rest.provider";

  private Endpoint endpoint;

  private URIEndpointObject endpointObject;

  @Override
  public void init(Vertx vertx, Context context) {
    super.init(vertx, context);
    this.endpoint = (Endpoint) context.config().getValue(AbstractTransport.ENDPOINT_KEY);
    this.endpointObject = (URIEndpointObject) endpoint.getAddress();
  }

  @Override
  public void start(Future<Void> startFuture) throws Exception {
    try {
      super.start();
      // 如果本地未配置地址，则表示不必监听，只需要作为客户端使用即可
      if (endpointObject == null) {
        LOGGER.warn("rest listen address is not configured, will not start.");
        startFuture.complete();
        return;
      }
      Router mainRouter = Router.router(vertx);
      mountTracePrepareHandler(mainRouter);
      mountAccessLogHandler(mainRouter);
      initDispatcher(mainRouter);
      HttpServer httpServer = createHttpServer();
      httpServer.requestHandler(mainRouter::accept);
      startListen(httpServer, startFuture);
    } catch (Throwable e) {
      // vert.x got some states that not print error and execute call back in VertexUtils.blockDeploy, we add a log our self.
      LOGGER.error("", e);
      throw e;
    }
  }

  private void mountTracePrepareHandler(Router mainRouter) {
    mainRouter.route().handler(new TracePrepareHandler());
  }

  private void mountAccessLogHandler(Router mainRouter) {
    if (AccessLogConfiguration.INSTANCE.getAccessLogEnabled()) {
      String pattern = AccessLogConfiguration.INSTANCE.getAccesslogPattern();
      LOGGER.info("access log enabled, pattern = {}", pattern);
      mainRouter.route()
          .handler(new AccessLogHandler(
              pattern,
              new DefaultAccessLogPatternParser()));
    }
  }

  private void initDispatcher(Router mainRouter) {
    List<VertxHttpDispatcher> dispatchers = SPIServiceUtils.getSortedService(VertxHttpDispatcher.class);
    for (VertxHttpDispatcher dispatcher : dispatchers) {
      dispatcher.init(mainRouter);
    }
  }

  private void startListen(HttpServer server, Future<Void> startFuture) {
    server.listen(endpointObject.getPort(), endpointObject.getHostOrIp(), ar -> {
      if (ar.succeeded()) {
        LOGGER.info("rest listen success. address={}:{}",
            endpointObject.getHostOrIp(),
            ar.result().actualPort());
        startFuture.complete();
        return;
      }

      String msg = String.format("rest listen failed, address=%s:%d",
          endpointObject.getHostOrIp(),
          endpointObject.getPort());
      LOGGER.error(msg, ar.cause());
      startFuture.fail(ar.cause());
    });
  }

  private HttpServer createHttpServer() {
    HttpServerOptions serverOptions = createDefaultHttpServerOptions();
    return vertx.createHttpServer(serverOptions);
  }

  private HttpServerOptions createDefaultHttpServerOptions() {
    HttpServerOptions serverOptions = new HttpServerOptions();
    serverOptions.setUsePooledBuffers(true);
    serverOptions.setIdleTimeout(TransportConfig.getConnectionIdleTimeoutInSeconds());
    serverOptions.setCompressionSupported(TransportConfig.getCompressed());
    serverOptions.setMaxHeaderSize(TransportConfig.getMaxHeaderSize());

    if (endpointObject.isSslEnabled()) {
      SSLOptionFactory factory =
          SSLOptionFactory.createSSLOptionFactory(SSL_KEY, null);
      SSLOption sslOption;
      if (factory == null) {
        sslOption = SSLOption.buildFromYaml(SSL_KEY);
      } else {
        sslOption = factory.createSSLOption();
      }
      SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
      VertxTLSBuilder.buildNetServerOptions(sslOption, sslCustom, serverOptions);
    }

    return serverOptions;
  }
}

this means h2 mode? but how h2c can work?


@@ -70,6 +70,11 @@ public final class CorrectForClockSkew {
     if (skew != null) {
       // the current span's skew may be a different endpoint than skewFromParent, adjust again.
       node.value(adjustTimestamps(node.value(), skew));
+    } else {
+      if (skewFromParent != null && isLocalSpan(node.value())) {
+        //Propagate skewFromParent to local spans
+         skew = skewFromParent;
+      }
     }
     // propagate skew to any children
     for (Node<Span> child : node.children()) {

/**
 * Copyright 2015-2017 The OpenZipkin Authors
 *
 * 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 zipkin.internal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import zipkin.Annotation;
import zipkin.BinaryAnnotation;
import zipkin.Constants;
import zipkin.Endpoint;
import zipkin.Span;

/**
 * Adjusts spans whose children happen before their parents, based on core annotation values.
 */
public final class CorrectForClockSkew {

  static class ClockSkew {
    final Endpoint endpoint;
    final long skew;

    public ClockSkew(Endpoint endpoint, long skew) {
      this.endpoint = endpoint;
      this.skew = skew;
    }
  }

  public static List<Span> apply(List<Span> spans) {
    for (Span s : spans) {
      if (s.parentId == null) {
        Node<Span> tree = Node.constructTree(spans);
        adjust(tree, null);
        List<Span> result = new ArrayList<>(spans.size());
        for (Iterator<Node<Span>> i = tree.traverse(); i.hasNext();) {
          result.add(i.next().value());
        }
        return result;
      }
    }
    return spans;
  }

  /**
   * Recursively adjust the timestamps on the span tree. Root span is the reference point, all
   * children's timestamps gets adjusted based on that span's timestamps.
   */
  static void adjust(Node<Span> node, @Nullable ClockSkew skewFromParent) {
    // adjust skew for the endpoint brought over from the parent span
    if (skewFromParent != null) {
      node.value(adjustTimestamps(node.value(), skewFromParent));
    }

    // Is there any skew in the current span?
    ClockSkew skew = getClockSkew(node.value());
    if (skew != null) {
      // the current span's skew may be a different endpoint than skewFromParent, adjust again.
      node.value(adjustTimestamps(node.value(), skew));
    }
    // propagate skew to any children
    for (Node<Span> child : node.children()) {
      adjust(child, skew);
    }
  }

  /** If any annotation has an IP with skew associated, adjust accordingly. */
  static Span adjustTimestamps(Span span, ClockSkew skew) {
    List<Annotation> annotations = null;
    Long annotationTimestamp = null;
    for (int i = 0, length = span.annotations.size(); i < length; i++) {
      Annotation a = span.annotations.get(i);
      if (a.endpoint == null) continue;
      if (ipsMatch(skew.endpoint, a.endpoint)) {
        if (annotations == null) annotations = new ArrayList<>(span.annotations);
        if (span.timestamp!= null && a.timestamp == span.timestamp) {
          annotationTimestamp = a.timestamp;
        }
        annotations.set(i, a.toBuilder().timestamp(a.timestamp - skew.skew).build());
      }
    }
    if (annotations != null) {
      Span.Builder builder = span.toBuilder().annotations(annotations);
      if (annotationTimestamp != null) {
        builder.timestamp(annotationTimestamp - skew.skew);
      }
      return builder.build();
    }
    // Search for a local span on the skewed endpoint
    for (int i = 0, length = span.binaryAnnotations.size(); i < length; i++) {
      BinaryAnnotation b = span.binaryAnnotations.get(i);
      if (b.endpoint == null) continue;
      if (b.key.equals(Constants.LOCAL_COMPONENT) && ipsMatch(skew.endpoint, b.endpoint)) {
        return span.toBuilder().timestamp(span.timestamp - skew.skew).build();
      }
    }
    return span;
  }

  static boolean ipsMatch(Endpoint skew, Endpoint that) {
    return (skew.ipv6 != null && Arrays.equals(skew.ipv6, that.ipv6))
        || (skew.ipv4 != 0 && skew.ipv4 == that.ipv4);
  }

  /** Use client/server annotations to determine if there's clock skew. */
  @Nullable
  static ClockSkew getClockSkew(Span span) {
    Map<String, Annotation> annotations = asMap(span.annotations);

    Long clientSend = getTimestamp(annotations, Constants.CLIENT_SEND);
    Long clientRecv = getTimestamp(annotations, Constants.CLIENT_RECV);
    Long serverRecv = getTimestamp(annotations, Constants.SERVER_RECV);
    Long serverSend = getTimestamp(annotations, Constants.SERVER_SEND);

    if (clientSend == null || clientRecv == null || serverRecv == null || serverSend == null) {
      return null;
    }

    Endpoint server = annotations.get(Constants.SERVER_RECV).endpoint;
    server = server == null ? annotations.get(Constants.SERVER_SEND).endpoint : server;
    if (server == null) return null;

    long clientDuration = clientRecv - clientSend;
    long serverDuration = serverSend - serverRecv;

    // There is only clock skew if CS is after SR or CR is before SS
    boolean csAhead = clientSend < serverRecv;
    boolean crAhead = clientRecv > serverSend;
    if (serverDuration > clientDuration || (csAhead && crAhead)) {
      return null;
    }
    long latency = (clientDuration - serverDuration) / 2;
    long skew = serverRecv - latency - clientSend;
    if (skew != 0L) {
      return new ClockSkew(server, skew);
    }
    return null;
  }

  /** Get the annotations as a map with value to annotation bindings. */
  static Map<String, Annotation> asMap(List<Annotation> annotations) {
    Map<String, Annotation> result = new LinkedHashMap<>(annotations.size());
    for (Annotation a : annotations) {
      result.put(a.value, a);
    }
    return result;
  }

  @Nullable
  static Long getTimestamp(Map<String, Annotation> annotations, String value) {
    Annotation result = annotations.get(value);
    return result != null ? result.timestamp : null;
  }

  private CorrectForClockSkew() {
  }
}


@@ -24,21 +24,9 @@ public class ExperimentalEIPs {
   // To make it easier for tests to reset the value to default
   public static final long EIP1559_BASEFEE_DEFAULT_VALUE = 1000000000L;

-  @Option(
-      hidden = true,
-      names = {"--Xeip1559-basefee-max-change-denominator"},
-      arity = "1")
-  public static Long basefeeMaxChangeDenominator = 8L;
-
   @Option(
       hidden = true,
       names = {"--Xeip1559-initial-base-fee"},
       arity = "1")
   public static Long initialBasefee = EIP1559_BASEFEE_DEFAULT_VALUE;
-
-  @Option(
-      hidden = true,
-      names = {"--Xeip1559-slack-coefficient"},
-      arity = "1")
-  public static Long slackCoefficient = 2L;
 }

/*
 * Copyright ConsenSys AG.
 *
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 */
package org.hyperledger.besu.config.experimental;

import picocli.CommandLine.Option;

/**
 * Flags defined in this class must be used with caution, and strictly reserved to experimental
 * EIPs.
 */
public class ExperimentalEIPs {
  // To make it easier for tests to reset the value to default
  public static final long EIP1559_BASEFEE_DEFAULT_VALUE = 1000000000L;

  @Option(
      hidden = true,
      names = {"--Xeip1559-basefee-max-change-denominator"},
      arity = "1")
  public static Long basefeeMaxChangeDenominator = 8L;

  @Option(
      hidden = true,
      names = {"--Xeip1559-initial-base-fee"},
      arity = "1")
  public static Long initialBasefee = EIP1559_BASEFEE_DEFAULT_VALUE;

  @Option(
      hidden = true,
      names = {"--Xeip1559-slack-coefficient"},
      arity = "1")
  public static Long slackCoefficient = 2L;
}

What do you think about deleting this class entirely and moving these constants? There are no `ExperimentalEIPs` anymore.


@@ -46,8 +46,26 @@ class ServiceImpl final : public MyGame::Example::MonsterStorage::Service {
                                   const flatbuffers::BufferRef<Stat> *request,
                                    ::grpc::ServerWriter< flatbuffers::BufferRef<Monster>>* writer)
                                   override {
-    assert(false);  // We're not actually using this RPC.
-    return grpc::Status::CANCELLED;
+       fbb_.Clear();
+       std::cout << "Hello, " << request->GetRoot()->id()->str()
+                 << request->GetRoot()->val()
+                 << request->GetRoot()->count()
+                 << std::endl;
+       std::cout << "Streaming test.\n";
+
+       for (int i=0; i<10; i++) {
+         fbb_.Clear();
+         auto monster_offset =
+           CreateMonster(fbb_, 0, 0, 0, fbb_.CreateString("Fred No." + std::to_string(i)));
+         fbb_.Finish(monster_offset);
+
+         flatbuffers::BufferRef<Monster> result(
+           fbb_.GetBufferPointer(), fbb_.GetSize());
+
+         writer->Write(result);
+       }
+
+       return grpc::Status::OK;
   }

  private:

/*
 * Copyright 2014 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.
 */

#include <thread>

#include <grpc++/grpc++.h>

#include "monster_test_generated.h"
#include "monster_test.grpc.fb.h"

using namespace MyGame::Example;

// The callback implementation of our server, that derives from the generated
// code. It implements all rpcs specified in the FlatBuffers schema.
class ServiceImpl final : public MyGame::Example::MonsterStorage::Service {
  virtual ::grpc::Status Store(::grpc::ServerContext* context,
                               const flatbuffers::BufferRef<Monster> *request,
                               flatbuffers::BufferRef<Stat> *response)
                               override {
    // Create a response from the incoming request name.
    fbb_.Clear();
    auto stat_offset = CreateStat(fbb_, fbb_.CreateString("Hello, " +
                                        request->GetRoot()->name()->str()));
    fbb_.Finish(stat_offset);
    // Since we keep reusing the same FlatBufferBuilder, the memory it owns
    // remains valid until the next call (this BufferRef doesn't own the
    // memory it points to).
    *response = flatbuffers::BufferRef<Stat>(fbb_.GetBufferPointer(),
                                             fbb_.GetSize());
    return grpc::Status::OK;
  }
  virtual ::grpc::Status Retrieve(::grpc::ServerContext *context,
                                  const flatbuffers::BufferRef<Stat> *request,
                                   ::grpc::ServerWriter< flatbuffers::BufferRef<Monster>>* writer)
                                  override {
    assert(false);  // We're not actually using this RPC.
    return grpc::Status::CANCELLED;
  }

 private:
  flatbuffers::FlatBufferBuilder fbb_;
};

// Track the server instance, so we can terminate it later.
grpc::Server *server_instance = nullptr;
// Mutex to protec this variable.
std::mutex wait_for_server;
std::condition_variable server_instance_cv;

// This function implements the server thread.
void RunServer() {
  auto server_address = "0.0.0.0:50051";
  // Callback interface we implemented above.
  ServiceImpl service;
  grpc::ServerBuilder builder;
  builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  builder.RegisterService(&service);

  // Start the server. Lock to change the variable we're changing.
  wait_for_server.lock();
  server_instance = builder.BuildAndStart().release();
  wait_for_server.unlock();
  server_instance_cv.notify_one();

  std::cout << "Server listening on " << server_address << std::endl;
  // This will block the thread and serve requests.
  server_instance->Wait();
}

int main(int /*argc*/, const char * /*argv*/[]) {
  // Launch server.
  std::thread server_thread(RunServer);

  // wait for server to spin up.
  std::unique_lock<std::mutex> lock(wait_for_server);
  while (!server_instance) server_instance_cv.wait(lock);

  // Now connect the client.
  auto channel = grpc::CreateChannel("localhost:50051",
                                     grpc::InsecureChannelCredentials());
  auto stub = MyGame::Example::MonsterStorage::NewStub(channel);

  grpc::ClientContext context;

  // Build a request with the name set.
  flatbuffers::FlatBufferBuilder fbb;
  auto monster_offset = CreateMonster(fbb, 0, 0, 0, fbb.CreateString("Fred"));
  fbb.Finish(monster_offset);
  auto request = flatbuffers::BufferRef<Monster>(fbb.GetBufferPointer(),
                                                 fbb.GetSize());
  flatbuffers::BufferRef<Stat> response;

  // The actual RPC.
  auto status = stub->Store(&context, request, &response);

  if (status.ok()) {
    auto resp = response.GetRoot()->id();
    std::cout << "RPC response: " << resp->str() << std::endl;
  } else {
    std::cout << "RPC failed" << std::endl;
  }

  server_instance->Shutdown();

  server_thread.join();

  delete server_instance;

  return 0;
}

Please use similar syntax to the rest of FlatBuffers, i.e. indentation, spacing etc.


@@ -5,18 +5,14 @@

 package net.sourceforge.pmd.lang.vf.ast;

-public class ASTAttribute extends AbstractVFNode {
+public class ASTAttribute extends AbstractVfNode {

     private String name;

-    public ASTAttribute(int id) {
+    ASTAttribute(int id) {
         super(id);
     }

-    public ASTAttribute(VfParser p, int id) {
-        super(p, id);
-    }
-
     /**
      * @return Returns the name.
      */

/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
/* Generated By:JJTree: Do not edit this line. ASTAttribute.java */

package net.sourceforge.pmd.lang.vf.ast;

public class ASTAttribute extends AbstractVFNode {

    private String name;

    public ASTAttribute(int id) {
        super(id);
    }

    public ASTAttribute(VfParser p, int id) {
        super(p, id);
    }

    /**
     * @return Returns the name.
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            The name to set.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return boolean - true if the element has a namespace-prefix, false
     *         otherwise
     */
    public boolean isHasNamespacePrefix() {
        return name.indexOf(':') >= 0;
    }

    /**
     * @return String - the part of the name that is before the (first) colon
     *         (":")
     */
    public String getNamespacePrefix() {
        int colonIndex = name.indexOf(':');
        return colonIndex >= 0 ? name.substring(0, colonIndex) : "";
    }

    /**
     * @return String - The part of the name that is after the first colon
     *         (":"). If the name does not contain a colon, the full name is
     *         returned.
     */
    public String getLocalName() {
        int colonIndex = name.indexOf(':');
        return colonIndex >= 0 ? name.substring(colonIndex + 1) : name;
    }

    /**
     * Accept the visitor. *
     */
    @Override
    public Object jjtAccept(VfParserVisitor visitor, Object data) {
        return visitor.visit(this, data);
    }
}

The setter "setName" can be package-private as well


@@ -80,6 +80,12 @@ const start = (passthroughArgs, buildConfig = config.defaultBuildConfig, options
     if (user_data_dir) {
       // clear the data directory before doing a network test
       fs.removeSync(user_data_dir.replace('\\', ''))
+      if (fs.existsSync(networkLogFile)) {
+        fs.unlinkSync(networkLogFile)
+      }
+      if (fs.existsSync('network-audit-results.json')) {
+        fs.unlinkSync('network-audit-results.json')
+      }
     }
   }

const path = require('path')
const fs = require('fs-extra')
const ip = require('ip')
const URL = require('url').URL
const config = require('../lib/config')
const util = require('../lib/util')
const whitelistedUrlPrefixes = require('./whitelistedUrlPrefixes')

const start = (passthroughArgs, buildConfig = config.defaultBuildConfig, options) => {
  config.buildConfig = buildConfig
  config.update(options)

  let braveArgs = [
    '--enable-logging',
    '--v=' + options.v,
  ]
  if (options.vmodule) {
    braveArgs.push('--vmodule=' + options.vmodule);
  }
  if (options.no_sandbox) {
    braveArgs.push('--no-sandbox')
  }
  if (options.disable_brave_extension) {
    braveArgs.push('--disable-brave-extension')
  }
  if (options.disable_brave_rewards_extension) {
    braveArgs.push('--disable-brave-rewards-extension')
  }
  if (options.disable_pdfjs_extension) {
    braveArgs.push('--disable-pdfjs-extension')
  }
  if (options.disable_webtorrent_extension) {
    braveArgs.push('--disable-webtorrent-extension')
  }
  if (options.ui_mode) {
    braveArgs.push(`--ui-mode=${options.ui_mode}`)
  }
  if (!options.enable_brave_update) {
    // This only has meaning with MacOS and official build.
    braveArgs.push('--disable-brave-update')
  }
  if (options.single_process) {
    braveArgs.push('--single-process')
  }
  if (options.show_component_extensions) {
    braveArgs.push('--show-component-extension-options')
  }
  if (options.rewards) {
    braveArgs.push(`--rewards=${options.rewards}`)
  }
  if (options.brave_ads_testing) {
    braveArgs.push('--brave-ads-testing')
  }
  if (options.brave_ads_debug) {
    braveArgs.push('--brave-ads-debug')
  }
  if (options.brave_ads_production) {
    braveArgs.push('--brave-ads-production')
  }
  if (options.brave_ads_staging) {
    braveArgs.push('--brave-ads-staging')
  }
  braveArgs = braveArgs.concat(passthroughArgs)

  let user_data_dir
  if (options.user_data_dir_name) {
    if (process.platform === 'darwin') {
      user_data_dir = path.join(process.env.HOME, 'Library', 'Application\\ Support', 'BraveSoftware', options.user_data_dir_name)
    } else if (process.platform === 'win32') {
      user_data_dir = path.join(process.env.LocalAppData, 'BraveSoftware', options.user_data_dir_name)
    } else {
      user_data_dir = path.join(process.env.HOME, '.config', 'BraveSoftware', options.user_data_dir_name)
    }
    braveArgs.push('--user-data-dir=' + user_data_dir);
  }
  const networkLogFile = path.resolve(path.join(__dirname, '..', 'network_log.json'))
  if (options.network_log) {
    braveArgs.push(`--log-net-log=${networkLogFile}`)
    braveArgs.push(`--net-log-capture-mode=IncludeSocketBytes`)
    if (user_data_dir) {
      // clear the data directory before doing a network test
      fs.removeSync(user_data_dir.replace('\\', ''))
    }
  }

  let cmdOptions = {
    stdio: 'inherit',
    timeout: options.network_log ? 120000 : undefined,
    continueOnFail: options.network_log ? true : false,
    shell: true
  }

  if (options.network_log) {
    console.log('Network audit started. Logging requests for the next 2min or until you quit Brave...')
  }

  let outputPath = options.output_path
  if (!outputPath) {
    if (process.platform === 'darwin') {
      outputPath = path.join(config.outputDir, config.macAppName() + '.app', 'Contents', 'MacOS', config.macAppName())
    } else if (process.platform === 'win32') {
      outputPath = path.join(config.outputDir, 'brave.exe')
    } else {
      outputPath = path.join(config.outputDir, 'brave')
    }
  }
  util.run(outputPath, braveArgs, cmdOptions)

  if (options.network_log) {
    let exitCode = 0
    // Read the network log
    const jsonOutput = fs.readJsonSync(networkLogFile)
    const URL_REQUEST_TYPE = jsonOutput.constants.logSourceType.URL_REQUEST
    const URL_REQUEST_FAKE_RESPONSE_HEADERS_CREATED = jsonOutput.constants.logEventTypes.URL_REQUEST_FAKE_RESPONSE_HEADERS_CREATED
    const urlRequests = jsonOutput.events.filter((event) => {
      if (event.type === URL_REQUEST_FAKE_RESPONSE_HEADERS_CREATED) {
        // showing these helps determine which URL requests which don't
        // actually hit the network
        return true
      }
      if (event.source.type === URL_REQUEST_TYPE) {
        if (!event.params) {
          return false
        }
        const url = event.params.url
        if (!url) {
          return false
        }
        if (url.startsWith('http') && url.includes('.')) {
          const found = whitelistedUrlPrefixes.find((prefix) => {
            return url.startsWith(prefix)
          })
          if (!found) {
            // Check if the URL is a private IP
            try {
              const hostname = new URL(url).hostname
              if (ip.isPrivate(hostname)) {
                // Warn but don't fail the audit
                console.log('NETWORK AUDIT WARN:', url)
                return true
              }
            } catch (e) {}
            // This is not a whitelisted URL! log it and exit with non-zero
            console.log('NETWORK AUDIT FAIL:', url)
            exitCode = 1
          }
          return true
        }
      }
      return false
    })
    fs.writeJsonSync('network-audit-results.json', urlRequests)
    if (exitCode > 0) {
      console.log(`network-audit failed. import ${networkLogFile} in chrome://net-internals for more details.`)
    } else {
      console.log('network audit passed.')
    }
    process.exit(exitCode)
  }
}

module.exports = start

Deleting the files before starting the audit helps avoid stale results if the new file is not created.


@@ -10,6 +10,17 @@ export function extend(obj, props) {
 	return obj;
 }

+/** Invoke or update a ref, depending on whether it is a function or object ref.
+ *  @param {object|function} [ref=null]
+ *  @param {any} [value]
+ */
+export function applyRef(ref, value) {
+	if (ref!=null) {
+		if (typeof ref=='function') ref(value);
+		else ref.current = value;
+	}
+}
+
 /**
  * Call a function asynchronously, as soon as possible. Makes
  * use of HTML Promise to schedule the callback if available,

/**
 * Copy all properties from `props` onto `obj`.
 * @param {object} obj Object onto which properties should be copied.
 * @param {object} props Object from which to copy properties.
 * @returns {object}
 * @private
 */
export function extend(obj, props) {
	for (let i in props) obj[i] = props[i];
	return obj;
}

/**
 * Call a function asynchronously, as soon as possible. Makes
 * use of HTML Promise to schedule the callback if available,
 * otherwise falling back to `setTimeout` (mainly for IE<11).
 * @type {(callback: function) => void}
 */
export const defer = typeof Promise=='function' ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;

This line is here to be compatible with the current way `refs` work, right?


@@ -48,11 +48,36 @@ Blockly.WidgetDiv.owner_ = null;

 /**
  * Optional cleanup function set by whichever object uses the widget.
+ * This is called as soon as a dispose is desired. If the dispose should
+ * be animated, the animation should start on the call of dispose_.
  * @type {Function}
  * @private
  */
 Blockly.WidgetDiv.dispose_ = null;

+/**
+ * Optional function called at the end of a dispose animation.
+ * Set by whichever object is using the widget.
+ * @type {Function}
+ * @private
+ */
+Blockly.WidgetDiv.disposeAnimateFinished_ = null;
+
+/**
+ * Timer ID for the dispose animation.
+ * @type {number}
+ * @private
+ */
+Blockly.WidgetDiv.disposeAnimationTimer_ = null;
+
+/**
+ * Length of time in seconds for the dispose animation.
+ * @type {number}
+ * @private
+ */
+Blockly.WidgetDiv.disposeAnimateTimerLength_ = 0;
+
+
 /**
  * Create the widget div and inject it onto the page.
  */

/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2013 Google Inc.
 * https://developers.google.com/blockly/
 *
 * 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.
 */

/**
 * @fileoverview A div that floats on top of Blockly.  This singleton contains
 *     temporary HTML UI widgets that the user is currently interacting with.
 *     E.g. text input areas, colour pickers, context menus.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.WidgetDiv');

goog.require('Blockly.Css');
goog.require('goog.dom');
goog.require('goog.style');

/**
 * The HTML container.  Set once by Blockly.WidgetDiv.createDom.
 * @type {Element}
 */
Blockly.WidgetDiv.DIV = null;

/**
 * The object currently using this container.
 * @type {Object}
 * @private
 */
Blockly.WidgetDiv.owner_ = null;

/**
 * Optional cleanup function set by whichever object uses the widget.
 * @type {Function}
 * @private
 */
Blockly.WidgetDiv.dispose_ = null;

/**
 * Create the widget div and inject it onto the page.
 */
Blockly.WidgetDiv.createDom = function() {
  if (Blockly.WidgetDiv.DIV) {
    return;  // Already created.
  }
  // Create an HTML container for popup overlays (e.g. editor widgets).
  Blockly.WidgetDiv.DIV = goog.dom.createDom('div', 'blocklyWidgetDiv');
  document.body.appendChild(Blockly.WidgetDiv.DIV);
};

/**
 * Initialize and display the widget div.  Close the old one if needed.
 * @param {!Object} newOwner The object that will be using this container.
 * @param {boolean} rtl Right-to-left (true) or left-to-right (false).
 * @param {Function} dispose Optional cleanup function to be run when the widget
 *   is closed.
 */
Blockly.WidgetDiv.show = function(newOwner, rtl, dispose) {
  Blockly.WidgetDiv.hide();
  Blockly.WidgetDiv.owner_ = newOwner;
  Blockly.WidgetDiv.dispose_ = dispose;
  // Temporarily move the widget to the top of the screen so that it does not
  // cause a scrollbar jump in Firefox when displayed.
  var xy = goog.style.getViewportPageOffset(document);
  Blockly.WidgetDiv.DIV.style.top = xy.y + 'px';
  Blockly.WidgetDiv.DIV.style.direction = rtl ? 'rtl' : 'ltr';
  Blockly.WidgetDiv.DIV.style.display = 'block';
  Blockly.Events.setGroup(true);
};

/**
 * Destroy the widget and hide the div.
 */
Blockly.WidgetDiv.hide = function() {
  if (Blockly.WidgetDiv.owner_) {
    Blockly.WidgetDiv.owner_ = null;
    Blockly.WidgetDiv.DIV.style.display = 'none';
    Blockly.WidgetDiv.DIV.style.left = '';
    Blockly.WidgetDiv.DIV.style.top = '';
    Blockly.WidgetDiv.DIV.style.height = '';
    Blockly.WidgetDiv.dispose_ && Blockly.WidgetDiv.dispose_();
    Blockly.WidgetDiv.dispose_ = null;
    goog.dom.removeChildren(Blockly.WidgetDiv.DIV);
    Blockly.Events.setGroup(false);
  }
};

/**
 * Is the container visible?
 * @return {boolean} True if visible.
 */
Blockly.WidgetDiv.isVisible = function() {
  return !!Blockly.WidgetDiv.owner_;
};

/**
 * Destroy the widget and hide the div if it is being used by the specified
 *   object.
 * @param {!Object} oldOwner The object that was using this container.
 */
Blockly.WidgetDiv.hideIfOwner = function(oldOwner) {
  if (Blockly.WidgetDiv.owner_ == oldOwner) {
    Blockly.WidgetDiv.hide();
  }
};

/**
 * Position the widget at a given location.  Prevent the widget from going
 * offscreen top or left (right in RTL).
 * @param {number} anchorX Horizontal location (window coorditates, not body).
 * @param {number} anchorY Vertical location (window coorditates, not body).
 * @param {!goog.math.Size} windowSize Height/width of window.
 * @param {!goog.math.Coordinate} scrollOffset X/y of window scrollbars.
 * @param {boolean} rtl True if RTL, false if LTR.
 */
Blockly.WidgetDiv.position = function(anchorX, anchorY, windowSize,
                                      scrollOffset, rtl) {
  // Don't let the widget go above the top edge of the window.
  if (anchorY < scrollOffset.y) {
    anchorY = scrollOffset.y;
  }
  if (rtl) {
    // Don't let the widget go right of the right edge of the window.
    if (anchorX > windowSize.width + scrollOffset.x) {
      anchorX = windowSize.width + scrollOffset.x;
    }
  } else {
    // Don't let the widget go left of the left edge of the window.
    if (anchorX < scrollOffset.x) {
      anchorX = scrollOffset.x;
    }
  }
  Blockly.WidgetDiv.DIV.style.left = anchorX + 'px';
  Blockly.WidgetDiv.DIV.style.top = anchorY + 'px';
  Blockly.WidgetDiv.DIV.style.height =
      (windowSize.height - anchorY + scrollOffset.y) + 'px';
};

Call all of these disposeAnimate\* or disposeAnimation*, but don't mix them.


@@ -15,7 +15,7 @@ export default AbstractEditController.extend({
   showUpdateButton: true,

   database: inject.service(),
-  editController: inject.controller('patients/edit'),
+  editController: null,
   filesystem: inject.service(),

   photoFileNotSet: computed('model.photoFile', function() {

import AbstractEditController from 'hospitalrun/controllers/abstract-edit-controller';
import Ember from 'ember';
import { translationMacro as t } from 'ember-i18n';

const { computed, get, inject, isEmpty, RSVP, set } = Ember;

export default AbstractEditController.extend({
  addAction: 'addPhoto',
  editTitle: t('patients.titles.editPhoto'),
  fileRequiredMessage: t('patients.messages.photoFileRequired'),
  modelName: 'photo',
  newTitle: t('patients.titles.addPhoto'),
  newModel: false,
  showFileRequired: false,
  showUpdateButton: true,

  database: inject.service(),
  editController: inject.controller('patients/edit'),
  filesystem: inject.service(),

  photoFileNotSet: computed('model.photoFile', function() {
    let model = get(this, 'model');
    let isNew = get(model, 'isNew');
    let photoFile = get(model, 'photoFile');
    return (isNew && isEmpty(photoFile));
  }),

  title: computed('model.isNew', function() {
    let isNew = get(this, 'model.isNew');
    if (isNew) {
      return get(this, 'newTitle');
    } else {
      return get(this, 'editTitle');
    }
  }),

  updateButtonAction: computed('photoFileNotSet', function() {
    let photoFileNotSet = get(this, 'photoFileNotSet');
    if (photoFileNotSet) {
      return 'showFileRequired';
    } else {
      set(this, 'showFileRequired', false);
      return 'update';
    }
  }),

  updateButtonClass: computed('photoFileNotSet', function() {
    let photoFileNotSet = get(this, 'photoFileNotSet');
    if (photoFileNotSet) {
      return 'disabled-btn';
    }
  }),

  afterUpdate(model) {
    let isNew = get(this, 'newModel');
    let editController = get(this, 'editController');
    if (isNew) {
      let photoFile = get(model, 'photoFile');
      let saveToDir = get(model, 'saveToDir');
      let fileSystem = get(this, 'filesystem');
      let modelName = get(this, 'modelName');
      let pouchDbId = get(this, 'database').getPouchId(get(model, 'id'), modelName);
      fileSystem.addFile(photoFile, saveToDir, pouchDbId).then((fileEntry) => {
        model.setProperties({
          localFile: true,
          fileName: fileEntry.fullPath,
          url: fileEntry.toURL()
        });
        model.save().then(() => {
          editController.send(get(this, 'addAction'), model);
        }).catch((err) => {
          throw err;
        });
      });
    } else {
      this.send('closeModal');
    }
  },

  beforeUpdate() {
    let model = get(this, 'model');
    let photoFile = get(model, 'photoFile');
    let isImage = get(model, 'isImage');
    let isNew = get(model, 'isNew');
    set(this, 'newModel', isNew);
    if (isNew) {
      model.setProperties({
        files: [Ember.Object.create({
          content_type: photoFile.type,
          data: photoFile,
          name: 'file'
        })],
        isImage
      });
    }
    return RSVP.resolve();
  },

  actions: {
    cancel() {
      this.send('closeModal');
    },

    showFileRequired() {
      set(this, 'showFileRequired', true);
    }
  }
});

This line should be removed as editController is not used from this context anymore.


@@ -20,23 +20,45 @@

 import Realm from 'realm';

-class Todo extends Realm.Object {}
-Todo.schema = {
-    name: 'Todo',
+class Task extends Realm.Object {}
+Task.schema = {
+    name: 'Task',
     properties: {
-        done: {type: 'bool', default: false},
+        completed: {type: 'bool', default: false},
         text: 'string',
     },
 };

-class TodoList extends Realm.Object {}
-TodoList.schema = {
-    name: 'TodoList',
+class TaskList extends Realm.Object {}
+TaskList.schema = {
+    name: 'TaskList',
     properties: {
-        name: 'string',
-        creationDate: 'date',
-        items: {type: 'list', objectType: 'Todo'},
+        id: 'string',
+        text: 'string',
+        completed: {type: 'bool', default: false},
+        items: {type: 'list', objectType: 'Task'},
+    },
+    primaryKey: 'id'
+};
+
+
+class TaskListList extends Realm.Object {}
+TaskListList.schema = {
+    name: 'TaskListList',
+    properties: {
+        id: 'int',
+        items: {type: 'list', objectType: 'TaskList'},
     },
+    primaryKey: 'id'
 };

-export default new Realm({schema: [Todo, TodoList]});
+var adminToken = "ewoJImlkZW50aXR5IjogImFkbWluIiwKCSJhY2Nlc3MiOiBbInVwbG9hZCIsICJkb3dubG9hZCIsICJtYW5hZ2UiXQp9Cg==:I1mEfddNdQo4wS/7dVgEIEm9pv7pLEyyx3zmGgWMCxkEHOxz8DxLjm/yLD8OD7iE9XcCHy4xs6SOu2ZbbRysezssyY+3z/anrz7u/EBDvyfHPRakaw3rTpD6RcTb4SaAeLBagtDP7YqycneZrGd3oUXofvJdWg4YpDOvr/+1zwntt3DGg5D1ghKzSWcF7FnosswjiqGk91t2hbZbPYNEPEJKwkCPj0exOZqQ73627rD9Jzbr3CcHpp0V4U1BEhVfgZyo9dchWYT9Qw0rkqjqc5ylvR73Ihpa9hN9+wKxhU1K6nNzsbhrD0sMfOOlxsuduWHrhiT8vkTL/WFOO4vC1Q==";
+var adminUser = Realm.Sync.User.adminUser(adminToken);
+export default new Realm({
+                         schema: [Task, TaskList, TaskListList],
+                         sync: {
+                            user: adminUser,
+                            url: "realm://192.168.157.64:9080/a46feb0c3959646acb7540971c411269/realmtasks"
+                         },
+                         path: "tasks.realm"
+                         });

////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

'use strict';

import Realm from 'realm';

class Todo extends Realm.Object {}
Todo.schema = {
    name: 'Todo',
    properties: {
        done: {type: 'bool', default: false},
        text: 'string',
    },
};

class TodoList extends Realm.Object {}
TodoList.schema = {
    name: 'TodoList',
    properties: {
        name: 'string',
        creationDate: 'date',
        items: {type: 'list', objectType: 'Todo'},
    },
};

export default new Realm({schema: [Todo, TodoList]});

How is this stored in the other examples?


@@ -57,11 +57,10 @@ module Selenium
               is_relative = Regexp.last_match(1).strip == '1'
             when /^Path=(.+)$/
               path = Regexp.last_match(1).strip
+              p = path_for(name, is_relative, path)
+              @profile_paths[name] = p if p
             end
           end
-
-          p = path_for(name, is_relative, path)
-          @profile_paths[name] = p if p
         end

         def path_for(name, is_relative, path)

# encoding: utf-8
#
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC 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.

module Selenium
  module WebDriver
    module Firefox
      # @api private
      class ProfilesIni
        def initialize
          @ini_path = File.join(Util.app_data_path, 'profiles.ini')
          @profile_paths = {}

          parse if File.exist?(@ini_path)
        end

        def [](name)
          path = @profile_paths[name]
          path && Profile.new(path)
        end

        def refresh
          @profile_paths.clear
          parse
        end

        private

        def parse
          string      = File.read @ini_path
          name        = nil
          is_relative = nil
          path        = nil

          string.split("\n").each do |line|
            case line
            when /^\[Profile/
              name, path = nil if path_for(name, is_relative, path)
            when /^Name=(.+)$/
              name = Regexp.last_match(1).strip
            when /^IsRelative=(.+)$/
              is_relative = Regexp.last_match(1).strip == '1'
            when /^Path=(.+)$/
              path = Regexp.last_match(1).strip
            end
          end

          p = path_for(name, is_relative, path)
          @profile_paths[name] = p if p
        end

        def path_for(name, is_relative, path)
          return unless [name, path].any?
          is_relative ? File.join(Util.app_data_path, path) : path
        end
      end # ProfilesIni
    end # Firefox
  end # WebDriver
end # Selenium

Moving this code inside the last case statement doesn't seem right. Why are we defining `name` and `is_relative` variables there if we aren't using them anywhere?


@@ -43,18 +43,25 @@ var TESTS = {
     QueryTests: require('./query-tests'),
     MigrationTests: require('./migration-tests'),
     EncryptionTests: require('./encryption-tests'),
-    ObjectIDTests: require('./object-id-tests'),
     AliasTests: require('./alias-tests'),
     BsonTests: require('./bson-tests'),
     // Garbagecollectiontests: require('./garbage-collection'),
 };

+//TODO: remove when MongoDB Realm test server can be hosted on Mac or other options exists
+if (isNodeProcess) {
+    TESTS.ObjectIDTests = require('./object-id-tests');
+}
+
 // If sync is enabled, run the sync tests
 if (global.enableSyncTests) {
-    TESTS.AppTests = require('./app-tests');
+    //TODO: remove when MongoDB Realm test server can be hosted on Mac or other options exists
+    if (isNodeProcess) {
+        TESTS.AppTests = require('./app-tests');
     // TESTS.OpenBehaviorTests = require('./open-behavior-tests'); // FIXME: figure out how to enable them
-    TESTS.UserTests = require('./user-tests');
-    TESTS.SessionTests = require('./session-tests');
+        TESTS.UserTests = require('./user-tests');
+        TESTS.SessionTests = require('./session-tests');
+    }
 }

 // If on node, run the async tests

////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

'use strict';

const Realm = require('realm');

if (typeof Realm.App !== 'undefined' && Realm.App !== null) {
    global.WARNING = "global is not available in React Native. Use it only in tests";
    global.enableSyncTests = process.env.REALM_DISABLE_SYNC_TESTS ? false : true;
}

const isNodeProcess = typeof process === 'object' && process + '' === '[object process]';
const isElectronProcess = typeof process === 'object' && process.versions && process.versions.electron;
const require_method = require;
function node_require(module) { return require_method(module); }

if (isNodeProcess && process.platform === 'win32') {
    global.enableSyncTests = false;
}

var TESTS = {
    ListTests: require('./list-tests'),
    LinkingObjectsTests: require('./linkingobjects-tests'),
    ObjectTests: require('./object-tests'),
    RealmTests: require('./realm-tests'),
    ResultsTests: require('./results-tests'),
    QueryTests: require('./query-tests'),
    MigrationTests: require('./migration-tests'),
    EncryptionTests: require('./encryption-tests'),
    ObjectIDTests: require('./object-id-tests'),
    AliasTests: require('./alias-tests'),
    BsonTests: require('./bson-tests'),
    // Garbagecollectiontests: require('./garbage-collection'),
};

// If sync is enabled, run the sync tests
if (global.enableSyncTests) {
    TESTS.AppTests = require('./app-tests');
    // TESTS.OpenBehaviorTests = require('./open-behavior-tests'); // FIXME: figure out how to enable them
    TESTS.UserTests = require('./user-tests');
    TESTS.SessionTests = require('./session-tests');
}

// If on node, run the async tests
if (isNodeProcess && process.platform !== 'win32') {
    TESTS.AsyncTests = node_require('./async-tests');
}

if (global.enableSyncTests) {
    // Ensure that the sync manager is initialized as initializing it
    // after calling clearTestState() doesn't work
    // Realm.Sync.User.all;
}

var SPECIAL_METHODS = {
    beforeEach: true,
    afterEach: true,
};

exports.getTestNames = function() {
    var testNames = {};

    for (var suiteName in TESTS) {
        var testSuite = TESTS[suiteName];

        testNames[suiteName] = Object.keys(testSuite).filter(function(testName) {
            return !(testName in SPECIAL_METHODS) && typeof testSuite[testName] == 'function';
        });
    }

    return testNames;
};

exports.registerTests = function(tests) {
    for (var suiteName in tests) {
        TESTS[suiteName] = tests[suiteName];
    }
};

exports.prepare = function (done) {
    done();
};

exports.runTest = function(suiteName, testName) {
    const testSuite = TESTS[suiteName];
    const testMethod = testSuite && testSuite[testName];

    if (testMethod) {
        Realm.clearTestState();
        console.warn("Starting test " + testName);
        var result = testMethod.call(testSuite);

        //make sure v8 GC can collect garbage after each test and does not fail
        if (isNodeProcess || isElectronProcess) {
            if (result instanceof Promise) {
                result.finally(() => global.gc());
                return result;
            }
            else {
                global.gc();
            }
        }

        return result;
    }

    if (!testSuite || !(testName in SPECIAL_METHODS)) {
        throw new Error(`Missing test: ${suiteName}.${testName}`);
    }
}


@@ -116,7 +116,7 @@ define(['layoutManager', 'browser', 'actionsheet', 'css!./emby-select', 'registe
             inputId++;
         }

-        if (!browser.firefox) {
+        if (browser) {
             this.classList.add('emby-select-withcolor');

 			if (layoutManager.tv) {

define(['layoutManager', 'browser', 'actionsheet', 'css!./emby-select', 'registerElement'], function (layoutManager, browser, actionsheet) {
    'use strict';

    var EmbySelectPrototype = Object.create(HTMLSelectElement.prototype);

    function enableNativeMenu() {

        if (browser.edgeUwp || browser.xboxOne) {
            return true;
        }

        // Doesn't seem to work at all
        if (browser.tizen || browser.orsay || browser.web0s) {
            return false;
        }

        // Take advantage of the native input methods
        if (browser.tv) {
            return true;
        }

        if (layoutManager.tv) {
            return false;
        }

        return true;
    }

    function triggerChange(select) {
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent("change", false, true);
        select.dispatchEvent(evt);
    }

    function setValue(select, value) {

        select.value = value;
    }

    function showActionSheet(select) {

        var labelElem = getLabel(select);
        var title = labelElem ? (labelElem.textContent || labelElem.innerText) : null;

        actionsheet.show({
            items: select.options,
            positionTo: select,
            title: title

        }).then(function (value) {
            setValue(select, value);
            triggerChange(select);
        });
    }

    function getLabel(select) {
        var elem = select.previousSibling;
        while (elem && elem.tagName !== 'LABEL') {
            elem = elem.previousSibling;
        }
        return elem;
    }

    function onFocus(e) {
        var label = getLabel(this);
        if (label) {
            label.classList.add('selectLabelFocused');
        }
    }

    function onBlur(e) {
        var label = getLabel(this);
        if (label) {
            label.classList.remove('selectLabelFocused');
        }
    }

    function onMouseDown(e) {

        // e.button=0 for primary (left) mouse button click
        if (!e.button && !enableNativeMenu()) {
            e.preventDefault();
            showActionSheet(this);
        }
    }

    function onKeyDown(e) {

        switch (e.keyCode) {

            case 13:
                if (!enableNativeMenu()) {
                    e.preventDefault();
                    showActionSheet(this);
                }
                return;
            case 37:
            case 38:
            case 39:
            case 40:
                if (layoutManager.tv) {
                    e.preventDefault();
                }
                return;
            default:
                break;
        }
    }

    var inputId = 0;

    EmbySelectPrototype.createdCallback = function () {

        if (!this.id) {
            this.id = 'embyselect' + inputId;
            inputId++;
        }

        if (!browser.firefox) {
            this.classList.add('emby-select-withcolor');

			if (layoutManager.tv) {
                this.classList.add('emby-select-tv-withcolor');
			}
        }

        if (layoutManager.tv) {
            this.classList.add('emby-select-focusscale');
        }

        this.addEventListener('mousedown', onMouseDown);
        this.addEventListener('keydown', onKeyDown);

        this.addEventListener('focus', onFocus);
        this.addEventListener('blur', onBlur);
    };

    EmbySelectPrototype.attachedCallback = function () {

        if (this.classList.contains('emby-select')) {
            return;
        }

        this.classList.add('emby-select');

        var label = this.ownerDocument.createElement('label');
        label.innerHTML = this.getAttribute('label') || '';
        label.classList.add('selectLabel');
        label.htmlFor = this.id;
        this.parentNode.insertBefore(label, this);

        if (this.classList.contains('emby-select-withcolor')) {
            this.parentNode.insertAdjacentHTML('beforeend', '

0

');
        }
    };

    EmbySelectPrototype.setLabel = function (text) {

        var label = this.parentNode.querySelector('label');

        label.innerHTML = text;
    };

    document.registerElement('emby-select', {
        prototype: EmbySelectPrototype,
        extends: 'select'
    });
});

this conditional is useless now so it should be removed