text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://code.google.com/p/google-apis-client-generator/
 * (build: 2015-03-26 20:30:19 UTC)
 * on 2015-04-22 at 10:26:21 UTC
 * Modify at your own risk.
 */

package com.appspot.lunch__mates__endpoints.lunchmates;

/**
 * Service definition for Lunchmates (v1).
 *
 *

 * LunchMates API
 *

 *
 *

 * For more information about this service, see the
 * API Documentation
 *

 *
 *

 * This service uses {@link LunchmatesRequestInitializer} to initialize global parameters via its
 * {@link Builder}.
 *

 *
 * @since 1.3
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public class Lunchmates extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {

  // Note: Leave this static initializer at the top of the file.
  static {
    com.google.api.client.util.Preconditions.checkState(
        com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
        com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15,
        "You are currently running with version %s of google-api-client. " +
        "You need at least version 1.15 of google-api-client to run version " +
        "1.20.0 of the lunchmates library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
  }

  /**
   * The default encoded root URL of the service. This is determined when the library is generated
   * and normally should not be changed.
   *
   * @since 1.7
   */
  public static final String DEFAULT_ROOT_URL = "https://lunch--mates--endpoints.appspot.com/_ah/api/";

  /**
   * The default encoded service path of the service. This is determined when the library is
   * generated and normally should not be changed.
   *
   * @since 1.7
   */
  public static final String DEFAULT_SERVICE_PATH = "lunchmates/v1/";

  /**
   * The default encoded base URL of the service. This is determined when the library is generated
   * and normally should not be changed.
   */
  public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;

  /**
   * Constructor.
   *
   *

   * Use {@link Builder} if you need to specify any of the optional parameters.
   *

   *
   * @param transport HTTP transport, which should normally be:
   *

   *
Google App Engine:
   *        {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}

   *
Android: {@code newCompatibleTransport} from
   *        {@code com.google.api.client.extensions.android.http.AndroidHttp}

   *
Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
   *

   *

   * @param jsonFactory JSON factory, which may be:
   *

   *
Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}

   *
Google GSON: {@code com.google.api.client.json.gson.GsonFactory}

   *
Android Honeycomb or higher:
   *        {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}

   *

   * @param httpRequestInitializer HTTP request initializer or {@code null} for none
   * @since 1.7
   */
  public Lunchmates(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
      com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
    this(new Builder(transport, jsonFactory, httpRequestInitializer));
  }

  /**
   * @param builder builder
   */
  Lunchmates(Builder builder) {
    super(builder);
  }

  @Override
  protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
    super.initialize(httpClientRequest);
  }

  /**
   * An accessor for creating requests from the Auth collection.
   *
   *
The typical use is:

   *

   *   {@code Lunchmates lunchmates = new Lunchmates(...);}
   *   {@code Lunchmates.Auth.List request = lunchmates.auth().list(parameters ...)}
   *

   *
   * @return the resource collection
   */
  public Auth auth() {
    return new Auth();
  }

  /**
   * The "auth" collection of methods.
   */
  public class Auth {

    /**
     * An accessor for creating requests from the Users collection.
     *
     *
The typical use is:

     *

     *   {@code Lunchmates lunchmates = new Lunchmates(...);}
     *   {@code Lunchmates.Users.List request = lunchmates.users().list(parameters ...)}
     *

     *
     * @return the resource collection
     */
    public Users users() {
      return new Users();
    }

    /**
     * The "users" collection of methods.
     */
    public class Users {

      /**
       * Create a request for the method "users.authenticate".
       *
       * This request holds the parameters needed by the lunchmates server.  After setting any optional
       * parameters, call the {@link Authenticate#execute()} method to invoke the remote operation.
       *
       * @param content the {@link com.appspot.lunch__mates__endpoints.lunchmates.model.UserDataProto}
       * @return the request
       */
      public Authenticate authenticate(com.appspot.lunch__mates__endpoints.lunchmates.model.UserDataProto content) throws java.io.IOException {
        Authenticate result = new Authenticate(content);
        initialize(result);
        return result;
      }

      public class Authenticate extends LunchmatesRequest<com.appspot.lunch__mates__endpoints.lunchmates.model.UserData> {

        private static final String REST_PATH = "authenticate";

        /**
         * Create a request for the method "users.authenticate".
         *
         * This request holds the parameters needed by the the lunchmates server.  After setting any
         * optional parameters, call the {@link Authenticate#execute()} method to invoke the remote
         * operation.
 {@link
         * Authenticate#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
         * must be called to initialize this instance immediately after invoking the constructor.

         *
         * @param content the {@link com.appspot.lunch__mates__endpoints.lunchmates.model.UserDataProto}
         * @since 1.13
         */
        protected Authenticate(com.appspot.lunch__mates__endpoints.lunchmates.model.UserDataProto content) {
          super(Lunchmates.this, "POST", REST_PATH, content, com.appspot.lunch__mates__endpoints.lunchmates.model.UserData.class);
        }

        @Override
        public Authenticate setAlt(java.lang.String alt) {
          return (Authenticate) super.setAlt(alt);
        }

        @Override
        public Authenticate setFields(java.lang.String fields) {
          return (Authenticate) super.setFields(fields);
        }

        @Override
        public Authenticate setKey(java.lang.String key) {
          return (Authenticate) super.setKey(key);
        }

        @Override
        public Authenticate setOauthToken(java.lang.String oauthToken) {
          return (Authenticate) super.setOauthToken(oauthToken);
        }

        @Override
        public Authenticate setPrettyPrint(java.lang.Boolean prettyPrint) {
          return (Authenticate) super.setPrettyPrint(prettyPrint);
        }

        @Override
        public Authenticate setQuotaUser(java.lang.String quotaUser) {
          return (Authenticate) super.setQuotaUser(quotaUser);
        }

        @Override
        public Authenticate setUserIp(java.lang.String userIp) {
          return (Authenticate) super.setUserIp(userIp);
        }

        @Override
        public Authenticate set(String parameterName, Object value) {
          return (Authenticate) super.set(parameterName, value);
        }
      }

    }
  }

  /**
   * An accessor for creating requests from the Meeting collection.
   *
   *
The typical use is:

   *

   *   {@code Lunchmates lunchmates = new Lunchmates(...);}
   *   {@code Lunchmates.Meeting.List request = lunchmates.meeting().list(parameters ...)}
   *

   *
   * @return the resource collection
   */
  public Meeting meeting() {
    return new Meeting();
  }

  /**
   * The "meeting" collection of methods.
   */
  public class Meeting {

    /**
     * An accessor for creating requests from the Meetings collection.
     *
     *
The typical use is:

     *

     *   {@code Lunchmates lunchmates = new Lunchmates(...);}
     *   {@code Lunchmates.Meetings.List request = lunchmates.meetings().list(parameters ...)}
     *

     *
     * @return the resource collection
     */
    public Meetings meetings() {
      return new Meetings();
    }

    /**
     * The "meetings" collection of methods.
     */
    public class Meetings {

      /**
       * Create a request for the method "meetings.create".
       *
       * This request holds the parameters needed by the lunchmates server.  After setting any optional
       * parameters, call the {@link Create#execute()} method to invoke the remote operation.
       *
       * @param content the {@link com.appspot.lunch__mates__endpoints.lunchmates.model.Meeting}
       * @return the request
       */
      public Create create(com.appspot.lunch__mates__endpoints.lunchmates.model.Meeting content) throws java.io.IOException {
        Create result = new Create(content);
        initialize(result);
        return result;
      }

      public class Create extends LunchmatesRequest<com.appspot.lunch__mates__endpoints.lunchmates.model.Meeting> {

        private static final String REST_PATH = "meetings";

        /**
         * Create a request for the method "meetings.create".
         *
         * This request holds the parameters needed by the the lunchmates server.  After setting any
         * optional parameters, call the {@link Create#execute()} method to invoke the remote operation.
         *
 {@link
         * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
         * be called to initialize this instance immediately after invoking the constructor.

         *
         * @param content the {@link com.appspot.lunch__mates__endpoints.lunchmates.model.Meeting}
         * @since 1.13
         */
        protected Create(com.appspot.lunch__mates__endpoints.lunchmates.model.Meeting content) {
          super(Lunchmates.this, "POST", REST_PATH, content, com.appspot.lunch__mates__endpoints.lunchmates.model.Meeting.class);
        }

        @Override
        public Create setAlt(java.lang.String alt) {
          return (Create) super.setAlt(alt);
        }

        @Override
        public Create setFields(java.lang.String fields) {
          return (Create) super.setFields(fields);
        }

        @Override
        public Create setKey(java.lang.String key) {
          return (Create) super.setKey(key);
        }

        @Override
        public Create setOauthToken(java.lang.String oauthToken) {
          return (Create) super.setOauthToken(oauthToken);
        }

        @Override
        public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
          return (Create) super.setPrettyPrint(prettyPrint);
        }

        @Override
        public Create setQuotaUser(java.lang.String quotaUser) {
          return (Create) super.setQuotaUser(quotaUser);
        }

        @Override
        public Create setUserIp(java.lang.String userIp) {
          return (Create) super.setUserIp(userIp);
        }

        @Override
        public Create set(String parameterName, Object value) {
          return (Create) super.set(parameterName, value);
        }
      }
      /**
       * Create a request for the method "meetings.list".
       *
       * This request holds the parameters needed by the lunchmates server.  After setting any optional
       * parameters, call the {@link List#execute()} method to invoke the remote operation.
       *
       * @return the request
       */
      public List list() throws java.io.IOException {
        List result = new List();
        initialize(result);
        return result;
      }

      public class List extends LunchmatesRequest<com.appspot.lunch__mates__endpoints.lunchmates.model.MeetingCollection> {

        private static final String REST_PATH = "meetings";

        /**
         * Create a request for the method "meetings.list".
         *
         * This request holds the parameters needed by the the lunchmates server.  After setting any
         * optional parameters, call the {@link List#execute()} method to invoke the remote operation.

         * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
         * must be called to initialize this instance immediately after invoking the constructor.

         *
         * @since 1.13
         */
        protected List() {
          super(Lunchmates.this, "GET", REST_PATH, null, com.appspot.lunch__mates__endpoints.lunchmates.model.MeetingCollection.class);
        }

        @Override
        public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
          return super.executeUsingHead();
        }

        @Override
        public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
          return super.buildHttpRequestUsingHead();
        }

        @Override
        public List setAlt(java.lang.String alt) {
          return (List) super.setAlt(alt);
        }

        @Override
        public List setFields(java.lang.String fields) {
          return (List) super.setFields(fields);
        }

        @Override
        public List setKey(java.lang.String key) {
          return (List) super.setKey(key);
        }

        @Override
        public List setOauthToken(java.lang.String oauthToken) {
          return (List) super.setOauthToken(oauthToken);
        }

        @Override
        public List setPrettyPrint(java.lang.Boolean prettyPrint) {
          return (List) super.setPrettyPrint(prettyPrint);
        }

        @Override
        public List setQuotaUser(java.lang.String quotaUser) {
          return (List) super.setQuotaUser(quotaUser);
        }

        @Override
        public List setUserIp(java.lang.String userIp) {
          return (List) super.setUserIp(userIp);
        }

        @com.google.api.client.util.Key
        private java.lang.String pageToken;

        /**

         */
        public java.lang.String getPageToken() {
          return pageToken;
        }

        public List setPageToken(java.lang.String pageToken) {
          this.pageToken = pageToken;
          return this;
        }

        @com.google.api.client.util.Key
        private java.lang.Long limit;

        /**

         */
        public java.lang.Long getLimit() {
          return limit;
        }

        public List setLimit(java.lang.Long limit) {
          this.limit = limit;
          return this;
        }

        @com.google.api.client.util.Key
        private java.lang.String order;

        /**

         */
        public java.lang.String getOrder() {
          return order;
        }

        public List setOrder(java.lang.String order) {
          this.order = order;
          return this;
        }

        @Override
        public List set(String parameterName, Object value) {
          return (List) super.set(parameterName, value);
        }
      }

    }
  }

  /**
   * An accessor for creating requests from the MeetingRequest collection.
   *
   *
The typical use is:

   *

   *   {@code Lunchmates lunchmates = new Lunchmates(...);}
   *   {@code Lunchmates.MeetingRequest.List request = lunchmates.meetingRequest().list(parameters ...)}
   *

   *
   * @return the resource collection
   */
  public MeetingRequest meetingRequest() {
    return new MeetingRequest();
  }

  /**
   * The "meeting_request" collection of methods.
   */
  public class MeetingRequest {

    /**
     * An accessor for creating requests from the MeetingRequests collection.
     *
     *
The typical use is:

     *

     *   {@code Lunchmates lunchmates = new Lunchmates(...);}
     *   {@code Lunchmates.MeetingRequests.List request = lunchmates.meetingRequests().list(parameters ...)}
     *

     *
     * @return the resource collection
     */
    public MeetingRequests meetingRequests() {
      return new MeetingRequests();
    }

    /**
     * The "meeting_requests" collection of methods.
     */
    public class MeetingRequests {

      /**
       * Create a request for the method "meeting_requests.create".
       *
       * This request holds the parameters needed by the lunchmates server.  After setting any optional
       * parameters, call the {@link Create#execute()} method to invoke the remote operation.
       *
       * @param meetingId
       * @param content the {@link com.appspot.lunch__mates__endpoints.lunchmates.model.MeetingRequest}
       * @return the request
       */
      public Create create(java.lang.Long meetingId, com.appspot.lunch__mates__endpoints.lunchmates.model.MeetingRequest content) throws java.io.IOException {
        Create result = new Create(meetingId, content);
        initialize(result);
        return result;
      }

      public class Create extends LunchmatesRequest<com.appspot.lunch__mates__endpoints.lunchmates.model.MeetingRequest> {

        private static final String REST_PATH = "meetings/{meeting_id}/join";

        /**
         * Create a request for the method "meeting_requests.create".
         *
         * This request holds the parameters needed by the the lunchmates server.  After setting any
         * optional parameters, call the {@link Create#execute()} method to invoke the remote operation.
         *
 {@link
         * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must
         * be called to initialize this instance immediately after invoking the constructor.

         *
         * @param meetingId
         * @param content the {@link com.appspot.lunch__mates__endpoints.lunchmates.model.MeetingRequest}
         * @since 1.13
         */
        protected Create(java.lang.Long meetingId, com.appspot.lunch__mates__endpoints.lunchmates.model.MeetingRequest content) {
          super(Lunchmates.this, "POST", REST_PATH, content, com.appspot.lunch__mates__endpoints.lunchmates.model.MeetingRequest.class);
          this.meetingId = com.google.api.client.util.Preconditions.checkNotNull(meetingId, "Required parameter meetingId must be specified.");
        }

        @Override
        public Create setAlt(java.lang.String alt) {
          return (Create) super.setAlt(alt);
        }

        @Override
        public Create setFields(java.lang.String fields) {
          return (Create) super.setFields(fields);
        }

        @Override
        public Create setKey(java.lang.String key) {
          return (Create) super.setKey(key);
        }

        @Override
        public Create setOauthToken(java.lang.String oauthToken) {
          return (Create) super.setOauthToken(oauthToken);
        }

        @Override
        public Create setPrettyPrint(java.lang.Boolean prettyPrint) {
          return (Create) super.setPrettyPrint(prettyPrint);
        }

        @Override
        public Create setQuotaUser(java.lang.String quotaUser) {
          return (Create) super.setQuotaUser(quotaUser);
        }

        @Override
        public Create setUserIp(java.lang.String userIp) {
          return (Create) super.setUserIp(userIp);
        }

        @com.google.api.client.util.Key("meeting_id")
        private java.lang.Long meetingId;

        /**

         */
        public java.lang.Long getMeetingId() {
          return meetingId;
        }

        public Create setMeetingId(java.lang.Long meetingId) {
          this.meetingId = meetingId;
          return this;
        }

        @Override
        public Create set(String parameterName, Object value) {
          return (Create) super.set(parameterName, value);
        }
      }
      /**
       * Create a request for the method "meeting_requests.list".
       *
       * This request holds the parameters needed by the lunchmates server.  After setting any optional
       * parameters, call the {@link List#execute()} method to invoke the remote operation.
       *
       * @param meetingId
       * @return the request
       */
      public List list(java.lang.Long meetingId) throws java.io.IOException {
        List result = new List(meetingId);
        initialize(result);
        return result;
      }

      public class List extends LunchmatesRequest<com.appspot.lunch__mates__endpoints.lunchmates.model.MeetingRequestCollection> {

        private static final String REST_PATH = "meetings/{meeting_id}/requests";

        /**
         * Create a request for the method "meeting_requests.list".
         *
         * This request holds the parameters needed by the the lunchmates server.  After setting any
         * optional parameters, call the {@link List#execute()} method to invoke the remote operation.

         * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
         * must be called to initialize this instance immediately after invoking the constructor.

         *
         * @param meetingId
         * @since 1.13
         */
        protected List(java.lang.Long meetingId) {
          super(Lunchmates.this, "GET", REST_PATH, null, com.appspot.lunch__mates__endpoints.lunchmates.model.MeetingRequestCollection.class);
          this.meetingId = com.google.api.client.util.Preconditions.checkNotNull(meetingId, "Required parameter meetingId must be specified.");
        }

        @Override
        public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
          return super.executeUsingHead();
        }

        @Override
        public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
          return super.buildHttpRequestUsingHead();
        }

        @Override
        public List setAlt(java.lang.String alt) {
          return (List) super.setAlt(alt);
        }

        @Override
        public List setFields(java.lang.String fields) {
          return (List) super.setFields(fields);
        }

        @Override
        public List setKey(java.lang.String key) {
          return (List) super.setKey(key);
        }

        @Override
        public List setOauthToken(java.lang.String oauthToken) {
          return (List) super.setOauthToken(oauthToken);
        }

        @Override
        public List setPrettyPrint(java.lang.Boolean prettyPrint) {
          return (List) super.setPrettyPrint(prettyPrint);
        }

        @Override
        public List setQuotaUser(java.lang.String quotaUser) {
          return (List) super.setQuotaUser(quotaUser);
        }

        @Override
        public List setUserIp(java.lang.String userIp) {
          return (List) super.setUserIp(userIp);
        }

        @com.google.api.client.util.Key("meeting_id")
        private java.lang.Long meetingId;

        /**

         */
        public java.lang.Long getMeetingId() {
          return meetingId;
        }

        public List setMeetingId(java.lang.Long meetingId) {
          this.meetingId = meetingId;
          return this;
        }

        @Override
        public List set(String parameterName, Object value) {
          return (List) super.set(parameterName, value);
        }
      }

    }
  }

  /**
   * An accessor for creating requests from the UserData collection.
   *
   *
The typical use is:

   *

   *   {@code Lunchmates lunchmates = new Lunchmates(...);}
   *   {@code Lunchmates.UserData.List request = lunchmates.userData().list(parameters ...)}
   *

   *
   * @return the resource collection
   */
  public UserData userData() {
    return new UserData();
  }

  /**
   * The "user_data" collection of methods.
   */
  public class UserData {

    /**
     * An accessor for creating requests from the Users collection.
     *
     *
The typical use is:

     *

     *   {@code Lunchmates lunchmates = new Lunchmates(...);}
     *   {@code Lunchmates.Users.List request = lunchmates.users().list(parameters ...)}
     *

     *
     * @return the resource collection
     */
    public Users users() {
      return new Users();
    }

    /**
     * The "users" collection of methods.
     */
    public class Users {

      /**
       * Create a request for the method "users.list".
       *
       * This request holds the parameters needed by the lunchmates server.  After setting any optional
       * parameters, call the {@link List#execute()} method to invoke the remote operation.
       *
       * @return the request
       */
      public List list() throws java.io.IOException {
        List result = new List();
        initialize(result);
        return result;
      }

      public class List extends LunchmatesRequest<com.appspot.lunch__mates__endpoints.lunchmates.model.UserDataCollection> {

        private static final String REST_PATH = "users";

        /**
         * Create a request for the method "users.list".
         *
         * This request holds the parameters needed by the the lunchmates server.  After setting any
         * optional parameters, call the {@link List#execute()} method to invoke the remote operation.

         * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
         * must be called to initialize this instance immediately after invoking the constructor.

         *
         * @since 1.13
         */
        protected List() {
          super(Lunchmates.this, "GET", REST_PATH, null, com.appspot.lunch__mates__endpoints.lunchmates.model.UserDataCollection.class);
        }

        @Override
        public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException {
          return super.executeUsingHead();
        }

        @Override
        public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException {
          return super.buildHttpRequestUsingHead();
        }

        @Override
        public List setAlt(java.lang.String alt) {
          return (List) super.setAlt(alt);
        }

        @Override
        public List setFields(java.lang.String fields) {
          return (List) super.setFields(fields);
        }

        @Override
        public List setKey(java.lang.String key) {
          return (List) super.setKey(key);
        }

        @Override
        public List setOauthToken(java.lang.String oauthToken) {
          return (List) super.setOauthToken(oauthToken);
        }

        @Override
        public List setPrettyPrint(java.lang.Boolean prettyPrint) {
          return (List) super.setPrettyPrint(prettyPrint);
        }

        @Override
        public List setQuotaUser(java.lang.String quotaUser) {
          return (List) super.setQuotaUser(quotaUser);
        }

        @Override
        public List setUserIp(java.lang.String userIp) {
          return (List) super.setUserIp(userIp);
        }

        @com.google.api.client.util.Key
        private java.lang.String pageToken;

        /**

         */
        public java.lang.String getPageToken() {
          return pageToken;
        }

        public List setPageToken(java.lang.String pageToken) {
          this.pageToken = pageToken;
          return this;
        }

        @com.google.api.client.util.Key
        private java.lang.Long limit;

        /**

         */
        public java.lang.Long getLimit() {
          return limit;
        }

        public List setLimit(java.lang.Long limit) {
          this.limit = limit;
          return this;
        }

        @com.google.api.client.util.Key
        private java.lang.String order;

        /**

         */
        public java.lang.String getOrder() {
          return order;
        }

        public List setOrder(java.lang.String order) {
          this.order = order;
          return this;
        }

        @Override
        public List set(String parameterName, Object value) {
          return (List) super.set(parameterName, value);
        }
      }

    }
  }

  /**
   * Builder for {@link Lunchmates}.
   *
   *

   * Implementation is not thread-safe.
   *

   *
   * @since 1.3.0
   */
  public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {

    /**
     * Returns an instance of a new builder.
     *
     * @param transport HTTP transport, which should normally be:
     *

     *
Google App Engine:
     *        {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}

     *
Android: {@code newCompatibleTransport} from
     *        {@code com.google.api.client.extensions.android.http.AndroidHttp}

     *
Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
     *

     *

     * @param jsonFactory JSON factory, which may be:
     *

     *
Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}

     *
Google GSON: {@code com.google.api.client.json.gson.GsonFactory}

     *
Android Honeycomb or higher:
     *        {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}

     *

     * @param httpRequestInitializer HTTP request initializer or {@code null} for none
     * @since 1.7
     */
    public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
        com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
      super(
          transport,
          jsonFactory,
          DEFAULT_ROOT_URL,
          DEFAULT_SERVICE_PATH,
          httpRequestInitializer,
          false);
    }

    /** Builds a new instance of {@link Lunchmates}. */
    @Override
    public Lunchmates build() {
      return new Lunchmates(this);
    }

    @Override
    public Builder setRootUrl(String rootUrl) {
      return (Builder) super.setRootUrl(rootUrl);
    }

    @Override
    public Builder setServicePath(String servicePath) {
      return (Builder) super.setServicePath(servicePath);
    }

    @Override
    public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
      return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
    }

    @Override
    public Builder setApplicationName(String applicationName) {
      return (Builder) super.setApplicationName(applicationName);
    }

    @Override
    public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
      return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
    }

    @Override
    public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
      return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
    }

    @Override
    public Builder setSuppressAllChecks(boolean suppressAllChecks) {
      return (Builder) super.setSuppressAllChecks(suppressAllChecks);
    }

    /**
     * Set the {@link LunchmatesRequestInitializer}.
     *
     * @since 1.12
     */
    public Builder setLunchmatesRequestInitializer(
        LunchmatesRequestInitializer lunchmatesRequestInitializer) {
      return (Builder) super.setGoogleClientRequestInitializer(lunchmatesRequestInitializer);
    }

    @Override
    public Builder setGoogleClientRequestInitializer(
        com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
      return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
    }
  }
}


text:
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import moxios from 'moxios';
import * as actionType from '../../src/actions/types';
import * as categoryAction from '../../src/actions/categoryActions';
import {
  categories1,
  category1
} from '../__mocks__/testData';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('Category actions', () => {
  beforeEach(() => {
    moxios.install();
    global.Materialize = { toast: () => {} };
  });
  afterEach(() => {
    moxios.uninstall();
  });
  describe('Category listing action', () => {
    it('should return all categories', (done) => {
      moxios.stubRequest('/api/v1/categories', {
        status: 200,
        response: {
          success: true,
          categories: categories1
        }
      });
      const expectedActions = [{
        type: actionType.SET_CATEGORIES,
        categories: categories1
      }];
      const store = mockStore({});
      store.dispatch(categoryAction.fetchCategories())
        .then(() => {
          expect(store.getActions()).toEqual(expectedActions);
          done();
        });
    });
  });

  describe('Category adding action', () => {
    it('should return the newly added category', (done) => {
      moxios.stubRequest('/api/v1/category', {
        status: 200,
        response: {
          success: true,
          category: category1
        }
      });
      const expectedActions = [{
        type: actionType.ADD_CATEGORY,
        category: category1
      }];
      const store = mockStore({});
      store.dispatch(categoryAction.saveCategory(category1))
        .then(() => {
          expect(store.getActions()).toEqual(expectedActions);
          done();
        });
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
package io.sarnowski.aci.writer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.google.common.hash.HashingOutputStream;
import io.sarnowski.aci.AppManifest;
import io.sarnowski.aci.FilesetManifest;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Preconditions.*;
import static com.google.common.base.Strings.isNullOrEmpty;

public final class ACIWriter {
    private static final ObjectMapper JSON_MAPPER = new ObjectMapper();
    private static final Charset MANIFEST_CHARSET = Charsets.UTF_8;

    private final String name;
    private final String version;

    private AppManifest appManifest;
    private FilesetManifest filesetManifest;

    private List<Content> contents = new ArrayList<>();

    private ACICompression compression = ACICompression.GZIP;

    private boolean buffering = true;

    private ACIWriter(final String name, final String version) {
        checkArgument(!isNullOrEmpty(name), "image name required");
        checkArgument(!isNullOrEmpty(version), "image version required");

        this.name = name;
        this.version = version;
    }

    public static ACIWriter newImage(final String name, final String version) {
        return new ACIWriter(name, version);
    }

    public ACIWriter withAppManifest(final AppManifest appManifest) {
        checkNotNull(appManifest, "app manifest required");
        this.appManifest = appManifest;
        return this;
    }

    public ACIWriter withFilesetManifest(final FilesetManifest filesetManifest) {
        checkNotNull(filesetManifest, "fileset manifest required");
        this.filesetManifest = filesetManifest;
        return this;
    }

    public ACIWriter addContent(final Content content) {
        this.contents.add(content);
        return this;
    }

    public ACIWriter addStream(final TarArchiveEntry destination, final InputStream source) {
        this.contents.add(new StreamingContent(destination, source));
        return this;
    }

    public ACIWriter addBytes(final TarArchiveEntry destination, final byte[] source) {
        destination.setSize(source.length);
        this.contents.add(new ByteContent(destination, source));
        return this;
    }

    public ACIWriter addText(final TarArchiveEntry destination, final String source) {
        destination.setSize(source.length());
        this.contents.add(new TextContent(destination, source));
        return this;
    }

    public ACIWriter addText(final TarArchiveEntry destination, final String source, final Charset charset) {
        destination.setSize(source.length());
        this.contents.add(new TextContent(destination, source, charset));
        return this;
    }

    public ACIWriter addDirectory(final TarArchiveEntry destination) {
        this.contents.add(new DirectoryContent(destination));
        return this;
    }

    public ACIWriter withCompression(final ACICompression compression) {
        this.compression = compression;
        return this;
    }

    public ACIWriter withoutBuffering() {
        this.buffering = false;
        return this;
    }

    public String writeTo(final OutputStream outputStream) throws IOException {
        checkState(appManifest != null || filesetManifest != null,
                "neither AppManifest nor a FilesetManifest is given");

        final OutputStream bufferedOutputStream;
        if (buffering) {
            bufferedOutputStream = new BufferedOutputStream(outputStream);
        } else {
            bufferedOutputStream = outputStream;
        }

        // TODO add encryption capabilities (before or after hashing/compression?) (https://github.com/coreos/rocket/issues/233)

        final OutputStream compressedOutputStream = compression.wrapStream(bufferedOutputStream);

        final HashingOutputStream hashingOutputStream = new HashingOutputStream(Hashing.sha256(),
                compressedOutputStream);

        final TarArchiveOutputStream imageOutputStream = new TarArchiveOutputStream(hashingOutputStream);

        if (appManifest != null) {
            final String appManifestJson = JSON_MAPPER.writeValueAsString(appManifest);

            final TarArchiveEntry appManifestEntry = new TarArchiveEntry("/app");
            appManifestEntry.setSize(appManifestJson.length());

            imageOutputStream.putArchiveEntry(appManifestEntry);
            imageOutputStream.write(appManifestJson.getBytes(MANIFEST_CHARSET));
            imageOutputStream.closeArchiveEntry();
        }

        if (filesetManifest != null) {
            final String filesetManifestJson = JSON_MAPPER.writeValueAsString(filesetManifest);

            final TarArchiveEntry filesetManifestEntry = new TarArchiveEntry("/fileset");
            filesetManifestEntry.setSize(filesetManifestJson.length());

            imageOutputStream.putArchiveEntry(filesetManifestEntry);
            imageOutputStream.write(filesetManifestJson.getBytes(MANIFEST_CHARSET));
            imageOutputStream.closeArchiveEntry();
        }

        for (final Content content : contents) {
            content.addToImage(imageOutputStream);
        }

        imageOutputStream.flush();

        return hashingOutputStream.hash().toString();
    }

    public void writeTo(final Path directory) {
        checkArgument(Files.isDirectory(directory), "given path is not a directory");

        // TODO writeTo file in directory - filename derived from writer
        // TODO write result of writeTo (hash) also to file

        throw new UnsupportedOperationException();
    }
}


text:
define(function (require) {
    'use strict';

var ct = require('cartoon');

var Viewer = ct.Class.extend({

    _sprites: null,

    init: function() {
        this._sprites = {};
    },

    getSprite: function(name) {
        return this._sprites[name];
    },

    parse: function(json) {
        return this.parseObj(json, true);
    },

    parseObj: function(json, root) {
        var self = this;
        if (root) {
            ct.setRenderMode(json.render);
        }

        var obj = this.parseDisplayObj(json);

        if (json.children) {
            json.children.forEach(function(a, i) {
                obj.add(self.parseObj(a));
            });
        }
    },

    parseDisplayObj: function(json) {
        var obj;
        switch(json.type) {
            case 'Bitmap':
                obj = new ct.Bitmap(json);
                break;
            case 'Text':
                obj = new ct.Text(json);
                break;
            case 'Sprite':
                obj = new ct.Sprite(json);
                break;
            case 'Rect':
                obj = new ct.Rect(json);
                break;
            case 'Circle':
                obj = new ct.Circle(json);
                break;
            case 'Button':
                obj = new ct.Button(json);
                break;
        }
        return obj;
    },

    json: function(obj) {
        return this.jsonObj(obj, true);
    },

    jsonObj: function(obj, root) {
        var self = this;

        var json = {
            type: obj.type
        }

        if (root) json.render = obj.renderMode;

        this.get(json, obj, 'x', 0);
        this.get(json, obj, 'y', 0);
        this.get(json, obj, 'width', 0);
        this.get(json, obj, 'height', 0);
        this.get(json, obj, 'alpha', 1);
        this.get(json, obj, 'visible', true);

        this.jsonDisplayObj(json, obj);

        if (obj.children.length) {
            json.children = [];
            obj.children.forEach(function(a, i) {
                json.children.push(self.jsonObj(a));
            });
        }
        return json;
    },

    jsonDisplayObj: function(json, obj) {
        switch(obj.type) {
            case 'Bitmap':
                json.image = obj._image;
                json.rect = [obj._srcRect.x, obj._srcRect.y, obj.width, obj.height]
                break;
            case 'Text':
                json.text = obj._text;
                break;
            case 'Sprite':
                json.ss = obj._spriteSheet.originName || obj._spriteSheet;
                break;
            case 'Rect':
                this.get(json, obj, 'fill', undefined);
                this.get(json, obj, 'stroke', undefined);
                this.get(json, obj, 'strokeWidth', undefined);
                break;
            case 'Circle':
                this.get(json, obj, 'radius', undefined);
                this.get(json, obj, 'fill', undefined);
                this.get(json, obj, 'stroke', undefined);
                this.get(json, obj, 'strokeWidth', undefined);
                break;
            case 'Button':
                json.ss = obj._spriteSheet.originName || obj._spriteSheet;
        }
    },

    get: function(json, obj, key, val) {
        if (obj[key] !== val) {
            json[key] = obj[key];
        }
    },

    set: function(json, obj, key) {
        if (json[key] !== undefined) {
            obj.style(key, json[key]);
        }
    }

});

return Viewer;
});


text:
<?php

use Rry\SignatureAuthenticator\Checker\SignatureValueChecker;

class SignatureValueCheckerTest extends PHPUnit_Framework_TestCase
{
    public function test_it_pass_when_request_value_equal_value()
    {
        $this->assertTrue(SignatureValueChecker::check(12, 12));
    }

    /**
     * @expectedException \Rry\SignatureAuthenticator\Exceptions\SignatureValueException
     */
    public function test_it_throw_signature_value_exception()
    {
        SignatureValueChecker::check(12, 21);
    }
}


text:
/**
 *
 * Game state
 *
 * This state is where everything happen. The game logic, the events, the players, the enemies...
 *
 *
 *
 *
 *  @params {Levels.level}
 *
 */

(function () {
    'use strict';

    var ns = window['awaken'];

    function Game() {
    }

    Game.prototype = {

        /** Constructor **/
        init: function(level){
            this.game.level = level;
        },

        /** Creation of the game (entities, events, etc.. ) based on the level information **/
        create: function () {

            // bug fix with the fullscreen : Exit the fullscreen remove the bounce collisions.
            // we have to trigger manually the event of the browser to make it work instead of trust phaser
            if (document.addEventListener)
            {
                var self = this;
                document.addEventListener('webkitfullscreenchange', function(){
                    self.exitHandler();
                }, false);
                document.addEventListener('mozfullscreenchange', function(){
                    self.exitHandler();
                }, false);
                document.addEventListener('fullscreenchange', function(){
                    self.exitHandler();
                }, false);
                document.addEventListener('MSFullscreenChange', function(){
                    self.exitHandler();
                }, false);
            }

            /** Keyboard input (Player has is own input) **/
            this.input.keyboard.addKey(Phaser.Keyboard.ESC).onDown.add(this.onInputDown, this);
            this.input.keyboard.addKey(Phaser.Keyboard.F).onDown.add(this.goFullscreen, this);

            /** Gamepad **/
            this.input.gamepad.start();
            this.game.pad = this.input.gamepad.pad1;
            if (this.game.input.gamepad.supported && this.game.input.gamepad.active && this.game.pad.connected){
                this.game.pad.addCallbacks(this, {onConnect: this.addButtons});
                this.addButtons();
            }

            /** Background color (ground) **/
            this.game.stage.backgroundColor = '#333';

            /** Enable P2JS physic in our game **/
            this.game.physics.startSystem(Phaser.Physics.P2JS);
            this.game.physics.p2.setImpactEvents(true);
            this.game.physics.p2.restitution = 0.8;
            this.game.world.setBounds(0,12,800, 595); // set borders(left/right/up/down) collidable

            /** Creation of the collisions groups **/
            this.game.entitiesCollisions = this.game.physics.p2.createCollisionGroup();
            this.game.physics.p2.updateBoundsCollisionGroup();
            this.game.debugCollisions = false;

            /** Creation of the sprites groups **/
            // ! Order of creation is also the order of render
            this.game.tiles = this.game.add.group();
            this.game.effects = this.game.add.group();
            this.game.entities = this.game.add.group(); // We can't separate each type of entities into different groups because of the sort. The sort on Y axe can only affect his own group
            this.game.ui = this.game.add.group();
            this.game.events = [];  // Events are'nt extended from sprites or an another components. They can't be in a group

            /** Instantiation of the Entities/events/tiles factory **/
            this.game.enemiesFactory = new ns.Enemies(this.game);
            this.game.bossesFactory = new ns.Bosses(this.game);
            this.game.tilesFactory = new ns.Tiles(this.game);
            this.game.eventsFactory = new ns.Events(this.game);

            /** Objectives **/
            this.game.enemiesKilled = 0;
            this.game.bossesKilled = 0;
            this.game.over = false;
            this.game.elapsedTime = 0;

            /** Creation of the player **/
            this.game.ken = new Ken(this.game, this.game.level.playerParameters);
            this.game.entities.add(this.game.ken);

            /** Creation of the ui **/
            this.game.notification = new Notification(this.game);
            this.lowPerf = new LowPerf(this.game);
            this.game.ui.add(this.game.notification);
            this.game.ui.add(this.lowPerf);
            this.game.ui.add(new Score(this.game));
            this.game.ui.add(new Objective(this.game));
            this.game.ui.add(new Debug(this.game));
            this.game.ui.add(new Fullscreen(this.game));
            this.game.dialogues = new Dialogue(this.game);

            /** Generation of the tiles, bosses, ennemies and events **/
            this.game.tilesFactory.addTiles();
            this.game.bossesFactory.addBosses();
            this.game.enemiesFactory.addEnemies();
            this.game.eventsFactory.setEvents(this.game.level.events);

            /** Timer to count the elapsed time (used for the objective using time) **/
            this.timer = this.game.time.create(false);
            this.timer.loop(1000, this.updateElapsedTime, this);
            this.timer.start();
        },

        /** Update the game every called {fps} times per seconds  **/
        update: function () {

            // Events are'nt extended from sprites or an another components. So we have to update them manually
            this.game.eventsFactory.update();

            // Phaser isn't really compatible with game in 2.5D view, so we have
            // to sort the entites group with the y axe
            // Some sprites (like David boss) are specific where the sort is not at the default y position
            // So, to get ride of the default y axe that we can't change, we use a custom yy
            // Also, that because of the sort y that we can't separate each type of entities into multiple groups.
            this.game.entities.sort("yy");

            // Check if the objective is complete
            this.objectivesComplete();

            // Call the game over
            if(this.game.over) this.gameOver();

            // Automatic trigger : If the game has a low fps, we disable the blood tiles
            if(this.game.time.fps < 25 && !ns.Boot.lowPerf) this.lowPerf.togglePerf();

        },

        /** Render function (called {fps} times per seconds) **/
        render: function (){
            /**debug**/
            //this.game.debug.spriteInfo(this.ken.sprite, 2, 32);
            this.game.debug.text(this.game.time.fps || '--', 2, 14, "#fff");

        },

        /** Increment each seconds; time to complete the objective timeLimit **/
        updateElapsedTime: function(){
            this.game.elapsedTime++;
        },

        /** Check if the objectives are complete **/
        objectivesComplete: function(){

              if(
                  (this.game.level.enemiesToKill != null && this.game.enemiesKilled >= this.game.level.enemiesToKill) //Number of enemies to kill
                    ||
                  (this.game.level.timeLimit != null && this.game.elapsedTime > this.game.level.timeLimit)  //Time elapsed in the level
                    ||
                  (this.game.level.bossesToKill != null && this.game.bossesKilled >= this.game.level.bossesToKill) //Number of bosses to kill
              ){

                  // Block the actions of all the entities, then, kill them
                  this.game.entities.setAll('blocked', true);

                  var nextLevelTimer = this.game.time.create(false);
                  nextLevelTimer.start();
                  nextLevelTimer.add(1000, this.killThemAll, this);
              }

        },

        /** Game Over: Block the actions of all the entities, then call transition state **/
        gameOver: function(){
            this.game.entities.setAll('blocked', true);

            var nextLevelTimer = this.game.time.create(false);
            nextLevelTimer.start();
            nextLevelTimer.add(3000, this.gameOverState, this);

        },

        /** Kill all the entities alive (enemies, bosses) then call the next level **/
        killThemAll: function(){
            this.game.entities.forEachAlive(function(entity){
                entity.blocked = true;
                if(entity.type != 'ken') {
                    entity.bleed();
                    entity.die();
                }
            });

            var nextLevelTimer = this.game.time.create(false);
            nextLevelTimer.start();
            nextLevelTimer.add(1000, this.nextLevel, this);

        },

        /** Change the state to the game over **/
        gameOverState: function(){
            // We have to reset the gamepad buttons otherwise they keep the action on the next state
            this.resetButtons();

            this.game.state.start('transition', true, false, new ns.Levels().getGameOver());
        },

        /** Change to the next level **/
        nextLevel: function(){

            // We have to reset the gamepad buttons otherwise they keep the action on the next state
            this.resetButtons();

            if(this.game.level.nextLevel()){
                this.game.state.start('transition', true, false, this.game.level.nextLevel());
            }
        },

        /** Exit the game, we go back to the menu **/
        onInputDown: function () {
            // We have to reset the gamepad buttons otherwise they keep the action on the next state
            this.resetButtons();
            this.game.state.start('menu');
        },

        /** Add the buttons to the gamepad **/
        addButtons: function(){
            this.game.pad.getButton(Phaser.Gamepad.XBOX360_START).onDown.add(this.onInputDown, this);
            //this.pad.getButton(Phaser.Gamepad.XBOX360_Y).onDown.add(this.goFullscreen, this);
        },

        /** Remove the buttons to the gamepad **/
        resetButtons: function(){
            if (this.game.input.gamepad.supported && this.game.input.gamepad.active && this.game.pad.connected){
                this.game.pad.getButton(Phaser.Gamepad.XBOX360_A).onDown.dispose();
                this.game.pad.getButton(Phaser.Gamepad.XBOX360_START).onDown.dispose();
            }
        },

        /** Switch the game to fullscreen / windowed **/
        goFullscreen: function(){

            if (this.game.scale.isFullScreen)
            {
                this.game.scale.stopFullScreen();
            }
            else
            {
                this.game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT;
                this.game.scale.startFullScreen(false);
            }

        },

        /** Reset the collisions on exit fullscreen **/
        exitHandler: function(){
            if (document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement !== null)
            {
                /* Run code on exit */
                this.game.world.setBounds(0,12,800, 595,true,true,true,true,false);//set borders(left/right/up/down) collidable
                this.game.physics.p2.updateBoundsCollisionGroup();

                this.game.entitiesCollisions = this.game.physics.p2.createCollisionGroup();
                this.game.entities.callAll("resetCollisions");
            }
        }

    };

    window['awaken'] = window['awaken'] || {};
    window['awaken'].Game = Game;
}());


text:
(function() {
  'use strict';

  /* global: localStorage */
  /* jshint forin: false */

  /**
   * session-transfer Module
   *
   * Transfer session data to other tabs
   * http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/
   * http://stackoverflow.com/questions/20325763/browser-sessionstorage-share-between-tabs
   */
  angular.module('app.session-transfer', []).run(init);

  function init() {

    // transfers sessionStorage from one tab to another
    var sessionStorageTransfer = function(event) {

      if (!event) {
        event = window.event;
      } // ie suq
      if (!event.newValue) {
        // do nothing if no value to work with
        return;
      }
      if (event.key === 'getSessionStorage') {
        // another tab asked for the sessionStorage -> send it
        localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
        // the other tab should now have it, so we're done with it.
        setTimeout(function() {
          localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
        });
      } else if (event.key === 'sessionStorage' && !sessionStorage.length) {
        // another tab sent data <- get it
        var data = JSON.parse(event.newValue);
        for (var key in data) {
          sessionStorage.setItem(key, data[key]);
        }
      }
    };

    // listen for changes to localStorage
    if (window.addEventListener) {
      window.addEventListener('storage', sessionStorageTransfer, false);
    } else {
      window.attachEvent('onstorage', sessionStorageTransfer);
    }

  }
})();


text:
#ifdef __cplusplus
extern "C"
{
#endif

#ifndef _dtex_wrap_c_h_
#define _dtex_wrap_c_h_

#include <stdbool.h>

void* dtex_query_cache(const char* key);

bool  dtex_loading_task_empty();

/************************************************************************/
/* cache pkg static                                                     */
/************************************************************************/

enum DTEX_TEXTURE_FORMAT {
	DTEX_TEXTURE_INVALID = 0,
	DTEX_TEXTURE_RGBA8,
	DTEX_TEXTURE_RGBA4,
	DTEX_TEXTURE_RGB,
	DTEX_TEXTURE_RGB565,
	DTEX_TEXTURE_A8,
    DTEX_TEXTURE_RED,
    DTEX_TEXTURE_R16,
	DTEX_TEXTURE_DEPTH,	// use for render target
	DTEX_TEXTURE_PVR2,
	DTEX_TEXTURE_PVR4,
	DTEX_TEXTURE_ETC1,
	DTEX_TEXTURE_ETC2,
};

void* dtex_cache_pkg_static_query(const char* key);
void* dtex_cache_pkg_static_create(const char* key, int tex_size, int tex_fmt);
void  dtex_cache_pkg_static_delete(const char* key);

int   dtex_cache_pkg_static_load(void* cache, int pkg_id, int lod);
int   dtex_cache_pkg_static_load_finish(void* cache, bool async);

bool  dtex_cache_pkg_static_is_empty(const void* cache);

bool  dtex_cache_pkg_static_is_available(const void* cache);

#endif // _dtex_wrap_c_h_

#ifdef __cplusplus
}
#endif


text:
/**
 * An assign expression. Assigns a constant or expression to a variable.
 * @author (Kevin Dittmar)
 * @author (William Ezekiel)
 * @author (Joseph Alacqua)
 * @version Mar 30 2016
 */
public class Assign extends Exp{

  /**
   * Create an Assign
   * @param v a variable
   * @param r the right expression
   */
  public Assign(Variable v, Exp r) {
    left = v;
    right = r;
  }

  /**
   * Accept a visitor.
   * @param v a visitor
   * @return the object produced by the visit.
   */
  public Object accept(Visitor v) {
    return v.visit(this);
  }
}


text:
package com.oce.springboot.training.d02.s05.service;

import com.oce.springboot.training.d02.s05.model.Product;
import com.oce.springboot.training.d02.s05.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ProductService {

    private final JdbcTemplate jdbcTemplate;
    private final ProductRepository productRepository;

    @Autowired
    public ProductService(final JdbcTemplate jdbcTemplate, final ProductRepository productRepository) {
        this.jdbcTemplate = jdbcTemplate; this.productRepository = productRepository;
    }

    @Scheduled(fixedDelay = 10000)
    public void searchForProducts() {
        //TODO insert complex logic here

        jdbcTemplate.execute("SELECT * FROM product p WHERE p.name = ?");
    }

    public void create(final Product product) {
        productRepository.save(product);
    }

    @Transactional(
            readOnly = true,
            propagation = Propagation.SUPPORTS,
            isolation = Isolation.READ_COMMITTED,
            rollbackFor = {IllegalArgumentException.class, IllegalAccessException.class}
    )
    @Cacheable(cacheManager = "cacheManager", cacheNames = "products", condition = "id > 10")
    public Product get(final int id) {
        return productRepository.findOne(id);
    }

    public Iterable<Product> getAll() {
        return productRepository.findAll();
    }

    public void update(final int id, final Product product) {
        final Product existingProduct = productRepository.findOne(id);

        existingProduct.setName(product.getName());

        productRepository.save(product);
    }

    @CacheEvict(cacheNames = "products", condition = "id > 10")
    public void delete(final int id) {
        productRepository.delete(id);
    }
}


text:
package test.pinpoint.plugin.kafka;

import com.navercorp.pinpoint.test.plugin.shared.SharedTestLifeCycle;
import com.navercorp.pinpoint.testcase.util.SocketUtils;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServer;
import org.apache.kafka.common.utils.Time;
import scala.Option;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.file.Files;
import java.util.Properties;

/**
 * Copy of https://github.com/chbatey/kafka-unit/blob/master/src/main/java/info/batey/kafka/unit/KafkaUnit.java
 * Some codes have been modified for testing from the copied code.
 */
public class Kafka3UnitServer implements SharedTestLifeCycle {

    private static final Logger logger = LogManager.getLogger(Kafka3UnitServer.class);

    private final OffsetStore OFFSET_STORE = new OffsetStore();

    private Kafka3Server server;
    private TestConsumer TEST_CONSUMER;

    @Override
    public Properties beforeAll() {
        final int zkPort = SocketUtils.findAvailableTcpPort(10000, 19999);
        final int brokerPort = SocketUtils.findAvailableTcpPort(20000, 29999);
        server = new Kafka3Server(zkPort, brokerPort);

        server.startup();

        String brokerUrl = "localhost:" + brokerPort;
        TEST_CONSUMER = new TestConsumer(OFFSET_STORE, brokerUrl);
        TEST_CONSUMER.start();

        Properties properties = new Properties();
        properties.setProperty("PORT", String.valueOf(server.getBrokerPort()));
        properties.setProperty("OFFSET", String.valueOf(OFFSET_STORE.getOffset()));
        return properties;
    }

    @Override
    public void afterAll() {
        if (server != null) {
            server.shutdown();
        }
        try {
            TEST_CONSUMER.shutdown();
        } catch (InterruptedException e) {
        }
    }

    class Kafka3Server extends KafkaUnitServer {
        private KafkaServer broker;

        public Kafka3Server(int zkPort, int brokerPort) {
            this(zkPort, brokerPort, 16);
        }

        public Kafka3Server(int zkPort, int brokerPort, int zkMaxConnections) {
            super(zkPort, brokerPort, zkMaxConnections);
        }

        public void startup() {
            zookeeper = new ZookeeperUnitServer(zkPort, zkMaxConnections);
            zookeeper.startup();

            try {
                logDir = Files.createTempDirectory("kafka").toFile();
            } catch (IOException e) {
                throw new RuntimeException("Unable to start Kafka", e);
            }
            logDir.deleteOnExit();
            Runtime.getRuntime().addShutdownHook(new Thread(getDeleteLogDirectoryAction()));

            kafkaBrokerConfig.setProperty("zookeeper.connect", zookeeperString);
            kafkaBrokerConfig.setProperty("broker.id", "1");
            kafkaBrokerConfig.setProperty("host.name", "localhost");
            kafkaBrokerConfig.setProperty("port", Integer.toString(brokerPort));
            kafkaBrokerConfig.setProperty("log.dir", logDir.getAbsolutePath());
            kafkaBrokerConfig.setProperty("log.flush.interval.messages", String.valueOf(1));
            kafkaBrokerConfig.setProperty("delete.topic.enable", String.valueOf(true));
            kafkaBrokerConfig.setProperty("offsets.topic.replication.factor", String.valueOf(1));
            kafkaBrokerConfig.setProperty("auto.create.topics.enable", String.valueOf(true));
            broker = new KafkaServer(new KafkaConfig(kafkaBrokerConfig), Time.SYSTEM, Option.apply(null), false);
            broker.startup();
        }

        public void shutdown() {
            if (broker != null) {
                broker.shutdown();
                broker.awaitShutdown();
            }
            if (zookeeper != null) {
                zookeeper.shutdown();
            }
        }

        private Runnable getDeleteLogDirectoryAction() {
            return new Runnable() {
                @Override
                public void run() {
                    if (logDir != null) {
                        try {
                            FileUtils.deleteDirectory(logDir);
                        } catch (IOException e) {
                            logger.warn("Problems deleting temporary directory " + logDir.getAbsolutePath(), e);
                        }
                    }
                }
            };
        }
    }
}


text:
local ReinforceCriterion, parent = torch.class('nn.ReinforceCriterion',
                                               'nn.Module')
-- This criterion implements the REINFORCE algorithm under the assumption that
-- the reward does not depend on the model parameters.
-- The constructor takes as input a function which is used to compute the reward
-- given the ground truth input sequence, the generated sequence and the current
-- time step.
-- The input to the criterion is a table whose entries are the output of the
-- RNN at a certain time step, namely:
-- (chosen_word, predicted_cumulative_reward)_t
-- It computes the total reward and bprop the derivative
-- w.r.t. the above provided inputs.
--  reward_func: user provided function to compute the reward
--   given ground truth, current sequence and current time step.
-- seq_length is the length of the sequence we use
-- skips is the number of time steps we skip from the input and target (init)
-- weight is the weight on the loss produced by this criterion
-- weight_predictive_reward is the weight on the gradient of the cumulative
--   reward predictor (only)
function ReinforceCriterion:__init(sampleStart, seqLen, batchSize)
   parent.__init(self)
   self.sampleStart = sampleStart
   self.cum_reward = torch.Tensor(seqLen, batchSize)
   self.grad_rf_sample = torch.Tensor(seqLen, batchSize)
   self.seqLen = seqLen
   self.grad_exp_reward = {}
   for t = 1, seqLen do
     self.grad_exp_reward[t] = torch.Tensor(batchSize, 1)
   end

   --[[
   self.gradInput = {}
   self.seq_length = seq_length
   for tt = 1, seq_length do
      self.gradInput[tt] = {}
      self.gradInput[tt][1] = torch.Tensor()
      self.gradInput[tt][2] = torch.Tensor()
   end
   self.sizeAverage = false
   self.reward_func = reward_func
   self.reward = torch.Tensor()
   self.cumreward = torch.Tensor()
   self.skips = (skips == nil) and 1 or skips
   assert(self.skips <= seq_length)
   assert(seq_length >= self.skips)
   -- by default, update the cumulative reward predictor
   -- at a slower pace.
   self.weight_predictive_reward =
       (weight_predictive_reward == nil) and 0.01 or weight_predictive_reward
   self.weight = (weight == nil) and 1 or weight
   self.num_samples = 0
   self.normalizing_coeff = 1
   self.eos = eos_index
   self.padding = padding_index
   self.reset = torch.Tensor()
   --]]
end

function ReinforceCriterion:setSampleStart(start)
  self.sampleStart = start
end

function ReinforceCriterion:type(tp)
   parent.type(self, tp)
   self.cum_reward:type(tp)
   self.grad_rf_sample:type(tp)
   for t = 1, self.seqLen do
     self.grad_exp_reward[t]:type(tp)
   end

   return self
end

function ReinforceCriterion:set_weight(ww)
   self.weight = ww
end

function ReinforceCriterion:setSampleStart(start)
  self.sampleStart = start
end

function ReinforceCriterion:updateOutput(input)
  local rf_sample, exp_reward, true_reward, reward_mask = unpack(input)
  local Ty_rf = rf_sample:size(1)
  self.cum_reward:resizeAs(true_reward):zero()
  for t = Ty_rf - 1, self.sampleStart, -1 do
    self.cum_reward[{ t, {} }]:add( true_reward[{ t+1, {} }], self.cum_reward[{ t+1, {} }] )
    self.cum_reward[{ t, {} }]:cmul( reward_mask[{ t+1, {} }] )
  end

  local seq_reward = self.cum_reward[{ self.sampleStart, {} }]
  local n_seq = seq_reward:ne(0):sum()

  return -seq_reward:sum() / rf_sample:size(2), n_seq
end

--[[
-- input is a table storing the tuple:
-- (chosen_word, predicted_cumulative_reward)_t, t=1..T
-- target is also a table storing the labels at each time step.
function ReinforceCriterion:updateOutput(input, target)
   -- compute the reward at each time step
   local mbsz = target[1]:size(1)
   local num_steps = self.seq_length - self.skips + 1
   self.reward:resize(mbsz, num_steps)
   self.cum_reward:resize(mbsz, num_steps)
   self.num_samples = 0
   for tt = self.seq_length, self.skips, -1 do
      local shifted_tt = tt - self.skips + 1
      self.reward:select(2, shifted_tt):copy(
         self.reward_func:get_reward(target, input, tt))
      if tt == self.seq_length then
         self.cumreward:select(2, shifted_tt):copy(
            self.reward:select(2, shifted_tt))
      else
         self.cumreward:select(2, shifted_tt):add(
            self.cumreward:select(2, shifted_tt + 1),
            self.reward:select(2, shifted_tt))
      end
   end
   self.num_samples = self.reward_func:num_samples(target, input)
   self.normalizing_coeff =
      self.weight / (self.sizeAverage and self.num_samples or 1)
   -- here there is a "-" because we minimize
   self.output = - self.cumreward:select(2,1):sum() * self.normalizing_coeff
   return self.output, self.num_samples
end
--]]

function ReinforceCriterion:updateGradInput(input)
  local rf_sample, exp_reward, true_reward, reward_mask = unpack(input)
  local Ty_rf = rf_sample:size(1)
  self.grad_rf_sample:resizeAs(rf_sample):zero()
  local grad_exp_reward = {}
  for t = Ty_rf - 1, self.sampleStart, -1 do
    self.grad_rf_sample[{ t+1, {} }] = (exp_reward[t]:squeeze() - self.cum_reward[{ t, {} }])
    self.grad_rf_sample[{ t+1, {} }]:div(rf_sample:size(2))
    self.grad_rf_sample[{ t+1, {} }]:cmul( reward_mask[{ t+1, {} }] )
    self.grad_exp_reward[t]:resizeAs(exp_reward[t]):zero()
    self.grad_exp_reward[t]:copy( self.grad_rf_sample[{ t+1, {} }] )
    grad_exp_reward[t] = self.grad_exp_reward[t]
  end

  for t = 1, self.sampleStart - 1 do
    self.grad_exp_reward[t]:zero()
    grad_exp_reward[t] = self.grad_exp_reward[t]
  end

  self.gradInput = {self.grad_rf_sample, grad_exp_reward}

  return self.gradInput
end

--[[
-- bprop through input at each time step.
-- derivative through chosen action is:
-- (predicted_cumulative_reward - actual_cumulative_reward)_t.
function ReinforceCriterion:updateGradInput(input, target)
   local mbsz = target[1]:size(1)
   for tt = self.seq_length, self.skips, -1 do
      local shifted_tt = tt - self.skips + 1
      -- derivative w.r.t. chosen action
      self.gradInput[tt][1]:resizeAs(input[tt][1])
      self.gradInput[tt][1]:add(
         input[tt][2]:squeeze(), -1, self.cumreward:select(2, shifted_tt))
      self.gradInput[tt][1]:mul(self.normalizing_coeff)
      -- reset gradient to 0 if input (at any time) has PAD
      self.reset:resize(mbsz)
      self.reset:ne(input[tt][1], self.padding) -- set in RNNreinforce
      self.gradInput[tt][1]:cmul(self.reset)
      -- copy over to the other input gradient as well
      self.gradInput[tt][2]:resizeAs(input[tt][2])
      self.gradInput[tt][2]:copy(self.gradInput[tt][1])
      self.gradInput[tt][2]:mul(self.weight_predictive_reward)
   end
   -- fill the remaining (skipped) steps with 0s
   for tt = self.skips - 1, 1, -1 do
      self.gradInput[tt][1]:resizeAs(input[tt][1])
      self.gradInput[tt][1]:fill(0)
      self.gradInput[tt][2]:resizeAs(input[tt][2])
      self.gradInput[tt][2]:fill(0)
   end
   return self.gradInput
end
--]]

function ReinforceCriterion:get_num_samples(input, target)
   return self.reward_func:num_samples(target, input)
end

function ReinforceCriterion:reset_reward()
    return self.reward_func:reset_vars()
end

function ReinforceCriterion:get_corpus_score()
    return self.reward_func:get_corpus_score()
end

function ReinforceCriterion:get_counts_corpus(target, pred)
    return self.reward_func:get_counts_corpus(target, pred)
end

function ReinforceCriterion:training_mode()
    self.reward_func:training_mode()
end

function ReinforceCriterion:test_mode()
    self.reward_func:test_mode()
end


text:
package teilchen.constraint;

import teilchen.Physics;

public interface IConstraint {

    void apply(final Physics theParticleSystem);

    boolean active();

    void active(boolean theActiveState);
}


text:
///
///@file   CrowdMonitor.h
///@brief  Multiple reader/single writer locks
///
///@author Steve Parker
///        Department of Computer Science
///        University of Utah
///@date   June 1997
///

#ifndef Core_Thread_CrowdMonitor_h
#define Core_Thread_CrowdMonitor_h

#include <Core/Thread/Legacy/share.h>

namespace SCIRun {
  struct CrowdMonitor_private;
/**************************************

@class
   CrowdMonitor

KEYWORDS
   Thread

@details
   Multiple reader, single writer synchronization primitive.  Some
   applications do not need the strict level of synchronization
   provided by the Mutex.  The CrowdMonitor relaxes
   the synchronization by allowing multiple threads access to a
   resource (usually a data area), on the condition that the thread
   will only read the data.  When a thread needs to write the data,
   it can access the monitor in write mode (using writeLock).
   At any given time, one writer thread can be active, or multiple
   reader threads can be active.  CrowdMonitor guards against
   multiple writers accessing a data, and against a thread writing
   to the data while other threads are reading it.

WARNING

 Calling readLock within a writeLock/write_unlock
   section may result in a deadlock.  Likewise, calling writeLock
   within a readLock/readUnlock section may result in a deadlock.
   Calling readUnlock or writeUnlock when the lock is
   not held is not legal and may result in undefined behavior.

****************************************/

	class SCISHARE CrowdMonitor {
	public:
	    //////////
	    /// Create and initialize the CrowdMonitor. name should
	    /// be a static which describes the primitive for debugging
	    /// purposes.
	    CrowdMonitor(const char* name);

	    //////////
	    /// Destroy the CrowdMonitor.
	    ~CrowdMonitor();

	    //////////
	    /// Acquire the read-only lock associated with this
	    /// CrowdMonitor. Multiple threads may hold the
	    /// read-only lock simultaneously.
	    void readLock();

	    //////////
	    /// Release the read-only lock obtained from readLock.
	    /// Undefined behavior may result when readUnlock is
	    /// called and a readLock is not held by the calling
	    /// Thread.
	    void readUnlock();

	    //////////
	    /// Acquire the write lock associated with this
	    /// CrowdMonitor. Only one thread may hold the write
	    /// lock, and during the time that this lock is not held, no
	    /// threads may hold the read-only lock.
	    void writeLock();

	    //////////
	    /// Release the write-only lock obtained from writeLock.
	    /// Undefined behavior may result when writeUnlock is
	    /// called and a writeLock is not held by the calling
	    /// Thread.
	    void writeUnlock();

	private:
	    const char* name_;
	    CrowdMonitor_private* priv_;

	    // Cannot copy them
	    CrowdMonitor(const CrowdMonitor&);
	    CrowdMonitor& operator=(const CrowdMonitor&);
	};
} // End namespace SCIRun

#endif


text:
package pro.taskana.workbasket.rest.models;

import java.time.Instant;

import pro.taskana.workbasket.api.models.Workbasket;

/** EntityModel class for {@link Workbasket}. */
public class WorkbasketRepresentationModel extends WorkbasketSummaryRepresentationModel {

  /**
   * The creation timestamp of the workbasket in the system.
   *
   *
The format is ISO-8601.
   */
  private Instant created;
  /**
   * The timestamp of the last modification.
   *
   *
The format is ISO-8601.
   */
  private Instant modified;

  public Instant getCreated() {
    return created;
  }

  public void setCreated(Instant created) {
    this.created = created;
  }

  public Instant getModified() {
    return modified;
  }

  public void setModified(Instant modified) {
    this.modified = modified;
  }
}


text:
from __future__ import unicode_literals, division, absolute_import
from builtins import *  # noqa pylint: disable=unused-import, redefined-builtin
from future.utils import native_str

import logging
from datetime import datetime

from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.exc import OperationalError

import flexget
from flexget.event import event
from flexget.manager import Base, Session
from flexget.utils.database import with_session
from flexget.utils.sqlalchemy_utils import table_schema
from flexget.utils.tools import get_current_flexget_version

log = logging.getLogger('schema')

# Stores a mapping of {plugin: {'version': version, 'tables': ['table_names'])}
plugin_schemas = {}

class FlexgetVersion(Base):
    __tablename__ = 'flexget_version'

    version = Column(String, primary_key=True)
    created = Column(DateTime, default=datetime.now)

    def __init__(self):
        self.version = get_current_flexget_version()

@event('manager.startup')
def set_flexget_db_version(manager=None):
    with Session() as session:
        db_version = session.query(FlexgetVersion).first()
        if not db_version:
            log.debug('entering flexget version %s to db', get_current_flexget_version())
            session.add(FlexgetVersion())
        elif db_version.version != get_current_flexget_version():
            log.debug('updating flexget version %s in db', get_current_flexget_version())
            db_version.version = get_current_flexget_version()
            db_version.created = datetime.now()
            session.commit()
        else:
            log.debug('current flexget version already exist in db %s', db_version.version)

def get_flexget_db_version():
    with Session() as session:
        version = session.query(FlexgetVersion).first()
        if version:
            return version.version

class PluginSchema(Base):
    __tablename__ = 'plugin_schema'

    id = Column(Integer, primary_key=True)
    plugin = Column(String)
    version = Column(Integer)

    def __init__(self, plugin, version=0):
        self.plugin = plugin
        self.version = version

    def __str__(self):
        return '<PluginSchema(plugin=%s,version=%i)>' % (self.plugin, self.version)

@with_session
def get_version(plugin, session=None):
    schema = session.query(PluginSchema).filter(PluginSchema.plugin == plugin).first()
    if not schema:
        log.debug('No schema version stored for %s' % plugin)
        return None
    else:
        return schema.version

@with_session
def set_version(plugin, version, session=None):
    if plugin not in plugin_schemas:
        raise ValueError(
            'Tried to set schema version for %s plugin with no versioned_base.' % plugin
        )
    base_version = plugin_schemas[plugin]['version']
    if version != base_version:
        raise ValueError(
            'Tried to set %s plugin schema version to %d when '
            'it should be %d as defined in versioned_base.' % (plugin, version, base_version)
        )
    schema = session.query(PluginSchema).filter(PluginSchema.plugin == plugin).first()
    if not schema:
        log.debug('Initializing plugin %s schema version to %i' % (plugin, version))
        schema = PluginSchema(plugin, version)
        session.add(schema)
    else:
        if version < schema.version:
            raise ValueError('Tried to set plugin %s schema version to lower value' % plugin)
        if version != schema.version:
            log.debug('Updating plugin %s schema version to %i' % (plugin, version))
            schema.version = version
    session.commit()

@with_session
def upgrade_required(session=None):
    """Returns true if an upgrade of the database is required."""
    old_schemas = session.query(PluginSchema).all()
    if len(old_schemas) < len(plugin_schemas):
        return True
    for old_schema in old_schemas:
        if (
            old_schema.plugin in plugin_schemas
            and old_schema.version < plugin_schemas[old_schema.plugin]['version']
        ):
            return True
    return False

class UpgradeImpossible(Exception):
    """
    Exception to be thrown during a db upgrade function which will cause the old tables to be removed and recreated from
    the new model.
    """

def upgrade(plugin):
    """Used as a decorator to register a schema upgrade function.

    The wrapped function will be passed the current schema version and a session object.
    The function should return the new version of the schema after the upgrade.

    There is no need to commit the session, it will commit automatically if an upgraded
    schema version is returned.

    Example::

      from flexget import schema
      @schema.upgrade('your_plugin')
      def upgrade(ver, session):
           if ver == 2:
               # upgrade
               ver = 3
           return ver
    """

    def upgrade_decorator(upgrade_func):
        @event('manager.upgrade')
        def upgrade_wrapper(manager):
            with Session() as session:
                current_ver = get_version(plugin, session=session)
                try:
                    new_ver = upgrade_func(current_ver, session)
                except UpgradeImpossible:
                    log.info(
                        'Plugin %s database is not upgradable. Flushing data and regenerating.'
                        % plugin
                    )
                    reset_schema(plugin, session=session)
                    manager.db_upgraded = True
                except Exception as e:
                    log.exception('Failed to upgrade database for plugin %s: %s' % (plugin, e))
                    session.rollback()
                    manager.shutdown(finish_queue=False)
                else:
                    current_ver = -1 if current_ver is None else current_ver
                    if new_ver > current_ver:
                        log.info('Plugin `%s` schema upgraded successfully' % plugin)
                        set_version(plugin, new_ver, session=session)
                        manager.db_upgraded = True
                    elif new_ver < current_ver:
                        log.critical(
                            'A lower schema version was returned (%s) from plugin %s upgrade function '
                            'than passed in (%s)' % (new_ver, plugin, current_ver)
                        )
                        session.rollback()
                        manager.shutdown(finish_queue=False)

        return upgrade_wrapper

    return upgrade_decorator

@with_session
def reset_schema(plugin, session=None):
    """
    Removes all tables from given plugin from the database,
    as well as removing current stored schema number.

    :param plugin: The plugin whose schema should be reset
    """
    if plugin not in plugin_schemas:
        raise ValueError('The plugin %s has no stored schema to reset.' % plugin)
    table_names = plugin_schemas[plugin].get('tables', [])
    tables = [table_schema(name, session) for name in table_names]
    # Remove the plugin's tables
    for table in tables:
        try:
            table.drop()
        except OperationalError as e:
            if 'no such table' in str(e):
                continue
            raise e  # Remove the plugin from schema table
    session.query(PluginSchema).filter(PluginSchema.plugin == plugin).delete()
    # We need to commit our current changes to close the session before calling create_all
    session.commit()
    # Create new empty tables
    Base.metadata.create_all(bind=session.bind)

def register_plugin_table(tablename, plugin, version):
    plugin_schemas.setdefault(plugin, {'version': version, 'tables': []})
    if plugin_schemas[plugin]['version'] != version:
        raise Exception('Two different schema versions received for plugin %s' % plugin)
    plugin_schemas[plugin]['tables'].append(tablename)

class Meta(type):
    """Metaclass for objects returned by versioned_base factory"""

    def __new__(mcs, metaname, bases, dict_):
        """This gets called when a class that subclasses VersionedBase is defined."""
        new_bases = []
        for base in bases:
            # Check if we are creating a subclass of VersionedBase
            if base.__name__ == 'VersionedBase':
                # Register this table in plugin_schemas
                register_plugin_table(dict_['__tablename__'], base.plugin, base.version)
                # Make sure the resulting class also inherits from Base
                if not any(isinstance(base, type(Base)) for base in bases):
                    # We are not already subclassing Base, add it in to the list of bases instead of VersionedBase
                    new_bases.append(Base)

                    # Since Base and VersionedBase have 2 different metaclasses, a class that subclasses both of them
                    # must have a metaclass that subclasses both of their metaclasses.

                    class mcs(type(Base), mcs):
                        pass

            else:
                new_bases.append(base)

        return type.__new__(mcs, native_str(metaname), tuple(new_bases), dict_)

    def register_table(cls, table):
        """
        This can be used if a plugin is declaring non-declarative sqlalchemy tables.

        :param table: Can either be the name of the table, or an :class:`sqlalchemy.Table` instance.
        """
        if isinstance(table, str):
            register_plugin_table(table, cls.plugin, cls.version)
        else:
            register_plugin_table(table.name, cls.plugin, cls.version)

    def __getattr__(self, item):
        """Transparently return attributes of Base instead of our own."""
        return getattr(Base, item)

def versioned_base(plugin, version):
    """
    Returns a class which can be used like Base,
    but automatically stores schema version when tables are created.
    """

    return Meta(
        'VersionedBase', (object,), {'__metaclass__': Meta, 'plugin': plugin, 'version': version}
    )

def after_table_create(event, target, bind, tables=None, **kw):
    """Sets the schema version to most recent for a plugin when it's tables are freshly created."""
    if tables:
        # TODO: Detect if any database upgrading is needed and acquire the lock only in one place
        with flexget.manager.manager.acquire_lock(event=False):
            tables = [table.name for table in tables]
            for plugin, info in plugin_schemas.items():
                # Only set the version if all tables for a given plugin are being created
                if all(table in tables for table in info['tables']):
                    set_version(plugin, info['version'])

# Register a listener to call our method after tables are created
Base.metadata.append_ddl_listener('after-create', after_table_create)


text:
package me.deftware.mixin.mixins.network;

import net.minecraft.client.util.telemetry.TelemetrySender;
import org.objectweb.asm.Opcodes;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;

/**
 * Disables Minecraft telemetry
 */
@Mixin(TelemetrySender.class)
public class MixinTelemetry {

	@Redirect(method = "<init>", at = @At(value = "FIELD", target = "Lnet/minecraft/SharedConstants;isDevelopment:Z", opcode = Opcodes.GETSTATIC))
	private boolean onIsDevelopment() {
		return true;
	}

}


text:
package CQS::CQSMirnaNTATable;

use strict;
use warnings;
use File::Basename;
use CQS::PBS;
use CQS::ConfigUtils;
use CQS::SystemUtils;
use CQS::FileUtils;
use CQS::NGSCommon;
use CQS::StringUtils;
use CQS::UniqueTask;

our @ISA = qw(CQS::UniqueTask);

sub new {
  my ($class) = @_;
  my $self = $class->SUPER::new();
  $self->{_name}   = __PACKAGE__;
  $self->{_suffix} = "_mnt";
  bless $self, $class;
  return $self;
}

sub perform {
  my ( $self, $config, $section ) = @_;

  my ( $task_name, $path_file, $pbs_desc, $target_dir, $log_dir, $pbs_dir, $result_dir, $option, $sh_direct, $cluster ) = $self->init_parameter( $config, $section );

  my %raw_files = %{ get_raw_files( $config, $section ) };

  $self->{_task_prefix} = get_option( $config, $section, "prefix", "" );
  $self->{_task_suffix} = get_option( $config, $section, "suffix", "" );

  my $pbs_file = $self->get_pbs_filename( $pbs_dir, $task_name );
  my $pbs_name = basename($pbs_file);
  my $log      = $self->get_log_filename( $log_dir, $task_name );

  my $log_desc = $cluster->get_log_description($log);

  my $pbs = $self->open_pbs( $pbs_file, $pbs_desc, $log_desc, $path_file, $result_dir );

  if ( defined $config->{$section}{groups} || defined $config->{$section}{groups_ref} ) {
    my $groups = get_raw_files( $config, $section, "groups" );
    for my $group_name ( sort keys %{$groups} ) {
      my $filelist   = $self->get_file( $pbs_dir,    "${task_name}_${group_name}", ".filelist", 0 );
      my $outputfile = $self->get_file( $result_dir, "${task_name}_${group_name}", ".count",    0 );
      my $outputname = basename($outputfile);

      my @samples = @{ $groups->{$group_name} };
      open( my $fl, ">$filelist" ) or die "Cannot create $filelist";
      for my $sample_name ( sort @samples ) {
        my @count_files = @{ $raw_files{$sample_name} };
        my $countFile   = $count_files[0];
        print $fl $sample_name, "\t", $countFile, "\n";
      }
      close($fl);

      print $pbs "
cqstools mirna_nta_table $option -o $outputname -l $filelist
";
    }
  }
  else {
    my $filelist   = $self->get_file( $pbs_dir,    ${task_name}, ".filelist", 0 );
    my $outputfile = $self->get_file( $result_dir, ${task_name}, ".count",    0 );
    my $outputname = basename($outputfile);

    open( my $fl, ">$filelist" ) or die "Cannot create $filelist";
    for my $sample_name ( sort keys %raw_files ) {
      my @count_files = @{ $raw_files{$sample_name} };
      my $countFile   = $count_files[0];
      print $fl $sample_name, "\t", $countFile, "\n";
    }
    close($fl);

    print $pbs "
cqstools mirna_nta_table $option -o $outputname -l $filelist
";
  }
  $self->close_pbs( $pbs, $pbs_file );
}

sub result {
  my ( $self, $config, $section, $pattern ) = @_;
  my ( $task_name, $path_file, $pbs_desc, $target_dir, $log_dir, $pbs_dir, $result_dir, $option, $sh_direct ) = $self->init_parameter( $config, $section, 0 );

  $self->{_task_prefix} = get_option( $config, $section, "prefix", "" );
  $self->{_task_suffix} = get_option( $config, $section, "suffix", "" );

  my $result = {};

  my @result_files = ();
  if ( defined $config->{$section}{groups} || defined $config->{$section}{groups_ref} ) {
    my $groups = get_raw_files( $config, $section, "groups" );
    for my $group_name ( sort keys %{$groups} ) {
      my $outputfile    = $self->get_file( $result_dir, "${task_name}_${group_name}", ".count",          0 );
      my $isomirfile    = $self->get_file( $result_dir, "${task_name}_${group_name}", ".isomir.tsv",     0 );
      my $isomirNTAfile = $self->get_file( $result_dir, "${task_name}_${group_name}", ".isomir_NTA.tsv", 0 );
      my $filelist      = $self->get_file( $pbs_dir,    "${task_name}_${group_name}", ".filelist",       0 );
      push( @result_files, $outputfile );
      push( @result_files, $isomirfile );
      push( @result_files, $isomirNTAfile );
      push( @result_files, $filelist );
    }
  }
  else {
    my $outputfile    = $self->get_file( $result_dir, ${task_name}, ".count",          0 );
    my $isomirfile    = $self->get_file( $result_dir, ${task_name}, ".isomir.tsv",     0 );
    my $isomirNTAfile = $self->get_file( $result_dir, ${task_name}, ".isomir_NTA.tsv", 0 );
    my $filelist      = $self->get_file( $pbs_dir,    ${task_name}, ".filelist",       0 );
    push( @result_files, $outputfile );
    push( @result_files, $isomirfile );
    push( @result_files, $isomirNTAfile );
    push( @result_files, $filelist );
  }
  $result->{$task_name} = filter_array( \@result_files, $pattern );

  return $result;
}

1;