text:
package com.google.gerrit.sshd.commands;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.io.CharStreams;
import com.google.gerrit.common.data.LabelType;
import com.google.gerrit.common.data.LabelValue;
import com.google.gerrit.extensions.api.GerritApi;
import com.google.gerrit.extensions.api.changes.AbandonInput;
import com.google.gerrit.extensions.api.changes.ChangeApi;
import com.google.gerrit.extensions.api.changes.RestoreInput;
import com.google.gerrit.extensions.api.changes.ReviewInput;
import com.google.gerrit.extensions.api.changes.ReviewInput.NotifyHandling;
import com.google.gerrit.extensions.api.changes.RevisionApi;
import com.google.gerrit.extensions.restapi.RestApiException;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.OutputFormat;
import com.google.gerrit.server.config.AllProjectsName;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.project.NoSuchProjectException;
import com.google.gerrit.server.project.ProjectControl;
import com.google.gerrit.server.util.LabelVote;
import com.google.gerrit.sshd.CommandMetaData;
import com.google.gerrit.sshd.SshCommand;
import com.google.gerrit.util.cli.CmdLineParser;
import com.google.gson.JsonSyntaxException;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import com.google.inject.Provider;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@CommandMetaData(name = "review", description = "Apply reviews to one or more patch sets")
public class ReviewCommand extends SshCommand {
  private static final Logger log =
      LoggerFactory.getLogger(ReviewCommand.class);

  @Override
  protected final CmdLineParser newCmdLineParser(Object options) {
    final CmdLineParser parser = super.newCmdLineParser(options);
    for (ApproveOption c : optionList) {
      parser.addOption(c, c);
    }
    return parser;
  }

  private final Set<PatchSet> patchSets = new HashSet<>();

  @Argument(index = 0, required = true, multiValued = true,
      metaVar = "{COMMIT | CHANGE,PATCHSET}",
      usage = "list of commits or patch sets to review")
  void addPatchSetId(final String token) {
    try {
      PatchSet ps = CommandUtils.parsePatchSet(token, db, projectControl,
          branch);
      patchSets.add(ps);
    } catch (UnloggedFailure e) {
      throw new IllegalArgumentException(e.getMessage(), e);
    } catch (OrmException e) {
      throw new IllegalArgumentException("database error", e);
    }
  }

  @Option(name = "--project", aliases = "-p", usage = "project containing the specified patch set(s)")
  private ProjectControl projectControl;

  @Option(name = "--branch", aliases = "-b", usage = "branch containing the specified patch set(s)")
  private String branch;

  @Option(name = "--message", aliases = "-m", usage = "cover message to publish on change(s)", metaVar = "MESSAGE")
  private String changeComment;

  @Option(name = "--notify", aliases = "-n", usage = "Who to send email notifications to after the review is stored.", metaVar = "NOTIFYHANDLING")
  private NotifyHandling notify;

  @Option(name = "--abandon", usage = "abandon the specified change(s)")
  private boolean abandonChange;

  @Option(name = "--restore", usage = "restore the specified abandoned change(s)")
  private boolean restoreChange;

  @Option(name = "--rebase", usage = "rebase the specified change(s)")
  private boolean rebaseChange;

  @Option(name = "--submit", aliases = "-s", usage = "submit the specified patch set(s)")
  private boolean submitChange;

  @Option(name = "--publish", usage = "publish the specified draft patch set(s)")
  private boolean publishPatchSet;

  @Option(name = "--delete", usage = "delete the specified draft patch set(s)")
  private boolean deleteDraftPatchSet;

  @Option(name = "--json", aliases = "-j", usage = "read review input json from stdin")
  private boolean json;

  @Option(name = "--label", aliases = "-l", usage = "custom label(s) to assign", metaVar = "LABEL=VALUE")
  void addLabel(final String token) {
    LabelVote v = LabelVote.parseWithEquals(token);
    LabelType.checkName(v.label()); // Disallow SUBM.
    customLabels.put(v.label(), v.value());
  }

  @Inject
  private ReviewDb db;

  @Inject
  private ProjectControl.Factory projectControlFactory;

  @Inject
  private AllProjectsName allProjects;

  @Inject
  private Provider<GerritApi> gApi;

  private List<ApproveOption> optionList;
  private Map<String, Short> customLabels;

  @Override
  protected void run() throws UnloggedFailure {
    if (abandonChange) {
      if (restoreChange) {
        throw error("abandon and restore actions are mutually exclusive");
      }
      if (submitChange) {
        throw error("abandon and submit actions are mutually exclusive");
      }
      if (publishPatchSet) {
        throw error("abandon and publish actions are mutually exclusive");
      }
      if (deleteDraftPatchSet) {
        throw error("abandon and delete actions are mutually exclusive");
      }
      if (rebaseChange) {
        throw error("abandon and rebase actions are mutually exclusive");
      }
    }
    if (publishPatchSet) {
      if (restoreChange) {
        throw error("publish and restore actions are mutually exclusive");
      }
      if (submitChange) {
        throw error("publish and submit actions are mutually exclusive");
      }
      if (deleteDraftPatchSet) {
        throw error("publish and delete actions are mutually exclusive");
      }
    }
    if (json) {
      if (restoreChange) {
        throw error("json and restore actions are mutually exclusive");
      }
      if (submitChange) {
        throw error("json and submit actions are mutually exclusive");
      }
      if (deleteDraftPatchSet) {
        throw error("json and delete actions are mutually exclusive");
      }
      if (publishPatchSet) {
        throw error("json and publish actions are mutually exclusive");
      }
      if (abandonChange) {
        throw error("json and abandon actions are mutually exclusive");
      }
      if (changeComment != null) {
        throw error("json and message are mutually exclusive");
      }
      if (rebaseChange) {
        throw error("json and rebase actions are mutually exclusive");
      }
    }
    if (rebaseChange) {
      if (deleteDraftPatchSet) {
        throw error("rebase and delete actions are mutually exclusive");
      }
      if (submitChange) {
        throw error("rebase and submit actions are mutually exclusive");
      }
    }
    if (deleteDraftPatchSet && submitChange) {
      throw error("delete and submit actions are mutually exclusive");
    }

    boolean ok = true;
    ReviewInput input = null;
    if (json) {
      input = reviewFromJson();
    }

    for (final PatchSet patchSet : patchSets) {
      try {
        if (input != null) {
          applyReview(patchSet, input);
        } else {
          reviewPatchSet(patchSet);
        }
      } catch (RestApiException | UnloggedFailure e) {
        ok = false;
        writeError("error: " + e.getMessage() + "\n");
      } catch (NoSuchChangeException e) {
        ok = false;
        writeError("no such change " + patchSet.getId().getParentKey().get());
      } catch (Exception e) {
        ok = false;
        writeError("fatal: internal server error while reviewing "
            + patchSet.getId() + "\n");
        log.error("internal error while reviewing " + patchSet.getId(), e);
      }
    }

    if (!ok) {
      throw error("one or more reviews failed; review output above");
    }
  }

  private void applyReview(PatchSet patchSet,
      final ReviewInput review) throws RestApiException {
    gApi.get().changes()
        .id(patchSet.getId().getParentKey().get())
        .revision(patchSet.getRevision().get())
        .review(review);
  }

  private ReviewInput reviewFromJson() throws UnloggedFailure {
    try (InputStreamReader r =
          new InputStreamReader(in, StandardCharsets.UTF_8)) {
      return OutputFormat.JSON.newGson().
          fromJson(CharStreams.toString(r), ReviewInput.class);
    } catch (IOException | JsonSyntaxException e) {
      writeError(e.getMessage() + '\n');
      throw error("internal error while reading review input");
    }
  }

  private void reviewPatchSet(final PatchSet patchSet) throws Exception {
    if (changeComment == null) {
      changeComment = "";
    }
    if (notify == null) {
      notify = NotifyHandling.ALL;
    }

    ReviewInput review = new ReviewInput();
    review.message = Strings.emptyToNull(changeComment);
    review.notify = notify;
    review.labels = Maps.newTreeMap();
    review.drafts = ReviewInput.DraftHandling.PUBLISH;
    review.strictLabels = false;
    for (ApproveOption ao : optionList) {
      Short v = ao.value();
      if (v != null) {
        review.labels.put(ao.getLabelName(), v);
      }
    }
    review.labels.putAll(customLabels);

    // If review labels are being applied, the comment will be included
    // on the review note. We don't need to add it again on the abandon
    // or restore comment.
    if (!review.labels.isEmpty() && (abandonChange || restoreChange)) {
      changeComment = null;
    }

    try {
      if (abandonChange) {
        AbandonInput input = new AbandonInput();
        input.message = changeComment;
        applyReview(patchSet, review);
        changeApi(patchSet).abandon(input);
      } else if (restoreChange) {
        RestoreInput input = new RestoreInput();
        input.message = changeComment;
        changeApi(patchSet).restore(input);
        applyReview(patchSet, review);
      } else {
        applyReview(patchSet, review);
      }

      if (rebaseChange){
        revisionApi(patchSet).rebase();
      }

      if (submitChange) {
        revisionApi(patchSet).submit();
      }

      if (publishPatchSet) {
        revisionApi(patchSet).publish();
      } else if (deleteDraftPatchSet) {
        revisionApi(patchSet).delete();
      }
    } catch (IllegalStateException | RestApiException e) {
      throw error(e.getMessage());
    }
  }

  private ChangeApi changeApi(PatchSet patchSet) throws RestApiException {
    return gApi.get().changes().id(patchSet.getId().getParentKey().get());
  }

  private RevisionApi revisionApi(PatchSet patchSet) throws RestApiException {
    return changeApi(patchSet).revision(patchSet.getRevision().get());
  }

  @Override
  protected void parseCommandLine() throws UnloggedFailure {
    optionList = new ArrayList<>();
    customLabels = Maps.newHashMap();

    ProjectControl allProjectsControl;
    try {
      allProjectsControl = projectControlFactory.controlFor(allProjects);
    } catch (NoSuchProjectException e) {
      throw new UnloggedFailure("missing " + allProjects.get());
    }

    for (LabelType type : allProjectsControl.getLabelTypes().getLabelTypes()) {
      StringBuilder usage = new StringBuilder("score for ")
        .append(type.getName())
        .append("\n");

      for (LabelValue v : type.getValues()) {
        usage.append(v.format()).append("\n");
      }

      final String name = "--" + type.getName().toLowerCase();
      optionList.add(new ApproveOption(name, usage.toString(), type));
    }

    super.parseCommandLine();
  }

  private void writeError(final String msg) {
    try {
      err.write(msg.getBytes(ENC));
    } catch (IOException e) {
    }
  }

  private static UnloggedFailure error(final String msg) {
    return new UnloggedFailure(1, msg);
  }
}


text:
def stub_anonymous_user_request options={}
  options.reverse_merge!(company: 'GitHacking',
                         name: 'Firstname Lastname',
                         created_at: '2007/10/19 22:24:19 -0700',
                         location: 'San Francisco CA',
                         public_repo_count: 98,
                         public_gist_count: 210,
                         blog: 'http://blog.com',
                         following_count: 129,
                         id: 3,
                         type: 'User',
                         permission: 'null',
                         followers_count: 1692,
                         login: 'someuser',
                         email: 'abc@email.com')
  stub_request(:get, "https://github.com/api/v2/yaml/user/show/#{options[:login]}?").
    to_return(status: 200, body: <<USER, headers: {})
user:
  company: #{options[:company]}
  name: #{options[:name]}
  created_at: #{options[:created_at]}
  location: #{options[:location]}
  public_repo_count: #{options[:public_repo_count]}
  public_gist_count: #{options[:public_gist_count]}
  blog: #{options[:blog]}
  gravatar_id: includedeventhoughwedontuseit
  following_count: #{options[:following_count]}
  id: #{options[:id]}
  type: #{options[:type]}
  permission: #{options[:permission]}
  followers_count: #{options[:followers_count]}
  login: #{options[:login]}
  email: #{options[:email]}
USER

end

def stub_anonymous_repo_request_from_factory repo=(Factory.build :repository)
  stub_anonymous_repo_request(repo.attributes.symbolize_keys)
end

def stub_anonymous_repo_request options={}
  # Set defaults
  options.reverse_merge!(url: "https://github.com/someowner/some_project",
                         owner: 'someowner',
                         name: 'some_project',
                         has_issues: true,
                         watchers: 25,
                         has_downloads: true,
                         created_at: '2008/04/18 16:14:24 -0700',
                         forks: 11,
                         fork: true,
                         source: '', # 'somesource/project',
                         parent: '', # 'parent/project',
                         has_wiki: true,
                         private: false,
                         homepage: 'http://homepage.com',
                         pushed_at: '2010/05/05 15:28:38 -0700',
                         description: "This is the description of #{options[:name] || 'some_project'}.",
                         open_issues: 3)

  stub_request(:get, "https://github.com/api/v2/yaml/repos/show/#{options[:owner]}/#{options[:name]}?").
    to_return(:status => 200, :body => <<BODY, :headers => {})
repository:
  url: #{options[:url]}
  has_issues: #{options[:has_issues]}
  homepage: #{options[:homepage]}
  watchers: #{options[:watchers]}
  source: #{options[:source]}
  parent: #{options[:parent]}
  has_downloads: #{options[:has_downloads]}
  created_at: #{options[:created_at]}
  forks: #{options[:forks]}
  fork: #{options[:fork]}
  has_wiki: #{options[:has_wiki]}
  private: #{options[:private]}
  pushed_at: #{options[:pushed_at]}
  name: #{options[:name]}
  description: #{options[:description]}
  owner: #{options[:owner]}
  open_issues: #{options[:open_issues]}
BODY
end

def stub_anonymous_repos_request options={}
  # Set defaults
  options.reverse_merge!(url: "https://github.com/someowner/some_project",
                         owner: 'someowner',
                         name: 'some_project',
                         has_issues: true,
                         watchers: 25,
                         has_downloads: true,
                         created_at: '2008/04/18 16:14:24 -0700',
                         forks: 11,
                         fork: true,
                         source: '', # 'somesource/project',
                         parent: '', # 'parent/project',
                         has_wiki: true,
                         private: false,
                         homepage: 'http://homepage.com',
                         pushed_at: '2010/05/05 15:28:38 -0700',
                         description: "This is the description of #{options[:name] || 'some_project'}.",
                         open_issues: 3)

  stub_request(:get, "https://github.com/api/v2/yaml/repos/show/#{options[:owner]}?").
    to_return(:status => 200, :body => <<BODY, :headers => {})
repositories:
  - url: #{options[:url]}
    has_issues: #{options[:has_issues]}
    homepage: #{options[:homepage]}
    watchers: #{options[:watchers]}
    source: #{options[:source]}
    parent: #{options[:parent]}
    has_downloads: #{options[:has_downloads]}
    created_at: #{options[:created_at]}
    forks: #{options[:forks]}
    fork: #{options[:fork]}
    has_wiki: #{options[:has_wiki]}
    private: #{options[:private]}
    pushed_at: #{options[:pushed_at]}
    name: #{options[:name]}
    description: #{options[:description]}
    owner: #{options[:owner]}
    open_issues: #{options[:open_issues]}
BODY
end

def stub_anonymous_repo_languages_request options={}
  options.reverse_merge!(owner: 'notspecifiedowner',
                         name: 'notspecifiedname',
                         languages: {'Ruby' => 12345, 'JavaScript' => 5431})
  languages = {}
  options[:languages].each do |language|
    languages[language.name] = language.bytes
  end if options[:languages].is_a? Array

  stub_request(:get, "https://github.com/api/v2/yaml/repos/show/#{options.delete :owner}/#{options.delete :name}/languages?").
    to_return(:status => 200, :body => options.to_yaml, :headers => {})
end

def stub_missing_repo_request options={}
  options.reverse_merge!(owner: 'notspecifiedowner',
                         name: 'notspecifiedname',
                         languages: {'Ruby' => 12345, 'JavaScript' => 5431})
  stub_request(:get, "https://github.com/api/v2/yaml/repos/show/#{options[:owner]}/#{options[:name]}?").
    to_return(:status => 404, :body => "This page doesn't exist", :headers => {})
end

def stub_anonymous_issues_request options={}
  stub_request(:get, "https://github.com/api/v2/json/issues/list/#{options[:owner]}/#{options[:name]}/label/#{options[:label]}").
    to_return(:status => 200, :body => options[:issues].to_json, :header => {})
end

def stub_anonymous_issues_request_with_labels repo, issues
  ['bytesize', 'easy', 'medium', 'hard'].each do |label|
    stub_anonymous_issues_request(:owner  => repo.owner,
                                  :name   => repo.name,
                                  :label  => label,
                                  :issues => issues)
  end
end

def stub_metadata_request owner, project_name
  stub_request(:get, "https://github.com/#{owner}/#{project_name}/raw/master/githacking.yml"). to_return(:status => 200, body: <<BODY, :headers => {})
---
long_description: >
    hello world this is a test for githacking at philly startup weekend!

categories:
    - clojure
    - rabbitmq

needs:
    roles:
        - role:        Evangelist
          language:    Any
          description: General hackers interested in the project eager to help spread the word and work with interested developers.

mentions:
    - http://aaronfeng.com
    - http://twitter.com/aaronfeng
BODY

end

def stub_authenticated_user_request options={}
  options.reverse_merge!(company: 'GitHacking',
                         name: 'Firstname Lastname',
                         created_at: '2007/10/19 22:24:19 -0700',
                         location: 'San Francisco CA',
                         public_repo_count: 98,
                         public_gist_count: 210,
                         blog: 'http://blog.com',
                         following_count: 129,
                         id: 3,
                         type: 'User',
                         permission: 'null',
                         followers_count: 1692,
                         login: 'someuser',
                         email: username + '@email.com',
                         total_private_repo_count: 1,
                         collaborators: 3,
                         disk_usage: 50384,
                         owned_private_repo_count: 1,
                         private_gist_count: 0,
                         plan_name: mega,
                         plan_collaborators: 60,
                         plan_space: 20971520,
                         plan_private_repos: 125)
  stub_request(:get, "https://github.com/api/v2/yaml/user/show/#{username}?").
    to_return(status: 200, body: <<BODY, headers: {})
---
user:
  company: #{options[:company]}
  name: #{options[:name]}
  created_at: #{options[:created_at]}
  location: #{options[:location]}
  public_repo_count: #{options[:public_repo_count]}
  public_gist_count: #{options[:public_gist_count]}
  blog: #{options[:blog]}
  following_count: #{options[:following_count]}
  id: #{options[:id]}
  type: #{options[:type]}
  permission: #{options[:permission]}
  followers_count: #{options[:followers_count]}
  login: #{options[:login]}
  gravatar_id: #{options[:gravatar_id]}
  email: #{options[:email]}
  total_private_repo_count: #{options[:total_private_repo_count]}
  collaborators: #{options[:collaborators]}
  disk_usage: #{options[:disk_usage]}
  owned_private_repo_count: #{options[:owned_private_repo_count]}
  private_gist_count: #{options[:private_gist_count]}
  plan:
    name: #{options[:plan_name]}
    collaborators: #{options[:plan_collaborators]}
    space: #{options[:plan_space]}
    private_repos: #{options[:plan_private_repos]}
BODY

end

def stub_github_requests_for repo
  stub_anonymous_user_request(login: repo.owner)
  stub_anonymous_repo_request_from_factory repo
  stub_anonymous_repo_languages_request(owner: repo.owner, name: repo.name, languages: repo.languages)
end

redpajama_set_name: RedPajamaGithub


text:
/***************************************************************************//**
 * \file ISC_out_ppm.c
 * \brief Module for PPM image output.
 *
 * ISC_out_ppm.c describes data structures and functions necessary to save/send
 * PPM-formatted images using the CMUcam3.  This code highly emphasizes the
 * scanline-by-scanline approach used by the ISC_histogram and ISC_convolution
 * systems.
*******************************************************************************/

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>

#include "ISC_out_ppm.h"

/**
 * \brief Creates an ISC_out_ppm module.
 *
 * This function creates a new ISC_out_ppm_start module.  Give it the image
 * context of the image expected to come in, and give it the file pointer to
 * dump the file to.  It will return an ISC_out_ppm state structure.
 *
 * \param context The intended context of the image to feed into the module.
 * \param fp The file pointer.  Make this stdout to send it over the serial port.
 * \return ISC_out_ppm state structure.
 */
__attribute__((gnu_inline)) inline ISC_out_ppm *ISC_out_ppm_start( ISC_util_imagecontext context, FILE *fp )
{
	// Make the new module state structure.
	ISC_out_ppm *ipw = malloc( sizeof( ISC_out_ppm ) );

	// Load it up with its initial values.
	ipw->filePointer = fp;
	ipw->finished = 0;

	ipw->theContext = context;
	ipw->width = ipw->theContext.frame.width;
	ipw->height = ipw->theContext.frame.height;
	ipw->rowsLeft = ipw->height;

	//Write the header of the PPM file, since enough stuff is now known
	//to do this.
	fprintf( ipw->filePointer, "P6\n%d %d\n255\n", ipw->width, ipw->height );

	return ipw;
}

/**
 * \brief Accepts rows of image data for PPM conversion.
 *
 * This function accepts a new row of image data into the ISC_out_ppm module.
 *
 * \param ipw The state structure of the ISC_out_ppm module.
 * \param row A pointer to the pixel row to feed in.
 * \return Nothing -- this is a data sink function.
 */
__attribute__((gnu_inline)) inline void ISC_out_ppm_feed( ISC_out_ppm *ipw, uint8_t *row )
{
	uint16_t x;

	if ( row && ipw->finished == 0 )
	{
		// Write out the row of pixels to the PPM file.
		for ( x = 0; x < ipw->width*3; x++ )
		{
			fputc( *(row+x), ipw->filePointer );
		}

		// One more row down, rowsLeft rows to go.  Unless rowsLeft is
		// 0, then we're done.
		ipw->rowsLeft--;
		if ( ipw->rowsLeft == 0 )
			ipw->finished = 1;

		// Feed functions are expected to free row pointers.
		free(row);
	}
}

/**
 * \brief Ends the ISC_out_ppm module.
 *
 * This function dellocates the memory used by ISC_out_ppm.  The user is still
 * expected to close the file pointer used, though.  This is because if the
 * module did this automatically, bad things could happen if it tried to close
 * stdout.
 *
 * \param ipw The state structure of the ISC_out_ppm module.
 * \return Nothing but the minty feeling of deallocated memory.
 */
__attribute__((gnu_inline)) inline void ISC_out_ppm_end( ISC_out_ppm *ipw )
{
	// Mmm...nothing like peace of mind.
	free(ipw);
}

/**
 * \brief Returns whether ISC_out_ppm is running.
 *
 * This function returns the current running state of ISC_out_ppm.  If the
 * module is finished (no more lines to feed()), it will return false.  If there
 * is still work to do, it will return true.
 *
 * \param ipw The state structure of the ISC_out_ppm module.
 * \return TRUE if running, FALSE if finished.
 */
__attribute__((gnu_inline)) inline bool ISC_out_ppm_running( ISC_out_ppm *ipw )
{
	return !ipw->finished;
}


text:
<Type Name="CTFontFeatureTransliteration+Selector" FullName="MonoMac.CoreText.CTFontFeatureTransliteration+Selector">
  <TypeSignature Language="C#" Value="public enum CTFontFeatureTransliteration.Selector" />
  <TypeSignature Language="ILAsm" Value=".class nested public auto ansi sealed CTFontFeatureTransliteration/Selector extends System.Enum" />
  <AssemblyInfo>
    <AssemblyName>MonoMac</AssemblyName>
    <AssemblyVersion>0.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Enum</BaseTypeName>
  </Base>
  <Docs>
    To be added.
    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName="HanjaToHangul">
      <MemberSignature Language="C#" Value="HanjaToHangul" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.CoreText.CTFontFeatureTransliteration/Selector HanjaToHangul = int32(1)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTFontFeatureTransliteration+Selector</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="HanjaToHangulAltOne">
      <MemberSignature Language="C#" Value="HanjaToHangulAltOne" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.CoreText.CTFontFeatureTransliteration/Selector HanjaToHangulAltOne = int32(7)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTFontFeatureTransliteration+Selector</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="HanjaToHangulAltThree">
      <MemberSignature Language="C#" Value="HanjaToHangulAltThree" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.CoreText.CTFontFeatureTransliteration/Selector HanjaToHangulAltThree = int32(9)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTFontFeatureTransliteration+Selector</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="HanjaToHangulAltTwo">
      <MemberSignature Language="C#" Value="HanjaToHangulAltTwo" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.CoreText.CTFontFeatureTransliteration/Selector HanjaToHangulAltTwo = int32(8)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTFontFeatureTransliteration+Selector</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="HiraganaToKatakana">
      <MemberSignature Language="C#" Value="HiraganaToKatakana" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.CoreText.CTFontFeatureTransliteration/Selector HiraganaToKatakana = int32(2)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTFontFeatureTransliteration+Selector</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="KanaToRomanization">
      <MemberSignature Language="C#" Value="KanaToRomanization" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.CoreText.CTFontFeatureTransliteration/Selector KanaToRomanization = int32(4)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTFontFeatureTransliteration+Selector</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="KatakanaToHiragana">
      <MemberSignature Language="C#" Value="KatakanaToHiragana" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.CoreText.CTFontFeatureTransliteration/Selector KatakanaToHiragana = int32(3)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTFontFeatureTransliteration+Selector</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="NoTransliteration">
      <MemberSignature Language="C#" Value="NoTransliteration" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.CoreText.CTFontFeatureTransliteration/Selector NoTransliteration = int32(0)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTFontFeatureTransliteration+Selector</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="RomanizationToHiragana">
      <MemberSignature Language="C#" Value="RomanizationToHiragana" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.CoreText.CTFontFeatureTransliteration/Selector RomanizationToHiragana = int32(5)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTFontFeatureTransliteration+Selector</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
    <Member MemberName="RomanizationToKatakana">
      <MemberSignature Language="C#" Value="RomanizationToKatakana" />
      <MemberSignature Language="ILAsm" Value=".field public static literal valuetype MonoMac.CoreText.CTFontFeatureTransliteration/Selector RomanizationToKatakana = int32(6)" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoMac.CoreText.CTFontFeatureTransliteration+Selector</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
      </Docs>
    </Member>
  </Members>
</Type>


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**_class** | **NSString*** |  | [optional]
**displayName** | **NSString*** |  | [optional]
**estimatedDurationInMillis** | **NSNumber*** |  | [optional]
**fullDisplayName** | **NSString*** |  | [optional]
**fullName** | **NSString*** |  | [optional]
**name** | **NSString*** |  | [optional]
**organization** | **NSString*** |  | [optional]
**parameters** | [**NSArray<OAIStringParameterDefinition>***](OAIStringParameterDefinition.md) |  | [optional]
**permissions** | [**OAIBranchImplpermissions***](OAIBranchImplpermissions.md) |  | [optional]
**weatherScore** | **NSNumber*** |  | [optional]
**pullRequest** | **NSString*** |  | [optional]
**links** | [**OAIBranchImpllinks***](OAIBranchImpllinks.md) |  | [optional]
**latestRun** | [**OAIPipelineRunImpl***](OAIPipelineRunImpl.md) |  | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
package com.hazelcast.transaction;

public interface TransactionManagerService {

    <T> T executeTransaction(TransactionOptions options, TransactionalTask<T> task) throws TransactionException;

    TransactionContext newTransactionContext(TransactionOptions options);

    TransactionContext newClientTransactionContext(TransactionOptions options, String clientUuid);
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Key Composer Test</title>

Key Composer test


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.4.4.15-8-b-ii-4
description: Array.prototype.lastIndexOf - search element is NaN
---*/

assert.sameValue([+NaN, NaN, -NaN].lastIndexOf(NaN), -1, '[+NaN, NaN, -NaN].lastIndexOf(NaN)');


text:
import React from 'react';
import PropTypes from 'prop-types';

import { connect } from 'react-redux';
import { FlatButton } from 'material-ui';
import { formSubmit, clickSubmit } from './actions';
import style from './style';
import { Modal } from '../../ui-components';
import componentStyle from '../../ui-components/style';
import Editor from '.';

export const ModalEditor = props => {
    let {
        name,
        children,
        onCancel,
        title,
        width,
        open,
        submitLabel,
        handleClick,
        errored,
        onDone,
    } = props;

    let buttons = [
        <FlatButton
            primary={true}
            onClick={() => handleClick(name)}
            disabled={errored}
            style={componentStyle.buttonFlat}
        >{submitLabel}</FlatButton>,
        <FlatButton
            primary={false}
            onClick={onCancel}
            style={componentStyle.buttonFlat}
        >Cancel</FlatButton>,
    ];

    return (
        <Modal
            actions={buttons}
            open={open}
            onClose={onCancel}
            title={title}
            width={width}
        >
            <div style={style.modalEditorContainer}>
                <Editor {...props} onDone={onDone}>
                    {children}
                </Editor>
            </div>
        </Modal>
    );
};

ModalEditor.defaultProps = {
    children: null,
};

ModalEditor.propTypes = {
    children: PropTypes.oneOfType([PropTypes.node, PropTypes.array]),
    onCancel: PropTypes.func.isRequired,
};

const mapStateToProps = (state) => ({
    query: state.router.location.query,
})

export default connect(mapStateToProps, {
    handleSubmit: formSubmit,
    handleClick: clickSubmit,
})(ModalEditor);


text:
namespace Nancy.Routing.Constraints
{
    /// <summary>
    /// Constraint for route segments with a maximum length.
    /// </summary>
    public class MaxLengthRouteSegmentConstraint : ParameterizedRouteSegmentConstraintBase<string>
    {
        public override string Name
        {
            get { return "maxlength"; }
        }

        protected override bool TryMatch(string segment, string[] parameters, out string matchedValue)
        {
            int maxLength;

            if (!this.TryParseInt(parameters[0], out maxLength))
            {
                matchedValue = null;
                return false;
            }

            if (segment.Length > maxLength)
            {
                matchedValue = null;
                return false;
            }

            matchedValue = segment;
            return true;
        }
    }
}


text:
package com.jornwu.weather_android.gson;

//
//	Wind.java
//
//	Create by JornWu on 30/7/2017
//	Copyright © 2017. All rights reserved.
//	Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport

import com.google.gson.annotations.SerializedName;

public class Wind{

	@SerializedName("deg")
	private String deg;
	@SerializedName("dir")
	private String dir;
	@SerializedName("sc")
	private String sc;
	@SerializedName("spd")
	private String spd;

	public void setDeg(String deg){
		this.deg = deg;
	}
	public String getDeg(){
		return this.deg;
	}
	public void setDir(String dir){
		this.dir = dir;
	}
	public String getDir(){
		return this.dir;
	}
	public void setSc(String sc){
		this.sc = sc;
	}
	public String getSc(){
		return this.sc;
	}
	public void setSpd(String spd){
		this.spd = spd;
	}
	public String getSpd(){
		return this.spd;
	}

}


text: Materials for iOS Developers Screening Jan-2015


text:
import { TrainHeart20 } from "../../";

export = TrainHeart20;


text:
BEGIN TRANSACTION;

--
-- Table: aliases
--
DROP TABLE IF EXISTS aliases;

CREATE TABLE aliases (
  identifier varchar(64),
  pki_realm varchar(255) NOT NULL,
  alias varchar(255) NOT NULL,
  group_id varchar(255),
  generation smallint,
  notafter integer,
  notbefore integer,
  PRIMARY KEY (pki_realm, alias)
);

--
-- Table: application_log
--
DROP TABLE IF EXISTS application_log;

CREATE TABLE application_log (
  application_log_id INTEGER PRIMARY KEY NOT NULL,
  logtimestamp bigint,
  workflow_id decimal(49,0) NOT NULL,
  priority integer DEFAULT 0,
  category varchar(255) NOT NULL,
  message longtext
);

--
-- Table: audittrail
--
DROP TABLE IF EXISTS audittrail;

CREATE TABLE audittrail (
  audittrail_key INTEGER PRIMARY KEY NOT NULL,
  logtimestamp bigint,
  category varchar(255),
  loglevel varchar(255),
  message text
);

--
-- Table: certificate
--
DROP TABLE IF EXISTS certificate;

CREATE TABLE certificate (
  pki_realm varchar(255),
  issuer_dn varchar(1000),
  cert_key decimal(49,0) NOT NULL,
  issuer_identifier varchar(64) NOT NULL,
  identifier varchar(64),
  subject varchar(1000),
  status varchar(255),
  subject_key_identifier varchar(255),
  authority_key_identifier varchar(255),
  notbefore integer,
  notafter integer,
  loa varchar(255),
  req_key bigint,
  public_key text,
  data longtext,
  PRIMARY KEY (issuer_identifier, cert_key)
);

--
-- Table: certificate_attributes
--
DROP TABLE IF EXISTS certificate_attributes;

CREATE TABLE certificate_attributes (
  identifier varchar(64) NOT NULL,
  attribute_key bigint NOT NULL,
  attribute_contentkey varchar(255),
  attribute_value varchar(4000),
  PRIMARY KEY (attribute_key, identifier)
);

--
-- Table: crl
--
DROP TABLE IF EXISTS crl;

CREATE TABLE crl (
  pki_realm varchar(255) NOT NULL,
  issuer_identifier varchar(64) NOT NULL,
  crl_key decimal(49,0) NOT NULL,
  data longtext,
  last_update integer,
  next_update integer,
  publication_date integer,
  PRIMARY KEY (issuer_identifier, crl_key)
);

--
-- Table: crr
--
DROP TABLE IF EXISTS crr;

CREATE TABLE crr (
  crr_key bigint NOT NULL,
  pki_realm varchar(255) NOT NULL,
  identifier varchar(64) NOT NULL,
  creator varchar(255),
  creator_role varchar(255),
  reason_code varchar(255),
  invalidity_time integer,
  crr_comment text,
  hold_code varchar(255),
  revocation_time integer,
  PRIMARY KEY (pki_realm, crr_key)
);

--
-- Table: csr
--
DROP TABLE IF EXISTS csr;

CREATE TABLE csr (
  req_key bigint NOT NULL,
  pki_realm varchar(255) NOT NULL,
  format varchar(25),
  profile varchar(255),
  loa varchar(255),
  subject varchar(1000),
  data longtext,
  PRIMARY KEY (pki_realm, req_key)
);

--
-- Table: csr_attributes
--
DROP TABLE IF EXISTS csr_attributes;

CREATE TABLE csr_attributes (
  attribute_key bigint NOT NULL,
  pki_realm varchar(255) NOT NULL,
  req_key decimal(49,0) NOT NULL,
  attribute_contentkey varchar(255),
  attribute_value longtext,
  attribute_source text,
  PRIMARY KEY (attribute_key, pki_realm, req_key)
);

--
-- Table: datapool
--
DROP TABLE IF EXISTS datapool;

CREATE TABLE datapool (
  pki_realm varchar(255) NOT NULL,
  namespace varchar(255) NOT NULL,
  datapool_key varchar(255) NOT NULL,
  datapool_value longtext,
  encryption_key varchar(255),
  notafter integer,
  last_update integer,
  PRIMARY KEY (pki_realm, namespace, datapool_key)
);

--
-- Table: secret
--
DROP TABLE IF EXISTS secret;

CREATE TABLE secret (
  pki_realm varchar(255) NOT NULL,
  group_id varchar(255) NOT NULL,
  data longtext,
  PRIMARY KEY (pki_realm, group_id)
);

--
-- Table: session
--
DROP TABLE IF EXISTS session;

CREATE TABLE session (
  session_id varchar(255) NOT NULL,
  data longtext,
  created decimal(49,0) NOT NULL,
  modified decimal(49,0) NOT NULL,
  ip_address varchar(45),
  PRIMARY KEY (session_id)
);

--
-- Table: seq_application_log
--
DROP TABLE IF EXISTS seq_application_log;

CREATE TABLE seq_application_log (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: seq_audittrail
--
DROP TABLE IF EXISTS seq_audittrail;

CREATE TABLE seq_audittrail (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: seq_certificate
--
DROP TABLE IF EXISTS seq_certificate;

CREATE TABLE seq_certificate (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: seq_certificate_attributes
--
DROP TABLE IF EXISTS seq_certificate_attributes;

CREATE TABLE seq_certificate_attributes (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: seq_crl
--
DROP TABLE IF EXISTS seq_crl;

CREATE TABLE seq_crl (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: seq_crr
--
DROP TABLE IF EXISTS seq_crr;

CREATE TABLE seq_crr (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: seq_csr
--
DROP TABLE IF EXISTS seq_csr;

CREATE TABLE seq_csr (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: seq_csr_attributes
--
DROP TABLE IF EXISTS seq_csr_attributes;

CREATE TABLE seq_csr_attributes (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: seq_secret
--
DROP TABLE IF EXISTS seq_secret;

CREATE TABLE seq_secret (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: seq_workflow
--
DROP TABLE IF EXISTS seq_workflow;

CREATE TABLE seq_workflow (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: seq_workflow_history
--
DROP TABLE IF EXISTS seq_workflow_history;

CREATE TABLE seq_workflow_history (
  seq_number INTEGER PRIMARY KEY NOT NULL,
  dummy integer
);

--
-- Table: workflow
--
DROP TABLE IF EXISTS workflow;

CREATE TABLE workflow (
  workflow_id INTEGER PRIMARY KEY NOT NULL,
  pki_realm varchar(255),
  workflow_type varchar(255),
  workflow_state varchar(255),
  workflow_last_update timestamp NOT NULL DEFAULT current_timestamp,
  workflow_proc_state varchar(32),
  workflow_wakeup_at integer,
  workflow_count_try integer,
  workflow_reap_at integer,
  workflow_session longtext,
  watchdog_key varchar(64)
);

--
-- Table: workflow_attributes
--
DROP TABLE IF EXISTS workflow_attributes;

CREATE TABLE workflow_attributes (
  workflow_id bigint NOT NULL,
  attribute_contentkey varchar(255) NOT NULL,
  attribute_value varchar(4000),
  PRIMARY KEY (workflow_id, attribute_contentkey)
);

--
-- Table: workflow_context
--
DROP TABLE IF EXISTS workflow_context;

CREATE TABLE workflow_context (
  workflow_id bigint NOT NULL,
  workflow_context_key varchar(255) NOT NULL,
  workflow_context_value longtext,
  PRIMARY KEY (workflow_id, workflow_context_key)
);

--
-- Table: workflow_history
--
DROP TABLE IF EXISTS workflow_history;

CREATE TABLE workflow_history (
  workflow_hist_id INTEGER PRIMARY KEY NOT NULL,
  workflow_id bigint,
  workflow_action varchar(255),
  workflow_description longtext,
  workflow_state varchar(255),
  workflow_user varchar(255),
  workflow_history_date timestamp NOT NULL DEFAULT current_timestamp
);

COMMIT;


text:
layout: page
subheadline: "Java keywords "
title: "Exploring java.lang"
teaser: "It is Java's most widely used package..."
header:
    image_fullwidth: "java_banner_java_se_7_programming-1.png"
    caption: Image by Ticket Synergy
    caption_url: "http://ticketsynergy.com/2015/06/hello-world/"
image:
    thumb:  java-thumb.png
    homepage: java_home.jpg
categories:
    - Reading
comments: true
show_meta: true
sidebar: right
---

Void
:  The Void class has one field, TYPE, which holds a reference to the Class object for type void. You do not create instances of this class.

Process
:  The abstract Process class encapsulates a process—that is, an executing program. It is used primarily as a superclass for the type of objects created by exec( ) in the Runtime class, or by start( ) in the ProcessBuilder class.

Runtime
:  The Runtime class encapsulates the run-time environment. You cannot instantiate a Runtime object. However, you can get a reference to the current Runtime object by calling the static method Runtime.getRuntime( ). Once you obtain a reference to the current Runtime object, you can call several methods that control the state and behavior of the Java Virtual Machine.

Memory Management
:   use the totalMemory( ) and freeMemory( ) methods.

ProcessBuilder
:   ProcessBuilder provides another way to start and manage processes (that is, programs). all processes are represented by the Process class, and a process can be started by Runtime.exec( ). ProcessBuilder offers more control over the processes.

ProcessBuilder defines these constructors:

~~~
ProcessBuilder(List<String> args)
ProccessBuilder(String ... args)
~~~

System
:  The System class holds a collection of static methods and variables. The standard input, output, and error output of the Java run time are stored in the in, out, and err variables.

Class
:  Class encapsulates the run-time state of a class or interface. Objects of type Class are created automatically, when classes are loaded. You cannot explicitly declare a Class object. Generally, you obtain a Class object by calling the getClass( ) method defined by Object.

Thread, ThreadGroup, and Runnable
:  The Runnable interface and the Thread and ThreadGroup classes support multithreaded programming.

~~~
Thread( )
Thread(Runnable threadOb)
Thread(Runnable threadOb, String threadName)
Thread(String threadName)
Thread(ThreadGroup groupOb, Runnable threadOb)
Thread(ThreadGroup groupOb, Runnable threadOb, String threadName)
Thread(ThreadGroup groupOb, String threadName)

NOTE: threadOb is an instance of a class that implements the Runnable interface and defines where execution of the thread will begin
~~~

ThreadGroup creates a group of threads. It defines these two constructors:

- ThreadGroup(String groupName)
- ThreadGroup(ThreadGroup parentOb, String groupName)

ThreadLocal and InheritableThreadLocal
Java defines two additional thread-related classes in java.lang:

- ThreadLocal: Used to create thread local variables. Each thread will have its own copy of a thread local variable.
- InheritableThreadLocal: Creates thread local variables that may be inherited.


text:
package armnetwork

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

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

// NewRouteFiltersClient creates a new instance of RouteFiltersClient with the specified values.
// subscriptionID - The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription
// ID forms part of the URI for every service call.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewRouteFiltersClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*RouteFiltersClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &RouteFiltersClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// BeginCreateOrUpdate - Creates or updates a route filter in a specified resource group.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-05-01
// resourceGroupName - The name of the resource group.
// routeFilterName - The name of the route filter.
// routeFilterParameters - Parameters supplied to the create or update route filter operation.
// options - RouteFiltersClientBeginCreateOrUpdateOptions contains the optional parameters for the RouteFiltersClient.BeginCreateOrUpdate
// method.
func (client *RouteFiltersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter, options *RouteFiltersClientBeginCreateOrUpdateOptions) (*runtime.Poller[RouteFiltersClientCreateOrUpdateResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.createOrUpdate(ctx, resourceGroupName, routeFilterName, routeFilterParameters, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller(resp, client.pl, &runtime.NewPollerOptions[RouteFiltersClientCreateOrUpdateResponse]{
			FinalStateVia: runtime.FinalStateViaAzureAsyncOp,
		})
	} else {
		return runtime.NewPollerFromResumeToken[RouteFiltersClientCreateOrUpdateResponse](options.ResumeToken, client.pl, nil)
	}
}

// CreateOrUpdate - Creates or updates a route filter in a specified resource group.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-05-01
func (client *RouteFiltersClient) createOrUpdate(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter, options *RouteFiltersClientBeginCreateOrUpdateOptions) (*http.Response, error) {
	req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, routeFilterName, routeFilterParameters, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// createOrUpdateCreateRequest creates the CreateOrUpdate request.
func (client *RouteFiltersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, routeFilterParameters RouteFilter, options *RouteFiltersClientBeginCreateOrUpdateOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if routeFilterName == "" {
		return nil, errors.New("parameter routeFilterName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-05-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, routeFilterParameters)
}

// BeginDelete - Deletes the specified route filter.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-05-01
// resourceGroupName - The name of the resource group.
// routeFilterName - The name of the route filter.
// options - RouteFiltersClientBeginDeleteOptions contains the optional parameters for the RouteFiltersClient.BeginDelete
// method.
func (client *RouteFiltersClient) BeginDelete(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFiltersClientBeginDeleteOptions) (*runtime.Poller[RouteFiltersClientDeleteResponse], error) {
	if options == nil || options.ResumeToken == "" {
		resp, err := client.deleteOperation(ctx, resourceGroupName, routeFilterName, options)
		if err != nil {
			return nil, err
		}
		return runtime.NewPoller(resp, client.pl, &runtime.NewPollerOptions[RouteFiltersClientDeleteResponse]{
			FinalStateVia: runtime.FinalStateViaLocation,
		})
	} else {
		return runtime.NewPollerFromResumeToken[RouteFiltersClientDeleteResponse](options.ResumeToken, client.pl, nil)
	}
}

// Delete - Deletes the specified route filter.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-05-01
func (client *RouteFiltersClient) deleteOperation(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFiltersClientBeginDeleteOptions) (*http.Response, error) {
	req, err := client.deleteCreateRequest(ctx, resourceGroupName, routeFilterName, options)
	if err != nil {
		return nil, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return nil, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) {
		return nil, runtime.NewResponseError(resp)
	}
	return resp, nil
}

// deleteCreateRequest creates the Delete request.
func (client *RouteFiltersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFiltersClientBeginDeleteOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if routeFilterName == "" {
		return nil, errors.New("parameter routeFilterName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-05-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// Get - Gets the specified route filter.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-05-01
// resourceGroupName - The name of the resource group.
// routeFilterName - The name of the route filter.
// options - RouteFiltersClientGetOptions contains the optional parameters for the RouteFiltersClient.Get method.
func (client *RouteFiltersClient) Get(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFiltersClientGetOptions) (RouteFiltersClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, resourceGroupName, routeFilterName, options)
	if err != nil {
		return RouteFiltersClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return RouteFiltersClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return RouteFiltersClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *RouteFiltersClient) getCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, options *RouteFiltersClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if routeFilterName == "" {
		return nil, errors.New("parameter routeFilterName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-05-01")
	if options != nil && options.Expand != nil {
		reqQP.Set("$expand", *options.Expand)
	}
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

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

// NewListPager - Gets all route filters in a subscription.
// Generated from API version 2022-05-01
// options - RouteFiltersClientListOptions contains the optional parameters for the RouteFiltersClient.List method.
func (client *RouteFiltersClient) NewListPager(options *RouteFiltersClientListOptions) *runtime.Pager[RouteFiltersClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[RouteFiltersClientListResponse]{
		More: func(page RouteFiltersClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *RouteFiltersClientListResponse) (RouteFiltersClientListResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listCreateRequest(ctx, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return RouteFiltersClientListResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return RouteFiltersClientListResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return RouteFiltersClientListResponse{}, runtime.NewResponseError(resp)
			}
			return client.listHandleResponse(resp)
		},
	})
}

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

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

// NewListByResourceGroupPager - Gets all route filters in a resource group.
// Generated from API version 2022-05-01
// resourceGroupName - The name of the resource group.
// options - RouteFiltersClientListByResourceGroupOptions contains the optional parameters for the RouteFiltersClient.ListByResourceGroup
// method.
func (client *RouteFiltersClient) NewListByResourceGroupPager(resourceGroupName string, options *RouteFiltersClientListByResourceGroupOptions) *runtime.Pager[RouteFiltersClientListByResourceGroupResponse] {
	return runtime.NewPager(runtime.PagingHandler[RouteFiltersClientListByResourceGroupResponse]{
		More: func(page RouteFiltersClientListByResourceGroupResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *RouteFiltersClientListByResourceGroupResponse) (RouteFiltersClientListByResourceGroupResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return RouteFiltersClientListByResourceGroupResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return RouteFiltersClientListByResourceGroupResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return RouteFiltersClientListByResourceGroupResponse{}, runtime.NewResponseError(resp)
			}
			return client.listByResourceGroupHandleResponse(resp)
		},
	})
}

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

// listByResourceGroupHandleResponse handles the ListByResourceGroup response.
func (client *RouteFiltersClient) listByResourceGroupHandleResponse(resp *http.Response) (RouteFiltersClientListByResourceGroupResponse, error) {
	result := RouteFiltersClientListByResourceGroupResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.RouteFilterListResult); err != nil {
		return RouteFiltersClientListByResourceGroupResponse{}, err
	}
	return result, nil
}

// UpdateTags - Updates tags of a route filter.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-05-01
// resourceGroupName - The name of the resource group.
// routeFilterName - The name of the route filter.
// parameters - Parameters supplied to update route filter tags.
// options - RouteFiltersClientUpdateTagsOptions contains the optional parameters for the RouteFiltersClient.UpdateTags method.
func (client *RouteFiltersClient) UpdateTags(ctx context.Context, resourceGroupName string, routeFilterName string, parameters TagsObject, options *RouteFiltersClientUpdateTagsOptions) (RouteFiltersClientUpdateTagsResponse, error) {
	req, err := client.updateTagsCreateRequest(ctx, resourceGroupName, routeFilterName, parameters, options)
	if err != nil {
		return RouteFiltersClientUpdateTagsResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return RouteFiltersClientUpdateTagsResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return RouteFiltersClientUpdateTagsResponse{}, runtime.NewResponseError(resp)
	}
	return client.updateTagsHandleResponse(resp)
}

// updateTagsCreateRequest creates the UpdateTags request.
func (client *RouteFiltersClient) updateTagsCreateRequest(ctx context.Context, resourceGroupName string, routeFilterName string, parameters TagsObject, options *RouteFiltersClientUpdateTagsOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeFilters/{routeFilterName}"
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if routeFilterName == "" {
		return nil, errors.New("parameter routeFilterName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{routeFilterName}", url.PathEscape(routeFilterName))
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-05-01")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, runtime.MarshalAsJSON(req, parameters)
}

// updateTagsHandleResponse handles the UpdateTags response.
func (client *RouteFiltersClient) updateTagsHandleResponse(resp *http.Response) (RouteFiltersClientUpdateTagsResponse, error) {
	result := RouteFiltersClientUpdateTagsResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.RouteFilter); err != nil {
		return RouteFiltersClientUpdateTagsResponse{}, err
	}
	return result, nil
}


text:
package org.apache.airavata.registry.core.replica.catalog.utils;

import org.apache.airavata.registry.cpi.ResultOrderType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.Map;

public class ReplicaCatalogQueryGenerator {

    private final static Logger logger = LoggerFactory.getLogger(ReplicaCatalogQueryGenerator.class);
	private String tableName;
	private Map<String,Object> matches=new HashMap<String, Object>();
	private static final String SELECT_OBJ="p";
	private static final String DELETE_OBJ="p";
	private static final String TABLE_OBJ="p";

	public ReplicaCatalogQueryGenerator(String tableName, Object[]... params) {
		setTableName(tableName);
		for (Object[] param : params) {
			addMatch(param[0].toString(), param[1]);
		}
	}

	public String getTableName() {
		return tableName;
	}

    public void setTableName(String tableName) {
		this.tableName = tableName;
	}

    public void addMatch(String colName, Object matchValue){
		matches.put(colName, matchValue);
	}

	public void setParameter(String colName, Object matchValue){
		addMatch(colName, matchValue);
	}

    public Query selectQuery(EntityManager entityManager){
        String queryString="SELECT "+ SELECT_OBJ + " FROM " +getTableName()+" "+TABLE_OBJ;
        return generateQueryWithParameters(entityManager, queryString);
    }

    public Query selectQuery(EntityManager entityManager, String orderByColumn,
                             ResultOrderType resultOrderType){
        String order = (resultOrderType == ResultOrderType.ASC) ? "ASC" : "DESC";
        String orderByClause = " ORDER BY " + SELECT_OBJ + "." + orderByColumn + " " + order;
        String queryString="SELECT "+ SELECT_OBJ + " FROM " +getTableName()+" "+TABLE_OBJ;
        return generateQueryWithParameters(entityManager, queryString, orderByClause);
    }

	public Query deleteQuery(EntityManager entityManager){
		String queryString="Delete FROM "+getTableName()+" "+TABLE_OBJ;
		return generateQueryWithParameters(entityManager, queryString);
	}

	private Query generateQueryWithParameters(EntityManager entityManager, String queryString) {
		return generateQueryWithParameters(entityManager, queryString, "");
	}

    private Query generateQueryWithParameters(EntityManager entityManager,
                                              String queryString, String orderByClause) {
        Map<String,Object> queryParameters=new HashMap<String, Object>();
        if (matches.size()>0){
            String matchString = "";
            int paramCount=0;
            for (String colName : matches.keySet()) {
                String paramName="param"+paramCount;
                queryParameters.put(paramName, matches.get(colName));
                if (!matchString.equals("")){
                    matchString+=" AND ";
                }
                matchString+=TABLE_OBJ+"."+colName+" =:"+paramName;
                paramCount++;
            }
            queryString+=" WHERE "+matchString;
        }
        queryString += orderByClause;
        Query query = entityManager.createQuery(queryString);
        for (String paramName : queryParameters.keySet()) {
            query.setParameter(paramName, queryParameters.get(paramName));
        }
        return query;
    }
}


text:
#ifndef LIBSSH2_SYS_SOCKET_H
#define LIBSSH2_SYS_SOCKET_H

/*
 *  <sys/socket.h> wrapper.
 *  Redefines connect().
 */

#include <qadrt.h>

#ifndef _QADRT_LT
# define _QADRT_LT <
#endif
#ifndef _QADRT_GT
# define _QADRT_GT >
#endif

#ifdef QADRT_SYSINC
# include _QADRT_LT QADRT_SYSINC/sys/socket.h _QADRT_GT
#elif __ILEC400_TGTVRM__ >= 710
# include_next <sys/socket.h>
#elif !defined(__SRCSTMF__)
# include <QSYSINC/sys/socket>
#else
# include </QIBM/include/sys/socket.h>
#endif

extern int  _libssh2_os400_connect(int sd,
                                   struct sockaddr * destaddr, int addrlen);

#ifndef LIBSSH2_DISABLE_QADRT_EXT
#define connect(sd, addr, len)  _libssh2_os400_connect((sd), (addr), (len))
#endif

#endif

/* vim: set expandtab ts=4 sw=4: */


text:
package org.wso2.carbon.device.mgt.extensions.device.type.template;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager;
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.*;
import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeDeployerPayloadException;
import org.wso2.carbon.device.mgt.extensions.device.type.template.exception.DeviceTypeMgtPluginException;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceDAODefinition;
import org.wso2.carbon.device.mgt.extensions.device.type.template.dao.DeviceTypePluginDAOManager;
import org.wso2.carbon.device.mgt.extensions.device.type.template.feature.ConfigurationBasedFeatureManager;
import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceTypePluginConstants;
import org.wso2.carbon.device.mgt.extensions.device.type.template.util.DeviceTypeUtils;
import org.wso2.carbon.device.mgt.extensions.license.mgt.registry.RegistryBasedLicenseManager;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.api.Resource;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.List;

/**
 * This holds the implementation of the device manager. From which an instance of it will be created using the
 * deployer file.
 */
public class DeviceTypeManager implements DeviceManager {

    private static final Log log = LogFactory.getLog(DeviceTypeManager.class);
    private String deviceType;
    private DeviceTypePluginDAOManager deviceTypePluginDAOManager;
    private LicenseManager licenseManager;
    private PlatformConfiguration defaultPlatformConfiguration;
    private boolean propertiesExist;
    private boolean requiredDeviceTypeAuthorization;
    private boolean claimable;

    private static final String PATH_MOBILE_PLUGIN_CONF_DIR =
            CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "device-mgt-plugin-configs" + File.separator
                    + "mobile";

    private FeatureManager featureManager;

    public DeviceTypeManager(DeviceTypeConfigIdentifier deviceTypeConfigIdentifier,
                             DeviceTypeConfiguration deviceTypeConfiguration) {
        deviceType = deviceTypeConfigIdentifier.getDeviceType();
        if (deviceTypeConfiguration.getFeatures() != null && deviceTypeConfiguration.getFeatures().
                getFeature() != null) {
            List<Feature> features = deviceTypeConfiguration.getFeatures().getFeature();
            if (features != null) {
                featureManager = new ConfigurationBasedFeatureManager(features);
            }
        }
        if (deviceTypeConfiguration.getDeviceAuthorizationConfig() != null) {
            requiredDeviceTypeAuthorization = deviceTypeConfiguration.getDeviceAuthorizationConfig().
                    isAuthorizationRequired();
        } else {
            requiredDeviceTypeAuthorization = true;
        }
        //add license to registry.
        this.licenseManager = new RegistryBasedLicenseManager();
        try {
            if (licenseManager.getLicense(deviceType, DeviceTypePluginConstants.LANGUAGE_CODE_ENGLISH_US) == null) {

                if (deviceTypeConfiguration.getLicense() != null) {
                    License defaultLicense = new License();
                    defaultLicense.setLanguage(deviceTypeConfiguration.getLicense().getLanguage());
                    defaultLicense.setVersion(deviceTypeConfiguration.getLicense().getVersion());
                    defaultLicense.setText(deviceTypeConfiguration.getLicense().getText());
                    licenseManager.addLicense(deviceType, defaultLicense);
                }
            }
        } catch (LicenseManagementException e) {
            String msg = "Error occurred while adding default license for " + deviceType + " devices";
            throw new DeviceTypeDeployerPayloadException(msg, e);
        }
        claimable = false;
        if (deviceTypeConfiguration.getClaimable() != null ) {
            claimable = deviceTypeConfiguration.getClaimable().isEnabled();
        }

        // Loading default platform configuration
        try {
            defaultPlatformConfiguration = this.getDefaultConfiguration();
        } catch (DeviceManagementException e) {
            String msg = "Error occurred while default platform configuration";
            throw new DeviceTypeDeployerPayloadException(msg, e);
        }

        DeviceDetails deviceDetails = deviceTypeConfiguration.getDeviceDetails();

        if (deviceDetails != null) {

            //Check whether device dao definition exist.
            String tableName = deviceTypeConfiguration.getDeviceDetails().getTableId();
            if (tableName != null && !tableName.isEmpty()) {
                DataSource dataSource = deviceTypeConfiguration.getDataSource();
                if (dataSource == null) {
                    throw new DeviceTypeDeployerPayloadException("Could not find the datasource related with the "
                            + "table id " +  tableName + " for the device type " + deviceType);
                }
                TableConfig tableConfig = dataSource.getTableConfig();

                if (tableConfig == null) {
                    throw new DeviceTypeDeployerPayloadException("Could not find the table config with the "
                            + "table id " +  tableName + " for the device type " + deviceType);
                }
                List<Table> tables = deviceTypeConfiguration.getDataSource().getTableConfig().getTable();
                Table deviceDefinitionTable = null;
                for (Table table : tables) {
                    if (tableName.equals(table.getName())) {
                        deviceDefinitionTable = table;
                        break;
                    }
                }
                if (deviceDefinitionTable == null) {
                    throw new DeviceTypeDeployerPayloadException("Could not find definition for table: " + tableName);
                }
                propertiesExist = true;

                try {
                    PrivilegedCarbonContext.startTenantFlow();
                    PrivilegedCarbonContext.getThreadLocalCarbonContext()
                            .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);

                    DeviceDAODefinition deviceDAODefinition = new DeviceDAODefinition(deviceDefinitionTable);
                    String datasourceName = deviceTypeConfiguration.getDataSource().getJndiConfig().getName();
                    if (datasourceName != null && !datasourceName.isEmpty()) {
                        String setupOption = System.getProperty("setup");
                        if (setupOption != null) {
                            if (log.isDebugEnabled()) {
                                log.debug("-Dsetup is enabled. Device management repository schema initialization is about " +
                                        "to begin");
                            }
                            try {
                                DeviceTypeUtils.setupDeviceManagementSchema(datasourceName, deviceType,
                                        deviceDAODefinition.getDeviceTableName());
                            } catch (DeviceTypeMgtPluginException e) {
                                log.error("Exception occurred while initializing device management database schema", e);
                            }
                        }
                        deviceTypePluginDAOManager = new DeviceTypePluginDAOManager(datasourceName, deviceDAODefinition);
                    } else {
                        throw new DeviceTypeDeployerPayloadException("Invalid datasource name.");
                    }
                } finally {
                    PrivilegedCarbonContext.endTenantFlow();
                }
            } else {
                if (deviceDetails.getProperties() != null && deviceDetails.getProperties().getProperty() != null
                        && deviceDetails.getProperties().getProperty().size() > 0 ) {
                    deviceTypePluginDAOManager = new DeviceTypePluginDAOManager(deviceType, deviceDetails);
                    propertiesExist = true;
                }
            }
        }
    }

    @Override
    public FeatureManager getFeatureManager() {
        return featureManager;
    }

    @Override
    public boolean saveConfiguration(PlatformConfiguration tenantConfiguration)
            throws DeviceManagementException {
        if (tenantConfiguration == null) {
            throw new DeviceManagementException("Platform configuration is null. Cannot save the configuration");
        }
        try {
            if (log.isDebugEnabled()) {
                log.debug("Persisting " + deviceType + " configurations in Registry");
            }
            StringWriter writer = new StringWriter();
            JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.marshal(tenantConfiguration, writer);

            Resource resource = DeviceTypeUtils.getConfigurationRegistry().newResource();
            resource.setContent(writer.toString());
            resource.setMediaType(DeviceTypePluginConstants.MEDIA_TYPE_XML);
            DeviceTypeUtils.putRegistryResource(deviceType, resource);
            return true;
        } catch (DeviceTypeMgtPluginException e) {
            throw new DeviceManagementException(
                    "Error occurred while retrieving the Registry instance : " + e.getMessage(), e);
        } catch (RegistryException e) {
            throw new DeviceManagementException(
                    "Error occurred while persisting the Registry resource of " + deviceType + " Configuration : "
                            + e.getMessage(), e);
        } catch (JAXBException e) {
            throw new DeviceManagementException(
                    "Error occurred while parsing the " + deviceType + " configuration : " + e.getMessage(), e);
        }
    }

    @Override
    public PlatformConfiguration getConfiguration() throws DeviceManagementException {
        Resource resource;
        try {
            resource = DeviceTypeUtils.getRegistryResource(deviceType);
            if (resource != null) {
                JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                return (PlatformConfiguration) unmarshaller.unmarshal(
                        new StringReader(new String((byte[]) resource.getContent(), Charset.
                                forName(DeviceTypePluginConstants.CHARSET_UTF8))));
            } else if (defaultPlatformConfiguration != null) {
                return defaultPlatformConfiguration;
            }
            return null;
        } catch (DeviceTypeMgtPluginException e) {
            throw new DeviceManagementException(
                    "Error occurred while retrieving the Registry instance : " + e.getMessage(), e);
        } catch (JAXBException e) {
            throw new DeviceManagementException(
                    "Error occurred while parsing the " + deviceType + " configuration : " + e.getMessage(), e);
        } catch (RegistryException e) {
            throw new DeviceManagementException(
                    "Error occurred while retrieving the Registry resource of " + deviceType + " Configuration : "
                            + e.getMessage(), e);
        }
    }

    @Override
    public boolean enrollDevice(Device device) throws DeviceManagementException {
        if (device == null) {
            throw new DeviceManagementException("Device is null. Cannot enroll the device.");
        }
        if (propertiesExist) {
            boolean status = false;
            boolean isEnrolled = this.isEnrolled(
                    new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Enrolling a new Android device : " + device.getDeviceIdentifier());
                }
                if (isEnrolled) {
                    this.modifyEnrollment(device);
                } else {
                    deviceTypePluginDAOManager.getDeviceTypeDAOHandler().beginTransaction();
                    status = deviceTypePluginDAOManager.getDeviceDAO().addDevice(device);
                    deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction();
                }
            } catch (DeviceTypeMgtPluginException e) {
                try {
                    deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
                } catch (DeviceTypeMgtPluginException ex) {
                    String msg = "Error occurred while roll back the device enrol transaction :" +
                            device.toString();
                    log.warn(msg, ex);
                }
                String msg = "Error while enrolling the " + deviceType + " device : " + device.getDeviceIdentifier();
                throw new DeviceManagementException(msg, e);
            }
            return status;
        }
        return true;
    }

    @Override
    public boolean modifyEnrollment(Device device) throws DeviceManagementException {
        if (propertiesExist) {
            boolean status;
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Modifying the Android device enrollment data");
                }
                deviceTypePluginDAOManager.getDeviceTypeDAOHandler().beginTransaction();
                status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(device);
                deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction();
            } catch (DeviceTypeMgtPluginException e) {
                try {
                    deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
                } catch (DeviceTypeMgtPluginException mobileDAOEx) {
                    String msg = "Error occurred while roll back the update device transaction :" +
                            device.toString();
                    log.warn(msg, mobileDAOEx);
                }
                String msg = "Error while updating the enrollment of the " + deviceType + " device : " +
                        device.getDeviceIdentifier();
                throw new DeviceManagementException(msg, e);
            }
            return status;
        }
        return true;
    }

    @Override
    public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
        //Here we don't have anything specific to do. Hence returning.
        return true;
    }

    @Override
    public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
        if (deviceId == null) {
            throw new DeviceManagementException("Cannot check the enrollment status of a null device");
        }
        if (propertiesExist) {
            boolean isEnrolled = false;
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Checking the enrollment of Android device : " + deviceId.getId());
                }
                Device device =
                        deviceTypePluginDAOManager.getDeviceDAO().getDevice(deviceId.getId());
                if (device != null) {
                    isEnrolled = true;
                }
            } catch (DeviceTypeMgtPluginException e) {
                String msg = "Error while checking the enrollment status of " + deviceType + " device : " +
                        deviceId.getId();
                throw new DeviceManagementException(msg, e);
            }
            return isEnrolled;
        }
        return true;
    }

    @Override
    public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
        return true;
    }

    @Override
    public boolean setActive(DeviceIdentifier deviceId, boolean status)
            throws DeviceManagementException {
        return true;
    }

    @Override
    public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
        if (deviceId == null) {
            throw new DeviceManagementException("Cannot get the device. DeviceIdentifier is null");
        }
        if (propertiesExist) {
            Device device;
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Getting the details of " + deviceType + " device : '" + deviceId.getId() + "'");
                }
                device = deviceTypePluginDAOManager.getDeviceDAO().getDevice(deviceId.getId());
            } catch (DeviceTypeMgtPluginException e) {
                throw new DeviceManagementException(
                        "Error occurred while fetching the " + deviceType + " device: '" + deviceId.getId() + "'", e);
            }
            return device;
        }
        return null;
    }

    @Override
    public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
            throws DeviceManagementException {
        return true;
    }

    @Override
    public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
        return claimable;
    }

    @Override
    public boolean setStatus(DeviceIdentifier deviceIdentifier, String currentUser,
                             EnrolmentInfo.Status status) throws DeviceManagementException {
        return false;
    }

    @Override
    public License getLicense(String languageCode) throws LicenseManagementException {
        return licenseManager.getLicense(deviceType, languageCode);
    }

    @Override
    public void addLicense(License license) throws LicenseManagementException {
        licenseManager.addLicense(deviceType, license);
    }

    @Override
    public boolean requireDeviceAuthorization() {
        return requiredDeviceTypeAuthorization;
    }

    private PlatformConfiguration getDefaultConfiguration() throws DeviceManagementException {

        if (log.isDebugEnabled()) {
            log.debug("Loading default " + deviceType + " platform configuration from " + deviceType +
                    "-default-platform-configuration.xml");
        }
        try {
            String platformConfigurationPath =
                    PATH_MOBILE_PLUGIN_CONF_DIR + File.separator + deviceType + "-default-platform-configuration.xml";
            File platformConfig = new File(platformConfigurationPath);

            if (platformConfig.exists()) {
                Document doc = DeviceTypeUtils.convertToDocument(platformConfig);
                JAXBContext context = JAXBContext.newInstance(PlatformConfiguration.class);
                Unmarshaller unmarshaller = context.createUnmarshaller();
                return (PlatformConfiguration) unmarshaller.unmarshal(doc);
            } else {
                log.warn(deviceType + "-default-platform-configuration.xml is not available, hence default " +
                        deviceType + "platform configuration cannot be loaded.");
            }
            return null;
        } catch (JAXBException e) {
            throw new DeviceManagementException(
                    "Error occurred while parsing the " + deviceType + " default platform configuration : " + e
                            .getMessage(), e);
        } catch (DeviceTypeMgtPluginException e) {
            throw new DeviceManagementException(
                    "Error occurred while parsing the " + deviceType + " default platform configuration : " + e
                            .getMessage(), e);
        }
    }

    @Override
    public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device)
            throws DeviceManagementException {
        if (propertiesExist) {
            boolean status;
            Device existingDevice = this.getDevice(deviceIdentifier);

            if (existingDevice == null) {
                return false;
            }
            existingDevice.setProperties(device.getProperties());
            try {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "updating the details of " + deviceType + " device : " + device.getDeviceIdentifier());
                }
                deviceTypePluginDAOManager.getDeviceTypeDAOHandler().beginTransaction();
                status = deviceTypePluginDAOManager.getDeviceDAO().updateDevice(existingDevice);
                deviceTypePluginDAOManager.getDeviceTypeDAOHandler().commitTransaction();
            } catch (DeviceTypeMgtPluginException e) {
                try {
                    deviceTypePluginDAOManager.getDeviceTypeDAOHandler().rollbackTransaction();
                } catch (DeviceTypeMgtPluginException e1) {
                    log.warn("Error occurred while roll back the update device info transaction : '" +
                            device.toString() + "'", e1);
                }
                throw new DeviceManagementException(
                        "Error occurred while updating the " + deviceType + " device: '" +
                                device.getDeviceIdentifier() + "'", e);
            }
            return status;
        }
        return true;
    }

    @Override
    public List<Device> getAllDevices() throws DeviceManagementException {
        if (propertiesExist) {
            List<Device> devices = null;
            try {
                if (log.isDebugEnabled()) {
                    log.debug("Fetching the details of all " + deviceType + " devices");
                }
                devices = deviceTypePluginDAOManager.getDeviceDAO().getAllDevices();
            } catch (DeviceTypeMgtPluginException e) {
                throw new DeviceManagementException("Error occurred while fetching all " + deviceType + " devices", e);
            }
            return devices;
        }
        return null;
    }

}


text:
title: Plugins
permalink: /docs/plugins/installation/
---

Jekyll has built-in support for using plugins to extend the core functionality.

Primarily, any file with extension `.rb` placed within a `_plugins` directory at the root of the site's `source`, will be automatically loaded
during a build session.

This behavior can be configured as follows:

- The `_plugins` directory may be changed either directly via the command-line or via the configuration file(s).
- Plugins in the `_plugins` directory (or its equivalent(s)) will not be loaded when Jekyll is running in `safe` mode.
- This route cannot be used to extend the Jekyll CLI.

To work with plugins packaged as gems, one has to list the desired gems in the configuration file under a top-level key named `plugins`.
Additionally, if you're building in `safe` mode, the gem needs to be listed under a top-level key named `whitelist`. For example:

```yaml
plugins:
  - jekyll-gist
  - jekyll-coffeescript
  - jekyll-seo-tag
  - some-other-jekyll-plugin

# Enable safe mode
safe: true

# Whitelist plugins under safe mode.
# Note that `some-other-jekyll-plugin` is not listed here. Therefore,
# it will not be loaded under safe mode.
whitelist:
  - jekyll-gist
  - jekyll-coffeescript
  - jekyll-seo-tag
```

In the absence of a Gemfile, one must manually ensure that listed plugins have been installed prior to invoking Jekyll. For example, the
latest versions of gems in the above list may be installed to a system-wide location by running:

```sh
gem install jekyll-gist jekyll-coffeescript jekyll-remote-theme some-other-jekyll-plugin
```

## Using a Gemfile

The maintenance of various gem dependencies may be greatly simplified by using a Gemfile (usually at the root of the site's source) in
conjunction with a Rubygem named `bundler`. The Gemfile however **should** list all the primary dependencies of your site, including Jekyll
itself, not just gem-based plugins of the site because Bundler narrows the scope of installed gems to just *runtime dependencies* resolved by
evaluating the Gemfile. For example:

```ruby
source "https://rubygems.org"

# Use the latest version.
gem "jekyll"

# The theme of current site, locked to a certain version.
gem "minima", "2.4.1"

# Plugins of this site loaded during a build with proper
# site configuration.
gem "jekyll-gist"
gem "jekyll-coffeescript"
gem "jekyll-seo-tag", "~> 1.5"
gem "some-other-jekyll-plugin"

# A dependency of a custom-plugin inside `_plugins` directory.
gem "nokogiri", "~> 1.11"
```

The gems listed in the Gemfile can be collectively installed by simply running `bundle install`.

### The `:jekyll_plugins` Gemfile group
{: #the-jekyll_plugins-group}

Jekyll gives a special treatment to gems listed as part of the `:jekyll_plugins` group in a Gemfile. Any gem under this group is loaded at
the very beginning of any Jekyll process, irrespective of the `--safe` CLI flag or entries in the configuration file(s).

While this route allows one to enhance Jekyll's CLI with additional subcommands and options, or avoid having to list gems in the configuration
file, the downside is the necessity to be mindful of what gems are included in the group. For example:

```ruby
source "https://rubygems.org"

# Use the latest version.
gem "jekyll"

# The theme of current site, locked to a certain version.
gem "minima", "2.4.1"

# Plugins of this site loaded only if configured correctly.
gem "jekyll-gist"
gem "jekyll-coffeescript"

# Gems loaded irrespective of site configuration.
group :jekyll_plugins do
  gem "jekyll-cli-plus"
  gem "jekyll-seo-tag", "~> 1.5"
  gem "some-other-jekyll-plugin"
end
```

Plugins on GitHub Pages

    GitHub Pages is powered by Jekyll. All GitHub Pages sites are generated using the
    --safe option to disable plugins (with the exception of some
    whitelisted plugins) for security reasons. Unfortunately, this means your plugins won't
    work if you're deploying via GitHub Pages.

    You can still use GitHub Pages to publish your site, but you'll need to build the site locally and push the generated files to your
    GitHub repository instead of the Jekyll source files.

    _plugins, _config.yml and Gemfile can be used simultaneously

    You may use any of the aforementioned plugin routes simultaneously in the same site if you so choose.
    Use of one does not restrict the use of the others.