text:
package com.hazelcast.spi;

import java.util.Collection;

/**
 * {@code FragmentedMigrationAwareService} is an extension to the {@link MigrationAwareService} which allows
 * migration/replication of partition replicas in smaller fragments.
 *

 * Each replica fragment is distinguished by a {@link ServiceNamespace}, all replica data belonging to
 * a specific namespace will be transferred in the same packet.
 *

 * Both backup and backup aware operations created by {@code FragmentedMigrationAwareService} must implement
 * {@link ServiceNamespaceAware} interface and must know their related {@link ServiceNamespace}s.
 *

 * Fragmented migration can be enabled/disabled using configuration property
 * {@link com.hazelcast.spi.properties.GroupProperty#PARTITION_FRAGMENTED_MIGRATION_ENABLED}. Anti-entropy system which
 * detects and completes inconsistent backup replicas, always uses fragmented replication for services having support.
 *
 * @see MigrationAwareService
 * @see ServiceNamespace
 * @see ServiceNamespaceAware
 * @since 3.9
 */
public interface FragmentedMigrationAwareService extends MigrationAwareService {

    /**
     * Returns all known namespaces for given replication event.
     *
     * @param event replication event
     * @return all known service namespaces for the replication
     */
    Collection<ServiceNamespace> getAllServiceNamespaces(PartitionReplicationEvent event);

    /**
     * Returns true if namespace is known by this service, false otherwise
     *
     * @param namespace namespace
     * @return true if namespace is known by this service, false otherwise
     */
    boolean isKnownServiceNamespace(ServiceNamespace namespace);

    /**
     * Returns an operation to replicate service data and/or state for a specific partition replica and namespaces
     * on another cluster member. This method is very similar to
     * {@link #prepareReplicationOperation(PartitionReplicationEvent)},
     * instead of copying whole partition replica, allows copying only some portion of replica,
     * specified by given namespaces.
     *
     *

     * This method will be called on source member whenever partitioning system requires
     * to copy/replicate a partition replica. Returned operation will be executed on destination member.
     * If operation fails by throwing exception, migration process will fail and will be rolled back.
     *

     * Returning null is allowed and means service does not have anything to replicate.
     *
     * @param event replication event
     * @param namespaces replica fragment namespaces to replicate
     * @return replication operation or null if nothing will be replicated
     * @see #prepareReplicationOperation(PartitionReplicationEvent)
     */
    Operation prepareReplicationOperation(PartitionReplicationEvent event, Collection<ServiceNamespace> namespaces);

}


text:
namespace WebsitePanel.Portal {

    public partial class VpsMenu {

        /// <summary>
        /// locMenuTitle control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Localize locMenuTitle;

        /// <summary>
        /// vpsMenu control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlGenericControl vpsMenu;

        /// <summary>
        /// menu control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Menu menu;
    }
}

redpajama_set_name: RedPajamaGithub


text:
var gulp = require('gulp');
var config = require('../gulp.config')();
var ts = require('gulp-typescript');
var tslint = require('gulp-tslint');
var sourcemaps = require('gulp-sourcemaps');

/* Initialize TS Project */
var typingFiles = [
    'typings/index.d.ts',
    'manual_typings/**/*.d.ts'
];
var tsUnitFiles = [].concat(config.tsTestFiles.unit, config.tsTestFiles.helper);
var tsE2EFiles = [].concat(config.tsTestFiles.e2e, config.tsTestFiles.helper);
var tsFiles = [].concat(config.tsFiles, tsUnitFiles, tsE2EFiles);

/* Watch changed typescripts file and compile it */
gulp.task('watch-ts', function () {
    return gulp.watch(tsFiles, function (file) {
        console.log('Compiling ' + file.path + '...');
        return compileTs(file.path, true);
    });
});

/* Compile typescripts */
gulp.task('tsc', function () {
	compileAppTs(tsFiles);
	return compileTestTs(tsFiles);
});

gulp.task('tsc-app', function () {
    return compileAppTs(config.tsFiles);
});

gulp.task('tsc-unit', function () {
    return compileTestTs(tsUnitFiles);
});

gulp.task('tsc-e2e', function () {
    return compileTestTs(tsE2EFiles);
});

/* Lint typescripts */
gulp.task('tslint', function () {
    return lintTs(tsFiles);
});

gulp.task('tslint-app', function () {
    return lintTs(config.tsFiles);
});

gulp.task('tslint-unit', function () {
    return lintTs(tsUnitFiles);
});

gulp.task('tslint-e2e', function () {
    return lintTs(tsE2EFiles);
});

function lintTs(files) {
    return gulp.src(files)
        .pipe(tslint())
        .pipe(tslint.report('prose', {
          summarizeFailureOutput: true
        }));
}

function compileAppTs(files, watchMode) {
    watchMode = watchMode || false;
    var tsProject = ts.createProject(config.root + 'tsconfig.json');
    var allFiles = [].concat(files, typingFiles);
    var res = gulp.src(allFiles, {
            base: config.client,
            outDir: config.build_dev.path
        })
        .pipe(tslint())
        .pipe(tslint.report('prose', {
            summarizeFailureOutput: true,
            emitError: !watchMode
        }))
        .pipe(sourcemaps.init())
        .pipe(ts(tsProject))
        .on('error', function () {
            // process.exit(1);
            console.warn('Error occured... waiting for changes');
        });
    return res.js
        .pipe(sourcemaps.write('.', {
              includeContent: false
            }))
        .pipe(gulp.dest(config.build_dev.path));
}
function compileTestTs(files, watchMode) {
    watchMode = watchMode || false;
    var tsProject = ts.createProject(config.root + 'tsconfig.json');
    var allFiles = [].concat(files, typingFiles);
    var res = gulp.src(allFiles, {
            base: config.test,
            outDir: config.test_js
        })
        .pipe(tslint())
        .pipe(tslint.report('prose', {
            summarizeFailureOutput: true,
            emitError: !watchMode
        }))
        // .pipe(sourcemaps.init())
        .pipe(ts(tsProject))
        .on('error', function () {
            console.warn('Error occured... waiting for changes');
        });
    return res.js
        .pipe(sourcemaps.write('.', {
              includeContent: false
            }))
        .pipe(gulp.dest(config.test_js));
}


text:
package org.sosy_lab.cpachecker.cpa.predicate.relevantpredicates;

import org.sosy_lab.cpachecker.cfa.blocks.Block;
import org.sosy_lab.cpachecker.util.predicates.AbstractionPredicate;

public interface RefineableRelevantPredicatesComputer extends RelevantPredicatesComputer {
  public void considerPredicateAsRelevant(Block block, AbstractionPredicate predicate);
}


text:
<ion-modal-view id="signup" style="border:solid 2px #d3d3d3; border-radius: 5px;">
  <ion-header-bar class="text-center">

15 Second Free Signup!

  </ion-header-bar>
  <ion-content>
    <ion-list>

        Full Name
        <input type="text" placeholder="Full Name" ng-model="newUser.name">

        Company Name
        <input type="text" placeholder="Company Name" ng-model="newUser.business_name">

        Cell Phone
        <input type="text" placeholder="Cell Phone" ng-model="newUser.mobile_phone">

        E-Mail
        <input type="text" placeholder="E-Mail" ng-model="newUser.email">

        Password
        <input placeholder="Password" type="{{chkState ? 'text' : 'password'}}" ng-model="newUser.password">

      <ion-item class="item item-checkbox" style="border-style:none;">

             <input type="checkbox" ng-click="showPassword()" checked>

           Show password
      </ion-item>
      <ion-item class="item item-checkbox" style="border-style:none;">

             <input type="checkbox" ng-model="newUser.terms_of_service" checked>

           Agree to Terms of Service and Privacy Policy.
      </ion-item>

      <ion-item style="border-style:none;">

            <button class="button button-block button-light" style="border:2px solid #336699;background-color:white;border-radius: 5px;display: block;line-height: 132%;white-space:normal;font-size:15px;" ng-click="doSignup()">

Let's get going!

            </button>

                <button class="button button-block button-light" style="border-radius: 5px;font-size: 107%;line-height: 132%;white-space:normal;" ng-click="openLogin()">

Already have account login here

                </button>

      </ion-item>
    </ion-list>
  </ion-content>
</ion-modal-view>


text:
import '@percy/cypress'

// custom command to make taking snapshots with full name
// formed from the test title + suffix easier
// cy.visualSnapshot() // default full test title
// cy.visualSnapshot('clicked') // full test title + ' - clicked'
// also sets the width and height to the current viewport
// from: https://github.com/cypress-io/cypress-realworld-app/blob/8d47eb252fd95126e9ce5fce0379fc8486fba86f/cypress/support/commands.ts#L9-L26
// Enable this command by setting the env var `CYPRESS_VISUAL_SNAPSHOT_TESTING` to `1`
Cypress.Commands.add('visualSnapshot', (maybeName) => {
  if (Number(Cypress.env('VISUAL_SNAPSHOT_TESTING')) !== 1) {
    return
  }

  let snapshotTitle = cy.state('runnable').fullTitle()

  if (maybeName) {
    snapshotTitle = `${snapshotTitle} - ${maybeName}`
  }

  cy.percySnapshot(snapshotTitle, {
    widths: [cy.state('viewportWidth')],
    minHeight: cy.state('viewportHeight'),
  })
})


text:
package com.ibm.wala.core.tests.ptrs;

import java.io.IOException;
import java.util.Iterator;

import org.junit.Assert;
import org.junit.Test;

import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil;
import com.ibm.wala.core.tests.util.TestConstants;
import com.ibm.wala.core.tests.util.WalaTestCase;
import com.ibm.wala.ipa.callgraph.AnalysisCache;
import com.ibm.wala.ipa.callgraph.AnalysisOptions;
import com.ibm.wala.ipa.callgraph.AnalysisScope;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.ipa.callgraph.CallGraphBuilder;
import com.ibm.wala.ipa.callgraph.Entrypoint;
import com.ibm.wala.ipa.callgraph.impl.Util;
import com.ibm.wala.ipa.callgraph.propagation.InstanceKey;
import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis;
import com.ibm.wala.ipa.callgraph.propagation.PointerKey;
import com.ibm.wala.ipa.cha.ClassHierarchy;
import com.ibm.wala.ipa.cha.ClassHierarchyException;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.OrdinalSet;

/**
 *
 * Test for pointer analysis of multidimensional arrays
 *
 * @author sfink
 */

public class MultiDimArrayTest extends WalaTestCase {

  public static void main(String[] args) {
    justThisTest(MultiDimArrayTest.class);
  }

  public MultiDimArrayTest() {

  }

  @Test public void testMultiDim() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException {
    AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope(TestConstants.WALA_TESTDATA, CallGraphTestUtil.REGRESSION_EXCLUSIONS);
    ClassHierarchy cha = ClassHierarchy.make(scope);
    Iterable<Entrypoint> entrypoints = com.ibm.wala.ipa.callgraph.impl.Util
        .makeMainEntrypoints(scope, cha, TestConstants.MULTI_DIM_MAIN);
    AnalysisOptions options = CallGraphTestUtil.makeAnalysisOptions(scope, entrypoints);

    CallGraphBuilder builder = Util.makeVanillaZeroOneCFABuilder(options, new AnalysisCache(),cha, scope);
    CallGraph cg = builder.makeCallGraph(options, null);
    PointerAnalysis<InstanceKey> pa = builder.getPointerAnalysis();

    CGNode node = findDoNothingNode(cg);
    PointerKey pk = pa.getHeapModel().getPointerKeyForLocal(node, 1);
    OrdinalSet<InstanceKey> ptsTo = pa.getPointsToSet(pk);
    Assert.assertEquals(1, ptsTo.size());
  }

  private final static CGNode findDoNothingNode(CallGraph cg) {
    for (Iterator<? extends CGNode> it = cg.iterator(); it.hasNext(); ) {
      CGNode n = it.next();
      if (n.getMethod().getName().toString().equals("doNothing")) {
        return n;
      }
    }
    Assertions.UNREACHABLE("Unexpected: failed to find doNothing node");
    return null;
  }
}


text:
$(document).ready(function() {

	$("#support-editor").live("click", function(){
		$("#message").fadeOut();
	});

	$('.save-continue-support').live('click', function(event) {
		save_continue_support();
		}// end function(event)
	);// end click

	$(".cancel-support-edit").live("click",function(event){
		var action = confirm("Are you sure you want to cancel? Any changes you made will not be saved.");
		if(action){
			var myStudent = $("#kStudent").val();
			document.location = base_url + "support/list_all/" + myStudent;
		}
	});

	$('.save-close-support').live('click', function(event) {
						document.forms["support-editor"].submit();
					}// end function(event)
			); // end click

	$('#delete-support').live('click', function(event) {
						var action = confirm("Do you really want to delete this? This cannot be undone!");
						var myStudent = $('#kStudent').val();
						var myNeed = $('#kSupport').val();
						var myUrl = base_url + "support/delete";
						var form_data = {
								kStudent: myStudent,
								kSupport: myNeed
						};
						if (action) {
							var real_action = confirm("Are you absolutely sure? This really cannot be undone!");
							if(real_action) {
								$("#action").val("delete");
								$("#support-editor").attr("action",base_url + "support/delete");
								$("#support-editor").submit();
							}

						}
					}

			);

	$('#print-support').live('click',function(event){
		var myStudent=$("#kStudent").val();
		var myNeed=$("#kSupport").val();
		if(myNeed!="") {
			var myUrl = base_url + "support/view/" + myNeed + "/print";
			window.open(myUrl);
		}
	});

	$('.show_support').live('click', function(event) {
		// $data=array("kStudent"=>$kStudent,"kTeach"=>$kTeach,"narrTerm"=>$narrTerm,"narrYear"=>$narrYear,"narrSubject"=>$narrSubject);
		var myStudent = $('#kStudent').val();
		var myTeacher = $('#kTeach').val();
		var myTerm = $('#narrTerm').val();
		var myYear = $('#narrYear').val();
		var mySubject = $('#narrSubject').val();
		var myNeed = this.id.split("_")[1];
		var form_data = {
				kStudent: myStudent,
				kTeacher: myTeacher,
				narrTerm: myTerm,
				narrYear: myYear,
				narrSubject: mySubject,
				kSupport: myNeed,
				ajax: 1
		};
		var myUrl = base_url + "support/view/" + myNeed + "/sidebar";
		$.ajax({
			type: "POST",
			url: myUrl,
			data: form_data,
			success: function(data){
				showSidebar('Accommodations and Needs',
						data, '95%', '60%', '35%');
			}
		});

});// end show_needs.click

	/*** FILE MANAGEMENT ***/
	$('.show-support-file-uploader').live('click', function(event){
		var myNeed = $("#kSupport").val();
		var myStudent = $("#kStudent").val();

		var myUrl = base_url + "support/new_file";
		var form_data = {
				kSupport: myNeed,
				kStudent: myStudent,
				ajax: 1
		};
		$.ajax({
			type: 'POST',
			data: form_data,
			url: myUrl,
			success: function(data){
			showPopup("Add a File", data, 'auto');
		}
		});
	});

	$(".attach-support-file").live("click", function(event){
		save_continue_support();
		$("#support-file-editor").submit();

	});

	$(".delete-support-file").live("click", function(event){
		var action = confirm("Are you sure you want to delete this file? This cannot be undone!");
		if(action) {
			var new_action = confirm("This really cannot be undone!");
			if(new_action) {
				var myFile = this.id.split("_")[1];
				var myUrl = base_url + "support/delete_file";
				var form_data = {
						kFile: myFile,
				};

				$.ajax({
					type: "POST",
					data: form_data,
					url: myUrl,
					success: function(data){
					$("#fr_" + myFile).fadeOut();

				}
				});
			}
		}
	});
	$('.accordion').accordion(
			{
				autoHeight: false,
				icons: { 'header': 'ui-icon-circle-plus', 'headerSelected': 'ui-icon-circle-minus'},
				collapsible: true,
				ffDefault: 'tahoma,sans-serif'
			}
		);

}// end ready
);// end $(document)

function save_continue_support(){
	var myAction = $('#action').val();
	$("#ajax").val(1);
	var form_data = $('#support-editor').serialize();
	form_data["ajax"] = 1;
	var myUrl = base_url + "support/" + myAction;
	$.ajax({
		type: "post",
		url: myUrl,
		data: form_data,
		success: function(data){
		if(myAction == "insert") {
			$("#kSupport").val(data);
			$("#action").val("update");
			$("#delete-support").removeClass("hidden");
			$("#print-support").removeClass("hidden");
			$(".insert-message").addClass("hidden");
			$(".show-support-file-uploader").removeClass("hidden");
			$("#support-editor").attr("action",base_url + "support/update");
			$("#message").html("The support record was successfully added" ).fadeIn();
		}else {
			$("#message").html("The support record was successfully updated " + data).fadeIn();
		}
	}

	});//end ajax
	$("#ajax").val(0);

}


text:
package com.example.balabh.pollrise.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.balabh.pollrise.R;
import com.example.balabh.pollrise.model.Poll;

import java.util.List;

/**
 * Created by balabh on 6/23/2015.
 */
public class PollViewAdapter extends RecyclerView.Adapter<PollViewAdapter.ViewHolder> {
    private List<Poll> mDataset;
    private static ClickListener clickListener;
    public static class ViewHolder extends RecyclerView.ViewHolder
            implements View.OnClickListener {
        TextView mQuestion,
                mDate;
        long id;
        public ViewHolder(View itemView) {
            super(itemView);
            mQuestion = (TextView) itemView.findViewById(R.id.poll_label);
            mDate = (TextView) itemView.findViewById(R.id.poll_date);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            clickListener.onClick(getPosition(), view);
        }
    }

    public void setClickListener(ClickListener clickListener) {
        PollViewAdapter.clickListener = clickListener;
    }

    public PollViewAdapter(List<Poll> mDataset) {
        this.mDataset = mDataset;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.poll_view_item, viewGroup, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {
        viewHolder.mDate.setText((CharSequence) mDataset.get(i).getDate().toString());
        viewHolder.mQuestion.setText(mDataset.get(i).getQuestion());
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    public void addItem(Poll poll, int index) {
        mDataset.add(poll);
        notifyItemInserted(index);
    }

    public void delete(int index) {
        mDataset.remove(index);
        notifyItemRemoved(index);
    }

    public interface ClickListener {
        public void onClick(int position, View v);
    }

}


text:
/*
  ==============================================================================

    player.hpp
    Created: 9 Apr 2015 1:37:30pm
    Author:  yvan

  ==============================================================================
*/

#ifndef PLAYER_HPP_INCLUDED
#define PLAYER_HPP_INCLUDED

namespace YSE {
  /** Every subSystem consists out of several class which are meant to work together.
  They all have an interface, implementation, manager, message and a message enumeration.
  */

  namespace PLAYER {
    class interfaceObject;
    class implementationObject;
    class messageObject;
    class managerObject;

    enum MESSAGE {
      PLAY,
      MIN_PITCH,
      MAX_PITCH,
      MIN_VELOCITY,
      MAX_VELOCITY,
      MIN_GAP,
      MAX_GAP,
      MIN_LENGTH,
      MAX_LENGTH,
      VOICES,
      SCALE,
      ADD_MOTIF,
      REM_MOTIF,
      ADJUST_MOTIF,
      PARTIAL_MOTIF,
      PLAY_MOTIF,
      MOTIF_FITS_SCALE,
    };
  }

  // the interface itself gets a more generic name, so that users can just
  // define a 'player' to get an interface object.
  typedef PLAYER::interfaceObject player;

}

#endif  // PLAYER_HPP_INCLUDED


text:
using blink::WebString;
using blink::WebURL;

namespace content {

void RendererWebCookieJarImpl::setCookie(
    const WebURL& url, const WebURL& first_party_for_cookies,
    const WebString& value) {
  std::string value_utf8 = base::UTF16ToUTF8(base::StringPiece16(value));
  RenderThreadImpl::current()->render_frame_message_filter()->SetCookie(
      sender_->GetRoutingID(), url, first_party_for_cookies, value_utf8);
}

WebString RendererWebCookieJarImpl::cookies(
    const WebURL& url, const WebURL& first_party_for_cookies) {
  std::string value_utf8;
  RenderThreadImpl::current()->render_frame_message_filter()->GetCookies(
      sender_->GetRoutingID(), url, first_party_for_cookies, &value_utf8);
  return WebString::fromUTF8(value_utf8);
}

bool RendererWebCookieJarImpl::cookiesEnabled(
    const WebURL& url, const WebURL& first_party_for_cookies) {
  bool cookies_enabled = false;
  sender_->Send(new FrameHostMsg_CookiesEnabled(
      sender_->GetRoutingID(), url, first_party_for_cookies, &cookies_enabled));
  return cookies_enabled;
}

}  // namespace content


text:
/**
 * Set up keyboard shortcuts & commands for notebook
 */
import { CommandRegistry } from '@lumino/commands';
import { sessionContextDialogs } from '@jupyterlab/apputils';
import { CompletionHandler } from '@jupyterlab/completer';
import { NotebookActions, NotebookPanel } from '@jupyterlab/notebook';
import {
  NotebookSearchProvider,
  SearchInstance
} from '@jupyterlab/documentsearch';
import { CommandPalette } from '@lumino/widgets';

/**
 * The map of command ids used by the notebook.
 */
const cmdIds = {
  invoke: 'completer:invoke',
  select: 'completer:select',
  invokeNotebook: 'completer:invoke-notebook',
  selectNotebook: 'completer:select-notebook',
  startSearch: 'documentsearch:start-search',
  findNext: 'documentsearch:find-next',
  findPrevious: 'documentsearch:find-previous',
  save: 'notebook:save',
  interrupt: 'notebook:interrupt-kernel',
  restart: 'notebook:restart-kernel',
  switchKernel: 'notebook:switch-kernel',
  runAndAdvance: 'notebook-cells:run-and-advance',
  run: 'notebook:run-cell',
  deleteCell: 'notebook-cells:delete',
  selectAbove: 'notebook-cells:select-above',
  selectBelow: 'notebook-cells:select-below',
  extendAbove: 'notebook-cells:extend-above',
  extendTop: 'notebook-cells:extend-top',
  extendBelow: 'notebook-cells:extend-below',
  extendBottom: 'notebook-cells:extend-bottom',
  editMode: 'notebook:edit-mode',
  merge: 'notebook-cells:merge',
  split: 'notebook-cells:split',
  commandMode: 'notebook:command-mode',
  undo: 'notebook-cells:undo',
  redo: 'notebook-cells:redo'
};

export const SetupCommands = (
  commands: CommandRegistry,
  palette: CommandPalette,
  nbWidget: NotebookPanel,
  handler: CompletionHandler
): void => {
  // Add commands.
  commands.addCommand(cmdIds.invoke, {
    label: 'Completer: Invoke',
    execute: () => handler.invoke()
  });
  commands.addCommand(cmdIds.select, {
    label: 'Completer: Select',
    execute: () => handler.completer.selectActive()
  });
  commands.addCommand(cmdIds.invokeNotebook, {
    label: 'Invoke Notebook',
    execute: () => {
      if (nbWidget.content.activeCell?.model.type === 'code') {
        return commands.execute(cmdIds.invoke);
      }
    }
  });
  commands.addCommand(cmdIds.selectNotebook, {
    label: 'Select Notebook',
    execute: () => {
      if (nbWidget.content.activeCell?.model.type === 'code') {
        return commands.execute(cmdIds.select);
      }
    }
  });
  commands.addCommand(cmdIds.save, {
    label: 'Save',
    execute: () => nbWidget.context.save()
  });

  let searchInstance: SearchInstance | undefined;
  commands.addCommand(cmdIds.startSearch, {
    label: 'Find…',
    execute: () => {
      if (searchInstance) {
        searchInstance.focusInput();
        return;
      }
      const provider = new NotebookSearchProvider();
      searchInstance = new SearchInstance(nbWidget, provider);
      searchInstance.disposed.connect(() => {
        searchInstance = undefined;
        // find next and previous are now not enabled
        commands.notifyCommandChanged();
      });
      // find next and previous are now enabled
      commands.notifyCommandChanged();
      searchInstance.focusInput();
    }
  });
  commands.addCommand(cmdIds.findNext, {
    label: 'Find Next',
    isEnabled: () => !!searchInstance,
    execute: async () => {
      if (!searchInstance) {
        return;
      }
      await searchInstance.provider.highlightNext();
      searchInstance.updateIndices();
    }
  });
  commands.addCommand(cmdIds.findPrevious, {
    label: 'Find Previous',
    isEnabled: () => !!searchInstance,
    execute: async () => {
      if (!searchInstance) {
        return;
      }
      await searchInstance.provider.highlightPrevious();
      searchInstance.updateIndices();
    }
  });
  commands.addCommand(cmdIds.interrupt, {
    label: 'Interrupt',
    execute: async () =>
      nbWidget.context.sessionContext.session?.kernel?.interrupt()
  });
  commands.addCommand(cmdIds.restart, {
    label: 'Restart Kernel',
    execute: () =>
      sessionContextDialogs.restart(nbWidget.context.sessionContext)
  });
  commands.addCommand(cmdIds.switchKernel, {
    label: 'Switch Kernel',
    execute: () =>
      sessionContextDialogs.selectKernel(nbWidget.context.sessionContext)
  });
  commands.addCommand(cmdIds.runAndAdvance, {
    label: 'Run and Advance',
    execute: () => {
      return NotebookActions.runAndAdvance(
        nbWidget.content,
        nbWidget.context.sessionContext
      );
    }
  });
  commands.addCommand(cmdIds.run, {
    label: 'Run',
    execute: () => {
      return NotebookActions.run(
        nbWidget.content,
        nbWidget.context.sessionContext
      );
    }
  });
  commands.addCommand(cmdIds.editMode, {
    label: 'Edit Mode',
    execute: () => {
      nbWidget.content.mode = 'edit';
    }
  });
  commands.addCommand(cmdIds.commandMode, {
    label: 'Command Mode',
    execute: () => {
      nbWidget.content.mode = 'command';
    }
  });
  commands.addCommand(cmdIds.selectBelow, {
    label: 'Select Below',
    execute: () => NotebookActions.selectBelow(nbWidget.content)
  });
  commands.addCommand(cmdIds.selectAbove, {
    label: 'Select Above',
    execute: () => NotebookActions.selectAbove(nbWidget.content)
  });
  commands.addCommand(cmdIds.extendAbove, {
    label: 'Extend Above',
    execute: () => NotebookActions.extendSelectionAbove(nbWidget.content)
  });
  commands.addCommand(cmdIds.extendTop, {
    label: 'Extend to Top',
    execute: () => NotebookActions.extendSelectionAbove(nbWidget.content, true)
  });
  commands.addCommand(cmdIds.extendBelow, {
    label: 'Extend Below',
    execute: () => NotebookActions.extendSelectionBelow(nbWidget.content)
  });
  commands.addCommand(cmdIds.extendBottom, {
    label: 'Extend to Bottom',
    execute: () => NotebookActions.extendSelectionBelow(nbWidget.content, true)
  });
  commands.addCommand(cmdIds.merge, {
    label: 'Merge Cells',
    execute: () => NotebookActions.mergeCells(nbWidget.content)
  });
  commands.addCommand(cmdIds.split, {
    label: 'Split Cell',
    execute: () => NotebookActions.splitCell(nbWidget.content)
  });
  commands.addCommand(cmdIds.undo, {
    label: 'Undo',
    execute: () => NotebookActions.undo(nbWidget.content)
  });
  commands.addCommand(cmdIds.redo, {
    label: 'Redo',
    execute: () => NotebookActions.redo(nbWidget.content)
  });

  let category = 'Notebook Operations';
  [
    cmdIds.interrupt,
    cmdIds.restart,
    cmdIds.editMode,
    cmdIds.commandMode,
    cmdIds.switchKernel,
    cmdIds.startSearch,
    cmdIds.findNext,
    cmdIds.findPrevious
  ].forEach(command => palette.addItem({ command, category }));

  category = 'Notebook Cell Operations';
  [
    cmdIds.runAndAdvance,
    cmdIds.run,
    cmdIds.split,
    cmdIds.merge,
    cmdIds.selectAbove,
    cmdIds.selectBelow,
    cmdIds.extendAbove,
    cmdIds.extendBelow,
    cmdIds.undo,
    cmdIds.redo
  ].forEach(command => palette.addItem({ command, category }));

  const bindings = [
    {
      selector: '.jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled',
      keys: ['Tab'],
      command: cmdIds.invokeNotebook
    },
    {
      selector: `.jp-mod-completer-active`,
      keys: ['Enter'],
      command: cmdIds.selectNotebook
    },
    {
      selector: '.jp-Notebook',
      keys: ['Ctrl Enter'],
      command: cmdIds.run
    },
    {
      selector: '.jp-Notebook',
      keys: ['Shift Enter'],
      command: cmdIds.runAndAdvance
    },
    {
      selector: '.jp-Notebook',
      keys: ['Accel S'],
      command: cmdIds.save
    },
    {
      selector: '.jp-Notebook',
      keys: ['Accel F'],
      command: cmdIds.startSearch
    },
    {
      selector: '.jp-Notebook',
      keys: ['Accel G'],
      command: cmdIds.findNext
    },
    {
      selector: '.jp-Notebook',
      keys: ['Accel Shift G'],
      command: cmdIds.findPrevious
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['I', 'I'],
      command: cmdIds.interrupt
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['0', '0'],
      command: cmdIds.restart
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['Enter'],
      command: cmdIds.editMode
    },
    {
      selector: '.jp-Notebook.jp-mod-editMode',
      keys: ['Escape'],
      command: cmdIds.commandMode
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['Shift M'],
      command: cmdIds.merge
    },
    {
      selector: '.jp-Notebook.jp-mod-editMode',
      keys: ['Ctrl Shift -'],
      command: cmdIds.split
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['J'],
      command: cmdIds.selectBelow
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['ArrowDown'],
      command: cmdIds.selectBelow
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['K'],
      command: cmdIds.selectAbove
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['ArrowUp'],
      command: cmdIds.selectAbove
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['Shift K'],
      command: cmdIds.extendAbove
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['Shift J'],
      command: cmdIds.extendBelow
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['Z'],
      command: cmdIds.undo
    },
    {
      selector: '.jp-Notebook.jp-mod-commandMode:focus',
      keys: ['Y'],
      command: cmdIds.redo
    }
  ];
  bindings.map(binding => commands.addKeyBinding(binding));
};


text:
class Train : public Object
{
public:
    Train();
protected:
    virtual void modelize(float indice);
};

#endif


text:
<?php
/**
 * Created by PhpStorm.
 * User: cmar
 * Date: 9/01/2015
 * Time: 14:11
 */

namespace sisconee\AppBundle\Entity;

use Doctrine\ORM\EntityRepository;

class LecturaDiariaServicioRepository extends EntityRepository
{

    public function getLectura($day, $month, $anno, $id_servicio){
        $em = $this->getEntityManager();
        $query = $em->createQueryBuilder();

        $fecha = date("Y-m-d",strtotime($anno.'/'.$month.'/'.$day));

        $query->select('registro')
            ->from('sisconeeAppBundle:LecturaDiariaServicio', 'registro')
            ->where('registro.idServicio = :idServicio')->setParameter('idServicio', $id_servicio)
            ->orderBy('registro.fecha','ASC')
            ->andWhere('registro.fecha = :fecha')->setParameter('fecha', $fecha);
        //->setParameters(array(1=> $id_servicio));

        $array = $query->getQuery()->getResult();
        if (count($array)==1)
            return $array[0];
        else
            return null;
    }

   public  function  getLecturas($month, $anno, $id_servicio){

       $em = $this->getEntityManager();
       $query = $em->createQueryBuilder();

       $fecha_inicial = date("Y-m-d",strtotime($anno.'/'.$month.'/01'));
       $fecha_final = date("Y-m-d",strtotime($anno.'/'.$month.'/31'));

       $query->select('registro')
           ->from('sisconeeAppBundle:LecturaDiariaServicio', 'registro')
           ->where('registro.idServicio = ?1')
           ->orderBy('registro.fecha','ASC')
           ->andWhere('registro.fecha >= ?2')
           ->andWhere('registro.fecha <= ?3')
           ->setParameters(array(1=> $id_servicio, 2=>$fecha_inicial, 3=>$fecha_final));
           //->setParameters(array(1=> $id_servicio));

       return  $query->getQuery()->getResult();
       //return $query->getResult();
   }

    public  function  getConsumoAcumuladoGeneral($month, $anno, $id_servicio){

        $em = $this->getEntityManager();

        $fecha_inicial = date("Y-m-d",strtotime($anno.'/'.$month.'/01'));
        $fecha_final = date("Y-m-d",strtotime($anno.'/'.$month.'/31'));

        $rsm = new \Doctrine\ORM\Query\ResultSetMapping();
        $rsm->addScalarResult('cantidad', 'cantidad');
        $rsm->addScalarResult('cantidadHP', 'cantidadHP');

        $query = $em->createNativeQuery('Select SUM(consumo) as cantidad, SUM(consumo_horariopico) as cantidadHP
                                         FROM  lectura_diaria_servicio
                                         Where (id_servicio =:servicio) and (fecha >=:fecha_inicial) and (fecha <=:fecha_final)
                                         Group by id_servicio',$rsm);

        /*$query->select('registro,SUM(registro.plan)')
            ->from('sisconeeAppBundle:LecturaDiariaServicio', 'registro')
            ->where('registro.idServicio = ?1')
            ->andWhere('registro.fecha >= ?2')
            ->andWhere('registro.fecha <= ?3')
            ->groupBy('registro.id')*/
         $query->setParameters(array('servicio'=> $id_servicio, 'fecha_inicial'=>$fecha_inicial, 'fecha_final'=>$fecha_final));
        //->setParameters(array(1=> $id_servicio));

        $result =  $query->getResult();
        if (sizeof($result)>=1) { return $result ;}
          else {return array(0=>array('cantidad'=>0,'cantidadHP'=>0)); }

    }

}


text:
/**
 * @desc        each loop that also returns item index in the loop
 */

Handlebars.registerHelper('eachWithIndex', function(array, fn) {
    var buffer = "";
    for (var i = 0, j = array.length; i < j; i++) {
        var item = array[i];

        // stick an index property onto the item, starting with 1, may make configurable later
        item.index = i+1;

        // show the inside of the block
        buffer += fn(item);
    }

    // return the finished buffer
    return buffer;
});


text:
require 'spec_helper_acceptance'

tmpdir = default.tmpdir('tmp')

describe 'ini_subsetting resource' do
  after :all do
    shell("rm #{tmpdir}/*.ini", acceptable_exit_codes: [0, 1, 2])
  end

  shared_examples 'has_content' do |path, pp, content|
    before :all do
      shell("rm #{path}", acceptable_exit_codes: [0, 1, 2])
    end
    after :all do
      shell("cat #{path}", acceptable_exit_codes: [0, 1, 2])
      shell("rm #{path}", acceptable_exit_codes: [0, 1, 2])
    end

    it 'applies the manifest twice' do
      apply_manifest(pp, catch_failures: true)
      apply_manifest(pp, catch_changes: true)
    end

    describe file(path) do
      it { is_expected.to be_file }

      describe '#content' do
        subject { super().content }

        it {
          is_expected.to match content
        }
      end
    end
  end

  shared_examples 'has_error' do |path, pp, error|
    before :all do
      shell("rm #{path}", acceptable_exit_codes: [0, 1, 2])
    end
    after :all do
      shell("cat #{path}", acceptable_exit_codes: [0, 1, 2])
      shell("rm #{path}", acceptable_exit_codes: [0, 1, 2])
    end

    it 'applies the manifest and gets a failure message' do
      expect(apply_manifest(pp, expect_failures: true).stderr).to match(error)
    end

    describe file(path) do
      it { is_expected.not_to be_file }
    end
  end

  describe 'ensure, section, setting, subsetting, & value parameters => present with subsections' do
    pp = <<-EOS
    ini_subsetting { 'ensure => present for alpha':
      ensure     => present,
      path       => "#{tmpdir}/ini_subsetting.ini",
      section    => 'one',
      setting    => 'key',
      subsetting => 'alpha',
      value      => 'bet',
    }
    ini_subsetting { 'ensure => present for beta':
      ensure     => present,
      path       => "#{tmpdir}/ini_subsetting.ini",
      section    => 'one',
      setting    => 'key',
      subsetting => 'beta',
      value      => 'trons',
      require    => Ini_subsetting['ensure => present for alpha'],
    }
    EOS

    it 'applies the manifest twice' do
      apply_manifest(pp, catch_failures: true)
      apply_manifest(pp, catch_changes: true)
    end

    describe file("#{tmpdir}/ini_subsetting.ini") do
      it { is_expected.to be_file }

      describe '#content' do
        subject { super().content }

        it { is_expected.to match %r{\[one\]\nkey = alphabet betatrons} }
      end
    end
  end

  describe 'ensure => absent' do
    before :all do
      if fact('osfamily') == 'Darwin'
        shell("echo \"[one]\nkey = alphabet betatrons\" > #{tmpdir}/ini_subsetting.ini")
      else
        shell("echo -e \"[one]\nkey = alphabet betatrons\" > #{tmpdir}/ini_subsetting.ini")
      end
    end

    pp = <<-EOS
    ini_subsetting { 'ensure => absent for subsetting':
      ensure     => absent,
      path       => "#{tmpdir}/ini_subsetting.ini",
      section    => 'one',
      setting    => 'key',
      subsetting => 'alpha',
    }
    EOS

    it 'applies the manifest twice' do
      apply_manifest(pp, catch_failures: true)
      apply_manifest(pp, catch_changes: true)
    end

    describe file("#{tmpdir}/ini_subsetting.ini") do
      it { is_expected.to be_file }

      describe '#content' do
        subject { super().content }

        it { is_expected.to match %r{\[one\]} }
        it { is_expected.to match %r{key = betatrons} }
        it { is_expected.not_to match %r{alphabet} }
      end
    end
  end

  describe 'subsetting_separator' do
    {
      '' => %r{two = twinethree foobar},
      "subsetting_separator => ',',"    => %r{two = twinethree,foobar},
      "subsetting_separator => '   ',"  => %r{two = twinethree   foobar},
      "subsetting_separator => ' == '," => %r{two = twinethree == foobar},
      "subsetting_separator => '=',"    => %r{two = twinethree=foobar},
    }.each do |parameter, content|
      context "with \"#{parameter}\" makes \"#{content}\"" do
        pp = <<-EOS
        ini_subsetting { "with #{parameter} makes #{content}":
          ensure     => present,
          section    => 'one',
          setting    => 'two',
          subsetting => 'twine',
          value      => 'three',
          path       => "#{tmpdir}/subsetting_separator.ini",
          before     => Ini_subsetting['foobar'],
          #{parameter}
        }
        ini_subsetting { "foobar":
          ensure     => present,
          section    => 'one',
          setting    => 'two',
          subsetting => 'foo',
          value      => 'bar',
          path       => "#{tmpdir}/subsetting_separator.ini",
          #{parameter}
        }
        EOS

        it_behaves_like 'has_content', "#{tmpdir}/subsetting_separator.ini", pp, content
      end
    end
  end

  describe 'subsetting_key_val_separator' do
    {
      '' => %r{two = twinethree foobar},
      "subsetting_key_val_separator => ':',"    => %r{two = twine:three foo:bar},
      "subsetting_key_val_separator => '-',"    => %r{two = twine-three foo-bar},
    }.each do |parameter, content|
      context "with '#{parameter}' makes '#{content}'" do
        pp = <<-EOS
        ini_subsetting { "with #{parameter} makes #{content}":
          ensure     => 'present',
          section    => 'one',
          setting    => 'two',
          subsetting => 'twine',
          value      => 'three',
          path       => "#{tmpdir}/subsetting_key_val_separator.ini",
          before     => Ini_subsetting['foobar'],
          #{parameter}
        }
        ini_subsetting { "foobar":
          ensure     => 'present',
          section    => 'one',
          setting    => 'two',
          subsetting => 'foo',
          value      => 'bar',
          path       => "#{tmpdir}/subsetting_key_val_separator.ini",
          #{parameter}
        }
        EOS

        it_behaves_like 'has_content', "#{tmpdir}/subsetting_key_val_separator.ini", pp, content
      end
    end
  end

  describe 'quote_char' do
    {
      ['-Xmx'] => %r{args=""},
      ['-Xmx', '256m'] => %r{args=-Xmx256m},
      ['-Xmx', '512m'] => %r{args="-Xmx512m"},
      ['-Xms', '256m'] => %r{args="-Xmx256m -Xms256m"},
    }.each do |parameter, content|
      context %(with '#{parameter.first}' #{(parameter.length > 1) ? '=> \'' << parameter[1] << '\'' : 'absent'} makes '#{content}') do
        path = File.join(tmpdir, 'ini_subsetting.ini')

        before :all do
          shell(%(echo '[java]\nargs=-Xmx256m' > #{path}))
        end
        after :all do
          shell("cat #{path}", acceptable_exit_codes: [0, 1, 2])
          shell("rm #{path}", acceptable_exit_codes: [0, 1, 2])
        end

        pp = <<-EOS
        ini_subsetting { '#{parameter.first}':
          ensure     => #{(parameter.length > 1) ? 'present' : 'absent'},
          path       => '#{path}',
          section    => 'java',
          setting    => 'args',
          quote_char => '"',
          subsetting => '#{parameter.first}',
          value      => '#{(parameter.length > 1) ? parameter[1] : ''}'
        }
        EOS

        it 'applies the manifest twice' do
          apply_manifest(pp, catch_failures: true)
          apply_manifest(pp, catch_changes: true)
        end

        describe file("#{tmpdir}/ini_subsetting.ini") do
          it { is_expected.to be_file }

          describe '#content' do
            subject { super().content }

            it { is_expected.to match content }
          end
        end
      end
    end
  end

  describe 'show_diff parameter and logging:' do
    [{ value: 'initial_value', matcher: 'created', show_diff: true },
     { value: 'public_value', matcher: %r{initial_value.*public_value}, show_diff: true },
     { value: 'secret_value', matcher: %r{redacted sensitive information.*redacted sensitive information}, show_diff: false },
     { value: 'md5_value', matcher: %r{\{md5\}881671aa2bbc680bc530c4353125052b.*\{md5\}ed0903a7fa5de7886ca1a7a9ad06cf51}, show_diff: :md5 }].each do |i|
      context "show_diff => #{i[:show_diff]}" do
        pp = <<-EOS
          ini_subsetting { 'test_show_diff':
            ensure      => present,
            section     => 'test',
            setting     => 'something',
            subsetting  => 'xxx',
            value       => '#{i[:value]}',
            path        => "#{tmpdir}/test_show_diff.ini",
            show_diff   => #{i[:show_diff]}
          }
        EOS

        config = { 'main' => { 'show_diff' => true } }
        configure_puppet_on(default, config)

        res = apply_manifest(pp, expect_changes: true)
        it 'applies manifest and expects changed value to be logged in proper form' do
          expect(res.stdout).to match(i[:matcher])
        end
        it 'applies manifest and expects changed value to be logged in proper form #optional test' do
          expect(res.stdout).not_to match(i[:value]) unless i[:show_diff] == true
        end
      end
    end
  end

  describe 'insert types:' do
    [
      {
        insert_type: :start,
        content: %r{d a b c},
      },
      {
        insert_type: :end,
        content: %r{a b c d},
      },
      {
        insert_type: :before,
        insert_value: 'c',
        content: %r{a b d c},
      },
      {
        insert_type: :after,
        insert_value: 'a',
        content: %r{a d b c},
      },
      {
        insert_type: :index,
        insert_value: 2,
        content: %r{a b d c},
      },
    ].each do |params|
      context "with '#{params[:insert_type]}' makes '#{params[:content]}'" do
        pp = <<-EOS
        ini_subsetting { "a":
          ensure     => present,
          section    => 'one',
          setting    => 'two',
          subsetting => 'a',
          path       => "#{tmpdir}/insert_types.ini",
        } ->
        ini_subsetting { "b":
          ensure     => present,
          section    => 'one',
          setting    => 'two',
          subsetting => 'b',
          path       => "#{tmpdir}/insert_types.ini",
        } ->
        ini_subsetting { "c":
          ensure     => present,
          section    => 'one',
          setting    => 'two',
          subsetting => 'c',
          path       => "#{tmpdir}/insert_types.ini",
        } ->
        ini_subsetting { "insert makes #{params[:content]}":
          ensure       => present,
          section      => 'one',
          setting      => 'two',
          subsetting   => 'd',
          path         => "#{tmpdir}/insert_types.ini",
          insert_type  => '#{params[:insert_type]}',
          insert_value => '#{params[:insert_value]}',
        }
        EOS

        it_behaves_like 'has_content', "#{tmpdir}/insert_types.ini", pp, params[:content]
      end
    end
  end
end


text:
const Task = require('../models/Task');

module.exports = {
    index: (req, res) => {
        Task.find().then(tasks => {
                res.render('task/index', {'tasks': tasks});
        });
    },
	createGet: (req, res) => {
        res.render('task/create');
	},
	createPost: (req, res) => {
        let task = req.body;
        Task.create(task).then(task => {
            res.redirect("/");
        }).catch(err => {
            task.error = 'Cannot create task.';
            res.render('task/create', task);
        });
	},
	deleteGet: (req, res) => {
        let taskId = req.params.id;
        Task.findById(taskId).then(task => {
            if (task) {
                return res.render('task/delete', task);
            }
            else {
                return res.redirect('/');
            }
        }).catch(err => res.redirect('/'));
	},
	deletePost: (req, res) => {
        let taskId = req.params.id;
        Task.findByIdAndRemove(taskId).then(task => {
            res.redirect('/');
        }).catch(err => res.redirect('/'));
	}
};


text:
import { lazyComponent } from '@waldur/core/lazyComponent';
import * as ResourceSummary from '@waldur/resource/summary/registry';

import './help';
import './provider';
const DigitalOceanDropletSummary = lazyComponent(
  () =>
    import(
      /* webpackChunkName: "DigitalOceanDropletSummary" */ './DigitalOceanDropletSummary'
    ),
  'DigitalOceanDropletSummary',
);

ResourceSummary.register('DigitalOcean.Droplet', DigitalOceanDropletSummary);


text:
package com.linkedin.pinot.common.utils.helix;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;

import org.apache.helix.AccessOption;
import org.apache.helix.BaseDataAccessor;
import org.apache.helix.HelixAdmin;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixManager;
import org.apache.helix.PropertyKey;
import org.apache.helix.PropertyKey.Builder;
import org.apache.helix.ZNRecord;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.HelixConfigScope;
import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.builder.HelixConfigScopeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Function;
import com.linkedin.pinot.common.utils.CommonConstants;
import com.linkedin.pinot.common.utils.CommonConstants.Helix.DataSource.SegmentAssignmentStrategyType;
import com.linkedin.pinot.common.utils.EqualityUtils;
import com.linkedin.pinot.common.utils.retry.RetryPolicies;
import com.linkedin.pinot.common.utils.retry.RetryPolicy;

public class HelixHelper {
  private static final RetryPolicy DEFAULT_RETRY_POLICY = RetryPolicies.exponentialBackoffRetryPolicy(5, 1000L, 2.0f);
  private static final Logger LOGGER = LoggerFactory.getLogger(HelixHelper.class);

  private static final String ONLINE = "ONLINE";
  private static final String OFFLINE = "OFFLINE";

  public static final String BROKER_RESOURCE = CommonConstants.Helix.BROKER_RESOURCE_INSTANCE;

  public static final Map<String, SegmentAssignmentStrategyType> SEGMENT_ASSIGNMENT_STRATEGY_MAP =
      new HashMap<String, SegmentAssignmentStrategyType>();

  /**
   * Updates the ideal state, retrying if necessary in case of concurrent updates to the ideal state.
   *
   * @param helixManager The HelixManager used to interact with the Helix cluster
   * @param resourceName The resource for which to update the ideal state
   * @param updater A function that returns an updated ideal state given an input ideal state
   */
  public static void updateIdealState(final HelixManager helixManager, final String resourceName,
      final Function<IdealState, IdealState> updater, RetryPolicy policy) {
    policy.attempt(new Callable<Boolean>() {
      @Override
      public Boolean call() {
        HelixDataAccessor dataAccessor = helixManager.getHelixDataAccessor();
        PropertyKey propertyKey = dataAccessor.keyBuilder().idealStates(resourceName);

        // Create an updated version of the ideal state
        IdealState idealState = dataAccessor.getProperty(propertyKey);
        PropertyKey key = dataAccessor.keyBuilder().idealStates(resourceName);
        String path = key.getPath();
        // Make a copy of the the idealState above to pass it to the updater, instead of querying again,
        // as the state my change between the queries.
        IdealState idealStateCopy = new IdealState(idealState.getRecord());
        IdealState updatedIdealState;

        try {
          updatedIdealState = updater.apply(idealStateCopy);
        } catch (Exception e) {
          LOGGER.error("Caught exception while updating ideal state", e);
          return false;
        }

        // If there are changes to apply, apply them
        if (!EqualityUtils.isEqual(idealState, updatedIdealState) && updatedIdealState != null) {
          BaseDataAccessor<ZNRecord> baseDataAccessor = dataAccessor.getBaseDataAccessor();
          boolean success;

          try {
            success =
                baseDataAccessor.set(path, updatedIdealState.getRecord(), idealState.getRecord().getVersion(),
                    AccessOption.PERSISTENT);
          } catch (Exception e) {
            LOGGER.warn("Caught exception: {} while updating ideal state for resource {}, retrying.", resourceName,
                e.getMessage());
            return false;
          }

          if (success) {
            return true;
          } else {
            LOGGER.warn("Failed to update ideal state for resource {}, retrying.", resourceName);
            return false;
          }
        } else {
          LOGGER.warn("Idempotent or null ideal state update for resource {}, skipping update.", resourceName);
          return true;
        }
      }
    });
  }

  /**
   * Returns all instances for the given cluster.
   *
   * @param helixAdmin The HelixAdmin object used to interact with the Helix cluster
   * @param clusterName Name of the cluster for which to get all the instances for.
   * @return Returns a List of strings containing the instance names for the given cluster.
   */
  public static List<String> getAllInstances(HelixAdmin helixAdmin, String clusterName) {
    return helixAdmin.getInstancesInCluster(clusterName);
  }

  /**
   * Returns all instances for the given resource.
   *
   * @param idealState IdealState of the resource for which to return the instances of.
   * @return Returns a Set of strings containing the instance names for the given cluster.
   */
  public static Set<String> getAllInstancesForResource(IdealState idealState) {
    final Set<String> instances = new HashSet<String>();

    for (final String partition : idealState.getPartitionSet()) {
      for (final String instance : idealState.getInstanceSet(partition)) {
        instances.add(instance);
      }
    }
    return instances;
  }

  /**
   * Toggle the state of the instance between OFFLINE and ONLINE.
   *
   * @param instanceName Name of the instance for which to toggle the state.
   * @param clusterName Name of the cluster to which the instance belongs.
   * @param admin HelixAdmin to access the cluster.
   * @param enable Set enable to true for ONLINE and FALSE for OFFLINE.
   */
  public static void setInstanceState(String instanceName, String clusterName, HelixAdmin admin, boolean enable) {
    admin.enableInstance(clusterName, instanceName, enable);
  }

  public static void setStateForInstanceList(List<String> instances, String clusterName, HelixAdmin admin,
      boolean enable) {
    for (final String instance : instances) {
      setInstanceState(instance, clusterName, admin, enable);
    }
  }

  public static void setStateForInstanceSet(Set<String> instances, String clusterName, HelixAdmin admin, boolean enable) {
    for (final String instanceName : instances) {
      setInstanceState(instanceName, clusterName, admin, enable);
    }
  }

  public static Map<String, String> getInstanceConfigsMapFor(String instanceName, String clusterName, HelixAdmin admin) {
    final HelixConfigScope scope = getInstanceScopefor(clusterName, instanceName);
    final List<String> keys = admin.getConfigKeys(scope);
    return admin.getConfig(scope, keys);
  }

  public static HelixConfigScope getInstanceScopefor(String clusterName, String instanceName) {
    return new HelixConfigScopeBuilder(ConfigScopeProperty.PARTICIPANT, clusterName).forParticipant(instanceName)
        .build();
  }

  public static HelixConfigScope getResourceScopeFor(String clusterName, String resourceName) {
    return new HelixConfigScopeBuilder(ConfigScopeProperty.RESOURCE, clusterName).forResource(resourceName).build();
  }

  public static Map<String, String> getResourceConfigsFor(String clusterName, String resourceName, HelixAdmin admin) {
    final HelixConfigScope scope = getResourceScopeFor(clusterName, resourceName);
    final List<String> keys = admin.getConfigKeys(scope);
    return admin.getConfig(scope, keys);
  }

  public static void updateResourceConfigsFor(Map<String, String> newConfigs, String resourceName, String clusterName,
      HelixAdmin admin) {
    final HelixConfigScope scope = getResourceScopeFor(clusterName, resourceName);
    admin.setConfig(scope, newConfigs);
  }

  public static void deleteResourcePropertyFromHelix(HelixAdmin admin, String clusterName, String resourceName,
      String configKey) {
    final List<String> keys = new ArrayList<String>();
    keys.add(configKey);

    final HelixConfigScope scope = getResourceScopeFor(clusterName, resourceName);
    admin.removeConfig(scope, keys);
  }

  public static IdealState getTableIdealState(HelixManager manager, String resourceName) {
    final HelixDataAccessor accessor = manager.getHelixDataAccessor();
    final Builder builder = accessor.keyBuilder();
    return accessor.getProperty(builder.idealStates(resourceName));
  }

  public static ExternalView getExternalViewForResource(HelixAdmin admin, String clusterName, String resourceName) {
    return admin.getResourceExternalView(clusterName, resourceName);
  }

  public static Map<String, String> getBrokerResourceConfig(HelixAdmin admin, String clusterName) {
    return HelixHelper.getResourceConfigsFor(clusterName, BROKER_RESOURCE, admin);
  }

  public static void updateBrokerConfig(Map<String, String> brokerResourceConfig, HelixAdmin admin, String clusterName) {
    HelixHelper.updateResourceConfigsFor(brokerResourceConfig, BROKER_RESOURCE, clusterName, admin);
  }

  public static IdealState getBrokerIdealStates(HelixAdmin admin, String clusterName) {
    return admin.getResourceIdealState(clusterName, BROKER_RESOURCE);
  }

  /**
   * Remove a resource (offline/realtime table) from the Broker's ideal state.
   *
   * @param helixManager The HelixManager object for accessing helix cluster.
   * @param resourceTag Name of the resource that needs to be removed from Broker ideal state.
   */
  public static void removeResourceFromBrokerIdealState(HelixManager helixManager, final String resourceTag) {
    Function<IdealState, IdealState> updater = new Function<IdealState, IdealState>() {
      @Override
      public IdealState apply(IdealState idealState) {
        if (idealState.getPartitionSet().contains(resourceTag)) {
          idealState.getPartitionSet().remove(resourceTag);
          return idealState;
        } else {
          return null;
        }
      }
    };

    // Removing partitions from ideal state
    LOGGER.info("Trying to remove resource from idealstats");
    HelixHelper.updateIdealState(helixManager, CommonConstants.Helix.BROKER_RESOURCE_INSTANCE, updater,
        DEFAULT_RETRY_POLICY);
  }

  /**
   * Returns the set of online instances from external view.
   *
   * @param resourceExternalView External view for the resource.
   * @return Set<String> of online instances in the external view for the resource.
   */
  public static Set<String> getOnlineInstanceFromExternalView(ExternalView resourceExternalView) {
    Set<String> instanceSet = new HashSet<String>();
    if (resourceExternalView != null) {
      for (String partition : resourceExternalView.getPartitionSet()) {
        Map<String, String> stateMap = resourceExternalView.getStateMap(partition);
        for (String instance : stateMap.keySet()) {
          if (stateMap.get(instance).equalsIgnoreCase(ONLINE)) {
            instanceSet.add(instance);
          }
        }
      }
    }
    return instanceSet;
  }

  /**
   * Get a set of offline instance from the external view of the resource.
   *
   * @param resourceExternalView External view of the resource
   * @return Set of string instance names of the offline instances in the external view.
   */
  public static Set<String> getOfflineInstanceFromExternalView(ExternalView resourceExternalView) {
    Set<String> instanceSet = new HashSet<String>();
    for (String partition : resourceExternalView.getPartitionSet()) {
      Map<String, String> stateMap = resourceExternalView.getStateMap(partition);
      for (String instance : stateMap.keySet()) {
        if (stateMap.get(instance).equalsIgnoreCase(OFFLINE)) {
          instanceSet.add(instance);
        }
      }
    }
    return instanceSet;
  }

  /**
   * Remove the segment from the cluster.
   *
   * @param helixManager The HelixManager object to access the helix cluster.
   * @param tableName Name of the table to which the new segment is to be added.
   * @param segmentName Name of the new segment to be added
   */
  public static void removeSegmentFromIdealState(HelixManager helixManager, String tableName, final String segmentName) {
    Function<IdealState, IdealState> updater = new Function<IdealState, IdealState>() {
      @Override
      public IdealState apply(IdealState idealState) {
        final Set<String> currentInstanceSet = idealState.getInstanceSet(segmentName);

        if (!currentInstanceSet.isEmpty() && idealState.getPartitionSet().contains(segmentName)) {
          idealState.getPartitionSet().remove(segmentName);
          return idealState;
        } else {
          return null;
        }
      }
    };

    updateIdealState(helixManager, tableName, updater, DEFAULT_RETRY_POLICY);
  }

  /**
   * Add the new specified segment to the idealState of the specified table in the specified cluster.
   *
   * @param helixManager The HelixManager object to access the helix cluster.
   * @param tableName Name of the table to which the new segment is to be added.
   * @param segmentName Name of the new segment to be added
   * @param getInstancesForSegment Callable returning list of instances where the segment should be uploaded.
   */
  public static void addSegmentToIdealState(HelixManager helixManager, String tableName, final String segmentName,
      final Callable<List<String>> getInstancesForSegment) {

    Function<IdealState, IdealState> updater = new Function<IdealState, IdealState>() {
      @Override
      public IdealState apply(IdealState idealState) {
        List<String> targetInstances = null;
        try {
          targetInstances = getInstancesForSegment.call();
        } catch (Exception e) {
          LOGGER.error("Unable to get new instances for segment uploading.");
          return null;
        }

        for (final String instance : targetInstances) {
          idealState.setPartitionState(segmentName, instance, ONLINE);
        }

        idealState.setNumPartitions(idealState.getNumPartitions() + 1);
        return idealState;
      }
    };

    updateIdealState(helixManager, tableName, updater, DEFAULT_RETRY_POLICY);
  }
}


text: default_app_config = 'inventario.apps.InventarioConfig'


text:
using Mandrill.Model;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Mandrill
{
    internal partial class MandrillWhitelistsApi : IMandrillWhitelistsApi
    {
        public MandrillWhitelistsApi(MandrillApi mandrillApi)
        {
            MandrillApi = mandrillApi;
        }

        public MandrillApi MandrillApi { get; private set; }

        public Task<IList<MandrillWhitelistInfo>> ListAsync(string email)
        {
            return MandrillApi.PostAsync<MandrillWhitelistRequest, IList<MandrillWhitelistInfo>>("whitelists/list.json",
                new MandrillWhitelistRequest
                {
                    Email = email
                });
        }

        public Task<MandrillWhitelistInfo> AddAsync(string email)
        {
            return MandrillApi.PostAsync<MandrillWhitelistRequest, MandrillWhitelistInfo>("whitelists/add.json",
                new MandrillWhitelistRequest
                {
                    Email = email
                });
        }

        public Task<MandrillWhitelistInfo> DeleteAsync(string email)
        {
            return MandrillApi.PostAsync<MandrillWhitelistRequest, MandrillWhitelistInfo>("whitelists/delete.json",
                new MandrillWhitelistRequest
                {
                    Email = email
                });
        }
    }

#if !DNXCORE50
    internal partial class MandrillWhitelistsApi
    {
        public IList<MandrillWhitelistInfo> List(string email)
        {
            return MandrillApi.Post<MandrillWhitelistRequest, IList<MandrillWhitelistInfo>>("whitelists/list.json",
                new MandrillWhitelistRequest
                {
                    Email = email
                });
        }

        public MandrillWhitelistInfo Add(string email)
        {
            return MandrillApi.Post<MandrillWhitelistRequest, MandrillWhitelistInfo>("whitelists/add.json",
                new MandrillWhitelistRequest
                {
                    Email = email
                });
        }

        public MandrillWhitelistInfo Delete(string email)
        {
            return MandrillApi.Post<MandrillWhitelistRequest, MandrillWhitelistInfo>("whitelists/delete.json",
                new MandrillWhitelistRequest
                {
                    Email = email
                });
        }
    }
#endif
}


text:
<?php

namespace Emmanix2002\Moneywave\Tests\Enum;

use Emmanix2002\Moneywave\Enum\Banks;
use PHPUnit\Framework\TestCase;

class BanksTest extends TestCase
{
    public function testGetSupportedBanks()
    {
        $banks = Banks::getSupportedBanks();
        $this->assertNotEmpty($banks);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string  name="mwm_should_be_installed">Offline maps are required to proceed. We have partnered with MAPS.ME to provide you with offline maps of the entire world.\nTo continue please download the app:</string>
    <string  name="down_pro">Download MAPS.ME</string>
    <string  name="url_pro">http://maps.me/get</string>
</resources>


text:
@class EditViewViewController;

@protocol EditViewDelegate <NSObject>

@optional
- (void)saveChangeContact:(EditViewViewController *)evVc contact:(Contact *)contact;

@end
@interface EditViewViewController : UIViewController

@property (nonatomic, strong) Contact *contact;

@property (nonatomic, strong) id<EditViewDelegate> delegate;

@end


text:
'use strict';

var authorize = require('../lib/authorize.js'),
    expect = require('chai').expect;

describe('authorize', function() {
  describe('#authorize', function() {
    var roles = [
        {role: 'admin'},
        {role: 'moderator'}
      ],
      test = function(roles, req, done) {
        return function() {
          authorize(roles)(req, {}, done);
        };
      };

    it('should throw when user is undefined', function() {
      expect(test(roles, {})).to.throw('User not authenticated');
    });

    it('should throw when user does not have role', function() {
      var req = {
        user: {}
      };

      expect(test(roles, req)).to.throw('User does not have a role');
    });

    it('should not authorize when user is not a member of specified roles', function() {
      var req = {
        user: {
          role: 'unknown'
        }
      };

      expect(test(roles, req)).to.throw('User not authorized');
    });

    it('should authorize when user is a member of specified roles', function(done) {
      var req = {
        user: {
          role: 'admin'
        }
      };

      test(roles, req, done)();
    });
  });
});


text:
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public configs: any;

  constructor(private http: Http, private router: Router) {
    this.http.get("/api/config/mongo").subscribe(data => this.configs = data.json());
  }

  public select(app, label, profile){
    this.router.navigate(['config', [app, label, profile].join('-')])
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<feature
      id="it.polimi.dice.lwdg.loadDemo.feature"
      label="DIDE-LWDG Load Demo"
      version="1.0.0.qualifier">

   <description url="http://www.example.com/description">
      This feature add a DICE-LWDG menu to download DDSM models and metamodels
   </description>

   <copyright url="http://www.example.com/copyright">
      [Enter Copyright Description here.]
   </copyright>

   <license url="http://www.example.com/license">
      [Enter License Description here.]
   </license>

   <plugin
         id="it.polimi.dice.lwdg.loadDemo"
         download-size="0"
         install-size="0"
         version="0.0.0"
         unpack="false"/>

</feature>


text: write your post here.use markup buttons to style your post.


text:
package com.cloudera.sqoop.mapreduce;

/**
 * @deprecated Moving to use org.apache.sqoop namespace.
 */
public class TextExportMapper
    extends org.apache.sqoop.mapreduce.TextExportMapper {
}


text:
<!DOCTYPE html>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>How the world is Learning How to Learn</title>

      Loading...


text:
module ActiveMerchant
  VERSION = "1.56.0"
end


text:
package org.springframework.retry.policy;

import org.springframework.retry.RetryContext;
import org.springframework.retry.RetryPolicy;

/**
 * A {@link RetryPolicy} that always permits a retry. Can also be used as a base
 * class for other policies, e.g. for test purposes as a stub.
 *
 * @author Dave Syer
 *
 */
public class AlwaysRetryPolicy extends NeverRetryPolicy {

	/**
	 * Always returns true.
	 *
	 * @see org.springframework.retry.RetryPolicy#canRetry(org.springframework.retry.RetryContext)
	 */
	public boolean canRetry(RetryContext context) {
		return true;
	}

}


text:
using abremir.AllMyBricks.Data.Enumerations;
using abremir.AllMyBricks.Data.Interfaces;
using abremir.AllMyBricks.DatabaseSeeder.Configuration;
using abremir.AllMyBricks.DatabaseSeeder.Services;
using abremir.AllMyBricks.DataSynchronizer.Interfaces;
using LightInject;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace abremir.AllMyBricks.DatabaseSeeder
{
    public static class NonInteractiveConsole
    {
        public static async Task Run(IList<string> synchronizationContext, bool compress, bool uncompress, bool encrypted)
        {
            if (!synchronizationContext.Contains(DatabaseSeederConstants.DatasetValueNone))
            {
                if (synchronizationContext.Contains(DatabaseSeederConstants.DatasetValueSets)
                    || synchronizationContext.Contains(DatabaseSeederConstants.DatasetValueAll))
                {
                    await IoC.IoCContainer.GetInstance<ISetSynchronizationService>().SynchronizeAllSets().ConfigureAwait(false);
                }

                if (synchronizationContext.Contains(DatabaseSeederConstants.DatasetValuePrimaryUsers)
                    || synchronizationContext.Contains(DatabaseSeederConstants.DatasetValueAll))
                {
                    var userRepository = IoC.IoCContainer.GetInstance<IBricksetUserRepository>();

                    foreach (var primaryUser in Settings.BricksetPrimaryUsers)
                    {
                        if (userRepository.Get(primaryUser.Key) is null)
                        {
                            userRepository.Add(BricksetUserType.Primary, primaryUser.Key);
                        }
                    }

                    await IoC.IoCContainer.GetInstance<IUserSynchronizationService>().SynchronizeBricksetPrimaryUsersSets().ConfigureAwait(false);
                }

                if (synchronizationContext.Contains(DatabaseSeederConstants.DatasetValueFriends)
                    || synchronizationContext.Contains(DatabaseSeederConstants.DatasetValueAll))
                {
                    await IoC.IoCContainer.GetInstance<IUserSynchronizationService>().SynchronizeBricksetFriendsSets().ConfigureAwait(false);
                }

                IoC.IoCContainer.GetInstance<IAssetManagementService>().CompactAllMyBricksDatabase();
            }

            if (compress)
            {
                IoC.IoCContainer.GetInstance<IAssetManagementService>().CompressDatabaseFile(encrypted);
            }

            if (uncompress)
            {
                IoC.IoCContainer.GetInstance<IAssetManagementService>().UncompressDatabaseFile(encrypted);
            }
        }
    }
}


text:
class IEvent
{
	public:
		static const UInt32 kDefaultTimeout = 1000 * 10;

		IEvent();
		~IEvent();

		bool	Block(void);
		bool	UnBlock(void);
		bool	Wait(UInt32 timeout = kDefaultTimeout);

		bool	IsBlocked(void)	{ return blockCount.Get() > 0; }

	private:
		HANDLE				theEvent;
		IInterlockedLong	blockCount;
};

class IAutoEvent
{
	public:
		static const UInt32 kDefaultTimeout = 1000 * 10;

		IAutoEvent()	{ ASSERT(theEvent = CreateEvent(NULL, false, true, NULL)); }
		~IAutoEvent()	{ CloseHandle(theEvent); }

		void	Pulse(void)	{ PulseEvent(theEvent); }
		bool	Wait(UInt32 timeout = kDefaultTimeout);

	private:
		HANDLE	theEvent;
};


text:
package org.bbsync.webservice.client.course;

import org.bbsync.webservice.client.generated.CourseWSStub.CartridgeVO;
import org.bbsync.webservice.client.generated.CourseWSStub.VersionVO;
import org.bbsync.webservice.client.proxytool.CourseProxyTool;

import java.io.Serializable;

public class BbCartridge extends CourseProxyTool {
    private static final long serialVersionUID = 3333000000003333L;
    private CartridgeVO _cartridge_vo = null;

    ///////////////////////////////////////////////////////////////////////////
    //  Constructors  /////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    public BbCartridge() {
    	_cartridge_vo = new CartridgeVO();
    }

    private BbCartridge(CartridgeVO cartridge_vo) {
    	_cartridge_vo = cartridge_vo;
    }

    ///////////////////////////////////////////////////////////////////////////
    //  Required ClientWebService Methods  ////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////
    public Serializable persist() {
    	return super.saveCartridge(_cartridge_vo);
    }
    /**
	 * Gets a BbCartridge by its ID.  The Cartridge's ID field must be set.
	 * Use setUniqueId
	 * @return Returns a BbCartridge object if successful, else returns null.
	 */
    public Object retrieve() {
    	return getBbCartridge(_cartridge_vo.getId());
    }

    /**
	 * Deletes this Cartridge from the AS.  The Cartridge's ID field must be
	 * set. Use setUniqueID().
	 * @return Returns true if successful, else returns false.
	 */
    public boolean delete() {
    	String cartridge_id = deleteCartridge(_cartridge_vo.getId());
    	if(cartridge_id==null || !cartridge_id.equals(_cartridge_vo.getId()))return false;
    	return true;
    }

    ///////////////////////////////////////////////////////////////////////////
    //  Implemented ProxyTool Methods  ////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    public boolean initializeCourseWS() {
        return super.initializeCourseWS(true);

    }

    public Long getServerVersion() {
        return super.getServerVersion(new VersionVO()).getVersion();
    }

    public String saveCartridge(BbCartridge bb_cartridge){
    	return super.saveCartridge(bb_cartridge.getVO());
    }

    public String deleteCartridge(String cartridge_id) {
    	return super.deleteCartridge(cartridge_id);
    }

    /**
     * Return a Cartridge object associated with the given ID.
     *
     * @param cartridge_id - the Cartridge ID
     * @return Returns a BbCartridge.
     */
    public BbCartridge getBbCartridge(String cartridge_id){
    	CartridgeVO cartridge_vo = super.getCartridge(cartridge_id);
    	if(cartridge_vo==null)return null;
    	return new BbCartridge(cartridge_vo);
    }

    ///////////////////////////////////////////////////////////////////////////
    //  Local Methods  ////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////
    public String getDescription(){
    	return _cartridge_vo.getDescription();
    }

    public String[] getExpansionData(){
    	return _cartridge_vo.getExpansionData();
    }

    /**
     * Returns the LMS_ID of the Course Cartridge.
     * @return
     */
    public String getId(){
    	return _cartridge_vo.getId();
    }

    public String getIdentifier(){
    	return _cartridge_vo.getIdentifier();
    }

    public String getPublisherName(){
    	return _cartridge_vo.getPublisherName();
    }

    public String getTitle(){
    	return _cartridge_vo.getTitle();
    }

    /**
     * set cartridge description for this CartridgeVO
     * @param description
     */
    public void setDescription(String description){
    	_cartridge_vo.setDescription(description);
    }

    /**
     * Expansion data is currently ignored.
     * @param expansionData
     */
    public void setExpansionData(String[] expansion_data){
    	_cartridge_vo.setExpansionData(expansion_data);
    }

    /**
     * You should not try to 'make up' an id here - only use
     * the ids that you are given from another api call.
     *
     * @param id - the ID to set. This ID should be generated by Blackboard, in
	 *             the form "_nnn_1" where nnn is an integer.
     */
    public void setId(String id){
    	_cartridge_vo.setId(id);
    }

    /**
     * set cartridge identifier
     * @param identifier
     */
    public void setIdentifier(String identifier){
    	_cartridge_vo.setIdentifier(identifier);
    }

    /**
     * set publisher name for this CartridgeVO
     * @param publisherName
     */
    public void setPublisherName(String publisher_name){
    	_cartridge_vo.setPublisherName(publisher_name);
    }

    /**
     * set cartridge title for this CartridgeVO
     * @param title
     */
    public void setTitle(String title){
    	_cartridge_vo.setTitle(title);
    }

    private CartridgeVO getVO(){
    	return _cartridge_vo;
    }
}


text:
CREATE TABLE tpcds.store_sales (
    ss_sold_date_sk integer,
    ss_sold_time_sk integer,
    ss_item_sk int NOT NULL,
    ss_customer_sk integer,
    ss_cdemo_sk integer,
    ss_hdemo_sk integer,
    ss_addr_sk integer,
    ss_store_sk integer,
    ss_promo_sk integer,
    ss_ticket_number bigint NOT NULL,
    ss_quantity integer,
    ss_wholesale_cost numeric(7,2),
    ss_list_price numeric(7,2),
    ss_sales_price numeric(7,2),
    ss_ext_discount_amt numeric(7,2),
    ss_ext_sales_price numeric(7,2),
    ss_ext_wholesale_cost numeric(7,2),
    ss_ext_list_price numeric(7,2),
    ss_ext_tax numeric(7,2),
    ss_coupon_amt numeric(7,2),
    ss_net_paid numeric(7,2),
    ss_net_paid_inc_tax numeric(7,2),
    ss_net_profit numeric(7,2)
)
WITH (:LARGE_STORAGE)
:DISTRIBUTED_BY
PARTITION BY RANGE (ss_sold_date_sk)
(start(2450815) INCLUSIVE end(2453005) INCLUSIVE every (10),
default partition others);


text:
class Administrator::UserController  < AdminController

  layout 'left_menu'

  before_filter :set_layout_variables

  before_filter :restrict_to_admins

  require 'csv'

  def index

    @page_title = I18n.t("web_users")

    @user_search_string = params[:user_search_string] || ''
    search_string_parameter = '%' + @user_search_string + '%'
    @start_date = params[:start_date] || "2008-02-28"
    @end_date = params[:end_date] || Date.today.to_s(:db)
    @blank_dates = EOLConvert.to_boolean(params[:blank_dates])
    @joined_mailing_list = EOLConvert.to_boolean(params[:joined_mailing_list])
    export = params[:export]

    begin
      @start_date_db = (Date.parse(@start_date)).to_s(:db)
      @start_date = @start_date_db # Reformat the string we'll show on the page, too, 'cause this is nicer.
      @end_date_db = (Date.parse(@end_date)+1).to_s(:db)
      @end_date = @end_date_db
    rescue
    end

    blank_date_condition = ' OR (created_at is null)' unless @blank_dates
    joined_mailing_list_condition = ' AND (mailing_list = 1)' unless !@joined_mailing_list

    condition = "( ( (created_at>=? AND created_at<=?) #{blank_date_condition}) #{joined_mailing_list_condition} )
    AND (id=? OR email like ? OR username like ? OR given_name like ? OR identity_url like ? OR family_name like ? OR username like ?)
    #{joined_mailing_list_condition} "

    if export
      @users = User.find(:all,
        :conditions => [condition,
        @start_date_db,
        @end_date_db,
        @user_search_string,
        search_string_parameter,
         search_string_parameter,
         search_string_parameter,
         search_string_parameter,
         search_string_parameter,
         search_string_parameter],
        :order => 'created_at desc')
      report = StringIO.new
      CSV::Writer.generate(report, ',') do |title|
          title << ['Id', 'Username', 'Name', 'Email', 'Registered Date', 'Mailings?']
          @users.each do |u|
            created_at = ''
            created_at = u.created_at.strftime("%m/%d/%y - %I:%M %p %Z") unless u.created_at.blank?
            title << [u.id, u.username, u.full_name, u.email, created_at, u.mailing_list]
          end
       end
       report.rewind
       send_data(report.read, :type => 'text/csv; charset=iso-8859-1; header=present', :filename => 'EOL_users_report_' + Time.now.strftime("%m_%d_%Y-%I%M%p") + '.csv', :disposition => 'attachment', :encoding => 'utf8')
       return false
    end

    @users = User.paginate(
      :conditions => [condition,
      @start_date_db,
      @end_date_db,
      @user_search_string,
      search_string_parameter,
       search_string_parameter,
       search_string_parameter,
       search_string_parameter,
       search_string_parameter,
       search_string_parameter],
      :order => 'created_at desc', :page => params[:page])

    @user_count = User.count(
      :conditions => [condition,
        @start_date_db,
        @end_date_db,
      @user_search_string,
      search_string_parameter,
      search_string_parameter,
      search_string_parameter,
      search_string_parameter,
      search_string_parameter,
      search_string_parameter])

  end

  def edit
    store_location(referred_url) if request.get?
    @user = User.find(params[:id])
    @page_title = I18n.t("edit_username", :username => @user.username)
  end

  def new
    @page_title = I18n.t("new_user")
    store_location(referred_url) if request.get?
    @user = User.create_new
  end

  def create

    @user = User.create_new(params[:user])
    @message = params[:message]

    Notifier.deliver_user_message(@user.full_name, @user.email, @message) unless @message.blank?

    @user.password = @user.entered_password

    if @user.save
      if EOLConvert.to_boolean(params[:user][:curator_approved])
        @user.grant_curator(:full, :by => current_user)
      end
      flash[:notice] = I18n.t("the_new_user_was_created")
      redirect_back_or_default(url_for(:action => 'index'))
    else
      render :action => 'new'
    end

  end

  def update

   @user = User.find(params[:id])
   was_curator = @user.full_curator? || @user.master_curator?
   @message = params[:message]

   Notifier.deliver_user_message(@user.full_name, @user.email, @message) unless @message.blank?

   user_params = params[:user]

   unless user_params[:entered_password].blank? && user_params[:entered_password_confirmation].blank?
      if user_params[:entered_password].length < 4 || user_params[:entered_password].length > 16
         @user.errors.add_to_base( I18n.t(:password_must_be_4to16_characters) )
         render :action => 'edit'
         return
     end
     @user.password = user_params[:entered_password]
   end

   if @user.update_attributes(user_params)
      if params[:curator_denied]
        @user.revoke_curator
      else
        if EOLConvert.to_boolean(params[:user][:curator_approved]) && !was_curator
          @user.grant_curator(:full, :by => current_user)
        end
      end
      flash[:notice] = I18n.t("the_user_was_updated")
      redirect_back_or_default(url_for(:action => 'index'))
    else
      render :action => 'edit'
    end
  end

  def destroy
    (redirect_to referred_url ;return) unless request.method == :delete
    user = User.find(params[:id])
    user.destroy
    flash[:notice] = I18n.t("admin_user_delete_successful_notice")
    redirect_to referred_url
  end

  # TODO - why are these here and not in curator?
  def grant_curator
    @user = User.find(params[:id])
    @user.grant_curator(:full, :by => current_user)
    respond_to do |format|
      format.html {
        redirect_to '/administrator/curator'
      }
      format.js {
        render :partial => 'administrator/curator/user_row', :locals => {:column_class => params[:class] || 'odd', :user => @user}
      }
    end
  end
  def revoke_curator
    @user = User.find(params[:id])
    @user.revoke_curator
    respond_to do |format|
      format.html {
        redirect_to '/administrator/curator'
      }
      format.js {
        render :partial => 'administrator/curator/user_row', :locals => {:column_class => params[:class] || 'even', :user => @user}
      }
    end
  end

  def clear_curatorship
    user = User.find(params[:id])
    user.revoke_curator
    user.save!
  end

  def login_as_user
      user = User.find_by_id(params[:id])
      if !user.blank?
        reset_session
        set_current_user(user)
        flash[:notice] = I18n.t("you_have_been_logged_in_as_username", :username => user.username)
        redirect_to root_url
      end
      return
  end

  def view_user_activity
    @page_title = I18n.t(:user_activity_page_title)
    @user_id = params[:user_id] || ''
    @user_list = User.users_with_activity_log
    @activity_id = params[:activity_id] || 'All'
    @translated_activity_list = TranslatedActivity.all.sort_by {|a| a.name }
    page = params[:page] || 1
    @activities = UserActivityLog.user_activity(@user_id, @activity_id, page)
  end

  def view_common_activities
    @page_title = I18n.t(:common_user_activity_page_title)
    page = params[:page] || 1
    @activities = UserActivityLog.most_common_activities(page)
  end

  def view_common_combinations
    start = Time.now
    activity_id = params[:activity_id]
    @page_title = I18n.t(:common_user_activity_page_title)
    @activities = UserActivityLog.most_common_combinations(activity_id)
    if(activity_id)
      @activity = Activity.find(activity_id)
      @activities.delete_if {|value1,value2| !value1.include? @activity.name}
    end
    b = DateTime.now
    time_elapsed = (Time.now - start)/60
    time_elapsed = '%.2f' % time_elapsed
    @time_elapsed = time_elapsed.to_s + " mins."
  end

private

  def set_layout_variables
    @page_title = $ADMIN_CONSOLE_TITLE
    @navigation_partial = '/admin/navigation'
  end

end


text:
package org.testcontainers.containers;

import org.junit.Test;
import org.rnorth.ducttape.TimeoutException;
import org.testcontainers.containers.wait.strategy.Wait;

import java.io.File;
import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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

public class DockerComposeContainerWithServicesTest {

    public static final File SIMPLE_COMPOSE_FILE = new File(
        "src/test/resources/compose-scaling-multiple-containers.yml"
    );

    public static final File COMPOSE_FILE_WITH_INLINE_SCALE = new File(
        "src/test/resources/compose-with-inline-scale-test.yml"
    );

    @Test
    public void testDesiredSubsetOfServicesAreStarted() {
        try (
            DockerComposeContainer<?> compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE).withServices("redis")
        ) {
            compose.start();

            verifyStartedContainers(compose, "redis_1");
        }
    }

    @Test
    public void testDesiredSubsetOfScaledServicesAreStarted() {
        try (
            DockerComposeContainer<?> compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE)
                .withScaledService("redis", 2)
        ) {
            compose.start();

            verifyStartedContainers(compose, "redis_1", "redis_2");
        }
    }

    @Test
    public void testDesiredSubsetOfSpecifiedAndScaledServicesAreStarted() {
        try (
            DockerComposeContainer<?> compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE)
                .withServices("redis")
                .withScaledService("redis", 2)
        ) {
            compose.start();

            verifyStartedContainers(compose, "redis_1", "redis_2");
        }
    }

    @Test
    public void testDesiredSubsetOfSpecifiedOrScaledServicesAreStarted() {
        try (
            DockerComposeContainer<?> compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE)
                .withServices("other")
                .withScaledService("redis", 2)
        ) {
            compose.start();

            verifyStartedContainers(compose, "redis_1", "redis_2", "other_1");
        }
    }

    @Test
    public void testAllServicesAreStartedIfNotSpecified() {
        try (DockerComposeContainer<?> compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE)) {
            compose.start();

            verifyStartedContainers(compose, "redis_1", "other_1");
        }
    }

    @Test
    public void testScaleInComposeFileIsRespected() {
        try (DockerComposeContainer<?> compose = new DockerComposeContainer<>(COMPOSE_FILE_WITH_INLINE_SCALE)) {
            compose.start();

            // the compose file includes `scale: 3` for the redis container
            verifyStartedContainers(compose, "redis_1", "redis_2", "redis_3");
        }
    }

    @Test
    public void testStartupTimeoutSetsTheHighestTimeout() {
        assertThat(
            catchThrowable(() -> {
                try (
                    DockerComposeContainer<?> compose = new DockerComposeContainer<>(SIMPLE_COMPOSE_FILE)
                        .withServices("redis")
                        .withStartupTimeout(Duration.ofMillis(1))
                        .withExposedService(
                            "redis",
                            80,
                            Wait.forListeningPort().withStartupTimeout(Duration.ofMinutes(1))
                        );
                ) {
                    compose.start();
                }
            })
        )
            .as("We expect a timeout from the startup timeout")
            .isInstanceOf(TimeoutException.class);
    }

    private void verifyStartedContainers(final DockerComposeContainer<?> compose, final String... names) {
        final List<String> containerNames = compose
            .listChildContainers()
            .stream()
            .flatMap(container -> Stream.of(container.getNames()))
            .collect(Collectors.toList());

        assertThat(containerNames)
            .as("number of running services of docker-compose is the same as length of listOfServices")
            .hasSize(names.length);

        for (final String expectedName : names) {
            final long matches = containerNames.stream().filter(foundName -> foundName.endsWith(expectedName)).count();

            assertThat(matches)
                .as("container with name starting '" + expectedName + "' should be running")
                .isEqualTo(1L);
        }
    }
}


text:
AUTHFAILURE = 'AuthFailure'

# 操作失败。
FAILEDOPERATION = 'FailedOperation'

# 尚未开通CLS日志服务,请开前往开通。
FAILEDOPERATION_CLSSERVICENOTACTIVED = 'FailedOperation.ClsServiceNotActived'

# 名称重复。
FAILEDOPERATION_DUPLICATENAME = 'FailedOperation.DuplicateName'

# 操作不允许。
FAILEDOPERATION_NOTALLOW = 'FailedOperation.NotAllow'

# 存储库有绑定的实例,请先删除绑定的实例。
FAILEDOPERATION_REPOBINDBYINSTANCE = 'FailedOperation.RepoBindByInstance'

# 内部错误。
INTERNALERROR = 'InternalError'

# 参数错误。
INVALIDPARAMETER = 'InvalidParameter'

# 参数取值错误。
INVALIDPARAMETERVALUE = 'InvalidParameterValue'

# 名称不合法。
INVALIDPARAMETERVALUE_BADNAME = 'InvalidParameterValue.BadName'

# 请设置日志集、日志主题ID。
INVALIDPARAMETERVALUE_CLSCONFIGREQUIRED = 'InvalidParameterValue.ClsConfigRequired'

# 存储库不存在。
INVALIDPARAMETERVALUE_CODEREPONOTFOUND = 'InvalidParameterValue.CodeRepoNotFound'

# 实例名称冲突,请更换名称后重试。
INVALIDPARAMETERVALUE_DUPLICATENAME = 'InvalidParameterValue.DuplicateName'

# 文件系统作为训练数据源时需要指定VPC配置。
INVALIDPARAMETERVALUE_FILESYSTEMNEEDVPCCONFIGSUPPORT = 'InvalidParameterValue.FileSystemNeedVpcConfigSupport'

# 文件系统超过限额,最大为2。
INVALIDPARAMETERVALUE_FILESYSTEMNUMLIMIT = 'InvalidParameterValue.FileSystemNumLimit'

# 文件系统的vpc必须和任务的vpc相同。
INVALIDPARAMETERVALUE_FILESYSTEMVPCNOTMATCH = 'InvalidParameterValue.FileSystemVpcNotMatch'

# 训练框架对应的版本不支持,请阅读文档查看TIONE目前支持的框架和版本。
INVALIDPARAMETERVALUE_FRAMEWORKVERSIONNOTSUPPORT = 'InvalidParameterValue.FrameworkVersionNotSupport'

# 训练任务镜像不存在。
INVALIDPARAMETERVALUE_IMAGENOTFOUND = 'InvalidParameterValue.ImageNotFound'

# 无效的资源类型,支持的资源类型参考:https://cloud.tencent.com/document/product/851/41239。
INVALIDPARAMETERVALUE_INVALIDINSTANCETYPE = 'InvalidParameterValue.InvalidInstanceType'

# 训练任务镜像名称无效。
INVALIDPARAMETERVALUE_INVALIDTRAININGIMAGENAME = 'InvalidParameterValue.InvalidTrainingImageName'

# KMS密钥不存在。
INVALIDPARAMETERVALUE_KMSKEYNOTFOUND = 'InvalidParameterValue.KmsKeyNotFound'

# 未找到当前日志集。
INVALIDPARAMETERVALUE_LOGSETNOTFOUND = 'InvalidParameterValue.LogSetNotFound'

# MPI分布式任务参数ti_mpi_num_of_processes_per_host不能超过GPU卡数。
INVALIDPARAMETERVALUE_MPIPROCESSESPERHOSTTOOMUCH = 'InvalidParameterValue.MpiProcessesPerHostTooMuch'

# 存储库地址无效。
INVALIDPARAMETERVALUE_REPOSITORYURLINVALID = 'InvalidParameterValue.RepositoryUrlInvalid'

# 子网不存在。
INVALIDPARAMETERVALUE_SUBNETNOTFOUND = 'InvalidParameterValue.SubnetNotFound'

# 未找到当前日志主题。
INVALIDPARAMETERVALUE_TOPICNOTFOUND = 'InvalidParameterValue.TopicNotFound'

# 训练代码不存在或无效。
INVALIDPARAMETERVALUE_TRAINCODENOTFOUND = 'InvalidParameterValue.TrainCodeNotFound'

# Notebook卷大小只能增加,如需减小容量请重新创建实例。
INVALIDPARAMETERVALUE_VOLUMESHRINKNOTALLOW = 'InvalidParameterValue.VolumeShrinkNotAllow'

# 超过配额限制。
LIMITEXCEEDED = 'LimitExceeded'

# 资源不足。
RESOURCEINSUFFICIENT = 'ResourceInsufficient'

# 资源不存在。
RESOURCENOTFOUND = 'ResourceNotFound'

# 资源不可用。
RESOURCEUNAVAILABLE = 'ResourceUnavailable'

# 未开通该地域服务,请先开通。
RESOURCEUNAVAILABLE_BILLNOTACTIVATED = 'ResourceUnavailable.BillNotActivated'

# 实例未成功启动。
RESOURCEUNAVAILABLE_NOTALIVE = 'ResourceUnavailable.NotAlive'

# 未授权操作。
UNAUTHORIZEDOPERATION = 'UnauthorizedOperation'