text:
package com.ltsllc.miranda.mina;

import com.google.gson.Gson;
import com.ltsllc.miranda.node.networkMessages.WireMessage;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import java.lang.reflect.Type;

/**
 * Created by Clark on 3/10/2017.
 */
public class MinaHandler extends IoHandlerAdapter {
    private static Gson ourGson = new Gson();
    private static Logger logger = Logger.getLogger(MinaHandler.class);

    private IoSession session;
    private MinaHandle minaHandle;

    public IoSession getSession() {
        return session;
    }

    public void setSession(IoSession session) {
        this.session = session;
    }

    public MinaHandle getMinaHandle() {
        return minaHandle;
    }

    public void setMinaHandle(MinaHandle minaHandle) {
        this.minaHandle = minaHandle;
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        logger.info("Got connection from " + session.getRemoteAddress());
        this.session = session;
    }

    /**
     * Called when a new message is received from the network.
     *

     *

     * The message is expected to be a JSON string for an object that subclasses
     * the WireMessage class.
     *

     *
     * @param session The IoSession the message was received from
     * @param message The message received
     * @throws Exception The method rethrows ClassNotFoundException if a class
     *                   that matches the className attribute of the message.
     */
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        String json = message.toString();

        logger.info("Receieved " + json);

        WireMessage pass1 = ourGson.fromJson(json, WireMessage.class);
        Type type = getClass().forName(pass1.getClassName());
        WireMessage wireMessage = ourGson.fromJson(json, type);

        getMinaHandle().deliver(wireMessage);
    }

    public void close() {
        if (null != getSession()) {
            getSession().closeNow();
        }
    }

    public void sendOnWire(WireMessage wireMessage) {
        String json = ourGson.toJson(wireMessage);
        logger.info("Sending " + json);
        getSession().write(json);
    }
}


text:
function perplexFormResource($http) {
    var apiRoot = "backoffice/api/PerplexUmbracoForm/";

    return {
        copyByGuid: function (id) {
            return $http.post(apiRoot + "CopyByGuid?guid=" + id);
        },

		createFolder: function(parentId, name) {
			return $http.post(apiRoot + "CreateFolder?parentId=" + parentId + "&name=" + name);
		},

		moveForm: function (formId, folderId) {
				return $http.post(apiRoot + "MoveForm?formId=" + formId + "&folderId=" + folderId);
		},

		moveFolder: function (id, folderId) {
				return $http.post(apiRoot + "MoveFolder?id=" + id + "&folderId=" + folderId);
		},

		update: function(folder) {
				return $http.post(apiRoot + "Update", folder);
		},

		getFolder: function(folderId) {
				return $http.get(apiRoot + "GetFolder?folderId=" + folderId);
		},

		getRootFolder: function () {
				return $http.get(apiRoot + "GetRootFolder");
		},

		deleteFolder: function (folderId, deleteForms) {
				return $http.post(apiRoot + "DeleteFolder?folderId=" + folderId + "&deleteForms=" + deleteForms);
		},

		setFormStartNodes: function (userId, folderIds) {
				return $http.post(apiRoot + "SetFormStartNodes?userId=" + userId + "&folderIds=" + folderIds.join(','));
		},

		getFormStartNodes: function (userId) {
				return $http.get(apiRoot + "GetFormStartNodes?userId=" + userId);
		},

		getFormFolder: function (formId) {
				return $http.get(apiRoot + "GetFormFolder?formId=" + formId);
		},

		getFormsRootNode: function () {
				return $http.get(apiRoot + "GetFormsRootNode")
		},

		getConfiguration: function () {
		    return $http.get(apiRoot + "GetConfiguration");
		},

		getHideFieldTypes: function () {
		    return $http.get(apiRoot + "GetHideFieldTypes");
		},

		getFileUploadAllowedExtensions: function () {
		    return $http.get(apiRoot + "GetFileUploadAllowedExtensions");
		},

		getImageUploadAllowedExtensions: function () {
		    return $http.get(apiRoot + "GetImageUploadAllowedExtensions");
		},
    };
}

angular.module('umbraco.resources').factory('perplexFormResource', perplexFormResource);

redpajama_set_name: RedPajamaGithub


text:
package com.google.android.exoplayer2.demo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.DefaultRenderersFactory;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Player.EventListener;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.drm.DefaultDrmSessionManager;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.FrameworkMediaCrypto;
import com.google.android.exoplayer2.drm.FrameworkMediaDrm;
import com.google.android.exoplayer2.drm.HttpMediaDrmCallback;
import com.google.android.exoplayer2.drm.UnsupportedDrmException;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer.DecoderInitializationException;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil.DecoderQueryException;
import com.google.android.exoplayer2.source.BehindLiveWindowException;
import com.google.android.exoplayer2.source.ConcatenatingMediaSource;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource;
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.MappingTrackSelector.MappedTrackInfo;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.DebugTextViewHelper;
import com.google.android.exoplayer2.ui.PlaybackControlView;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.HttpDataSource;
import com.google.android.exoplayer2.util.Util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.UUID;

/**
 * An activity that plays media using {@link SimpleExoPlayer}.
 */
public class PlayerActivity extends Activity implements OnClickListener, EventListener,
    PlaybackControlView.VisibilityListener {

  public static final String DRM_SCHEME_UUID_EXTRA = "drm_scheme_uuid";
  public static final String DRM_LICENSE_URL = "drm_license_url";
  public static final String DRM_KEY_REQUEST_PROPERTIES = "drm_key_request_properties";
  public static final String PREFER_EXTENSION_DECODERS = "prefer_extension_decoders";

  public static final String ACTION_VIEW = "com.google.android.exoplayer.demo.action.VIEW";
  public static final String EXTENSION_EXTRA = "extension";

  public static final String ACTION_VIEW_LIST =
      "com.google.android.exoplayer.demo.action.VIEW_LIST";
  public static final String URI_LIST_EXTRA = "uri_list";
  public static final String EXTENSION_LIST_EXTRA = "extension_list";
  public static final String AD_TAG_URI_EXTRA = "ad_tag_uri";

  private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
  private static final CookieManager DEFAULT_COOKIE_MANAGER;
  static {
    DEFAULT_COOKIE_MANAGER = new CookieManager();
    DEFAULT_COOKIE_MANAGER.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
  }

  private Handler mainHandler;
  private Observer observer;
  private SimpleExoPlayerView simpleExoPlayerView;
  private LinearLayout debugRootView;
  private TextView debugTextView;
  private Button retryButton;

  private DataSource.Factory mediaDataSourceFactory;
  private SimpleExoPlayer player;
  private DefaultTrackSelector trackSelector;
  private TrackSelectionHelper trackSelectionHelper;
  private DebugTextViewHelper debugViewHelper;
  private boolean inErrorState;
  private TrackGroupArray lastSeenTrackGroupArray;

  private boolean shouldAutoPlay;
  private int resumeWindow;
  private long resumePosition;

  // Fields used only for ad playback. The ads loader is loaded via reflection.

  private Object imaAdsLoader; // com.google.android.exoplayer2.ext.ima.ImaAdsLoader
  private Uri loadedAdTagUri;
  private ViewGroup adOverlayViewGroup;
  public PlayerMonitor playerMonitor;

  // Activity lifecycle

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    shouldAutoPlay = true;
    clearResumePosition();
    mediaDataSourceFactory = buildDataSourceFactory(true);
    mainHandler = new Handler();
    if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
      CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
    }

    setContentView(R.layout.player_activity);
    View rootView = findViewById(R.id.root);
    rootView.setOnClickListener(this);
    debugRootView = (LinearLayout) findViewById(R.id.controls_root);
    debugTextView = (TextView) findViewById(R.id.debug_text_view);
    retryButton = (Button) findViewById(R.id.retry_button);
    retryButton.setOnClickListener(this);

    simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view);
    simpleExoPlayerView.setControllerVisibilityListener(this);
    simpleExoPlayerView.requestFocus();
  }

  @Override
  public void onNewIntent(Intent intent) {
    releasePlayer();
    shouldAutoPlay = true;
    clearResumePosition();
    setIntent(intent);
  }

  @Override
  public void onStart() {
    super.onStart();
    if (Util.SDK_INT > 23) {
      initializePlayer();
    }
  }

  @Override
  public void onResume() {
    super.onResume();
    if ((Util.SDK_INT <= 23 || player == null)) {
      initializePlayer();
    }
  }

  @Override
  public void onPause() {
    super.onPause();
    if (Util.SDK_INT <= 23) {
      releasePlayer();
    }
  }

  @Override
  public void onStop() {
    super.onStop();
    if (Util.SDK_INT > 23) {
      releasePlayer();
    }
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    releaseAdsLoader();
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
      @NonNull int[] grantResults) {
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
      initializePlayer();
    } else {
      showToast(R.string.storage_permission_denied);
      finish();
    }
  }

  // Activity input

  @Override
  public boolean dispatchKeyEvent(KeyEvent event) {
    // If the event was not handled then see if the player view can handle it.
    return super.dispatchKeyEvent(event) || simpleExoPlayerView.dispatchKeyEvent(event);
  }

  // OnClickListener methods

  @Override
  public void onClick(View view) {
    if (view == retryButton) {
      initializePlayer();
    } else if (view.getParent() == debugRootView) {
      MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
      if (mappedTrackInfo != null) {
        trackSelectionHelper.showSelectionDialog(this, ((Button) view).getText(),
            trackSelector.getCurrentMappedTrackInfo(), (int) view.getTag());
      }
    }
  }

  // PlaybackControlView.VisibilityListener implementation

  @Override
  public void onVisibilityChange(int visibility) {
    debugRootView.setVisibility(visibility);
  }

  // Internal methods

  private void initializePlayer() {
    Intent intent = getIntent();
    boolean needNewPlayer = player == null;
    if (needNewPlayer) {
      TrackSelection.Factory adaptiveTrackSelectionFactory =
          new AdaptiveTrackSelection.Factory(BANDWIDTH_METER);
      trackSelector = new DefaultTrackSelector(adaptiveTrackSelectionFactory);
      trackSelectionHelper = new TrackSelectionHelper(trackSelector, adaptiveTrackSelectionFactory);
      lastSeenTrackGroupArray = null;

      playerMonitor = new PlayerMonitor(getApplicationContext(),false, "Source", 5000 ,  "userAgent", "dev_id",
              "user_extid", "source", "dequeueingIntervalTime"

//              ,"onClosing", "offset"
      );

      playerMonitor.activate("Vendor","OBSERVER","OS","OBSERVER");

//      //if is a Live Channel
//      playerMonitor.updateChannelInfo("Channel Name","Channel ID","Channel type","Channel EPG");
//
//      //if is a VOD
//      playerMonitor.updateVODInfo("VOD ID","VOD Title","VOD Type","VOD Path");

//      observer = new Observer(
//              player,
//              trackSelector,
//              getApplicationContext(),
//              playerMonitor,
//              "session ID",
//              "url",
//              true,false,false,
//              "originalSessionId",
//              "restartSec",
//              true,
//              "channelName", "channelID", "channelType",
//              "VOD_ID","VODTitle","assetType","assetPath" );

      UUID drmSchemeUuid = intent.hasExtra(DRM_SCHEME_UUID_EXTRA)
          ? UUID.fromString(intent.getStringExtra(DRM_SCHEME_UUID_EXTRA)) : null;
      DrmSessionManager<FrameworkMediaCrypto> drmSessionManager = null;
      if (drmSchemeUuid != null) {
        String drmLicenseUrl = intent.getStringExtra(DRM_LICENSE_URL);
        String[] keyRequestPropertiesArray = intent.getStringArrayExtra(DRM_KEY_REQUEST_PROPERTIES);
        int errorStringId = R.string.error_drm_unknown;
        if (Util.SDK_INT < 18) {
          errorStringId = R.string.error_drm_not_supported;
        } else {
          try {
            drmSessionManager = buildDrmSessionManagerV18(drmSchemeUuid, drmLicenseUrl,
                keyRequestPropertiesArray);
          } catch (UnsupportedDrmException e) {
            errorStringId = e.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
                ? R.string.error_drm_unsupported_scheme : R.string.error_drm_unknown;
          }
        }
        if (drmSessionManager == null) {
          showToast(errorStringId);
          return;
        }
      }

      boolean preferExtensionDecoders = intent.getBooleanExtra(PREFER_EXTENSION_DECODERS, false);
      @DefaultRenderersFactory.ExtensionRendererMode int extensionRendererMode =
          ((DemoApplication) getApplication()).useExtensionRenderers()
              ? (preferExtensionDecoders ? DefaultRenderersFactory.EXTENSION_RENDERER_MODE_PREFER
              : DefaultRenderersFactory.EXTENSION_RENDERER_MODE_ON)
              : DefaultRenderersFactory.EXTENSION_RENDERER_MODE_OFF;
      DefaultRenderersFactory renderersFactory = new DefaultRenderersFactory(this,
          drmSessionManager, extensionRendererMode);

      player = ExoPlayerFactory.newSimpleInstance(renderersFactory, trackSelector);
      observer = new Observer(
              player,
              trackSelector,
              playerMonitor,
              "session ID",
              true,false,false,
              "originalSessionId",
              "restartSec",
              true,
              "channelName", "channelID", "channelType",
              "VOD_ID","VODTitle","assetType","assetPath" );
      observer.activate();
      player.addListener(this);
      player.addListener(observer);
      player.addMetadataOutput(observer);
      player.setAudioDebugListener(observer);
      player.setVideoDebugListener(observer);

      int percentage = player.getBufferedPercentage();

      simpleExoPlayerView.setPlayer(player);
      player.setPlayWhenReady(shouldAutoPlay);
      debugViewHelper = new DebugTextViewHelper(player, debugTextView);
      debugViewHelper.start();
    }
    String action = intent.getAction();
    Uri[] uris;
    String[] extensions;
    if (ACTION_VIEW.equals(action)) {
      uris = new Uri[]{intent.getData()};
      extensions = new String[]{intent.getStringExtra(EXTENSION_EXTRA)};
    } else if (ACTION_VIEW_LIST.equals(action)) {
      String[] uriStrings = intent.getStringArrayExtra(URI_LIST_EXTRA);
      uris = new Uri[uriStrings.length];
      for (int i = 0; i < uriStrings.length; i++) {
        uris[i] = Uri.parse(uriStrings[i]);
      }
      extensions = intent.getStringArrayExtra(EXTENSION_LIST_EXTRA);
      if (extensions == null) {
        extensions = new String[uriStrings.length];
      }
    } else {
      showToast(getString(R.string.unexpected_intent_action, action));
      return;
    }
    if (Util.maybeRequestReadExternalStoragePermission(this, uris)) {
      // The player will be reinitialized if the permission is granted.
      return;
    }
    MediaSource[] mediaSources = new MediaSource[uris.length];
    for (int i = 0; i < uris.length; i++) {
      mediaSources[i] = buildMediaSource(uris[i], extensions[i]);
    }
    MediaSource mediaSource = mediaSources.length == 1 ? mediaSources[0]
        : new ConcatenatingMediaSource(mediaSources);
    String adTagUriString = intent.getStringExtra(AD_TAG_URI_EXTRA);
    if (adTagUriString != null) {
      Uri adTagUri = Uri.parse(adTagUriString);
      if (!adTagUri.equals(loadedAdTagUri)) {
        releaseAdsLoader();
        loadedAdTagUri = adTagUri;
      }
      try {
        mediaSource = createAdsMediaSource(mediaSource, Uri.parse(adTagUriString));
      } catch (Exception e) {
        showToast(R.string.ima_not_loaded);
      }
    } else {
      releaseAdsLoader();
    }
    boolean haveResumePosition = resumeWindow != C.INDEX_UNSET;
    if (haveResumePosition) {
      player.seekTo(resumeWindow, resumePosition);
    }
    player.prepare(mediaSource, !haveResumePosition, false);

    inErrorState = false;
    updateButtonVisibilities();
  }

  private MediaSource buildMediaSource(Uri uri, String overrideExtension) {
    int type = TextUtils.isEmpty(overrideExtension) ? Util.inferContentType(uri)
        : Util.inferContentType("." + overrideExtension);
    switch (type) {
      case C.TYPE_SS:
        return new SsMediaSource(uri, buildDataSourceFactory(false),
            new DefaultSsChunkSource.Factory(mediaDataSourceFactory), mainHandler, observer);
      case C.TYPE_DASH:
        return new DashMediaSource(uri, buildDataSourceFactory(false),
            new DefaultDashChunkSource.Factory(mediaDataSourceFactory), mainHandler, observer);
      case C.TYPE_HLS:
        return new HlsMediaSource(uri, mediaDataSourceFactory, mainHandler, observer);
      case C.TYPE_OTHER:
        return new ExtractorMediaSource(uri, mediaDataSourceFactory, new DefaultExtractorsFactory(),
            mainHandler, observer);
      default: {
        throw new IllegalStateException("Unsupported type: " + type);
      }
    }
  }

  private DrmSessionManager<FrameworkMediaCrypto> buildDrmSessionManagerV18(UUID uuid,
      String licenseUrl, String[] keyRequestPropertiesArray) throws UnsupportedDrmException {
    HttpMediaDrmCallback drmCallback = new HttpMediaDrmCallback(licenseUrl,
        buildHttpDataSourceFactory(false));
    if (keyRequestPropertiesArray != null) {
      for (int i = 0; i < keyRequestPropertiesArray.length - 1; i += 2) {
        drmCallback.setKeyRequestProperty(keyRequestPropertiesArray[i],
            keyRequestPropertiesArray[i + 1]);
      }
    }
    return new DefaultDrmSessionManager<>(uuid, FrameworkMediaDrm.newInstance(uuid), drmCallback,
        null, mainHandler, observer);
  }

  private void releasePlayer() {
    if (player != null) {
      debugViewHelper.stop();
      debugViewHelper = null;
      shouldAutoPlay = player.getPlayWhenReady();
      updateResumePosition();
      player.release();
      player = null;
      trackSelector = null;
      trackSelectionHelper = null;
      observer = null;
    }
  }

  private void updateResumePosition() {
    resumeWindow = player.getCurrentWindowIndex();
    resumePosition = Math.max(0, player.getContentPosition());
  }

  private void clearResumePosition() {
    resumeWindow = C.INDEX_UNSET;
    resumePosition = C.TIME_UNSET;
  }

  /**
   * Returns a new DataSource factory.
   *
   * @param useBandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new
   *     DataSource factory.
   * @return A new DataSource factory.
   */
  private DataSource.Factory buildDataSourceFactory(boolean useBandwidthMeter) {
    return ((DemoApplication) getApplication())
        .buildDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
  }

  /**
   * Returns a new HttpDataSource factory.
   *
   * @param useBandwidthMeter Whether to set {@link #BANDWIDTH_METER} as a listener to the new
   *     DataSource factory.
   * @return A new HttpDataSource factory.
   */
  private HttpDataSource.Factory buildHttpDataSourceFactory(boolean useBandwidthMeter) {
    return ((DemoApplication) getApplication())
        .buildHttpDataSourceFactory(useBandwidthMeter ? BANDWIDTH_METER : null);
  }

  /**
   * Returns an ads media source, reusing the ads loader if one exists.
   *
   * @throws Exception Thrown if it was not possible to create an ads media source, for example, due
   *     to a missing dependency.
   */
  private MediaSource createAdsMediaSource(MediaSource mediaSource, Uri adTagUri) throws Exception {
    // Load the extension source using reflection so the demo app doesn't have to depend on it.
    // The ads loader is reused for multiple playbacks, so that ad playback can resume.
    Class<?> loaderClass = Class.forName("com.google.android.exoplayer2.ext.ima.ImaAdsLoader");
    if (imaAdsLoader == null) {
      imaAdsLoader = loaderClass.getConstructor(Context.class, Uri.class)
          .newInstance(this, adTagUri);
      adOverlayViewGroup = new FrameLayout(this);
      // The demo app has a non-null overlay frame layout.
      simpleExoPlayerView.getOverlayFrameLayout().addView(adOverlayViewGroup);
    }
    Class<?> sourceClass =
        Class.forName("com.google.android.exoplayer2.ext.ima.ImaAdsMediaSource");
    Constructor<?> constructor = sourceClass.getConstructor(MediaSource.class,
        DataSource.Factory.class, loaderClass, ViewGroup.class);
    return (MediaSource) constructor.newInstance(mediaSource, mediaDataSourceFactory, imaAdsLoader,
        adOverlayViewGroup);
  }

  private void releaseAdsLoader() {
    if (imaAdsLoader != null) {
      try {
        Class<?> loaderClass = Class.forName("com.google.android.exoplayer2.ext.ima.ImaAdsLoader");
        Method releaseMethod = loaderClass.getMethod("release");
        releaseMethod.invoke(imaAdsLoader);
      } catch (Exception e) {
        // Should never happen.
        throw new IllegalStateException(e);
      }
      imaAdsLoader = null;
      loadedAdTagUri = null;
      simpleExoPlayerView.getOverlayFrameLayout().removeAllViews();
    }
  }

  // Player.EventListener implementation

  @Override
  public void onLoadingChanged(boolean isLoading) {
    // Do nothing.
  }

  @Override
  public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
    if (playbackState == Player.STATE_ENDED) {
      showControls();
    }
    updateButtonVisibilities();
  }

  @Override
  public void onRepeatModeChanged(int repeatMode) {
    // Do nothing.
  }

  @Override
  public void onPositionDiscontinuity() {
    if (inErrorState) {
      // This will only occur if the user has performed a seek whilst in the error state. Update the
      // resume position so that if the user then retries, playback will resume from the position to
      // which they seeked.
      updateResumePosition();
    }
  }

  @Override
  public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
    // Do nothing.
  }

  @Override
  public void onTimelineChanged(Timeline timeline, Object manifest) {

    // Do nothing.

  }

  @Override
  public void onPlayerError(ExoPlaybackException e) {
    String errorString = null;
    if (e.type == ExoPlaybackException.TYPE_RENDERER) {
      Exception cause = e.getRendererException();
      if (cause instanceof DecoderInitializationException) {
        // Special case for decoder initialization failures.
        DecoderInitializationException decoderInitializationException =
            (DecoderInitializationException) cause;
        if (decoderInitializationException.decoderName == null) {
          if (decoderInitializationException.getCause() instanceof DecoderQueryException) {
            errorString = getString(R.string.error_querying_decoders);
          } else if (decoderInitializationException.secureDecoderRequired) {
            errorString = getString(R.string.error_no_secure_decoder,
                decoderInitializationException.mimeType);
          } else {
            errorString = getString(R.string.error_no_decoder,
                decoderInitializationException.mimeType);
          }
        } else {
          errorString = getString(R.string.error_instantiating_decoder,
              decoderInitializationException.decoderName);
        }
      }
    }
    if (errorString != null) {
      showToast(errorString);
    }
    inErrorState = true;
    if (isBehindLiveWindow(e)) {
      clearResumePosition();
      initializePlayer();
    } else {
      updateResumePosition();
      updateButtonVisibilities();
      showControls();
    }
  }

  @Override
  @SuppressWarnings("ReferenceEquality")
  public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
    updateButtonVisibilities();
    if (trackGroups != lastSeenTrackGroupArray) {
      MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
      if (mappedTrackInfo != null) {
        if (mappedTrackInfo.getTrackTypeRendererSupport(C.TRACK_TYPE_VIDEO)
            == MappedTrackInfo.RENDERER_SUPPORT_UNSUPPORTED_TRACKS) {
          showToast(R.string.error_unsupported_video);
        }
        if (mappedTrackInfo.getTrackTypeRendererSupport(C.TRACK_TYPE_AUDIO)
            == MappedTrackInfo.RENDERER_SUPPORT_UNSUPPORTED_TRACKS) {
          showToast(R.string.error_unsupported_audio);
        }
      }
      lastSeenTrackGroupArray = trackGroups;
    }
  }

  // User controls

  private void updateButtonVisibilities() {
    debugRootView.removeAllViews();

    retryButton.setVisibility(inErrorState ? View.VISIBLE : View.GONE);
    debugRootView.addView(retryButton);

    if (player == null) {
      return;
    }

    MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
    if (mappedTrackInfo == null) {
      return;
    }

    for (int i = 0; i < mappedTrackInfo.length; i++) {
      TrackGroupArray trackGroups = mappedTrackInfo.getTrackGroups(i);
      if (trackGroups.length != 0) {
        Button button = new Button(this);
        int label;
        switch (player.getRendererType(i)) {
          case C.TRACK_TYPE_AUDIO:
            label = R.string.audio;
            break;
          case C.TRACK_TYPE_VIDEO:
            label = R.string.video;
            break;
          case C.TRACK_TYPE_TEXT:
            label = R.string.text;
            break;
          default:
            continue;
        }
        button.setText(label);
        button.setTag(i);
        button.setOnClickListener(this);
        debugRootView.addView(button, debugRootView.getChildCount() - 1);
      }
    }
  }

  private void showControls() {
    debugRootView.setVisibility(View.VISIBLE);
  }

  private void showToast(int messageId) {
    showToast(getString(messageId));
  }

  private void showToast(String message) {
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
  }

  private static boolean isBehindLiveWindow(ExoPlaybackException e) {
    if (e.type != ExoPlaybackException.TYPE_SOURCE) {
      return false;
    }
    Throwable cause = e.getSourceException();
    while (cause != null) {
      if (cause instanceof BehindLiveWindowException) {
        return true;
      }
      cause = cause.getCause();
    }
    return false;
  }

}


text:
#include "server/options.h"

namespace Server
{
    void Options::additionalOptions()
    {
        m_visibleOptions.add_options()
            ("port,p", boost::program_options::value<int>()->default_value(9876),
             "Port listen to")
            ("host,H", boost::program_options::value<std::string>(),
             "Host listen to")
            ("socket,s", boost::program_options::value<std::string>()->default_value("boostcached.sock"),
             "Socket listen to")
            ("fork,f", "Fork server process")
            ("workers,w", boost::program_options::value<int>()->default_value(2),
             "Number of workers-threads")
        ;
    }
}


text:
package de.iritgo.aktario.framework.server.cadencemanager;

import de.iritgo.aktario.core.Engine;
import de.iritgo.aktario.core.thread.Threadable;
import de.iritgo.aktario.framework.base.shutdown.ShutdownManager;
import de.iritgo.aktario.framework.base.shutdown.ShutdownObserver;
import de.iritgo.aktario.framework.user.User;
import de.iritgo.aktario.framework.user.UserEvent;
import de.iritgo.aktario.framework.user.UserListener;
import java.util.Iterator;

/**
 *
 */
public class CadenceManager extends Threadable implements UserListener, ShutdownObserver
{
	static public int TURN_INTERVAL = 60 * 100 * 5; //Milliseconds

	static public int DELAY_INTERVAL = 5; // ThreadSleepTime

	private CadeneContextRegistry turnContextRegistry;

	private int currentMilli = 60 * 100 * 5;

	private long tmpTime;

	private long tmpTime2;

	private int addTurnDelay;

	/**
	 * Standard constructor
	 */
	public CadenceManager()
	{
		super("turn");
		turnContextRegistry = new CadeneContextRegistry();

		((ShutdownManager) Engine.instance().getManagerRegistry().getManager("shutdown")).addObserver(this);

		Engine.instance().getEventRegistry().addListener("User", this);
		currentMilli = 0;
		addTurnDelay = 0;
	}

	public void run()
	{
		setState(Threadable.FREE);

		long c = System.currentTimeMillis();
		long diff = c - tmpTime;

		tmpTime = c;

		int add = Math.round(diff);

		if (add == 0)
		{
			add = 1;
		}

		synchronized (turnContextRegistry)
		{
			for (Iterator i = turnContextRegistry.getTurnContextIterator(); i.hasNext();)
			{
				CadenceContext turnContext = (CadenceContext) i.next();

				if ((! turnContext.isTurnFired()) && (currentMilli >= (turnContext.getPingTime() + addTurnDelay)))
				{
					turnContext.turn();
				}
			}
		}

		if (currentMilli >= (TURN_INTERVAL + addTurnDelay))
		{
			long c2 = System.currentTimeMillis();
			long diff2 = c2 - tmpTime2;

			tmpTime2 = c;

			if (diff2 == 0)
			{
				addTurnDelay = addTurnDelay * 100;
			}
			else
			{
				addTurnDelay = addTurnDelay + (TURN_INTERVAL - Math.round(diff2));
			}

			currentMilli = 0;

			for (Iterator i = turnContextRegistry.getTurnContextIterator(); i.hasNext();)
			{
				CadenceContext turnContext = (CadenceContext) i.next();

				if (turnContext.isTurnFired())
				{
					turnContext.reset();
				}
				else
				{
				}
			}
		}

		try
		{
			Thread.sleep(DELAY_INTERVAL);
		}
		catch (InterruptedException x)
		{
		}

		currentMilli = currentMilli + add;
	}

	/**
	 * Its called if a new user login successful.
	 *
	 * @param event The EventOject.
	 */
	public void userEvent(UserEvent event)
	{
		synchronized (turnContextRegistry)
		{
			turnContextRegistry.add(new CadenceContext(event.getUser()));
		}
	}

	public void onShutdown()
	{
		synchronized (turnContextRegistry)
		{
			turnContextRegistry.clear();
		}
	}

	public void onUserLogoff(User user)
	{
		synchronized (turnContextRegistry)
		{
			turnContextRegistry.remove(user);
		}
	}
}


text:
require File.dirname(__FILE__)+'/config'
require File.dirname(__FILE__)+'/mdproj'
require File.dirname(__FILE__)+'/batch'
require File.dirname(__FILE__)+'/utility'
require File.dirname(__FILE__)+'/mpplist'
require 'git'
require 'shellwords'

#处理参数

def defaultDir
	@defaultDir  = './config'
end

def isValidProject
	project = Dir['*.xcworkspace'].first
	project = Dir['*.xcodeproj'].first unless project
	valid = false
	if project
		valid = true
	end
	valid
end

def modifyFile(oldFile,newFile)
	if oldFile and newFile
		cmdString = "cp -r #{oldFile} #{newFile}"
		system cmdString
		puts "[M:File] #{oldFile} >> #{newFile}"
	else
		puts "[M:File] do nothing of oldFile: #{oldFile} newFile: #{newFile}"
	end
end

def setEnv(cfg)
	file = cfg
	fullPath = "#{defaultDir}/#{file}"
	if file.class == NilClass
		puts "argument missed [config file]!"
	elsif !File.exist?(fullPath)
		puts "config file[#{fullPath}] not exist!"
	else
		config = XRbConfig.new
		config.read(fullPath)

		config.datas.each do |key,value|
			extname = File.extname(key)

			puts "[--#{key}--]"
			if extname == ".plist" or key == ".plist" \
				or extname == ".entitlements" or key == ".entitlements"
				value.each do |k,v|
					rets = match(key)
					rets.each do |tempFile|
						if tempFile.class == NilClass
							puts "#{value} find no result!"
							next
						elsif !File.exist?(tempFile)
							puts "#{tempFile} not exist!"
							next
						end
						modifyPlist(k,v,tempFile)
					end
				end
			elsif extname == ".xcscheme" or key == ".xcscheme"
				value.each do |k,v|
					rets = match(key)
					rets.each do |tempFile|
						if tempFile.class == NilClass
							puts "#{value} find no result!"
							next
						elsif !File.exist?(tempFile)
							puts "#{tempFile} not exist!"
							next
						end
						scheme = Xcodeproj::XCScheme.new File.join(tempFile)
						scheme.launch_action.build_configuration = v
						puts "[M:Scheme] #{k} >> #{v}"
						scheme.save!
					end
				end
			elsif extname.index(".xcodeproj") == 0
				project = key
				target = ""
				if key.split('->').count > 1
					project = key.split('->')[0]
					target = key.split('->')[1]
				end

				value.each do |k,v|
					modifyMode = KModifyModeSet
					if v.class != NilClass and v.index("++") == 0
						modifyMode = KModifyModeAdd
						v = v.delete("++")
					end

					mdproj = Mdproj.new
					mdproj.open(project)

					mdproj.modifyProject(k,v,modifyMode,target,KMatchModeFuzzy)

					mdproj.save
				end
			elsif extname == ".file" or value == ".file"
				value.each do |k,v|
					oldFile = match(k).first
					newFile = match(v).first
					modifyFile(oldFile,newFile)
				end
			else
				puts "unknow value : #{extname} or #{value}"
			end
		end
	end
end

def modeArg(arg)
	debugMode = arg

	debug = false

	if debugMode.class != NilClass and debugMode.downcase == "debug"
		debug = true
	end

	debug
end

def showHelp
	puts ""
	puts "To see help for the available commands run:"
	puts ""
	puts "-read     [-r]Read configuration files in default folder"
    puts "-write:   [-w]Write the example data to configuration files in default folder"
    puts "-env:     [-e]Change xcode project env with given config"
    puts "-build:   [-b]Build xcode workspace/porject"
    puts "-clean:   [-c]Clean xcode workspace/porject"
    puts "-make:    [-m]Build xcode workspace/porject And Make ipa file to output folder"
    puts "-batch:    [-bat]Batch build xcode workspace/porject And Make ipa file to output folder"
    puts "-output:    [-o]Config output folder path"
    puts ""
end

#程序入口

cmd = ARGV[0]

if !isValidProject

	puts "No xcworkspace|xcproj file found"

elsif (cmd.class == NilClass)

	showHelp

elsif cmd.downcase == "-read" or cmd.downcase == "-r"

	#读取配置文件
	read

elsif cmd.downcase == "-write" or cmd.downcase == "-w"
	if !Dir.exist?(defaultDir)
		Dir.mkdir(defaultDir)
	end
	#写配置文件
	write

elsif cmd.downcase == '-env' or cmd.downcase == '-e'
	running = isXcodeRunning
	if running
		killXcode
	end
	#修改xcode工程配置
	setEnv(ARGV[1])

	if running
		launchXcode
	end

elsif cmd.downcase == '-clean' or cmd.downcase == '-c'
	#清理工程
	clean(modeArg(ARGV[1]))

elsif cmd.downcase == '-build' or cmd.downcase == '-b'
	#编译工程
	build(modeArg(ARGV[1]), arguments=ARGV[2])

	increaseBuildVersion()
elsif cmd.downcase == '-make' or cmd.downcase == '-m'
	#打包工程
	build(modeArg(ARGV[1]), arguments=ARGV[2])
	make(modeArg(ARGV[1]),true,true)

	increaseBuildVersion()

elsif cmd.downcase == '-batch' or cmd.downcase == '-bat'
	if !Dir.exist?(defaultDir)
		Dir.mkdir(defaultDir)
	end

	if !File.exist?('config/batch.ini')
		`touch ./config/batch.ini`
		puts "No chanel info in ./config/batch.ini"

	else
		#批量打包工程
		batchMake(modeArg(ARGV[1]))
	end
elsif cmd.downcase == '-output' or cmd.downcase == '-o'
	if ARGV[1].class != NilClass
		#修改输出目录
		`touch ./config/output.ini`
		`echo #{ARGV[1]} > ./config/output.ini`
	end
	puts "Current output path is: #{outputFolder}"
else
	showHelp
end


text:
namespace markdown
{

bool EmptyBlockProcessor::test(const Element &, const QString &block)
{
    return block.isEmpty() || block.startsWith('\n');
}

bool EmptyBlockProcessor::run(const Element &parent, QStringList &blocks)
{
    QString block = blocks.front();
    blocks.pop_front();
    QString filler = "\n\n";
    if ( ! block.isEmpty() ) {
        //! Starts with empty line
        //! Only replace a single line.
        filler = "\n";
        //! Save the rest for later.
        QString theRest = block.mid(1);
        if ( ! theRest.isEmpty() ) {
            //! Add remaining lines to master blocks for later.
            blocks.push_front(theRest);
        }
    }
    Element sibling = this->lastChild(parent);
    if ( sibling && sibling->tag == "pre" && sibling->size() > 0 && (*sibling)[0]->tag == "code" ) {
        //! Last block is a codeblock. Append to preserve whitespace.
        QString codeText = (*sibling)[0]->text;
        (*sibling)[0]->text = QString("%1%2").arg(codeText).arg(filler);
        (*sibling)[0]->atomic = true;
    }
    return true;
}

} // namespace markdown


text:
import scala.meta.dialects.Scala211

class TrickySuite extends ParseSuite {
  test("annot > \n > comment \n > > defn") {
    templStat("@foo\n//bar bar\ndef baz = qux")
  }
  test("annot > whitespace > \n > defn") {
    templStat("@foo \ndef baz = qux")
  }
}


text:
package djinni

import djinni.ast.Record.DerivingType
import djinni.ast._
import djinni.generatorTools._
import djinni.meta._
import djinni.writer.IndentWriter

import scala.collection.mutable

class CppGenerator(spec: Spec) extends Generator(spec) {

  val writeCppFile = writeCppFileGeneric(spec.cppOutFolder.get, spec.cppNamespace, spec.cppFileIdentStyle, spec.cppIncludePrefix) _
  def writeHppFile(name: String, origin: String, includes: Iterable[String], fwds: Iterable[String], f: IndentWriter => Unit, f2: IndentWriter => Unit = (w => {})) =
    writeHppFileGeneric(spec.cppHeaderOutFolder.get, spec.cppNamespace, spec.cppFileIdentStyle)(name, origin, includes, fwds, f, f2)

  class CppRefs(name: String) {
    var hpp = mutable.TreeSet[String]()
    var hppFwds = mutable.TreeSet[String]()
    var cpp = mutable.TreeSet[String]()

    def find(ty: TypeRef) { find(ty.resolved) }
    def find(tm: MExpr) {
      tm.args.map(find).mkString("<", ", ", ">")
      find(tm.base)
    }
    def find(m: Meta) = m match {
      case o: MOpaque =>
        o match {
          case p: MPrimitive =>
            val n = p.idlName
            if (n == "i8" || n == "i16" || n == "i32" || n == "i64") {
              hpp.add("#include <cstdint>")
            }
          case MString =>
            hpp.add("#include <string>")
          case MBinary =>
            hpp.add("#include <vector>")
            hpp.add("#include <cstdint>")
          case MOptional =>
            hpp.add("#include " + spec.cppOptionalHeader)
          case MList =>
            hpp.add("#include <vector>")
          case MSet =>
            hpp.add("#include <unordered_set>")
          case MMap =>
            hpp.add("#include <unordered_map>")
        }
      case d: MDef =>
        d.defType match {
          case DEnum
             | DRecord =>
            if (d.name != name) {
              hpp.add("#include " + q(spec.cppIncludePrefix + spec.cppFileIdentStyle(d.name) + "." + spec.cppHeaderExt))
            }
          case DInterface =>
            hpp.add("#include <memory>")
            if (d.name != name) {
              hppFwds.add(s"class ${idCpp.ty(d.name)};")
            }
        }
      case p: MParam =>
    }

  }

  override def generateEnum(origin: String, ident: Ident, doc: Doc, e: Enum) {
    val refs = new CppRefs(ident.name)
    val self = idCpp.enumType(ident)

    if (spec.cppEnumHashWorkaround) {
      refs.hpp.add("#include <functional>") // needed for std::hash
    }

    writeHppFile(ident, origin, refs.hpp, refs.hppFwds, w => {
      w.w(s"enum class $self : int").bracedSemi {
        for (o <- e.options) {
          writeDoc(w, o.doc)
          w.wl(idCpp.enum(o.ident.name) + ",")
        }
      }
    },
    w => {
      // std::hash specialization has to go *outside* of the wrapNs
      if (spec.cppEnumHashWorkaround) {
        val fqSelf = withNs(spec.cppNamespace, self)
        w.wl
        wrapNamespace(w, Some("std"),
          (w: IndentWriter) => {
            w.wl("template <>")
            w.w(s"struct hash<$fqSelf>").bracedSemi {
              w.w(s"size_t operator()($fqSelf type) const").braced {
                w.wl("return std::hash<int>()(static_cast<int>(type));")
              }
            }
          }
        )
      }
    })
  }

  def generateHppConstants(w: IndentWriter, consts: Seq[Const]) = {
    for (c <- consts) {
      w.wl
      writeDoc(w, c.doc)
      w.wl(s"static const ${toCppType(c.ty)} ${idCpp.const(c.ident)};")
    }
  }

  def generateCppConstants(w: IndentWriter, consts: Seq[Const], selfName: String) = {
    def writeCppConst(w: IndentWriter, ty: TypeRef, v: Any): Unit = v match {
      case l: Long => w.w(l.toString)
      case d: Double => w.w(d.toString)
      case b: Boolean => w.w(if (b) "true" else "false")
      case s: String => w.w(s)
      case e: EnumValue => w.w(idCpp.enumType(e.ty) + "::" + idCpp.enum(e.ty.name + "_" + e.name))
      case v: ConstRef => w.w(selfName + "::" + idCpp.const(v))
      case z: Map[_, _] => { // Value is record
      val recordMdef = ty.resolved.base.asInstanceOf[MDef]
        val record = recordMdef.body.asInstanceOf[Record]
        val vMap = z.asInstanceOf[Map[String, Any]]
        w.wl(idCpp.ty(recordMdef.name) + "(")
        w.increase()
        // Use exact sequence
        val skipFirst = SkipFirst()
        for (f <- record.fields) {
          skipFirst {w.wl(",")}
          writeCppConst(w, f.ty, vMap.apply(f.ident.name))
          w.w(" /* " + idCpp.field(f.ident) + " */ ")
        }
        w.w(")")
        w.decrease()
      }
    }

    val skipFirst = SkipFirst()
    for (c <- consts) {
      skipFirst{ w.wl }
      w.w(s"const ${toCppType(c.ty)} $selfName::${idCpp.const(c.ident)} = ")
      writeCppConst(w, c.ty, c.value)
      w.wl(";")
    }
  }

  override def generateRecord(origin: String, ident: Ident, doc: Doc, params: Seq[TypeParam], r: Record) {
    val refs = new CppRefs(ident.name)
    r.fields.foreach(f => refs.find(f.ty))
    r.consts.foreach(c => refs.find(c.ty))
    refs.hpp.add("#include <utility>") // Add for std::move

    val self = idCpp.ty(ident)
    val (cppName, cppFinal) = if (r.ext.cpp) (ident.name + "_base", "") else (ident.name, " final")
    val actualSelf = idCpp.ty(cppName)

    // Requiring the extended class
    if (r.ext.cpp) {
      refs.hpp.add(s"class $self; // Requiring extended class")
      refs.cpp.add("#include "+q("../" + spec.cppFileIdentStyle(ident) + "." + spec.cppHeaderExt))
    }

    // C++ Header
    def writeCppPrototype(w: IndentWriter) {
      writeDoc(w, doc)
      writeCppTypeParams(w, params)
      w.w("struct " + actualSelf + cppFinal).bracedSemi {
        generateHppConstants(w, r.consts)
        // Field definitions.
        for (f <- r.fields) {
          w.wl
          writeDoc(w, f.doc)
          w.wl(toCppType(f.ty) + " " + idCpp.field(f.ident) + ";")
        }

        w.wl
        if (r.derivingTypes.contains(DerivingType.Eq)) {
          w.wl(s"bool operator==(const $actualSelf & other) const;")
          w.wl(s"bool operator!=(const $actualSelf & other) const;")
        }
        if (r.derivingTypes.contains(DerivingType.Ord)) {
          w.wl(s"bool operator<(const $actualSelf & other) const;")
          w.wl(s"bool operator>(const $actualSelf & other) const;")
        }
        if (r.derivingTypes.contains(DerivingType.Eq) && r.derivingTypes.contains(DerivingType.Ord)) {
          w.wl(s"bool operator<=(const $actualSelf & other) const;")
          w.wl(s"bool operator>=(const $actualSelf & other) const;")
        }

        // Constructor.
        w.wl
        if (r.fields.nonEmpty) {
          w.wl(actualSelf + "(").nestedN(2) {
            val skipFirst = SkipFirst()
            for (f <- r.fields) {
              skipFirst { w.wl(",") }
              w.w(toCppType(f.ty) + " " + idCpp.local(f.ident))
            }
            w.wl(") :")
            w.nested {
              val skipFirst = SkipFirst()
              for (f <- r.fields) {
                skipFirst { w.wl(",") }
                w.w(idCpp.field(f.ident) + "(std::move(" + idCpp.local(f.ident) + "))")
              }
              w.wl(" {")
            }
          }
          w.wl("}")
        } else {
          w.wl(actualSelf + "() {};")
        }

        if (r.ext.cpp) {
          w.wl
          w.wl(s"virtual ~$actualSelf() {}")
        }
      }
    }

    writeHppFile(cppName, origin, refs.hpp, refs.hppFwds, writeCppPrototype)

    if (r.consts.nonEmpty || r.derivingTypes.nonEmpty) {
      writeCppFile(cppName, origin, refs.cpp, w => {
        generateCppConstants(w, r.consts, actualSelf)

        if (r.derivingTypes.contains(DerivingType.Eq)) {
          w.wl
          w.w(s"bool $actualSelf::operator==(const $actualSelf & other) const").braced {
            w.w("return ").nested {
              val skipFirst = SkipFirst()
              for (f <- r.fields) {
                skipFirst { w.wl(" &&") }
                w.w(s"${idCpp.field(f.ident)} == other.${idCpp.field(f.ident)}")
              }
              w.wl(";")
            }
          }
          w.wl
          w.w(s"bool $actualSelf::operator!=(const $actualSelf & other) const").braced {
            w.wl("return !(*this == other);")
          }
        }
        if (r.derivingTypes.contains(DerivingType.Ord)) {
          w.wl
          w.w(s"bool $actualSelf::operator<(const $actualSelf & other) const").braced {
            for (f <- r.fields) {
              w.w(s"if (${idCpp.field(f.ident)} < other.${idCpp.field(f.ident)})").braced {
                w.wl("return true;")
              }
              w.w(s"if (other.${idCpp.field(f.ident)} < ${idCpp.field(f.ident)})").braced {
                w.wl("return false;")
              }
            }
            w.wl("return false;")
          }
          w.wl
          w.w(s"bool $actualSelf::operator>(const $actualSelf & other) const").braced {
            w.wl("return other < *this;")
          }
        }
        if (r.derivingTypes.contains(DerivingType.Eq) && r.derivingTypes.contains(DerivingType.Ord)) {
          w.wl
          w.w(s"bool $actualSelf::operator<=(const $actualSelf & other) const").braced {
            w.wl("return (*this < other || *this == other);")
          }
          w.wl
          w.w(s"bool $actualSelf::operator>=(const $actualSelf & other) const").braced {
            w.wl("return other <= *this;")
          }
        }
      })
    }

  }

  override def generateInterface(origin: String, ident: Ident, doc: Doc, typeParams: Seq[TypeParam], i: Interface) {
    val refs = new CppRefs(ident.name)
    i.methods.map(m => {
      m.params.map(p => refs.find(p.ty))
      m.ret.foreach(refs.find)
    })
    i.consts.map(c => {
      refs.find(c.ty)
    })

    val self = idCpp.ty(ident)

    writeHppFile(ident, origin, refs.hpp, refs.hppFwds, w => {
      writeDoc(w, doc)
      writeCppTypeParams(w, typeParams)
      w.w(s"class $self").bracedSemi {
        w.wlOutdent("public:")
        // Destructor
        w.wl("virtual ~" + idCpp.ty(ident) + "() {}")
        // Constants
        generateHppConstants(w, i.consts)
        // Methods
        for (m <- i.methods) {
          w.wl
          writeDoc(w, m.doc)
          val ret = m.ret.fold("void")(toCppType(_))
          val params = m.params.map(toCppParamType)
          if (m.static) {
            w.wl(s"static $ret ${idCpp.method(m.ident)}${params.mkString("(", ", ", ")")};")
          } else {
            val constFlag = if (m.const) " const" else ""
            w.wl(s"virtual $ret ${idCpp.method(m.ident)}${params.mkString("(", ", ", ")")}$constFlag = 0;")
          }
        }
      }
    })

    // Cpp only generated in need of Constants
    if (i.consts.nonEmpty) {
      writeCppFile(ident, origin, refs.cpp, w => {
        generateCppConstants(w, i.consts, self)
      })
    }

  }

  def writeCppTypeParams(w: IndentWriter, params: Seq[TypeParam]) {
    if (params.isEmpty) return
    w.wl("template " + params.map(p => "typename " + idCpp.typeParam(p.ident)).mkString("<", ", ", ">"))
  }

}


text:
add_custom_target(utility
  COMMAND ${CMAKE_COMMAND} -E echo test
)
target_link_libraries(utility m)


text:
package com.busqueumlugar.form;

import java.util.Date;

import com.busqueumlugar.util.DateUtil;

/**
 *
 * @author Israel
 */
public class ParamservicoForm {

    private Long id;
    private String labelServico = "";
    private String valueServico = "";
    private String descricao = "";
    private Date dataCriacao;
    private String statusServico = "";
    private String tipoParamServico = "";
    private String cobranca = "";
    private String dataCriacaoFmt;

    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return the labelServico
     */
    public String getLabelServico() {
        return labelServico;
    }

    /**
     * @param labelServico the labelServico to set
     */
    public void setLabelServico(String labelServico) {
        this.labelServico = labelServico;
    }

    /**
     * @return the valueServico
     */
    public String getValueServico() {
        return valueServico;
    }

    /**
     * @param valueServico the valueServico to set
     */
    public void setValueServico(String valueServico) {
        this.valueServico = valueServico;
    }

    /**
     * @return the descricao
     */
    public String getDescricao() {
        return descricao;
    }

    /**
     * @param descricao the descricao to set
     */
    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    /**
     * @return the dataCriacao
     */
    public Date getDataCriacao() {
        return dataCriacao;
    }

    /**
     * @param dataCriacao the dataCriacao to set
     */
    public void setDataCriacao(Date dataCriacao) {
        this.dataCriacao = dataCriacao;
    }

    /**
     * @return the statusServico
     */
    public String getStatusServico() {
        return statusServico;
    }

    /**
     * @param statusServico the statusServico to set
     */
    public void setStatusServico(String statusServico) {
        this.statusServico = statusServico;
    }

    /**
     * @return the tipoParamServico
     */
    public String getTipoParamServico() {
        return tipoParamServico;
    }

    /**
     * @param tipoParamServico the tipoParamServico to set
     */
    public void setTipoParamServico(String tipoParamServico) {
        this.tipoParamServico = tipoParamServico;
    }

    /**
     * @return the cobranca
     */
    public String getCobranca() {
        return cobranca;
    }

    /**
     * @param cobranca the cobranca to set
     */
    public void setCobranca(String cobranca) {
        this.cobranca = cobranca;
    }

	public String getDataCriacaoFmt() {
		if ( this.dataCriacao != null)
			return DateUtil.formataData(this.dataCriacao);
		else
			return this.dataCriacaoFmt;
	}

	public void setDataCriacaoFmt(String dataCriacaoFmt) {
		this.dataCriacaoFmt = dataCriacaoFmt;
	}

}


text:
{% extends "/admin/layout.html" %}

{% block title %}photo{% endblock %}

{% block content %}

{{photo.title}}

Ajouter comme photo de couverture

    		<form action="/admin/photos/{{ photo.id }}/" method="POST">
				<fieldset>
					<legend>Informations</legend>

							Titre
							<input class="wide text input" name="title" id="title" type="text" placeholder="Titre" value="{{ photo.title }}" readonly>

							    <input name="is_published" id="is_published" type="checkbox" {% if photo.is_published == 1 %}checked="checked"{% endif %}>
							     Publié

<input type="submit" value="Modifier">

Retour

				</fieldset>
			</form>

{% endblock %}


text:
package org.apache.ode.utils;

import org.apache.xerces.jaxp.DocumentBuilderFactoryImpl;
import org.apache.xerces.jaxp.SAXParserFactoryImpl;
import org.apache.xerces.parsers.DOMParser;
import org.apache.xerces.parsers.SAXParser;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.xml.sax.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;

/**
 * A collection of utility methods for the Apache Xerces XML parser.
 */
public class XMLParserUtils {

  public static final String NAMESPACES_SAXF =
    "http://xml.org/sax/features/namespaces";
  public static final String VALIDATION_SAXF =
    "http://xml.org/sax/features/validation";
  public static final String SCHEMA_V_XERCESF =
    "http://apache.org/xml/features/validation/schema";
  private static final String XERCES_P_ROOT =
    "http://apache.org/xml/properties/schema/";
  private static final String EXTERNAL_SCHEMA_LOC_XERCESP =
    XERCES_P_ROOT + "external-schemaLocation";
  private static final String EXTERNAL_SCHEMA_NNS_LOC_XERCESP =
    XERCES_P_ROOT + "external-noNamespaceSchemaLocation";

  /**
   *

   * Get the 'correct' implementation of a JAXP SAXParserFactory; this is
   * intended to ensure that local implementations (e.g., Crimson) don't sneak into
   * the mix.
   *

   * @return the Xerces-specific implementaiton
   */
  public static SAXParserFactory getSAXParserFactory() {
    return new SAXParserFactoryImpl();
  }

  /**
   *

   * Get the 'correct' implementation of a JAXP DocumentBuilderFactory;
   * this is intended to ensure that local implementations (e.g., Crimson) don't
   * sneak into the mix.
   *

   * @return the Xerces-specific implementation
   */
  public static DocumentBuilderFactory getDocumentBuilderFactory() {
    return new DocumentBuilderFactoryImpl();
  }

  /**
   * Set the namespaces SAX property on the supplied
   * XMLReader.
   * @param xr the XMLReader to apply the feature to.
   */
  public static void setNamespaces(XMLReader xr) {
    try {
      xr.setFeature(NAMESPACES_SAXF, true);
    } catch (SAXException snse) {
      throw new SystemConfigurationException(snse);
    }
  }

  /**
   * @return a Xerces-specific XMLReader instance.
   */
  public static XMLReader getXMLReader() {
    return new SAXParser();
  }

  /**
   * @return a Xerces-specific DOM parser.
   */
  public static DOMParser getDOMParser() {
    return new DOMParser();
  }

  /**
   *

   * Specify an external schema location and turn on validation via setting features
   * and properties.
   *

   * @param xr the XMLReader to apply the features and properties to.
   * @param namespace the namespace URI of the schema to validate, with the empty
   * string or null serving to represent the empty namespace.
   * @param u the URL (or relative URL) that contains the schema.
   * @throws SAXNotSupportedException if one of the underlying feature/property
   * settings does.
   * @throws SAXNotRecognizedException if one of the underlying feature/property
   * settings does.
   */
  public static void setExternalSchemaURL(XMLReader xr, String namespace, String u)
      throws SAXNotRecognizedException, SAXNotSupportedException
  {
    xr.setFeature(NAMESPACES_SAXF,true);
    if (namespace != null && namespace.length() > 0) {
      xr.setProperty(EXTERNAL_SCHEMA_LOC_XERCESP, namespace + " " + u);
    } else {
      xr.setProperty(EXTERNAL_SCHEMA_NNS_LOC_XERCESP, u);
    }
    xr.setFeature(VALIDATION_SAXF,true);
    xr.setFeature(SCHEMA_V_XERCESF,true);
  }

  /**
   *

   * Specify an external schema location and turn on validation via setting features
   * and properties.
   *

   * @param dp the DOMParser to apply the features and properties to.
   * @param namespace the namespace URI of the schema to validate, with the empty
   * string or null serving to represent the empty namespace.
   * @param u the URL or relative URL that contains the schema.
   * @throws SAXNotSupportedException if one of the underlying feature/property
   * settings does.
   * @throws SAXNotRecognizedException if one of the underlying feature/property
   * settings does.
   */
  public static void setExternalSchemaURL(DOMParser dp, String namespace, String u)
      throws SAXNotRecognizedException, SAXNotSupportedException
  {
    dp.setFeature(VALIDATION_SAXF,true);
    dp.setFeature(SCHEMA_V_XERCESF,true);
    if (namespace != null && namespace.length() > 0) {
      dp.setProperty(EXTERNAL_SCHEMA_LOC_XERCESP, namespace + " " + u);
    } else {
      dp.setProperty(EXTERNAL_SCHEMA_NNS_LOC_XERCESP, u);
    }
  }

  /**
   *

   * Add a namespace/URL pair to the mapping between namespaces and the schemas used
   * to validate elements in them.  Adding a pair for a namespace that's already
   * bound will result in overwriting the URL previously bound.
   *

   * @param xr
   * @param namespace
   * @param u
   * @throws SAXNotRecognizedException
   * @throws SAXNotSupportedException
   */
  public static void addExternalSchemaURL(XMLReader xr, String namespace, String u)
    throws SAXNotRecognizedException,SAXNotSupportedException
  {
    xr.setFeature(VALIDATION_SAXF,true);
    xr.setFeature(SCHEMA_V_XERCESF,true);
    if (namespace == null || namespace.length() == 0) {
      setExternalSchemaURL(xr,namespace,u);
      return;
    }
    String s = (String) xr.getProperty(EXTERNAL_SCHEMA_LOC_XERCESP);
    if (s == null) {
      setExternalSchemaURL(xr,namespace,u);
      return;
    }
    StringTokenizer st = new StringTokenizer(s);
    HashMap<String,String> namespaces = new HashMap<String,String>();
    while (st.hasMoreTokens()) {
      String key = st.nextToken();
      if (!st.hasMoreTokens()) {
        throw new RuntimeException("Property has been misconfigured; expected an " +
            "even number of tokens.  Value was: " + s);
      }
      String value = st.nextToken();
      namespaces.put(key,value);
    }
    namespaces.put(namespace,u);
    StringBuffer sb = new StringBuffer();
    Iterator it = namespaces.keySet().iterator();
    while (it.hasNext()) {
      String ns = (String) it.next();
      sb.append(ns);
      sb.append(' ');
      sb.append(namespaces.get(ns));
      if (it.hasNext()) {
        sb.append(' ');
      }
    }
    xr.setProperty(EXTERNAL_SCHEMA_LOC_XERCESP,sb.toString());
    xr.setFeature(VALIDATION_SAXF,true);
    xr.setFeature(SCHEMA_V_XERCESF,true);
  }

  /**
   *

   * Add a namespace/URL pair to the mapping between namespaces and the schemas used
   * to validate elements in them.  Adding a pair for a namespace that's already
   * bound will result in overwriting the URL previously bound.
   *

   * @param dp the DOMParser to apply the features and properties to.
   * @param namespace the namespace URI of the schema to validate, with the empty
   * string or null serving to represent the empty namespace.
   * @param u the URL or relative URL that contains the schema.
   * @throws SAXNotSupportedException if one of the underlying feature/property
   * settings does.
   * @throws SAXNotRecognizedException if one of the underlying feature/property
   * settings does.
   */
  public static void addExternalSchemaURL(DOMParser dp, String namespace, String u)
    throws SAXNotRecognizedException,SAXNotSupportedException
  {
    dp.setFeature(VALIDATION_SAXF,true);
    dp.setFeature(SCHEMA_V_XERCESF,true);
    if (namespace == null || namespace.length() == 0) {
      setExternalSchemaURL(dp,namespace,u);
      return;
    }
    String s = (String) dp.getProperty(EXTERNAL_SCHEMA_LOC_XERCESP);
    if (s == null) {
      setExternalSchemaURL(dp,namespace,u);
      return;
    }
    StringTokenizer st = new StringTokenizer(s);
    HashMap<String,String> namespaces = new HashMap<String,String>();
    while (st.hasMoreTokens()) {
      String key = st.nextToken();
      if (!st.hasMoreTokens()) {
        throw new RuntimeException("Property has been misconfigured; expected an " +
            "even number of tokens.  Value was: " + s);
      }
      String value = st.nextToken();
      namespaces.put(key,value);
    }
    namespaces.put(namespace,u);
    StringBuffer sb = new StringBuffer();
    Iterator it = namespaces.keySet().iterator();
    while (it.hasNext()) {
      String ns = (String) it.next();
      sb.append(ns);
      sb.append(' ');
      sb.append(namespaces.get(ns));
      if (it.hasNext()) {
        sb.append(' ');
      }
    }
    dp.setProperty(EXTERNAL_SCHEMA_LOC_XERCESP,sb.toString());
    dp.setFeature(VALIDATION_SAXF,true);
    dp.setFeature(SCHEMA_V_XERCESF,true);
  }

  public static ContentHandler getXercesSerializer(OutputStream os) {
    XMLSerializer serializer =  new XMLSerializer();
    OutputFormat format = new OutputFormat();
    format.setPreserveSpace(true);
    format.setOmitDocumentType(true);
    serializer.setOutputFormat(format);
    serializer.setOutputByteStream(os);
    return serializer;

  }
}


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GeneralFuncController : MonoBehaviour
{
    public GameObject TownPanel;
    private bool scrollStartFlg = false; // スクロールが始まったかのフラグ
    private Vector2 scrollStartPos = new Vector2(); // スクロールの起点となるタッチポジション
    private static float SCROLL_END_LEFT = -4f; // 左側への移動制限(これ以上左には進まない)
    private static float SCROLL_END_RIGHT = 4; // 右側への移動制限(これ以上右には進まない)
    private static float SCROLL_DISTANCE_CORRECTION = 0.9f; // スクロール距離の調整
    private static float SCROLL_END_Up = 3f; // 上側への移動制限
    private static float SCROLL_END_Down = -3f; // 上側への移動制限

    private Vector2 touchPosition = new Vector2(); // タッチポジション初期化
    private Collider2D collide2dObj = null; // タッチ位置にあるオブジェクトの初期化

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {

            touchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            collide2dObj = Physics2D.OverlapPoint(touchPosition);

            if (scrollStartFlg == false && collide2dObj)
            {
                // タッチ位置にオブジェクトがあったらそのオブジェクトを取得する
                // スクロール移動とオブジェクトタッチの処理を区別するために記載しました
                GameObject obj = collide2dObj.transform.gameObject;
                Debug.Log(obj.name);
            }
            else
            {
              // TownPanel.SetActive(false);
                // タッチした場所に何もない場合、スクロールフラグをtrueに
                scrollStartFlg = true;
                if (scrollStartPos.x == 0.0f && scrollStartPos.y==0)
                {
                    // スクロール開始位置を取得
                    scrollStartPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                }
                else
                {
                    Vector2 touchMovePos = touchPosition;
                    if (scrollStartPos.x != touchMovePos.x || scrollStartPos.y != touchMovePos.y)
                    {
                        // 直前のタッチ位置との差を取得する
                        float diffPosX = SCROLL_DISTANCE_CORRECTION * (touchMovePos.x - scrollStartPos.x);
                        float diffPosY = SCROLL_DISTANCE_CORRECTION * (touchMovePos.y - scrollStartPos.y);
                        Vector2 pos = this.transform.position;
                        pos.x -= diffPosX;
                        pos.y -= diffPosY;
                        // スクロールが制限を超過する場合、処理を止める
                        if (pos.x > SCROLL_END_RIGHT || pos.x < SCROLL_END_LEFT||pos.y > SCROLL_END_Up || pos.y < SCROLL_END_Down)
                        {
                            return;
                        }

                        this.transform.position = new Vector3(pos.x,pos.y,-10);
                        scrollStartPos = touchMovePos;
                    }
                                  }
            }
        }
        else
        {
            // タッチを離したらフラグを落とし、スクロール開始位置も初期化する
            scrollStartFlg = false;
            scrollStartPos = new Vector2();
        }
    }
}


text:
#ifndef __ASM_ARCH_DEVICES_H__
#define __ASM_ARCH_DEVICES_H__

struct platform_device;
struct amba_device;

extern struct platform_device u5500_gpio_devs[];
extern struct platform_device u8500_gpio_devs[];

extern struct amba_device ux500_pl031_device;

extern struct platform_device u8500_dma40_device;
extern struct platform_device ux500_ske_keypad_device;

void dma40_u8500ed_fixup(void);

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="../../assets/ico/favicon.png">

    <title>Off Canvas Reveal Menu Template for Bootstrap</title>

    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../dist/css/jasny-bootstrap.min.css" rel="stylesheet">

    <link href="navmenu-reveal.css" rel="stylesheet">

      Project name

Slide in

Push

Reveal

Off canvas navbar

Link

Link

Link

          Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

        <button type="button" class="navbar-toggle" data-toggle="offcanvas" data-recalc="false" data-target=".navmenu" data-canvas=".canvas">

        </button>

Off Canvas Reveal Menu Template

This example demonstrates the use of the offcanvas plugin with a reveal effect.

On the contrary of the push effect, the menu doesn't move with the canvas.

You get the reveal effect by wrapping the content in a div and setting the canvas option to target that div.

Note that in this example, the navmenu doesn't have the offcanvas class, but is placed under the canvas by setting the z-index.

Also take a look at the examples for a navmenu with slide in effect and push effect.


text:
import flatMap from 'lodash/flatMap';
import Mediator from '../src/mediator';
import SCORM from '../src/SCORM';

describe('SCORM hashi shim', () => {
  let scorm;
  let mediator;
  beforeEach(() => {
    mediator = new Mediator(window);
    scorm = new SCORM(mediator);
  });
  describe('__setData', () => {
    it('should set data to the passed in data', () => {
      const testData = {
        test: 'test',
      };
      scorm.__setData(testData);
      expect(scorm.data).toEqual(testData);
    });
    it('should set data to an empty state if no data passed in', () => {
      scorm.__setData();
      expect(scorm.data).toEqual({});
    });
  });
  describe('__setUserData', () => {
    it('should set userData to the passed in data', () => {
      const testData = {
        test: 'test',
      };
      scorm.__setUserData(testData);
      expect(scorm.userData).toEqual(testData);
    });
    it('should set userData to an empty state if no data passed in', () => {
      scorm.__setUserData();
      expect(scorm.userData).toEqual({});
    });
  });
  describe('shim management and instance methods', () => {
    let shim;
    beforeEach(() => {
      shim = scorm.__setShimInterface();
      scorm.stateUpdated = jest.fn();
    });
    describe('__setShimInterface method', () => {
      it('should set scorm shim property', () => {
        expect(scorm.shim).not.toBeUndefined();
      });
    });
    describe('iframeInitialize method', () => {
      it('should set API property on object', () => {
        const obj = {};
        scorm.iframeInitialize(obj);
        expect(obj.API).toEqual(scorm.shim);
      });
    });
    describe('LMSInitialize method', () => {
      it('should return "true"', () => {
        expect(shim.LMSInitialize()).toEqual('true');
      });
      it('should stateUpdated', () => {
        shim.LMSInitialize();
        expect(scorm.stateUpdated).toHaveBeenCalled();
      });
    });
    describe('LMSSetValue and LMSGetValue methods', () => {
      const types = [
        'true-false',
        'choice',
        'fill-in',
        'matching',
        'performance',
        'sequencing',
        'likert',
        'numeric',
      ];
      const results = ['correct', 'wrong', 'unanticipated', 'neutral'];
      const statuses = ['passed', 'completed', 'failed', 'incomplete', 'browsed', 'not attempted'];
      const objectivesValues = flatMap(statuses, (s, i) => [
        ['cmi.objectives.' + i + '.id', `id${i}`],
        ['cmi.objectives.' + i + '.score.raw', 1 + i],
        ['cmi.objectives.' + i + '.score.min', 0],
        ['cmi.objectives.' + i + '.score.max', 10],
        ['cmi.objectives.' + i + '.status', s],
      ]);
      const interactionsValues = flatMap(types, (t, i) => [
        ['cmi.interactions.' + i + '.id', `id${i}`],
      ]);
      const values = [
        ['cmi.core.lesson_location', 'somewhere'],
        ['cmi.core.score.raw', 5],
        ['cmi.core.score.min', 0],
        ['cmi.core.score.max', 10],
        ['cmi.suspend_data', 'suspension'],
        ['cmi.comments', 'learning here'],
        ...statuses.map(status => ['cmi.core.lesson_status', status]),
        ...objectivesValues,
        ...interactionsValues,
      ];
      const writeOnlyInteractionsValues = flatMap(types, (t, i) => [
        ['cmi.interactions.' + i + '.time', '10:57:54'],
        ['cmi.interactions.' + i + '.type', t],
        ['cmi.interactions.' + i + '.weighting', 0.5],
        ['cmi.interactions.' + i + '.student_response', 3],
        ...results.map(r => ['cmi.interactions.' + i + '.result', r]),
        ['cmi.interactions.' + i + '.latency', '9:13:12'],
      ]);
      const notImplementedValues = [
        ['cmi.student_preference.audio', 3],
        ['cmi.student_preference.speed', 1],
        ['cmi.student_preference.text', 1],
      ];
      it.each(values)('should set and get %s properly', (key, value) => {
        shim.LMSSetValue(key, value);
        expect(shim.LMSGetValue(key)).toEqual(value);
      });
      it.each(writeOnlyInteractionsValues)(
        'should set without errors, but not get %s properly for write only properties',
        (key, value) => {
          shim.LMSSetValue(key, value);
          expect(shim.LMSGetLastError()).toEqual(0);
          expect(shim.LMSGetValue(key)).toEqual('');
          expect(shim.LMSGetLastError()).toEqual('404');
        }
      );
      it.each(notImplementedValues)(
        'should set with errors, and get %s with errors for not implemented properties',
        (key, value) => {
          shim.LMSSetValue(key, value);
          expect(shim.LMSGetLastError()).toEqual('401');
          expect(shim.LMSGetValue(key)).toEqual('');
          expect(shim.LMSGetLastError()).toEqual('401');
        }
      );
      it('should read language from the userData', () => {
        const language = 'fr-fr';
        scorm.userData.language = language;
        expect(shim.LMSGetValue('cmi.student_preference.language')).toEqual(language);
      });
      it('should count interactions properly', () => {
        interactionsValues.forEach(([k, v]) => shim.LMSSetValue(k, v));
        expect(shim.LMSGetValue('cmi.interactions._count')).toEqual(interactionsValues.length);
      });
      it('should count objectives properly', () => {
        statuses.map((s, i) => shim.LMSSetValue('cmi.objectives.' + i + '.id', `id${s}`));
        expect(shim.LMSGetValue('cmi.objectives._count')).toEqual(statuses.length);
      });
      it('should count objectives in an interaction properly', () => {
        shim.LMSSetValue('cmi.interactions.0.id', 'test');
        statuses.map((s, i) =>
          shim.LMSSetValue('cmi.interactions.0.objectives.' + i + '.id', `id${s}`)
        );
        expect(shim.LMSGetValue('cmi.interactions.0.objectives._count')).toEqual(statuses.length);
      });
    });
  });
});


text:
package tracer.differencing.core.diff;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;

public class GetAllITypeVisitor {

	public List<IType> types=new ArrayList<IType>();
	public void visit(ICompilationUnit unit){
		try {
			for(IType type:unit.getAllTypes()){
				visit(type);
			}
		} catch (JavaModelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void visit(IType type) throws JavaModelException{
		types.add(type);
		for(IMethod method:type.getMethods()){
			visit(method);
		}
	}
	public void visit(IMethod method) throws JavaModelException{
		IJavaElement[] elems=method.getChildren();
		for(IJavaElement elem:elems){
			if(elem instanceof IType)
				visit((IType)elem);
		}
	}
}


text:
from time import ctime,sleep
import multiprocessing
#定义两个方法说和写
def talk(content,loop):
    for i in range(loop):
        print("Talk: %s %s" %(content,ctime()))
        sleep(3)

def write(content, loop):
    for i in range(loop):
        print("write: %s %s" % (content, ctime()))
        sleep(3)
#定义两个进程
process=[]
p1=multiprocessing.Process(target=talk,args=('hello,51zxw',2))
process.append(p1)
p2=multiprocessing.Process(target=write,args=('python',2))
process.append(p2)
#调用进程
if __name__=='__main__':
    for p in process:
        p.start()
    for p in process:
        p.join()
    print ('All progress end %r' %ctime())


text:
var express = require('express');
var router = express.Router();

router.get('/tickets', function(req, res) {
  res.render('dashboard/tickets.html', {user: req.user});
});

router.get('/reports', function(req, res) {
  res.render('dashboard/reports.html', {user: req.user, customer: req.query.customer, show: req.query.show, search: req.query.search, start: req.query.start, end: req.query.end });
});

router.get('/customers', function(req, res) {
  res.render('dashboard/customers.html', {user: req.user});
});

router.get('/ticket/new', function(req, res) {
  res.render('dashboard/new_ticket.html', {user: req.user});
});

router.get('/ticket/:id', function(req, res) {
  res.render('dashboard/view_ticket.html', {id : req.params.id, user: req.user});
});

router.get('/counters', function(req, res) {
  res.render('dashboard/counters.html', {user: req.user});
});

module.exports = router;


text:
using IdentityServer4.Models;
using IdentityServer4.Services;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace IdentityServer.UnitTests.Common
{
    public class MockLogoutNotificationService : ILogoutNotificationService
    {
        public bool GetFrontChannelLogoutNotificationsUrlsCalled { get; set; }
        public List<string> FrontChannelLogoutNotificationsUrls { get; set; } = new List<string>();

        public bool SendBackChannelLogoutNotificationsCalled { get; set; }
        public List<BackChannelLogoutRequest> BackChannelLogoutRequests { get; set; } = new List<BackChannelLogoutRequest>();

        public Task<IEnumerable<string>> GetFrontChannelLogoutNotificationsUrlsAsync(LogoutNotificationContext context)
        {
            GetFrontChannelLogoutNotificationsUrlsCalled = true;
            return Task.FromResult(FrontChannelLogoutNotificationsUrls.AsEnumerable());
        }

        public Task<IEnumerable<BackChannelLogoutRequest>> GetBackChannelLogoutNotificationsAsync(LogoutNotificationContext context)
        {
            SendBackChannelLogoutNotificationsCalled = true;
            return Task.FromResult(BackChannelLogoutRequests.AsEnumerable());
        }
    }
}


text:
namespace MicroMapper
{
    using System;
    using System.Linq.Expressions;

    /// <summary>
    /// Custom resolver options
    /// </summary>
    /// <typeparam name="TSource">Source type</typeparam>
    public interface IResolverConfigurationExpression<TSource> : IResolutionExpression<TSource>
    {
        /// <summary>
        /// Construct the value resolver with the supplied constructor function
        /// </summary>
        /// <param name="constructor">Value resolver constructor function</param>
        /// <returns>Itself</returns>
        IResolutionExpression<TSource> ConstructedBy(Func<IValueResolver> constructor);
    }

    /// <summary>
    /// Custom resolver options
    /// </summary>
    /// <typeparam name="TSource">Source type</typeparam>
    /// <typeparam name="TValueResolver">Value resolver type</typeparam>
    public interface IResolverConfigurationExpression<TSource, TValueResolver>
        where TValueResolver : IValueResolver
    {
        /// <summary>
        /// Use the specified member as the input to the resolver instead of the root <typeparamref name="TSource"/> object
        /// </summary>
        /// <param name="sourceMember">Expression for the source member</param>
        /// <returns>Itself</returns>
        IResolverConfigurationExpression<TSource, TValueResolver> FromMember(Expression<Func<TSource, object>> sourceMember);

        /// <summary>
        /// Use the specified member as the input to the resolver instead of the root <typeparamref name="TSource"/> object
        /// </summary>
        /// <param name="sourcePropertyName">Name of the source member</param>
        /// <returns>Itself</returns>
        IResolverConfigurationExpression<TSource, TValueResolver> FromMember(string sourcePropertyName);

        /// <summary>
        /// Construct the value resolver with the supplied constructor function
        /// </summary>
        /// <param name="constructor">Value resolver constructor function</param>
        /// <returns>Itself</returns>
        IResolverConfigurationExpression<TSource, TValueResolver> ConstructedBy(Func<TValueResolver> constructor);
    }

    /// <summary>
    /// Custom resolver options
    /// </summary>
    public interface IResolverConfigurationExpression : IResolutionExpression
    {
        /// <summary>
        /// Construct the value resolver using supplied constructor function
        /// </summary>
        /// <param name="constructor">Value resolver constructor function</param>
        /// <returns>Itself</returns>
        IResolutionExpression ConstructedBy(Func<IValueResolver> constructor);
    }
}


text:
from datetime import datetime
import json

from freezegun import freeze_time

from django.core.urlresolvers import reverse
from django.test.client import Client
from django.test.utils import override_settings
from django.utils import timezone

from bulbs.content.models import Tag
from bulbs.utils.test import BaseIndexableTestCase, make_content

from example.testcontent.models import TestContentObj

@override_settings(BETTY_IMAGE_URL='//images.onionstatic.com/onion')
class GlanceFeedTestCase(BaseIndexableTestCase):

    maxDiff = None  # Show full diffs on error

    def get_feed(self, status_code=200, *args, **kwargs):
        TestContentObj.search_objects.refresh()
        resp = Client().get(reverse('glance-feed'), kwargs, SERVER_NAME='www.theonion.com')
        self.assertEqual(status_code, resp.status_code)
        if resp.status_code == 200:
            self.assertEqual('application/json', resp['content-type'])
            return json.loads(resp.content.decode('utf-8'))

    def test_empty(self):
        resp = self.get_feed()
        self.assertEqual(resp, {'count': 0,
                                'next': None,
                                'previous': None,
                                'results': []})

    @freeze_time('2016-5-3 10:11:12')
    def test_single_item(self):
        content = make_content(TestContentObj,
                               id=52852,
                               title='The Pros And Cons Of Taking A Gap Year',
                               published=datetime(2016, 5, 2, 14, 43, 0, tzinfo=timezone.utc),
                               thumbnail_override=53338)
        for name in ['College', 'Technology']:
            content.tags.add(Tag.objects.create(name=name))
        content.save()

        resp = self.get_feed()
        self.assertEqual(
            resp,
            {
                'count': 1,
                'next': None,
                'previous': None,
                'results': [{
                    'type': 'post',
                    'id': 52852,
                    'title': 'The Pros And Cons Of Taking A Gap Year',
                    'link': 'http://www.theonion.com/detail/52852/',
                    'modified': '2016-05-03T10:11:12+00:00',
                    'published': '2016-05-02T14:43:00+00:00',
                    'slug': 'the-pros-and-cons-of-taking-a-gap-year',
                    'images': {
                        'post-16-9-thumbnail': '//images.onionstatic.com/onion/5333/8/16x9/600.jpg',
                    },
                    'authors': ["America's Finest News Source"],
                    'tags': {
                        'section': ['College', 'Technology']
                    }
                }]
            })

    def test_pagination(self):
        make_content(TestContentObj,
                     published=datetime(2016, 5, 2, 14, 43, 0, tzinfo=timezone.utc),
                     _quantity=11)

        resp = self.get_feed(page=1, page_size=5)
        self.assertEqual(11, resp['count'])
        self.assertEqual(5, len(resp['results']))

        resp = self.get_feed(page=2, page_size=5)
        self.assertEqual(5, len(resp['results']))

        resp = self.get_feed(page=3, page_size=5)
        self.assertEqual(1, len(resp['results']))

    def test_pagination_bounds_404(self):
        # One page past last should trigger 404
        make_content(TestContentObj,
                     published=datetime(2016, 5, 2, 14, 43, 0, tzinfo=timezone.utc))
        self.get_feed(page=2, page_size=1, status_code=404)

    def test_sort_last_modified(self):
        now = timezone.now()
        content = make_content(TestContentObj,
                               published=now - timezone.timedelta(hours=1),
                               _quantity=5)
        # Stagger "last_modified" (an "auto_now" field)
        for c, offset in zip(content, [0, 4, 1, 3, 2]):
            with freeze_time(now - timezone.timedelta(hours=offset)):
                c.save()

        resp = self.get_feed()
        self.assertEqual([content[i].id for i in [0, 2, 4, 3, 1]],
                         [c['id'] for c in resp['results']])

    def test_filter_published(self):
        content = make_content(TestContentObj, published=None)
        self.assertEqual(0, self.get_feed()['count'])
        content.published = timezone.now() - timezone.timedelta(hours=1)
        content.save()
        self.assertEqual(1, self.get_feed()['count'])


text:
0.0.1-alpha.2
- Fix vendor name for Windows
- Fix app name
- Update `electron` to 0.34.3

0.0.1-alpha.1
- Added zooming with saving it to preferences
- Added window resizing with saving it to preferences
- Added external links

0.0.1-alpha
- First release


text:
using UnityEngine;
using System.Collections;
using System;

// Wraps UnityEngine.Microphone with Voice.IAudioStream interface.
internal class MicWrapper : ExitGames.Client.Photon.Voice.IAudioStreamFloat
{
    private AudioClip mic;
    private string device;

    public MicWrapper(string device, int suggestedFrequency)
    {
        if (Microphone.devices.Length < 1)
        {
            return;
        }
        this.device = device;
        int minFreq;
        int maxFreq;
        Microphone.GetDeviceCaps(device, out minFreq, out maxFreq);
        var frequency = suggestedFrequency;
//        minFreq = maxFreq = 44100; // test like android client
        if (suggestedFrequency < minFreq || maxFreq != 0 && suggestedFrequency > maxFreq)
        {
            Debug.LogWarningFormat("PUNVoice: MicWrapper does not support suggested frequency {0} (min: {1}, max: {2}). Setting to {2}",
                suggestedFrequency, minFreq, maxFreq);
            frequency = maxFreq;
        }
        this.mic = Microphone.Start(device, true, 1, frequency);
    }

    public void Dispose()
    {
		Microphone.End(this.device);
    }

    public int SamplingRate { get { return this.mic.frequency; } }
    public int Channels { get { return this.mic.channels; } }

    private int micPrevPos;
    private int micLoopCnt;
    private int readAbsPos;

    public bool GetData(float[] buffer)
    {
        int micPos = Microphone.GetPosition(this.device);
        // loop detection
        if (micPos < micPrevPos)
        {
            micLoopCnt++;
        }
        micPrevPos = micPos;

        var micAbsPos = micLoopCnt * this.mic.samples + micPos;

        var bufferSamplesCount = buffer.Length / mic.channels;

        var nextReadPos = this.readAbsPos + bufferSamplesCount;
        if (nextReadPos < micAbsPos)
        {
            this.mic.GetData(buffer, this.readAbsPos % this.mic.samples);
            this.readAbsPos = nextReadPos;
            return true;
        }
        else
        {
            return false;
        }
    }
}