text:
/*global DiabloCalc*/
import React from 'react';
import classNames from 'classnames';
import { MenuItem, Navbar, Nav, NavItem, FormGroup, ControlLabel, FormControl, Checkbox,
  InputGroup, OverlayTrigger, Tooltip, Dropdown } from 'react-bootstrap';
import { SlideDown } from 'react-slidedown'

import { ErrorView, withAsync, Cache } from 'utils';
import { charClasses, classIcons } from 'game';

import './kadala.css';

function formatNumber(num, decimal, separator) {
  if (separator == null) {
    return num.toFixed(decimal || 0);
  }
  const parts = num.toFixed(decimal || 0).split(".");
  if (parseFloat(num) >= separator) {
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }
  return parts.join(".");
}

const ItemTooltip = ({tooltip, className, style}) => (

);

class KadalaList extends React.Component {
  render() {
    const { build, data, charClass, charLevel, hardcore, percent, collapsed, onToggle } = this.props;
    const kadalaWeight = {}, typeItems = {}, typeWeight = {};
    Object.keys(data.Items).forEach(id => {
      const item = data.Items[id];
      if (!item[charClass] || (item.hardcore && !hardcore) || !data.ItemTypes[item.type]) {
        return;
      }
      if (item.level <= charLevel) {
        const kc = data.ItemTypes[item.type].kadala;
        kadalaWeight[kc] = (kadalaWeight[kc] || 0) + item.weight;
        typeItems[item.type] = (typeItems[item.type] || []);
        typeItems[item.type].push(id);
      }
      typeWeight[item.type] = (typeWeight[item.type] || 0) + item.weight;
    });
    return (

        {Object.keys(data.ItemTypes).sort().map(type => {
          if (!typeItems[type]) return null;
          typeItems[type].sort((a, b) => data.Items[a].name.localeCompare(data.Items[b].name));
          return (

 onToggle(type)}>
                {data.ItemTypes[type].name}

              <SlideDown closed={collapsed[type]}>

                  {typeItems[type].map(id => {
                    const item = data.Items[id];
                    const kc = data.ItemTypes[item.type].kadala;
                    const chance = item.weight / kadalaWeight[kc];
                    const uchance = item.weight / typeWeight[item.type];
                    const average = data.Types[kc].cost * 10 / chance;
                    const uaverage = 25 / uchance;
                    const percentile = data.Types[kc].cost * 10 * Math.log(1 - percent / 100) / Math.log(1 - chance);
                    const iconid = (DiabloCalc.itemIcons[id] || [0])[0];
                    let name = (

                        <span className="item-icon" style={{
                          backgroundImage: `url(/css/items/${type}.png)`,
                          backgroundPosition: `0 -${(iconid || 0) * 24}px`
                        }}/>
                        {item.name}

                    );
                    if (item.tooltip) {
                      let tooltip = item.tooltip;
                      if (tooltip.includes("h3 class=\"d3-color-green\"")) {
                        tooltip = tooltip.replace("tooltip-head-orange", "tooltip-head-green");
                      }
                      name = (
                        <OverlayTrigger placement="right" overlay={<ItemTooltip tooltip={tooltip}/>}>
                          {name}
                        </OverlayTrigger>
                      );
                    }
                    return (

                        {name}

{item.level}

{formatNumber(average, 0, 10000)}

{formatNumber(percentile, 0, 10000)}

{formatNumber(uaverage, 0, 10000)}

                    );
                  })}

              </SlideDown>

          );
        })}

    );
  }
}

class KadalaViewComponent extends React.Component {
  static state = {charClass: "demonhunter", charLevel: 70, hardcore: false, percent: 80, collapsed: {}};
  constructor(props, context) {
    super(props, context);
    this.state = KadalaViewComponent.state;
  }
  componentDidUpdate() {
    KadalaViewComponent.state = this.state;
  }
  setClass = (charClass) => {
    this.setState({charClass});
  }
  setLevel = (e) => {
    let charLevel = parseInt(e.target.value, 10);
    if (isNaN(charLevel)) charLevel = 70;
    charLevel = Math.min(charLevel, 70);
    charLevel = Math.max(charLevel, 1);
    this.setState({charLevel});
  }
  setHardcore = (e) => {
    this.setState({hardcore: e.target.checked});
  }
  setPercent = (e) => {
    let percent = parseInt(e.target.value, 10);
    if (isNaN(percent)) percent = 80;
    percent = Math.min(percent, 99);
    percent = Math.max(percent, 1);
    this.setState({percent});
  }
  toggleType = (type) => {
    this.setState(({collapsed}) => ({collapsed: {...collapsed, [type]: !collapsed[type]}}));
  }
  expand = () => {
    this.setState({collapsed: {}});
  }
  collapse = () => {
    const collapsed = {};
    Object.keys(this.props.data.ItemTypes).forEach(type => collapsed[type] = true);
    this.setState({collapsed});
  }
  render() {
    const { charClass, charLevel, hardcore, percent, collapsed } = this.state;
    return (

        <Navbar fluid className="KadalaHeader">

            <Dropdown componentClass="li" onSelect={this.setClass}>
              <Dropdown.Toggle useAnchor>

                {charClasses[charClass]}
              </Dropdown.Toggle>
              <Dropdown.Menu>
                {Object.keys(charClasses).map(id => (
                  <MenuItem eventKey={id} active={charClass === id}>

                    {charClasses[id]}
                  </MenuItem>
                ))}
              </Dropdown.Menu>
            </Dropdown>
            <Navbar.Toggle/>

          <Navbar.Collapse>
            <Navbar.Form pullLeft>
              <FormGroup controlId="char-level">
                <ControlLabel>Level</ControlLabel>{" "}
                <FormControl type="number" value={charLevel} min={1} max={70} onChange={this.setLevel}/>
              </FormGroup>
              <Checkbox inline checked={hardcore} onChange={this.setHardcore} className="hc-box">Hardcore</Checkbox>
            </Navbar.Form>

              <NavItem eventKey="expand" onClick={this.expand}>Expand All</NavItem>
              <NavItem eventKey="collapse" onClick={this.collapse}>Collapse All</NavItem>

          </Navbar.Collapse>
          <OverlayTrigger placement="bottom" overlay={
              <Tooltip id="level-tooltip">Required level to gamble (if below 16, can be gambled by any character)</Tooltip>
            }>

              Level

          </OverlayTrigger>
          <OverlayTrigger placement="bottom" overlay={
              <Tooltip id="level-tooltip">Average Bood Shards required to obtain the item</Tooltip>
            }>

              Average

          </OverlayTrigger>
          <OverlayTrigger placement="bottom" overlay={
              <Tooltip id="level-tooltip">Blood Shards required to obtain the item with {percent}% certainty</Tooltip>
            }>

              <Navbar.Form>
                <FormGroup>
                  <InputGroup>
                    <FormControl type="number" value={percent} min={1} max={99} onChange={this.setPercent}/>
                    <InputGroup.Addon>%</InputGroup.Addon>
                  </InputGroup>
                </FormGroup>
              </Navbar.Form>

          </OverlayTrigger>
          <OverlayTrigger placement="bottom" overlay={
              <Tooltip id="level-tooltip">Average Death's Breaths required to cube the item by upgrading rares</Tooltip>
            }>

              Breaths

          </OverlayTrigger>
        </Navbar>
        <KadalaList {...this.props}
                    charClass={charClass}
                    charLevel={Math.max(charLevel, 16)}
                    hardcore={hardcore}
                    percent={percent}
                    collapsed={collapsed}
                    onToggle={this.toggleType}/>

    );
  }
}

const KadalaView = withAsync({
  data: ({match}, {cache}) => cache.fetch(`/api/${match.params.build}/kadala`, {global: true})
}, ({data, match}) => (
  <KadalaViewComponent build={match.params.build} data={data}/>
), undefined, ErrorView);
KadalaView.contextTypes = Cache.context;

export { KadalaView };


text:
CurlRequest::CurlRequest(const std::string& username,
                         const std::string& password,
                         const std::string& url,
                         const std::string& cacert,
                         const bool insecure,
                         curl_api* curl)
    : userpwd_(),
      url_(url),
      curl_easy_handle_(NULL),
      curl_slist_(NULL),
      curl_(curl) {
  curl_easy_handle_ = curl_->easy_init();
  if (curl_easy_handle_ == NULL) {
    notify(NFY_FATAL, "Could not start libcurl easy session.");
  }
  curl_->easy_setopt(curl_easy_handle_, CURLOPT_NOSIGNAL, true);
  curl_->easy_setopt(curl_easy_handle_, CURLOPT_FAILONERROR, true);
  curl_->easy_setopt(curl_easy_handle_, CURLOPT_FOLLOWLOCATION, true);
  curl_->easy_setopt(curl_easy_handle_, CURLOPT_MAXREDIRS, 16);
  curl_->easy_setopt(curl_easy_handle_, CURLOPT_ERRORBUFFER, error_buffer_);
  if (insecure) {
    curl_->easy_setopt(curl_easy_handle_, CURLOPT_SSL_VERIFYPEER, 0L);
  } else if (!cacert.empty()) {
    curl_->easy_setopt(curl_easy_handle_, CURLOPT_CAINFO, cacert.c_str());
  }

  // Ask for a persistent connection
  curl_slist_ = curl_->slist_append(curl_slist_, "Connection: Keep-Alive");
  if (curl_slist_ != NULL)
    curl_->easy_setopt(curl_easy_handle_, CURLOPT_HTTPHEADER, curl_slist_);

  SetUserPwd(username, password);
}

CurlRequest::~CurlRequest() {
  if (curl_easy_handle_) {
    curl_->slist_free_all(curl_slist_);
    curl_->easy_cleanup(curl_easy_handle_);
  }
}

void CurlRequest::SetUserPwd(const std::string& username,
                             const std::string& password) {
  if (!username.empty() && !password.empty()) {
    userpwd_ = username + ":" + password;
    curl_->easy_setopt(curl_easy_handle_, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_->easy_setopt(curl_easy_handle_, CURLOPT_USERPWD, userpwd_.c_str());
  }
}

size_t CurlRequest::CurlWriteFunc(void* buffer,
                                  size_t size,
                                  size_t nmemb,
                                  void* userp) {
  return size * nmemb;
}

UploadRequest::UploadRequest(const std::string& username,
                             const std::string& password,
                             const std::string& url,
                             const std::string& cacert,
                             const bool insecure,
                             const std::string& root_dir,
                             const std::vector<ManifestEntry>* const entries,
                             curl_api* curl)
    : CurlRequest(username, password, url, cacert, insecure, curl),
      root_dir_(root_dir),
      entries_(entries),
      src_fp_(NULL) {
  assert(entries_ != NULL);
}

UploadRequest::~UploadRequest() {
}

bool UploadRequest::Init(std::string src_file_path) {
  curl_->easy_setopt(curl_easy_handle_,
                   CURLOPT_READFUNCTION, UploadRequest::CurlReadFunc);
  curl_->easy_setopt(curl_easy_handle_,
                   CURLOPT_WRITEFUNCTION, CurlRequest::CurlWriteFunc);
  curl_->easy_setopt(
      curl_easy_handle_, CURLOPT_INFILE, reinterpret_cast<void*>(this));
  src_fp_ = fopen(src_file_path.c_str(), "r");
  if (src_fp_ == NULL) {
    notify(NFY_DEBUG, "src file open failed");
    return false;
  }

  return true;
}

void UploadRequest::Close() {
  if (src_fp_ != NULL) {
    fclose(src_fp_);
    src_fp_ = NULL;
  }
}

bool UploadRequest::CreateDir(const std::string& dir) {
  notify(NFY_VERBOSE, "Creating directory: %s", dir.c_str());
  std::string dest_root = url_;
  std::string complete_dir = url_ + "/" + dir;
  curl_->easy_setopt(curl_easy_handle_, CURLOPT_URL, complete_dir.c_str());
  // Create MKCOL request to create directory. We don't need to check if the
  // directory already exists coz if it does then we'll get a
  // METHOD_NOT_ALLOWED. This way is more efficient.
  curl_->easy_setopt(curl_easy_handle_, CURLOPT_CUSTOMREQUEST, "MKCOL");
  curl_->easy_perform(curl_easy_handle_);
  // Set the custom request back to null so that the following requests can
  // be set correctly.
  curl_->easy_setopt(curl_easy_handle_, CURLOPT_CUSTOMREQUEST, nullptr);
  long result_code = 0;
  curl_->easy_getinfo(curl_easy_handle_, CURLINFO_RESPONSE_CODE, &result_code);
  // We're OK with METHOD_NOT_ALLOWED coz that just means that the directory
  // already exists.
  if (result_code > 400 && result_code != METHOD_NOT_ALLOWED) {
    notify(NFY_DEBUG, "Could not create directory: %s", dir.c_str());
    notify(NFY_DEBUG, "MKCOL resulted in: %ld", result_code);
    return false;
  }
  return true;
}

bool UploadRequest::EnsureDestPath(const std::string& escaped_file_path) {
  std::vector<std::string> tokens;
  // Add the dest path to the list of dirs.
  TokenizeString(escaped_file_path, tokens, "/");
  std::string dir = root_dir_;
  for (int i = 0; i < static_cast<int>(tokens.size()) - 1; ++i) {
    dir += "/" + tokens[i];
    if (!CreateDir(dir))
      return false;
  }
  return true;
}

bool UploadRequest::Start(bool report_progress, geProgress* progress) {
  int64 processed_size = 0;
  size_t num_entries = entries_->size();
  for (size_t i = 0; i < num_entries; ++i) {
    const ManifestEntry& entry = (*entries_)[i];
    notify(NFY_DEBUG, "uploading: %s", entry.orig_path.c_str());
    if (!Init(entry.current_path)) {
      notify(NFY_VERBOSE, "Upload request Init() failed");
      return false;
    }

    if (!CreateDir(root_dir_)) {
      notify(NFY_VERBOSE, "Upload request CreateDir() failed");
      return false;
    }

    // We cannot escape the entire URL because that results in an invalid
    // PUT request (all the '/' and '.' chars are also replaced)
    std::string escaped_orig_path = ReplaceString(entry.orig_path, " ", "%20");

    if (!EnsureDestPath(escaped_orig_path)) {
      notify(NFY_VERBOSE, "Upload request EnsureDestPath() failed");
      return false;
    }

    std::string dest_url = url_ + "/" + root_dir_ + escaped_orig_path;
    curl_->easy_setopt(curl_easy_handle_, CURLOPT_URL, dest_url.c_str());
    curl_->easy_setopt(curl_easy_handle_, CURLOPT_UPLOAD, true);
    CURLcode code = curl_->easy_perform(curl_easy_handle_);
    curl_->easy_setopt(curl_easy_handle_, CURLOPT_UPLOAD, false);
    if (code != CURLE_OK) {
      notify(NFY_DEBUG, "Could not copy: Curl error code: %d", code);
      notify(NFY_DEBUG, "HTTP Error: %s", error_buffer_);
      notify(NFY_DEBUG, "  for: %s", url_.c_str());
      return false;
    }
    Close();
    processed_size += entry.data_size;
    if (report_progress && progress != NULL) {
      if (!progress->incrementDone(entry.data_size)) {
        notify(NFY_WARN, "Push interrupted");
        return false;
      }
      notify(NFY_DEBUG, "Done files: %zd/%zd, bytes: %zd",
             i + 1, num_entries, processed_size);
    } else {
      notify(NFY_VERBOSE, "Done files: %zd/%zd, bytes: %zd",
             i + 1, num_entries, processed_size);
    }
  }
  return true;
}

size_t UploadRequest::CurlReadFunc(void* buffer,
                             size_t size,
                             size_t nmemb,
                             UploadRequest* request) {
  return request->ReadData(buffer, size * nmemb);
}

size_t UploadRequest::ReadData(void* buffer, size_t requested_size) {
  size_t bytes_read = fread(buffer, 1, requested_size, src_fp_);
  return bytes_read;
}

GetRequest::GetRequest(const std::string& username,
                       const std::string& password,
                       const std::string& url,
                       const std::string& cacert,
                       const bool insecure,
                       const std::vector<std::string> &header_names,
                       int timeout_secs,
                       curl_api* curl)
    : CurlRequest(username, password, url, cacert, insecure, curl),
      status_code_(-1),
      timeout_secs_(timeout_secs) {
  for (uint i = 0; i < header_names.size(); ++i) {
    if (!header_names[i].empty())
      headers_[header_names[i]] = std::vector<std::string>();
  }
}

GetRequest::~GetRequest() {
}

bool GetRequest::Init() {
  curl_->easy_setopt(curl_easy_handle_,
                   CURLOPT_WRITEFUNCTION, GetRequest::CurlWriteFunc);
  curl_->easy_setopt(
      curl_easy_handle_, CURLOPT_WRITEDATA, reinterpret_cast<void*>(this));
  return true;
}

int GetRequest::Start(const std::string& args) {
  Init();
  curl_->easy_setopt(curl_easy_handle_, CURLOPT_POSTFIELDS, args.c_str());
  curl_->easy_setopt(curl_easy_handle_, CURLOPT_URL, url_.c_str());

  notify(NFY_DEBUG, "GetRequest: url: %s", url_.c_str());
  notify(NFY_DEBUG, "GetRequest: args: %s", args.c_str());

  if (timeout_secs_ > 0) {
    curl_->easy_setopt(curl_easy_handle_, CURLOPT_TIMEOUT, timeout_secs_);
  }
  CURLcode code = curl_->easy_perform(curl_easy_handle_);

  if (code != CURLE_OK) {
    long result_code = 0;
    CURLcode getinfoCode =
        curl_->easy_getinfo(curl_easy_handle_, CURLINFO_RESPONSE_CODE, &result_code);
    // Authentication required.
    if (getinfoCode == CURLE_OK && result_code == AUTH_REQD)
      return result_code;
    // Ignore the GOT_NOTHING error code. This happens sometimes when
    // tomcat restarts apache and for some reason apache sends out an
    // empty response. The confusing part is that this does not happen
    // every time. We need to revisit this problem and see if this
    // can be fixed in a different way.
    if (code == CURLE_GOT_NOTHING)
      return 0;
    // Else error out.
    notify(NFY_DEBUG, "Curl error code: %d", code);
    notify(NFY_DEBUG, "HTTP Error: %s", error_buffer_);
    notify(NFY_DEBUG, "  for: %s", url_.c_str());
    notify(NFY_DEBUG, "  args: %s", args.c_str());
  }
  ParseResponse();
  return status_code_;
}

size_t GetRequest::CurlWriteFunc(void* buffer, size_t size, size_t nmemb,
                                  GetRequest* request) {
  request->response_str_ +=
      std::string(reinterpret_cast<char*>(buffer), size*nmemb);
  return size * nmemb;
}

void GetRequest::ParseResponse() {
  // Split the response into lines.
  std::vector<std::string> lines;

  notify(NFY_DEBUG, "Response: %s",
         response_str_.empty() ? "empty" : response_str_.c_str());

  TokenizeString(response_str_, lines, "\n");
  for (uint i = 0; i < lines.size(); ++i) {
    std::string kDelim = ":";
    std::string kStatusCode = "Gepublish-StatusCode";
    std::string kStatusMessage = "Gepublish-StatusMessage";
    std::vector<std::string> tokens;
    CleanString(&lines[i], "\r\n");
    TokenizeString(lines[i], tokens, kDelim, 2);
    // We don't want to report an error for an invalid header coz we don't care!
    if (tokens.size() < 2)
      continue;
    // Skip this header if it is not the one we are looking for.
    HeaderMap::iterator it = headers_.find(tokens[0]);
    if (it != headers_.end()) {
      it->second.push_back(tokens[1]);
    } else if (tokens[0] == kStatusCode) {
      status_code_ = atoi(tokens[1].c_str());
    } else if (tokens[0] == kStatusMessage) {
      status_message_ = tokens[1];
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.twosigma.beaker.groovy.autocomplete;

import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.Lexer;
import org.antlr.v4.runtime.atn.ATN;
import org.antlr.v4.runtime.atn.LexerATNSimulator;
import org.antlr.v4.runtime.atn.PredictionContextCache;
import org.antlr.v4.runtime.dfa.DFA;

class PositionAdjustingLexerATNSimulator extends LexerATNSimulator {
    public PositionAdjustingLexerATNSimulator(Lexer recog, ATN atn, DFA[] decisionToDFA, PredictionContextCache sharedContextCache) {
        super(recog, atn, decisionToDFA, sharedContextCache);
    }

    protected void resetAcceptPosition(CharStream input, int index, int line, int charPositionInLine) {
        input.seek(index);
        this.line = line;
        this.charPositionInLine = charPositionInLine;
        consume(input);
    }
}


text:
package com.faforever.client.api;

import com.faforever.client.api.dto.AchievementDefinition;
import com.faforever.client.api.dto.Clan;
import com.faforever.client.api.dto.CoopMission;
import com.faforever.client.api.dto.CoopResult;
import com.faforever.client.api.dto.FeaturedModFile;
import com.faforever.client.api.dto.Game;
import com.faforever.client.api.dto.GamePlayerStats;
import com.faforever.client.api.dto.GameReview;
import com.faforever.client.api.dto.GlobalLeaderboardEntry;
import com.faforever.client.api.dto.Ladder1v1LeaderboardEntry;
import com.faforever.client.api.dto.Ladder1v1Map;
import com.faforever.client.api.dto.Map;
import com.faforever.client.api.dto.MapVersion;
import com.faforever.client.api.dto.MapVersionReview;
import com.faforever.client.api.dto.Mod;
import com.faforever.client.api.dto.ModVersion;
import com.faforever.client.api.dto.ModVersionReview;
import com.faforever.client.api.dto.PlayerAchievement;
import com.faforever.client.api.dto.PlayerEvent;
import com.faforever.client.game.KnownFeaturedMod;
import com.faforever.client.mod.FeaturedMod;
import com.faforever.client.vault.search.SearchController.SearchConfig;
import com.faforever.client.vault.search.SearchController.SortConfig;
import com.faforever.commons.io.ByteCountListener;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

/**
 * Provides access to the FAF REST API. Services should not access this class directly, but use {@link
 * com.faforever.client.remote.FafService} instead.
 */
public interface FafApiAccessor {

  List<PlayerAchievement> getPlayerAchievements(int playerId);

  @SuppressWarnings("unchecked")
  List<PlayerEvent> getPlayerEvents(int playerId);

  List<AchievementDefinition> getAchievementDefinitions();

  AchievementDefinition getAchievementDefinition(String achievementId);

  void authorize(int playerId, String username, String password);

  List<Mod> getMods();

  List<com.faforever.client.api.dto.FeaturedMod> getFeaturedMods();

  List<Ladder1v1LeaderboardEntry> getLadder1v1Leaderboard();

  List<GlobalLeaderboardEntry> getGlobalLeaderboard();

  Ladder1v1LeaderboardEntry getLadder1v1EntryForPlayer(int playerId);

  List<GamePlayerStats> getGamePlayerStats(int playerId, KnownFeaturedMod knownFeaturedMod);

  List<Map> getMostPlayedMaps(int count, int page);

  List<Map> getHighestRatedMaps(int count, int page);

  List<Map> getNewestMaps(int count, int page);

  List<Game> getLastGamesOnMap(int playerId, String mapVersionId, int count);

  void uploadMod(Path file, ByteCountListener listener);

  void uploadMap(Path file, boolean isRanked, ByteCountListener listener) throws IOException;

  List<CoopMission> getCoopMissions();

  List<CoopResult> getCoopLeaderboard(String missionId, int numberOfPlayers);

  void changePassword(String username, String currentPasswordHash, String newPasswordHash) throws IOException;

  ModVersion getModVersion(String uid);

  List<FeaturedModFile> getFeaturedModFiles(FeaturedMod featuredMod, Integer version);

  List<Game> getNewestReplays(int count, int page);

  List<Game> getHighestRatedReplays(int count, int page);

  List<Game> findReplaysByQuery(String condition, int maxResults, int page, SortConfig sortConfig);

  Optional<MapVersion> findMapByFolderName(String folderName);

  List<com.faforever.client.api.dto.Player> getPlayersByIds(Collection<Integer> playerIds);

  GameReview createGameReview(GameReview review);

  void updateGameReview(GameReview review);

  ModVersionReview createModVersionReview(ModVersionReview review);

  void updateModVersionReview(ModVersionReview review);

  MapVersionReview createMapVersionReview(MapVersionReview review);

  void updateMapVersionReview(MapVersionReview review);

  void deleteGameReview(String id);

  Optional<Clan> getClanByTag(String tag);

  List<Map> findMapsByQuery(String query, int page, int maxResults, SortConfig sortConfig);

  Optional<MapVersion> findMapVersionById(String id);

  void deleteMapVersionReview(String id);

  void deleteModVersionReview(String id);

  Optional<Game> findReplayById(int id);

  List<Mod> findModsByQuery(SearchConfig query, int page, int maxResults);

  List<Ladder1v1Map> getLadder1v1Maps(int count, int page);
}


text:
import CommentsSerializer from '../comments'

class AdminCommentsSerializer extends CommentsSerializer {

}

export default AdminCommentsSerializer


text:
<!doctype html>
<html lang="en-US">
<head>
  <meta charset="UTF-8">
  <title>Dogecoin Wallet</title>

  <meta name="description" content="A Dogecoin wallet for Kik. Wow Doge">
  <link rel="kik-icon" href="images/dogecoin2.png">
  <link rel="canonical" href="https://kikdogewallet.herokuapp.com/">

  <link rel="icon" href="images/dogecoin2.png">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
  <meta name="kik-unsupported" content="android-2.2">

  <script src="scripts/kik.js"></script>
  <script src="bower_components/ionic/release/js/ionic.bundle.js"></script>
  <script src="bower_components/underscore/underscore.js"></script>
  <link rel="stylesheet" href="bower_components/ionic/release/css/ionic.min.css">

  <link rel="stylesheet" href="styles/wow.css"/>
  <script src="app.js"></script>
  <script src="scripts/controllers/Sidebar.js"></script>
  <script src="scripts/controllers/Wallet.js"></script>
  <script src="scripts/controllers/SendCoins.js"></script>
  <script src="scripts/controllers/Withdraw.js"></script>
  <script src="scripts/controllers/History.js"></script>
  <script src="scripts/services/DogecoinService.js"></script>
  <script src="scripts/services/InterfaceState.js"></script>
  <script src="scripts/services/WalletManager.js"></script>
  <script src="scripts/directives/selectOnClick.js"></script>
  <script src="scripts/kikMock.js"></script>
</head>
<body ng-app="kikDogeWalletApp">

<div ng-controller="SidebarCtrl">
<ion-nav-view></ion-nav-view>
</div>

</body>
</html>


text:
<?php
/**
 * Created by PhpStorm.
 * User: ww
 * Date: 15.10.15
 * Time: 3:31
 */
namespace React\PublisherPulsar;

use FractalBasic\Inventory\InitStartMethodDto;
use React\FractalBasic\Abstracts\BaseSubsidiary;
use React\FractalBasic\Inventory\ErrorsConstants;
use React\FractalBasic\Inventory\EventsConstants;
use React\PublisherPulsar\Inventory\PreparingRequestDto;
use React\PublisherPulsar\Inventory\PulsarErrorConstants;
use React\PublisherPulsar\Inventory\PulsarToReplyStackReplyDto;
use React\PublisherPulsar\Inventory\ReplyStackErrorDto;
use React\PublisherPulsar\Inventory\ReplyStackDto;
use React\PublisherPulsar\Inventory\ReplyStackToPulsarGetTaskRequestDto;
use React\PublisherPulsar\Inventory\ReplyStackToPulsarReturnResultRequestDto;
use Monolog\Logger;

class ReplyStack extends BaseSubsidiary
{
    /**
     * @var \ZMQSocket
     */
    protected $pulsarRequestSocket;

    /**
     * @var \ZMQSocket
     */
    protected $performersReplySocket;

    /**
     * @var \ZMQContext
     */
    protected $context;

    /**
     * @var Logger
     */
    protected $logger;

    /**
     * @var string
     */
    protected $loggerPostfix;

    /**
     * @return null
     */
    public function startCommunication()
    {
        $this->initLoop();

        $this->context = new \ZMQContext();
        $this->pulsarRequestSocket = $this->context->getSocket(\ZMQ::SOCKET_REQ);
        $this->performersReplySocket = $this->context->getSocket(\ZMQ::SOCKET_REP);

        $this->initStreams();

        $replyStackErrorDtoAlreadySent = false;

        /**
         * Receive sockets params from Pulsar and start cyclical communication
         */
        $this->readStream->on(EventsConstants::DATA, function ($data) use ($replyStackErrorDtoAlreadySent) {

            $replyStackDto = null;
            $replyStackDto = @unserialize($data);

            if (($replyStackDto !== false) && ($replyStackDto instanceof ReplyStackDto)) {

                $this->pulsarRequestSocket->connect($replyStackDto->getReplyStackVsPulsarSocketAddress());
                $this->performersReplySocket->bind($replyStackDto->getReplyStackVsPerformersSocketAddress());

                $this->moduleDto = $replyStackDto;
                $initDto = new InitStartMethodDto();
                $initDto->setShutDownArg('warning');
                $this->initStartMethods($initDto);

                //TODO: make resolver of ways of ReplyStack logging
                //$this->logger->debug("ReplyStack receive initDto from Pulsar.");
                $this->loop->nextTick([$this, 'startStackWork']);

            } else {

                if ($replyStackErrorDtoAlreadySent === false) {

                    $replyStackErrorDtoAlreadySent = true;

                    $replyStackError = new ReplyStackErrorDto();
                    $replyStackError->setErrorLevel(ErrorsConstants::CRITICAL);
                    $replyStackError->setErrorReason(PulsarErrorConstants::REPLY_STACK_RECEIVE_NOT_CORRECT_DTO);

                    //write to Pulsar's allotted STDIN about critical error
                    $this->writeStream->write(serialize($replyStackError));

                    $this->loop->nextTick(function () {
                        $this->loop->stop();
                    });

                }
            }
        });

        $this->loop->run();

        return null;
    }

    /**
     * @return null
     */
    public function startStackWork()
    {
        $getTaskDto = new ReplyStackToPulsarGetTaskRequestDto();
        $considerMeAsSubscriber = 0;

        while (true) {

            //$this->logger->debug("Start ReplyStack while.");

            $this->pulsarRequestSocket->send(serialize($getTaskDto));

            /**Blocking wait reply from Pulsar
             * @var PulsarToReplyStackReplyDto $pulsarToReplyStackReplyDto
             */
            $pulsarToReplyStackReplyDto = unserialize($this->pulsarRequestSocket->recv());

            //$this->logger->debug("REPLY STACK asked to prepare subscribers: " . $pulsarToReplyStackReplyDto->getSubscribersNumber());

            for ($i = 1; $i <= $pulsarToReplyStackReplyDto->getSubscribersNumber(); $i++) {

                $preparingDto = unserialize($this->performersReplySocket->recv());
                //$this->logger->debug("REPLY STACK: receive request $i");

                if ($preparingDto instanceof PreparingRequestDto) {
                    $considerMeAsSubscriber++;
                    //$this->logger->debug("REPLY STACK: considerMeAsSubscriber: $considerMeAsSubscriber");
                    $this->performersReplySocket->send(serialize($pulsarToReplyStackReplyDto->getDtoToTransfer()));
                }
            }

            //$this->logger->debug("REPLY STACK prepared subscribers: " . $considerMeAsSubscriber);

            $replyStackResult = new ReplyStackToPulsarReturnResultRequestDto();
            $replyStackResult->setConsiderMeAsSubscriber($considerMeAsSubscriber);

            $this->pulsarRequestSocket->send(serialize($replyStackResult));

            //$this->logger->debug("Wait finishing message from Pulsar.");
            $this->pulsarRequestSocket->recv();
            //$this->logger->debug("Got finish message from Pulsar.");
            $considerMeAsSubscriber = 0;

            //$this->logger->debug("Finish ReplyStack while.");
        }

        return null;
    }

}


text:
angular.module('checkboxDemo1', ['ngMaterial'])
    .controller('AppCtrl', function ($scope) {
        $scope.data = {};
        $scope.data.cb1 = true;
        $scope.data.cb2 = false;
        $scope.data.cb3 = false;
        $scope.data.cb4 = false;
        $scope.data.cb5 = false;
    });


text:
<?php

namespace App\Model;

use App\Model\Tables\LocCountryTable;
use App\Model\Tables\LocStateTable;
use App\Model\Tables\LocCityTable;
use Doctrine\Common\Util\Debug;

/* * ********************************************************
 * MODELO Module
 * =======================================================
 *
 * ATRIBUTOS
 * $personaTable   // Tabla modulos
 *
 *
 * METODOS
 * getFamilia ($cedula = '', $codigo = '');
 *
 * ******************************************************** */

class Location {

    protected $countryTable;
    protected $stateTable;
    protected $cityTable;

    public function __construct() {
        $this->countryTable = new LocCountryTable();
        $this->stateTable = new LocStateTable();
        $this->cityTable = new LocCityTable();
    }

    public function getLocation() {
        $paises = $this->countryTable->fetchAll();
        $estados = $this->stateTable->fetchAll();
        $ciudades = $this->cityTable->fetchAll();

        $data = array();

        $data['paises'] = $paises;
        $data['estados'] = $estados;
        $data['ciudades'] = $ciudades;

        return $data;
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.apptik.widget.example.multislider" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="io.apptik.widget.example.multislider.MyActivity"
            android:label="@string/title_activity_my"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
<?php

class Services_Twilio_Rest_TaskRouter_WorkspaceStatistics extends Services_Twilio_TaskRouterInstanceResource
{

}


text:
package rabbit.cache.ncache;

import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;

/** A class that stores cache keys in compressed form.
 *
 * @param <K> they key object type
 *
 * @author Robert Olofsson
 */
class FiledKey<K> extends FileData<K> {
    private static final long serialVersionUID = 20050430;

    protected int hashCode; // the hashCode for the contained object.
    private long id;
    protected transient NCache<K, ?> cache;

    protected String getExtension () {
	return "key";
    }

    protected <V> void setCache (NCache<K, V> cache) {
	this.cache = cache;
    }

    protected <V> long storeKey (NCache<K, V> cache,
				 long id, K key,
				 Logger logger)
	throws IOException {
	setCache (cache);
	hashCode = key.hashCode ();
	this.id = id;
	return writeData (getFileName (), cache.getKeyFileHandler (),
			  key, logger);
    }

    private File getFileName () {
	return cache.getEntryName (id, true, getExtension ());
    }

    /** Get the hashCode for the contained key object. */
    @Override public int hashCode () {
	return hashCode;
    }

    /** Check if the given object is equal to the contained key. */
    @Override public boolean equals (Object data) {
	if (data == null)
	    return false;
	try {
	    K myData = getData ();
	    if (data instanceof FiledKey) {
		data = ((FiledKey)data).getData ();
	    }
	    if (myData != null) {
		return myData.equals (data);
	    }
	    return data == null;
	} catch (IOException e) {
	    throw new RuntimeException ("Failed to read contents", e);
	}
    }

    /** Get the actual key object.
     * @return the key object
     * @throws IOException if reading the data fails
     */
    public K getData () throws IOException {
	return readData (getFileName (), cache.getKeyFileHandler (),
			 cache.getLogger ());
    }

    /** Get the unique id for this object.
     * @return the id of this object
     */
    public long getId () {
	return id;
    }

    @Override public String toString () {
	return "FiledKey: " + hashCode + ", " + getFileName ();
    }
}


text:
<?php

namespace Magento\Vault\Block;

use Magento\Framework\View\Element\Template;
use Magento\Payment\Model\CcConfigProvider;
use Magento\Vault\Api\Data\PaymentTokenInterface;

/**
 * Class AbstractCardRenderer
 * @api
 */
abstract class AbstractCardRenderer extends Template implements CardRendererInterface
{
    /**
     * @var PaymentTokenInterface|null
     */
    private $token;

    /**
     * @var array|null
     */
    private $tokenDetails;

    /**
     * @var CcConfigProvider
     */
    private $iconsProvider;

    /**
     * Constructor
     *
     * @param Template\Context $context
     * @param CcConfigProvider $iconsProvider
     * @param array $data
     */
    public function __construct(
        Template\Context $context,
        CcConfigProvider $iconsProvider,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->iconsProvider = $iconsProvider;
    }

    /**
     * Renders specified token
     *
     * @param PaymentTokenInterface $token
     * @return string
     */
    public function render(PaymentTokenInterface $token)
    {
        $this->token = $token;
        $this->tokenDetails = json_decode($this->getToken()->getTokenDetails() ?: '{}', true);
        $result = $this->toHtml();
        $this->token = null;
        $this->tokenDetails = null;

        return $result;
    }

    /**
     * @return PaymentTokenInterface
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * @return array
     */
    protected function getTokenDetails()
    {
        return $this->tokenDetails;
    }

    /**
     * @param string $type
     * @return array
     */
    protected function getIconForType($type)
    {
        if (isset($this->iconsProvider->getIcons()[$type])) {
            return $this->iconsProvider->getIcons()[$type];
        }

        return [
            'url' => '',
            'width' => 0,
            'height' => 0
        ];
    }
}


text:
<!-- Licensed under a BSD license. See license.html for license -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Three.js - Background CSS</title>
    <style>
    html, body {
        height: 100%;
        margin: 0;
    }
    #c {
        width: 100%;
        height: 100%;
        display: block;
    }
    </style>
  </head>
  <body>
    <canvas id="c"></canvas>
  </body>
<script type="module">
import * as THREE from '../../build/three.module.js';

function main() {
  const canvas = document.querySelector('#c');
  const renderer = new THREE.WebGLRenderer({canvas});
  renderer.autoClearColor = false;

  const fov = 75;
  const aspect = 2;  // the canvas default
  const near = 0.1;
  const far = 5;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.z = 2;

  const scene = new THREE.Scene();

  {
    const color = 0xFFFFFF;
    const intensity = 1;
    const light = new THREE.DirectionalLight(color, intensity);
    light.position.set(-1, 2, 4);
    scene.add(light);
  }

  const boxWidth = 1;
  const boxHeight = 1;
  const boxDepth = 1;
  const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);

  function makeInstance(geometry, color, x) {
    const material = new THREE.MeshPhongMaterial({color});

    const cube = new THREE.Mesh(geometry, material);
    scene.add(cube);

    cube.position.x = x;

    return cube;
  }

  const cubes = [
    makeInstance(geometry, 0x44aa88,  0),
    makeInstance(geometry, 0x8844aa, -2),
    makeInstance(geometry, 0xaa8844,  2),
  ];

  const bgCamera = new THREE.OrthographicCamera(
    -1, // left
     1, // right
     1, // top
    -1, // bottom
    -1, // near,
     1, // far
  );

  const bgScene = new THREE.Scene();

  const loader = new THREE.TextureLoader();
  const bgTexture = loader.load('resources/images/daikanyama.jpg');
  let bgMesh;
  {
    const plane = new THREE.PlaneGeometry(2, 2);
    const material = new THREE.MeshBasicMaterial({
      map: bgTexture,
      depthTest: false,
    });
    bgMesh = new THREE.Mesh(plane, material);
    bgScene.add(bgMesh);
  }

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }

  function render(time) {
    time *= 0.001;

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
    }

    // Scale the background plane to cover and keep the image's aspect correct.
    // Note the image may not have loaded yet.
    const canvasAspect = canvas.clientWidth / canvas.clientHeight;
    const imageAspect = bgTexture.image ? bgTexture.image.width / bgTexture.image.height : 1;
    const aspect = imageAspect / canvasAspect;
    // choose an axis to have a scale of 1 and the other >= 1
    bgMesh.scale.x = aspect > 1 ? aspect : 1;
    bgMesh.scale.y = aspect > 1 ? 1 : 1 / aspect;

    cubes.forEach((cube, ndx) => {
      const speed = 1 + ndx * .1;
      const rot = time * speed;
      cube.rotation.x = rot;
      cube.rotation.y = rot;
    });

    renderer.render(bgScene, bgCamera);
    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }

  requestAnimationFrame(render);
}

main();
</script>
</html>


text:
package org.python.core;

import junit.framework.TestCase;

import org.python.util.PythonInterpreter;

public class WrappedBooleanTest extends TestCase {

    // Simulate the use case where you want to expose some (possibly mutable)
    // java boolean field to an interpreter without having to set the value to a
    // new PyBoolean each time it changes.
    @SuppressWarnings("serial")
    static class WrappedBoolean extends PyBoolean {
        public WrappedBoolean() {
            super(true);
        }

        private boolean mutableValue;

        @Override
        public boolean getBooleanValue() {
            return mutableValue;
        }

        public void setMutableValue(final boolean newValue) {
            mutableValue = newValue;
        }
    }

    private PythonInterpreter interp;
    private WrappedBoolean a, b;

    @Override
    protected void setUp() throws Exception {
        interp = new PythonInterpreter(new PyStringMap(), new PySystemState());
        a = new WrappedBoolean();
        b = new WrappedBoolean();
        a.setMutableValue(true);
        b.setMutableValue(false);
        interp.set("a", a);
        interp.set("b", b);
    }

    public void testAnd() {
        interp.exec("c = a and b");
        assertEquals(new PyBoolean(false), interp.get("c"));
        b.setMutableValue(true);
        interp.exec("c = a and b");
        assertEquals(new PyBoolean(true), interp.get("c"));
    }

    public void testOr() {
        interp.exec("c = a or b");
        assertEquals(new PyBoolean(true), interp.get("c"));
        a.setMutableValue(false);
        interp.exec("c = a or b");
        assertEquals(new PyBoolean(false), interp.get("c"));
    }
}


text:
package org.conqat.engine.persistence.store.rmi;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import org.conqat.engine.persistence.store.IStorageSystem;
import org.conqat.engine.persistence.store.IStore;
import org.conqat.engine.persistence.store.StorageException;
import org.conqat.lib.commons.net.LocalhostRMISocketFactory;
import org.conqat.lib.commons.net.SmartRMISocketFactory;

/**
 * A simple storage system based on RMI communication.
 *
 * @author $Author: heineman $
 * @version $Rev: 37938 $
 * @ConQAT.Rating GREEN Hash: F76A5B7DAFBB974089DE3F273ED6849C
 */
public class RmiStorageSystem implements IStorageSystem {

	/** The remote store. */
	private IRemoteStore remoteStore;

	/** Constructor. */
	public RmiStorageSystem(String host, int port) throws RemoteException,
			NotBoundException {
		SmartRMISocketFactory factory;
		if ("localhost".equals(host) || "127.0.0.1".equals(host)) {
			factory = new LocalhostRMISocketFactory();
		} else {
			factory = new SmartRMISocketFactory();
		}

		Registry registry = LocateRegistry.getRegistry(host, port, factory);
		remoteStore = (IRemoteStore) registry
				.lookup(RmiStorageServer.STORAGE_SERVER_URL);
	}

	/** {@inheritDoc} */
	@Override
	public IStore openStore(String name) throws StorageException {
		if (remoteStore == null) {
			throw new StorageException("May not access store after closing!");
		}

		return new RmiStore(name, remoteStore);
	}

	/** {@inheritDoc} */
	@Override
	public void removeStore(String storeName) throws StorageException {
		throw new StorageException("Removal not supported via RMI.");
	}

	/** {@inheritDoc} */
	@Override
	public void close() {
		// allow garbage collector to kill the connection
		remoteStore = null;
	}
}


text:
package eu.aylett.atunit.example;

import eu.aylett.atunit.AtUnit;
import eu.aylett.atunit.Unit;
import eu.aylett.atunit.example.subjects.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertEquals;

/**
 * This example shows AtUnit at its most basic:  No mocks, no container.
 */
@RunWith(AtUnit.class) // tell JUnit to use AtUnit
public class ExampleAtUnitTest {

    /*
     * An AtUnit test must have exactly one field annotated with @Unit to
     * indicate the unit under test. (The @Unit annotation doesn't do anything,
     * it just serves to encourage good testing practice.)
     */
    @Unit
    User user;

    @Before
    public void setUp() {
        user = new User(123, "testusername");
    }

    @Test
    public void testGetId() {
        assertEquals(123, user.getId().intValue());
    }

    @Test
    public void testGetUsername() {
        assertEquals("testusername", user.getUsername());
    }

}


text:
import axios from 'axios';

const token = window.document.querySelector('meta[name="csrf-token"]')
          && window.document.querySelector('meta[name="csrf-token"]').content;
const CSRFHEADER = { headers: { 'X-CSRF-TOKEN': token } };

export const get = (url, params) =>
  axios.get(url, {...CSRFHEADER, params});

export const patch = (url, params, config) =>
  axios.patch(url, params, {...CSRFHEADER, ...config });

export const destroy = (url, params, config) =>
  axios.delete(url, params, {...CSRFHEADER, ...config });


text:
#ifndef __ANT_EVENT_RX_H__
#define __ANT_EVENT_RX_H__

#include <string.h>
#include "ant_parameters.h"
#include "ant_stack_handler_types.h"

/**
 * @addtogroup ser_conn_s212_codecs
 * @{
 * @ingroup ser_codecs_conn
 */

/**
 * @brief Encodes ant_event_rx event.
 *
 * @param[in] p_event          Pointer to the \ref ant_evt_t buffer that shall be encoded.
 * @param[in] event_len        Size (in bytes) of \p p_event buffer.
 * @param[out] p_buf           Pointer to the beginning of a buffer for encoded event packet.
 * @param[in,out] p_buf_len    \c in: Size (in bytes) of \p p_buf buffer.
 *                             \c out: Length of encoded contents in \p p_buf.
 *
 * @retval NRF_SUCCESS               Encoding success.
 * @retval NRF_ERROR_NULL            Encoding failure. NULL pointer supplied.
 * @retval NRF_ERROR_INVALID_LENGTH  Encoding failure. Incorrect buffer length.
 */
uint32_t ant_event_rx_enc(ant_evt_t const * const p_event,
                          uint32_t                event_len,
                          uint8_t * const         p_buf,
                          uint32_t * const        p_buf_len);

/** @} */
#endif


text:
package org.apache.bval.jsr.issues;

import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
import java.util.Set;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;

public class BVAL174 {

    @Audience("movies")
    public String getMovie() {
        return "";
    }

    @Audience("movies")
    public void addMovie(String newMovie) {

    }

    @Documented
    @javax.validation.Constraint(validatedBy = {Audience.Constraint.class})
    @Target({METHOD, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    public @interface Audience {

        String value();

        Class<?>[] groups() default {};

        String message() default "The 'aud' claim must contain '{value}'";

        Class<? extends Payload>[] payload() default {};

        class Constraint implements ConstraintValidator<Audience, JsonWebToken> {
            private Audience audience;

            @Override
            public void initialize(final Audience constraint) {
                this.audience = constraint;
            }

            @Override
            public boolean isValid(final JsonWebToken value, final ConstraintValidatorContext context) {
                final Set<String> audience = value.getAudience();
                return audience != null && audience.contains(this.audience.value());
            }
        }
    }

    public class JsonWebToken {

        public Set<String> getAudience() {
            return null;
        }
    }
}


text:
title: User GPG Keys
---

{% if page.version == 'dotcom' %}

# GPG Keys

{{#tip}}

  APIs for managing user GPG keys are currently available for developers to preview.
  During the preview period, the APIs may change without advance notice.
  Please see the [blog post](/changes/2016-04-04-git-signing-api-preview) for full details.

  To access the API you must provide a custom [media type](/v3/media) in the `Accept` header:

      application/vnd.github.cryptographer-preview

{{/tip}}

{:toc}

## List your GPG keys

    GET /user/gpg_keys

Lists the current user's GPG keys. Requires that you are authenticated via
Basic Auth or via OAuth with at least `read:gpg_key`
[scope](/v3/oauth/#scopes).

### Response

<%= headers 200, :pagination => default_pagination_rels %>
<%= json(:gpg_key) { |h| [h] } %>

## Get a single GPG key

View extended details for a single GPG key. Requires that you are
authenticated via Basic Auth or via OAuth with at least `read:gpg_key`
[scope](/v3/oauth/#scopes).

    GET /user/gpg_keys/:id

### Response

<%= headers 200 %>
<%= json :gpg_key %>

## Create a GPG key

Creates a GPG key. Requires that you are authenticated via Basic Auth,
or OAuth with at least `write:gpg_key` [scope](/v3/oauth/#scopes).

    POST /user/gpg_keys

### Input

<%= json :armored_public_key => "-----BEGIN PGP PUBLIC KEY BLOCK-----\n...\n-----END PGP PUBLIC KEY BLOCK-----" %>

### Response

<%= headers 201, :Location => get_resource(:gpg_key)['url'] %>
<%= json :gpg_key %>

## Delete a GPG key

Removes a GPG key. Requires that you are authenticated via Basic Auth
or via OAuth with at least `admin:gpg_key` [scope](/v3/oauth/#scopes).

    DELETE /user/gpg_keys/:id

### Response

<%= headers 204 %>

{% endif %}


text:
//===--- AutoDiff.cpp - Swift automatic differentiation utilities ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/AST/AutoDiff.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/ImportCache.h"
#include "swift/AST/Module.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"

using namespace swift;

AutoDiffDerivativeFunctionKind::AutoDiffDerivativeFunctionKind(
    StringRef string) {
  Optional<innerty> result = llvm::StringSwitch<Optional<innerty>>(string)
                                 .Case("jvp", JVP)
                                 .Case("vjp", VJP);
  assert(result && "Invalid string");
  rawValue = *result;
}

NormalDifferentiableFunctionTypeComponent::
    NormalDifferentiableFunctionTypeComponent(
        AutoDiffDerivativeFunctionKind kind) {
  switch (kind) {
  case AutoDiffDerivativeFunctionKind::JVP:
    rawValue = JVP;
    return;
  case AutoDiffDerivativeFunctionKind::VJP:
    rawValue = VJP;
    return;
  }
}

NormalDifferentiableFunctionTypeComponent::
    NormalDifferentiableFunctionTypeComponent(StringRef string) {
  Optional<innerty> result = llvm::StringSwitch<Optional<innerty>>(string)
                                 .Case("original", Original)
                                 .Case("jvp", JVP)
                                 .Case("vjp", VJP);
  assert(result && "Invalid string");
  rawValue = *result;
}

Optional<AutoDiffDerivativeFunctionKind>
NormalDifferentiableFunctionTypeComponent::getAsDerivativeFunctionKind() const {
  switch (rawValue) {
  case Original:
    return None;
  case JVP:
    return {AutoDiffDerivativeFunctionKind::JVP};
  case VJP:
    return {AutoDiffDerivativeFunctionKind::VJP};
  }
  llvm_unreachable("invalid derivative kind");
}

LinearDifferentiableFunctionTypeComponent::
    LinearDifferentiableFunctionTypeComponent(StringRef string) {
  Optional<innerty> result = llvm::StringSwitch<Optional<innerty>>(string)
                                 .Case("original", Original)
                                 .Case("transpose", Transpose);
  assert(result && "Invalid string");
  rawValue = *result;
}

DifferentiabilityWitnessFunctionKind::DifferentiabilityWitnessFunctionKind(
    StringRef string) {
  Optional<innerty> result = llvm::StringSwitch<Optional<innerty>>(string)
                                 .Case("jvp", JVP)
                                 .Case("vjp", VJP)
                                 .Case("transpose", Transpose);
  assert(result && "Invalid string");
  rawValue = *result;
}

Optional<AutoDiffDerivativeFunctionKind>
DifferentiabilityWitnessFunctionKind::getAsDerivativeFunctionKind() const {
  switch (rawValue) {
  case JVP:
    return {AutoDiffDerivativeFunctionKind::JVP};
  case VJP:
    return {AutoDiffDerivativeFunctionKind::VJP};
  case Transpose:
    return None;
  }
  llvm_unreachable("invalid derivative kind");
}

void SILAutoDiffIndices::print(llvm::raw_ostream &s) const {
  s << "(parameters=(";
  interleave(
      parameters->getIndices(), [&s](unsigned p) { s << p; },
      [&s] { s << ' '; });
  s << ") results=(";
  interleave(
      results->getIndices(), [&s](unsigned p) { s << p; }, [&s] { s << ' '; });
  s << "))";
}

void SILAutoDiffIndices::dump() const {
  print(llvm::errs());
  llvm::errs() << '\n';
}

SILAutoDiffIndices AutoDiffConfig::getSILAutoDiffIndices() const {
  return SILAutoDiffIndices(parameterIndices, resultIndices);
}

void AutoDiffConfig::print(llvm::raw_ostream &s) const {
  s << "(parameters=";
  parameterIndices->print(s);
  s << " results=";
  resultIndices->print(s);
  if (derivativeGenericSignature) {
    s << " where=";
    derivativeGenericSignature->print(s);
  }
  s << ')';
}

bool swift::isDifferentiableProgrammingEnabled(SourceFile &SF) {
  auto &ctx = SF.getASTContext();
  // Return true if differentiable programming is explicitly enabled.
  if (ctx.LangOpts.EnableExperimentalDifferentiableProgramming)
    return true;
  // Otherwise, return true iff the `_Differentiation` module is imported in
  // the given source file.
  bool importsDifferentiationModule = false;
  for (auto import : namelookup::getAllImports(&SF)) {
    if (import.importedModule->getName() == ctx.Id_Differentiation) {
      importsDifferentiationModule = true;
      break;
    }
  }
  return importsDifferentiationModule;
}

// TODO(TF-874): This helper is inefficient and should be removed. Unwrapping at
// most once (for curried method types) is sufficient.
static void unwrapCurryLevels(AnyFunctionType *fnTy,
                              SmallVectorImpl<AnyFunctionType *> &results) {
  while (fnTy != nullptr) {
    results.push_back(fnTy);
    fnTy = fnTy->getResult()->getAs<AnyFunctionType>();
  }
}

static unsigned countNumFlattenedElementTypes(Type type) {
  if (auto *tupleTy = type->getCanonicalType()->getAs<TupleType>())
    return accumulate(tupleTy->getElementTypes(), 0,
                      [&](unsigned num, Type type) {
                        return num + countNumFlattenedElementTypes(type);
                      });
  return 1;
}

// TODO(TF-874): Simplify this helper and remove the `reverseCurryLevels` flag.
void AnyFunctionType::getSubsetParameters(
    IndexSubset *parameterIndices,
    SmallVectorImpl<AnyFunctionType::Param> &results, bool reverseCurryLevels) {
  SmallVector<AnyFunctionType *, 2> curryLevels;
  unwrapCurryLevels(this, curryLevels);

  SmallVector<unsigned, 2> curryLevelParameterIndexOffsets(curryLevels.size());
  unsigned currentOffset = 0;
  for (unsigned curryLevelIndex : llvm::reverse(indices(curryLevels))) {
    curryLevelParameterIndexOffsets[curryLevelIndex] = currentOffset;
    currentOffset += curryLevels[curryLevelIndex]->getNumParams();
  }

  // If `reverseCurryLevels` is true, reverse the curry levels and offsets.
  if (reverseCurryLevels) {
    std::reverse(curryLevels.begin(), curryLevels.end());
    std::reverse(curryLevelParameterIndexOffsets.begin(),
                 curryLevelParameterIndexOffsets.end());
  }

  for (unsigned curryLevelIndex : indices(curryLevels)) {
    auto *curryLevel = curryLevels[curryLevelIndex];
    unsigned parameterIndexOffset =
        curryLevelParameterIndexOffsets[curryLevelIndex];
    for (unsigned paramIndex : range(curryLevel->getNumParams()))
      if (parameterIndices->contains(parameterIndexOffset + paramIndex))
        results.push_back(curryLevel->getParams()[paramIndex]);
  }
}

void autodiff::getFunctionSemanticResultTypes(
    AnyFunctionType *functionType,
    SmallVectorImpl<AutoDiffSemanticFunctionResultType> &result,
    GenericEnvironment *genericEnv) {
  auto &ctx = functionType->getASTContext();

  // Remap type in `genericEnv`, if specified.
  auto remap = [&](Type type) {
    if (!genericEnv)
      return type;
    return genericEnv->mapTypeIntoContext(type);
  };

  // Collect formal result type as a semantic result, unless it is
  // `Void`.
  auto formalResultType = functionType->getResult();
  if (auto *resultFunctionType =
          functionType->getResult()->getAs<AnyFunctionType>()) {
    formalResultType = resultFunctionType->getResult();
  }
  if (!formalResultType->isEqual(ctx.TheEmptyTupleType))
    result.push_back({remap(formalResultType), /*isInout*/ false});

  // Collect `inout` parameters as semantic results.
  for (auto param : functionType->getParams())
    if (param.isInOut())
      result.push_back({remap(param.getPlainType()), /*isInout*/ true});
  if (auto *resultFunctionType =
          functionType->getResult()->getAs<AnyFunctionType>()) {
    for (auto param : resultFunctionType->getParams())
      if (param.isInOut())
        result.push_back({remap(param.getPlainType()), /*isInout*/ true});
  }
}

// TODO(TF-874): Simplify this helper. See TF-874 for WIP.
IndexSubset *
autodiff::getLoweredParameterIndices(IndexSubset *parameterIndices,
                                     AnyFunctionType *functionType) {
  SmallVector<AnyFunctionType *, 2> curryLevels;
  unwrapCurryLevels(functionType, curryLevels);

  // Compute the lowered sizes of all AST parameter types.
  SmallVector<unsigned, 8> paramLoweredSizes;
  unsigned totalLoweredSize = 0;
  auto addLoweredParamInfo = [&](Type type) {
    unsigned paramLoweredSize = countNumFlattenedElementTypes(type);
    paramLoweredSizes.push_back(paramLoweredSize);
    totalLoweredSize += paramLoweredSize;
  };
  for (auto *curryLevel : llvm::reverse(curryLevels))
    for (auto &param : curryLevel->getParams())
      addLoweredParamInfo(param.getPlainType());

  // Build lowered SIL parameter indices by setting the range of bits that
  // corresponds to each "set" AST parameter.
  llvm::SmallVector<unsigned, 8> loweredSILIndices;
  unsigned currentBitIndex = 0;
  for (unsigned i : range(parameterIndices->getCapacity())) {
    auto paramLoweredSize = paramLoweredSizes[i];
    if (parameterIndices->contains(i)) {
      auto indices = range(currentBitIndex, currentBitIndex + paramLoweredSize);
      loweredSILIndices.append(indices.begin(), indices.end());
    }
    currentBitIndex += paramLoweredSize;
  }

  return IndexSubset::get(functionType->getASTContext(), totalLoweredSize,
                          loweredSILIndices);
}

GenericSignature autodiff::getConstrainedDerivativeGenericSignature(
    SILFunctionType *originalFnTy, IndexSubset *diffParamIndices,
    GenericSignature derivativeGenSig, LookupConformanceFn lookupConformance,
    bool isTranspose) {
  if (!derivativeGenSig)
    derivativeGenSig = originalFnTy->getInvocationGenericSignature();
  if (!derivativeGenSig)
    return nullptr;
  auto &ctx = originalFnTy->getASTContext();
  auto *diffableProto = ctx.getProtocol(KnownProtocolKind::Differentiable);
  SmallVector<Requirement, 4> requirements;
  for (unsigned paramIdx : diffParamIndices->getIndices()) {
    // Require differentiability parameters to conform to `Differentiable`.
    auto paramType = originalFnTy->getParameters()[paramIdx].getInterfaceType();
    Requirement req(RequirementKind::Conformance, paramType,
                    diffableProto->getDeclaredInterfaceType());
    requirements.push_back(req);
    if (isTranspose) {
      // Require linearity parameters to additionally satisfy
      // `Self == Self.TangentVector`.
      auto tanSpace = paramType->getAutoDiffTangentSpace(lookupConformance);
      auto paramTanType = tanSpace->getCanonicalType();
      Requirement req(RequirementKind::SameType, paramType, paramTanType);
      requirements.push_back(req);
    }
  }
  return evaluateOrDefault(
      ctx.evaluator,
      AbstractGenericSignatureRequest{derivativeGenSig.getPointer(),
                                      /*addedGenericParams*/ {},
                                      std::move(requirements)},
      nullptr);
}

// Given the rest of a `Builtin.applyDerivative_{jvp|vjp}` or
// `Builtin.applyTranspose` operation name, attempts to parse the arity and
// throwing-ness from the operation name. Modifies the operation name argument
// in place as substrings get dropped.
static void parseAutoDiffBuiltinCommonConfig(
    StringRef &operationName, unsigned &arity, bool &throws) {
  // Parse '_arity'.
  constexpr char arityPrefix[] = "_arity";
  if (operationName.startswith(arityPrefix)) {
    operationName = operationName.drop_front(sizeof(arityPrefix) - 1);
    auto arityStr = operationName.take_while(llvm::isDigit);
    operationName = operationName.drop_front(arityStr.size());
    auto converted = llvm::to_integer(arityStr, arity);
    assert(converted); (void)converted;
    assert(arity > 0);
  } else {
    arity = 1;
  }
  // Parse '_throws'.
  constexpr char throwsPrefix[] = "_throws";
  if (operationName.startswith(throwsPrefix)) {
    operationName = operationName.drop_front(sizeof(throwsPrefix) - 1);
    throws = true;
  } else {
    throws = false;
  }
}

bool autodiff::getBuiltinApplyDerivativeConfig(
    StringRef operationName, AutoDiffDerivativeFunctionKind &kind,
    unsigned &arity, bool &throws) {
  constexpr char prefix[] = "applyDerivative";
  if (!operationName.startswith(prefix))
    return false;
  operationName = operationName.drop_front(sizeof(prefix) - 1);
  // Parse 'jvp' or 'vjp'.
  constexpr char jvpPrefix[] = "_jvp";
  constexpr char vjpPrefix[] = "_vjp";
  if (operationName.startswith(jvpPrefix))
    kind = AutoDiffDerivativeFunctionKind::JVP;
  else if (operationName.startswith(vjpPrefix))
    kind = AutoDiffDerivativeFunctionKind::VJP;
  operationName = operationName.drop_front(sizeof(jvpPrefix) - 1);
  parseAutoDiffBuiltinCommonConfig(operationName, arity, throws);
  return operationName.empty();
}

bool autodiff::getBuiltinApplyTransposeConfig(
    StringRef operationName, unsigned &arity, bool &throws) {
  constexpr char prefix[] = "applyTranspose";
  if (!operationName.startswith(prefix))
    return false;
  operationName = operationName.drop_front(sizeof(prefix) - 1);
  parseAutoDiffBuiltinCommonConfig(operationName, arity, throws);
  return operationName.empty();
}

bool autodiff::getBuiltinDifferentiableOrLinearFunctionConfig(
    StringRef operationName, unsigned &arity, bool &throws) {
  constexpr char differentiablePrefix[] = "differentiableFunction";
  constexpr char linearPrefix[] = "linearFunction";
  if (operationName.startswith(differentiablePrefix))
    operationName = operationName.drop_front(sizeof(differentiablePrefix) - 1);
  else if (operationName.startswith(linearPrefix))
    operationName = operationName.drop_front(sizeof(linearPrefix) - 1);
  else
    return false;
  parseAutoDiffBuiltinCommonConfig(operationName, arity, throws);
  return operationName.empty();
}

GenericSignature autodiff::getDifferentiabilityWitnessGenericSignature(
    GenericSignature origGenSig, GenericSignature derivativeGenSig) {
  // If there is no derivative generic signature, return the original generic
  // signature.
  if (!derivativeGenSig)
    return origGenSig;
  // If derivative generic signature has all concrete generic parameters and is
  // equal to the original generic signature, return `nullptr`.
  auto derivativeCanGenSig = derivativeGenSig.getCanonicalSignature();
  auto origCanGenSig = origGenSig.getCanonicalSignature();
  if (origCanGenSig == derivativeCanGenSig &&
      derivativeCanGenSig->areAllParamsConcrete())
    return GenericSignature();
  // Otherwise, return the derivative generic signature.
  return derivativeGenSig;
}

Type TangentSpace::getType() const {
  switch (kind) {
  case Kind::TangentVector:
    return value.tangentVectorType;
  case Kind::Tuple:
    return value.tupleType;
  }
  llvm_unreachable("invalid tangent space kind");
}

CanType TangentSpace::getCanonicalType() const {
  return getType()->getCanonicalType();
}

NominalTypeDecl *TangentSpace::getNominal() const {
  assert(isTangentVector());
  return getTangentVector()->getNominalOrBoundGenericNominal();
}

const char DerivativeFunctionTypeError::ID = '\0';

void DerivativeFunctionTypeError::log(raw_ostream &OS) const {
  OS << "original function type '";
  functionType->print(OS);
  OS << "' ";
  switch (kind) {
  case Kind::NoSemanticResults:
    OS << "has no semantic results ('Void' result)";
    break;
  case Kind::MultipleSemanticResults:
    OS << "has multiple semantic results";
    break;
  case Kind::NoDifferentiabilityParameters:
    OS << "has no differentiability parameters";
    break;
  case Kind::NonDifferentiableDifferentiabilityParameter: {
    auto nonDiffParam = getNonDifferentiableTypeAndIndex();
    OS << "has non-differentiable differentiability parameter "
       << nonDiffParam.second << ": " << nonDiffParam.first;
    break;
  }
  case Kind::NonDifferentiableResult: {
    auto nonDiffResult = getNonDifferentiableTypeAndIndex();
    OS << "has non-differentiable result " << nonDiffResult.second << ": "
       << nonDiffResult.first;
    break;
  }
  }
}

inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
                                     const DeclNameRefWithLoc &name) {
  os << name.Name;
  if (auto accessorKind = name.AccessorKind)
    os << '.' << getAccessorLabel(*accessorKind);
  return os;
}

bool swift::operator==(const TangentPropertyInfo::Error &lhs,
                       const TangentPropertyInfo::Error &rhs) {
  if (lhs.kind != rhs.kind)
    return false;
  switch (lhs.kind) {
  case TangentPropertyInfo::Error::Kind::NoDerivativeOriginalProperty:
  case TangentPropertyInfo::Error::Kind::NominalParentNotDifferentiable:
  case TangentPropertyInfo::Error::Kind::OriginalPropertyNotDifferentiable:
  case TangentPropertyInfo::Error::Kind::ParentTangentVectorNotStruct:
  case TangentPropertyInfo::Error::Kind::TangentPropertyNotFound:
  case TangentPropertyInfo::Error::Kind::TangentPropertyNotStored:
    return true;
  case TangentPropertyInfo::Error::Kind::TangentPropertyWrongType:
    return lhs.getType()->isEqual(rhs.getType());
  }
}

void swift::simple_display(llvm::raw_ostream &os, TangentPropertyInfo info) {
  os << "{ ";
  os << "tangent property: "
     << (info.tangentProperty ? info.tangentProperty->printRef() : "null");
  if (info.error) {
    os << ", error: ";
    switch (info.error->kind) {
    case TangentPropertyInfo::Error::Kind::NoDerivativeOriginalProperty:
      os << "'@noDerivative' original property has no tangent property";
      break;
    case TangentPropertyInfo::Error::Kind::NominalParentNotDifferentiable:
      os << "nominal parent does not conform to 'Differentiable'";
      break;
    case TangentPropertyInfo::Error::Kind::OriginalPropertyNotDifferentiable:
      os << "original property type does not conform to 'Differentiable'";
      break;
    case TangentPropertyInfo::Error::Kind::ParentTangentVectorNotStruct:
      os << "'TangentVector' type is not a struct";
      break;
    case TangentPropertyInfo::Error::Kind::TangentPropertyNotFound:
      os << "'TangentVector' struct does not have stored property with the "
            "same name as the original property";
      break;
    case TangentPropertyInfo::Error::Kind::TangentPropertyWrongType:
      os << "tangent property's type is not equal to the original property's "
            "'TangentVector' type";
      break;
    case TangentPropertyInfo::Error::Kind::TangentPropertyNotStored:
      os << "'TangentVector' property '" << info.tangentProperty->getName()
         << "' is not a stored property";
      break;
    }
  }
  os << " }";
}

TangentPropertyInfo TangentStoredPropertyRequest::evaluate(
    Evaluator &evaluator, VarDecl *originalField, CanType baseType) const {
  assert(((originalField->hasStorage() && originalField->isInstanceMember()) ||
          originalField->hasAttachedPropertyWrapper()) &&
         "Expected a stored property or a property-wrapped property");
  auto *parentDC = originalField->getDeclContext();
  assert(parentDC->isTypeContext());
  auto *moduleDecl = originalField->getModuleContext();
  auto parentTan =
      baseType->getAutoDiffTangentSpace(LookUpConformanceInModule(moduleDecl));
  // Error if parent nominal type does not conform to `Differentiable`.
  if (!parentTan) {
    return TangentPropertyInfo(
        TangentPropertyInfo::Error::Kind::NominalParentNotDifferentiable);
  }
  // Error if original stored property is `@noDerivative`.
  if (originalField->getAttrs().hasAttribute<NoDerivativeAttr>()) {
    return TangentPropertyInfo(
        TangentPropertyInfo::Error::Kind::NoDerivativeOriginalProperty);
  }
  // Error if original property's type does not conform to `Differentiable`.
  auto originalFieldType = baseType->getTypeOfMember(
      originalField->getModuleContext(), originalField);
  auto originalFieldTan = originalFieldType->getAutoDiffTangentSpace(
      LookUpConformanceInModule(moduleDecl));
  if (!originalFieldTan) {
    return TangentPropertyInfo(
        TangentPropertyInfo::Error::Kind::OriginalPropertyNotDifferentiable);
  }
  // Get the parent `TangentVector` type.
  auto parentTanType =
      baseType->getAutoDiffTangentSpace(LookUpConformanceInModule(moduleDecl))
          ->getType();
  auto *parentTanStruct = parentTanType->getStructOrBoundGenericStruct();
  // Error if parent `TangentVector` is not a struct.
  if (!parentTanStruct) {
    return TangentPropertyInfo(
        TangentPropertyInfo::Error::Kind::ParentTangentVectorNotStruct);
  }
  // Find the corresponding field in the tangent space.
  VarDecl *tanField = nullptr;
  // If `TangentVector` is the original struct, then the tangent property is the
  // original property.
  if (parentTanStruct == parentDC->getSelfStructDecl()) {
    tanField = originalField;
  }
  // Otherwise, look up the field by name.
  else {
    auto tanFieldLookup =
        parentTanStruct->lookupDirect(originalField->getName());
    llvm::erase_if(tanFieldLookup,
                   [](ValueDecl *v) { return !isa<VarDecl>(v); });
    // Error if tangent property could not be found.
    if (tanFieldLookup.empty()) {
      return TangentPropertyInfo(
          TangentPropertyInfo::Error::Kind::TangentPropertyNotFound);
    }
    tanField = cast<VarDecl>(tanFieldLookup.front());
  }
  // Error if tangent property's type is not equal to the original property's
  // `TangentVector` type.
  auto originalFieldTanType = originalFieldTan->getType();
  auto tanFieldType =
      parentTanType->getTypeOfMember(tanField->getModuleContext(), tanField);
  if (!originalFieldTanType->isEqual(tanFieldType)) {
    return TangentPropertyInfo(
        TangentPropertyInfo::Error::Kind::TangentPropertyWrongType,
        originalFieldTanType);
  }
  // Error if tangent property is not a stored property.
  if (!tanField->hasStorage()) {
    return TangentPropertyInfo(
        TangentPropertyInfo::Error::Kind::TangentPropertyNotStored);
  }
  // Otherwise, tangent property is valid.
  return TangentPropertyInfo(tanField);
}