text:
module Edi835
  class Aggregator
    class GS < ControlSegment
      def initialize(hash, options={})
        super()
        @parent_segment_id = options.fetch(:parent_segment_id)
        @group_key         = options.fetch(:group_key)
        @sets              = get_nested_segments(hash)
      end

      private
      def get_nested_segments(hash)
        hash.each do |key, set|
          segments = set[@parent_segment_id][@group_key]
          set[@parent_segment_id][@group_key] = aggregate(segments, Aggregator::ST, {parent_segment_id: header_id, group_key: children_label})
        end
        hash
      end

      def header_id
        'GS'
      end

      def trailer_id
        'GE'
      end

      def segment_label
        'functional_group'
      end

      def children_label
        :transaction_sets
      end
    end
  end
end


text:
namespace Poco {

class Foundation_API LogFileImpl
	/// The implementation of LogFile for OpenVMS.
	/// The C Standard Library functions for file I/O
	/// are used with OpenVMS-specific extensions to
	/// control sharing and locking behavior.
{
public:
	LogFileImpl(const std::string& path);
	~LogFileImpl();
	void writeImpl(const std::string& text, bool flush);
	UInt64 sizeImpl() const;
	Timestamp creationDateImpl() const;
	const std::string& pathImpl() const;

private:
	std::string   _path;
	mutable FILE* _file;
	Timestamp     _creationDate;
};

} // namespace Poco

#endif // Foundation_LogFile_VMS_INCLUDED

redpajama_set_name: RedPajamaGithub


text:
"""
Produce the k-mer abundance distribution for the given file.

% python scripts/abundance-dist-single.py <data> <histout>

The script does not load a prebuilt k-mer counting table.

Use '-h' for parameter help.
"""
import os
import sys
import csv
import khmer
import threading
import textwrap
from khmer.khmer_args import (build_counting_args, add_threading_args,
                              report_on_config, info)
from khmer.kfile import (check_input_files, check_space,
                         check_space_for_hashtable)

def get_parser():
    epilog = '''
    Note that with :option:`-b` this script is constant memory; in exchange,
    k-mer counts will stop at 255. The memory usage of this script with
    :option:`-b` will be about 1.15x the product of the :option:`-x` and
    :option:`-N` numbers.

    To count k-mers in multiple files use :program:`load_into_counting.py` and
    :program:`abundance_dist.py`.
    '''
    parser = build_counting_args(
        descr="Calculate the abundance distribution of k-mers from a "
        "single sequence file.", epilog=textwrap.dedent(epilog))
    add_threading_args(parser)

    parser.add_argument('input_sequence_filename', help='The name of the input'
                        ' FAST[AQ] sequence file.')
    parser.add_argument('output_histogram_filename', help='The name of the '
                        'output histogram file. The columns are: (1) k-mer '
                        'abundance, (2) k-mer count, (3) cumulative count, '
                        '(4) fraction of total distinct k-mers.')
    parser.add_argument('-z', '--no-zero', dest='output_zero', default=True,
                        action='store_false',
                        help='Do not output 0-count bins')
    parser.add_argument('-b', '--no-bigcount', dest='bigcount', default=True,
                        action='store_false',
                        help='Do not count k-mers past 255')
    parser.add_argument('-s', '--squash', dest='squash_output', default=False,
                        action='store_true',
                        help='Overwrite output file if it exists')
    parser.add_argument('--csv', default=False, action='store_true',
                        help='Use the CSV format for the histogram. '
                        'Includes column headers.')
    parser.add_argument('--savetable', default='', metavar="filename",
                        help="Save the k-mer counting table to the specified "
                        "filename.")
    parser.add_argument('--report-total-kmers', '-t', action='store_true',
                        help="Prints the total number of k-mers to stderr")
    parser.add_argument('-f', '--force', default=False, action='store_true',
                        help='Overwrite output file if it exists')
    return parser

def main():  # pylint: disable=too-many-locals,too-many-branches
    info('abundance-dist-single.py', ['counting', 'SeqAn'])
    args = get_parser().parse_args()
    report_on_config(args)

    check_input_files(args.input_sequence_filename, args.force)
    check_space([args.input_sequence_filename], args.force)
    if args.savetable:
        check_space_for_hashtable(args.n_tables * args.min_tablesize,
                                  args.force)

    if (not args.squash_output and
            os.path.exists(args.output_histogram_filename)):
        print >> sys.stderr, 'ERROR: %s exists; not squashing.' % \
            args.output_histogram_filename
        sys.exit(1)
    else:
        hist_fp = open(args.output_histogram_filename, 'w')
        if args.csv:
            hist_fp_csv = csv.writer(hist_fp)
            # write headers:
            hist_fp_csv.writerow(['abundance', 'count', 'cumulative',
                                  'cumulative_fraction'])

    print >>sys.stderr, 'making k-mer counting table'
    counting_hash = khmer.new_counting_hash(args.ksize, args.min_tablesize,
                                            args.n_tables)
    counting_hash.set_use_bigcount(args.bigcount)

    print >> sys.stderr, 'building k-mer tracking table'
    tracking = khmer.new_hashbits(counting_hash.ksize(), args.min_tablesize,
                                  args.n_tables)

    print >>sys.stderr, 'kmer_size:', counting_hash.ksize()
    print >>sys.stderr, 'k-mer counting table sizes:', \
        counting_hash.hashsizes()
    print >>sys.stderr, 'outputting to', args.output_histogram_filename

    # start loading
    rparser = khmer.ReadParser(args.input_sequence_filename)
    threads = []
    print >>sys.stderr, 'consuming input, round 1 --', \
        args.input_sequence_filename
    for _ in xrange(args.threads):
        thread = \
            threading.Thread(
                target=counting_hash.consume_fasta_with_reads_parser,
                args=(rparser, )
            )
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

    if args.report_total_kmers:
        print >> sys.stderr, 'Total number of unique k-mers: {0}'.format(
            counting_hash.n_unique_kmers())

    abundance_lists = []

    def __do_abundance_dist__(read_parser):
        abundances = counting_hash.abundance_distribution_with_reads_parser(
            read_parser, tracking)
        abundance_lists.append(abundances)

    print >>sys.stderr, 'preparing hist from %s...' % \
        args.input_sequence_filename
    rparser = khmer.ReadParser(args.input_sequence_filename)
    threads = []
    print >>sys.stderr, 'consuming input, round 2 --', \
        args.input_sequence_filename
    for _ in xrange(args.threads):
        thread = \
            threading.Thread(
                target=__do_abundance_dist__,
                args=(rparser, )
            )
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

    assert len(abundance_lists) == args.threads, len(abundance_lists)
    abundance = {}
    for abundance_list in abundance_lists:
        for i, count in enumerate(abundance_list):
            abundance[i] = abundance.get(i, 0) + count

    total = sum(abundance.values())

    if 0 == total:
        print >> sys.stderr, \
            "ERROR: abundance distribution is uniformly zero; " \
            "nothing to report."
        print >> sys.stderr, "\tPlease verify that the input files are valid."
        sys.exit(1)

    sofar = 0
    for _, i in sorted(abundance.items()):
        if i == 0 and not args.output_zero:
            continue

        sofar += i
        frac = sofar / float(total)

        if args.csv:
            hist_fp_csv.writerow([_, i, sofar, round(frac, 3)])
        else:
            print >> hist_fp, _, i, sofar, round(frac, 3)

        if sofar == total:
            break

    if args.savetable:
        print >>sys.stderr, 'Saving k-mer counting table ', args.savetable
        print >>sys.stderr, '...saving to', args.savetable
        counting_hash.save(args.savetable)

    print >> sys.stderr, 'wrote to: ' + args.output_histogram_filename

if __name__ == '__main__':
    main()

# vim: set ft=python ts=4 sts=4 sw=4 et tw=79:


text:
ALTER TABLE {$NAMESPACE}_phame.phame_blog
  ADD parentDomain VARCHAR(128) NOT NULL COLLATE {$COLLATE_TEXT};


text:
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Created by jayapriya on 12/29/14.
 */
public class TestClockAngle {
    @Test
    public void testAngle() {
        int hours = 3;
        int minutes = 40;
        double expected = 130.0;
        assertEquals(expected, ClockAngle.calculateAngle(hours, minutes),0.1);
    }
    @Test
    public void testZeroAngle() {
        int hours = 12;
        int minutes = 0;
        double expected = 0.0;
        assertEquals(expected,ClockAngle.calculateAngle(hours, minutes),0.1);
    }
    @Test
    public void test12hrs() {
        int hours = 12;
        int minutes = 50;
        double expected = 85.0;
        assertEquals(expected,ClockAngle.calculateAngle(hours,minutes),0.1);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<plugin
   id="summary-basic"
   name="Basic Summarizer Plug-in"
   version="1.0.0"
   provider-name="org.apache.nutch">

   <runtime>
      <library name="summary-basic.jar">
         <export name="*"/>
      </library>
   </runtime>

   <requires>
      <import plugin="nutch-extensionpoints"/>
   </requires>

   <extension id="org.apache.nutch.summary.basic"
              name="Basic Summarizer"
              point="org.apache.nutch.searcher.Summarizer">

      <implementation id="Basic Summarizer"
                      class="org.apache.nutch.summary.basic.BasicSummarizer"/>

   </extension>

</plugin>


text:
WIP

Uses https://github.com/davezuko/react-redux-starter-kit for scaffolding

## Data model


text:
<!DOCTYPE html>

		<meta charset="utf-8" />

		<link href="asset/css/bootstrap.css" rel="stylesheet" />
		<link rel="stylesheet" href="asset/css/dexter.min.css" />
		<link rel="stylesheet" href="asset/css/font-awesome.min.css" />

		<link rel="stylesheet" href="asset/css/prettify.css" />

 Checker Code

					functionStatic

 Description

The member function 'funcname' can be static.

 Severity

					Minor

 Detector / Bug Pattern

The member function 'funcname' can be static.

 More Information

/* The member function 'funcname' can be static.
No, a static method can only see static members of the class. It doesn't make sense for it to access instance
members (as in, standard variables etc) as they don't exist unless the class has been instantiated.

It seems like you want something like the Singleton design pattern. This allows for only a single instance of
 the class to exist at a time.
*/

 Bad Code

 Good Code

 CWE ID

				0

 Code Review Asset

					N/A

 URLs

					https://social.msdn.microsoft.com/Forums/office/en-US/3812714f-2e95-40e3-882c-22eb8cc5e85a/how-to-make-void-myclassfuncname-compatible-with-void-funcname?forum=vcgeneral

					http://stackoverflow.com/questions/2576022/efficient-thread-safe-singleton-in-c


text:
function ConvertTo-JiraProjectRole {
    [CmdletBinding()]
    param(
        [Parameter( ValueFromPipeline )]
        [PSObject[]]
        $InputObject
    )

    process {
        foreach ($i in $InputObject) {
            Write-Debug "[$($MyInvocation.MyCommand.Name)] Converting `$InputObject to custom object"

            $props = @{
                'ID'          = $i.id
                'Name'        = $i.name
                'Description' = $i.description
                'Actors'      = $i.actors
                'RestUrl'     = $i.self
            }

            $result = New-Object -TypeName PSObject -Property $props
            $result.PSObject.TypeNames.Insert(0, 'JiraPS.ProjectRole')
            $result | Add-Member -MemberType ScriptMethod -Name "ToString" -Force -Value {
                Write-Output "$($this.Name)"
            }

            Write-Output $result
        }
    }
}


text:
package com.locationlabs.porchlight.activity.main;

import android.util.Log;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.locationlabs.porchlight.PorchlightApplication;
import com.locationlabs.porchlight.api.ApiResources;
import com.locationlabs.porchlight.api.model.Flows;
import com.locationlabs.porchlight.api.model.UserFlow;
import com.locationlabs.porchlight.util.DataStore;
import com.locationlabs.porchlight.util.VolleyUtil;
import com.locationlabs.porchlight.util.base.BaseInteractorImpl;

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

/**
 * Real interactor implementation doing API calls.
 * Backend is currently down so using mock instead for Github.
 */
public class MainInteractorImpl extends BaseInteractorImpl implements MainInteractor {

   private static final String TAG = MainInteractorImpl.class.getSimpleName();

   private static final String REQUEST_TAG = "REQUEST_TAG";

   private MainPresenter mPresenter;

   public MainInteractorImpl(MainPresenter presenter) {
      super(presenter);
      mPresenter = presenter;
   }

   @Override
   public void requestFlows() {
      String url = ApiResources.getUrl(ApiResources.BASE_URL, ApiResources.FLOW_PATH);
      StringRequest stringRequest = new StringRequest(
            Request.Method.GET, url,
            new Response.Listener<String>() {
               @Override
               public void onResponse(String response) {
                  Log.d(TAG, "Received: " + response);

                  List<UserFlow> flows = new ArrayList<>();
                  if (response != null) {
                     Flows flowList = new Gson().fromJson(response, Flows.class);
                     flows.addAll(Arrays.asList(flowList.flows));
                  }

                  mPresenter.updateFlows(flows);
               }
            },
            new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
                  mPresenter.onError(error);
               }
            });

      stringRequest.setTag(REQUEST_TAG);
      VolleyUtil
            .getInstance(PorchlightApplication.getContext())
            .addToRequestQueue(stringRequest);
   }

   @Override
   public void clearNewFlow() {
      DataStore.setNewFlowData(PorchlightApplication.getContext(), null);
   }

   @Override
   public void cancelBackgroundTasks() {
      super.cancelBackgroundTasks();
      VolleyUtil
            .getInstance(PorchlightApplication.getContext())
            .getRequestQueue()
            .cancelAll(REQUEST_TAG);
   }
}


text:
package com.google.android.imaging.pixelvisualcorecamera.api2;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.hardware.Camera.CameraInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.util.Size;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.imaging.pixelvisualcorecamera.R;
import com.google.android.imaging.pixelvisualcorecamera.common.FileSystem;
import com.google.android.imaging.pixelvisualcorecamera.common.Intents;
import com.google.android.imaging.pixelvisualcorecamera.common.Preferences;
import com.google.android.imaging.pixelvisualcorecamera.common.Toasts;
import com.google.android.imaging.pixelvisualcorecamera.common.Utils;
import java.io.IOException;

/**
 *  Primary activity for an API 2 camera.
 */
public class CameraApi2Activity extends Activity {

  private static final String TAG = "PvcCamApi2";

  private static final String CAMERA_FACING_BACK = "0";
  private static final String CAMERA_FACING_FRONT = "1";
  private static final String STATE_ZOOM = "zoom";

  private String cameraId;
  private HandlerThread backgroundThread;
  private Handler backgroundHandler;
  private Camera2Controller cameraController;
  private Preferences preferences;
  private Size outputSize;
  private ScaleGestureDetector zoomScaleGestureDetector;
  private ZoomScaleGestureListener zoomScaleGestureListener;
  private boolean resumed;
  private boolean cameraAcquired;

  private final Camera2Controller.OnImageAvailableListener onImageAvailableListener =
      (image) -> FileSystem.saveImage(getApplicationContext(), image, /*isApi1*/ false);

  // ===============================================================================================
  // Activity Framework Callbacks
  // ===============================================================================================

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "[onCreate]");
    preferences = new Preferences(this);
    setContentView(R.layout.camera2);
    AutoFitTextureView textureView = findViewById(R.id.camera_preview);
    Utils.setSystemUiOptionsForFullscreen(this);

    Button captureButton = findViewById(R.id.button_capture);
    captureButton.setOnClickListener(v -> cameraController.takePicture());
    Button doubleShotButton = findViewById(R.id.doubleshot_button);
    doubleShotButton.setVisibility(View.VISIBLE);
    doubleShotButton.setOnClickListener(v -> cameraController.takeDoubleShot());

    cameraController = new Camera2Controller(
        getApplicationContext(),
        getWindowManager().getDefaultDisplay().getRotation(),
        captureButton,
        doubleShotButton,
        textureView,
        onImageAvailableListener);

    initTopControls();
    configureOutputSize();

    zoomScaleGestureListener = new ZoomScaleGestureListener(
        cameraController, findViewById(R.id.zoom_level_label), STATE_ZOOM);
    zoomScaleGestureListener.restoreInstanceState(savedInstanceState);
    zoomScaleGestureDetector = new ScaleGestureDetector(this, zoomScaleGestureListener);
  }

  @Override
  public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    Log.d(TAG, "[onWindowFocusChanged] hasFocus: " + hasFocus);
    if (hasFocus) {
      Utils.setSystemUiOptionsForFullscreen(this);
      acquireCameraIfReady();
    }
  }

  @Override
  public void onResume() {
    super.onResume();
    Log.d(TAG, "[onResume]");
    startBackgroundThread();
    cameraController.setBackgroundHandler(backgroundHandler);
    zoomScaleGestureListener.initZoomParameters(cameraId);
    resumed = true;
    acquireCameraIfReady();
  }

  @Override
  public void onPause() {
    super.onPause();
    Log.d(TAG, "[onPause]");
    resumed = false;
    cameraController.closeCamera();
    cameraAcquired = false;
    stopBackgroundThread();
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    zoomScaleGestureListener.saveInstanceState(outState);
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    return zoomScaleGestureDetector.onTouchEvent(event);
  }

  /** Acquires the camera if the window has focus and the activity has been resumed. */
  private void acquireCameraIfReady() {
    if (!cameraAcquired && resumed && hasWindowFocus()) {
      try {
        cameraController.acquireCamera(cameraId, outputSize, zoomScaleGestureListener.getZoom());
        cameraAcquired = true;
      } catch (IOException e) {
        String errorMessage = "Failed to acquire camera";
        Toasts.showToast(this, errorMessage, Toast.LENGTH_LONG);
        Log.w(TAG, errorMessage, e);
        finish();
      }
    }
  }

  // ===============================================================================================
  // Top Controls
  // ===============================================================================================

  private void initTopControls() {
    initApiSwitch();
    initCameraSelection();
    setCameraIconForCurrentCamera();
    ImageButton cameraSelectionButton = findViewById(R.id.control_camera_selection);
    cameraSelectionButton.setOnClickListener(cameraSelectionOnClickListener);
  }

  @SuppressLint("SetTextI18n")
  private void initApiSwitch() {
    Button button = findViewById(R.id.api_selector);
    button.setText("API 2");
    button.setOnClickListener(v -> {
      Log.i(TAG, "switching to API 1");
      preferences.setModeApi1(true);
      finish();
      startActivity(Intents.createApi1Intent());
    });
  }

  /** Initializes cameraId state from global preferences. */
  @SuppressWarnings("deprecation")
  private void initCameraSelection() {
    int cameraIdInt = preferences.getCameraId();
    if (cameraIdInt > CameraInfo.CAMERA_FACING_FRONT) {
      Log.e(TAG, "out of bounds camera id: " + cameraIdInt);
      cameraIdInt = CameraInfo.CAMERA_FACING_BACK;
      preferences.setCameraId(cameraIdInt);
    }
    cameraId = String.valueOf(cameraIdInt);
  }

  private void setCameraIconForCurrentCamera() {
    ImageButton button = findViewById(R.id.control_camera_selection);
    switch (cameraId) {
      case CAMERA_FACING_BACK:
        button.setImageResource(R.drawable.ic_camera_rear_white_24);
        break;
      case CAMERA_FACING_FRONT:
        button.setImageResource(R.drawable.ic_camera_front_white_24);
        break;
      default:
        break;
    }
  }

  /** Handles clicks on the camera selection button. */
  private final OnClickListener cameraSelectionOnClickListener = new OnClickListener() {

    @Override
    public void onClick(View view) {
      Log.i(TAG, "changing cameras, releasing camera");
      // Swap camera ids.
      switch (cameraId) {
        case CAMERA_FACING_BACK:
          cameraId = CAMERA_FACING_FRONT;
          break;
        case CAMERA_FACING_FRONT:
          cameraId = CAMERA_FACING_BACK;
          break;
        default:
          Log.e(TAG, "unrecognized camera id: " + cameraId);
          cameraId = CAMERA_FACING_BACK;
      }
      preferences.setCameraId(Integer.valueOf(cameraId));
      setCameraIconForCurrentCamera();

      Log.i(TAG, "restarting with new camera");
      zoomScaleGestureListener.reset();
      closeAndOpenCamera();
    }
  };

  /** Call this when the camera is not acquired, to select the output size when it is acquired. */
  private void configureOutputSize() {
    Log.d(TAG, "configureOutputSize");
    Size[] sizes = cameraController.getSupportedPictureSizes(cameraId);
    outputSize = sizes[0];
  }

  /** Closes the camera and reacquires with the given outputSize. */
  private void closeAndOpenCamera() {
    Log.d(TAG, "closeAndOpenCamera");
    cameraController.closeCamera();
    cameraAcquired = false;
    configureOutputSize();
    zoomScaleGestureListener.initZoomParameters(cameraId);
    try {
      cameraController.acquireCamera(cameraId, outputSize, zoomScaleGestureListener.getZoom());
      cameraAcquired = true;
    } catch (IOException e) {
      Log.w(TAG, e);
    }
  }

  // ===============================================================================================
  // Thread
  // ===============================================================================================

  /** Starts a background thread and its {@link Handler}. */
  private void startBackgroundThread() {
    backgroundThread = new HandlerThread("CameraBackground");
    backgroundThread.start();
    backgroundHandler = new Handler(backgroundThread.getLooper());
  }

  /** Stops the background thread and its {@link Handler}. */
  private void stopBackgroundThread() {
    backgroundThread.quitSafely();
    try {
      backgroundThread.join();
      backgroundThread = null;
      backgroundHandler = null;
    } catch (InterruptedException e) {
      Log.w(TAG, "Interrupted while shutting background thread down", e);
    }
  }
}


text:
{% extends "base_admin.html" %}

{% block head_additions %}
{{ block.super }}

{% endblock %}

{% block content_admin %}

{% for group in exam_groups %}

	{% ifequal group exam_group %}  {% endifequal %} {{ group.name }} {% ifequal group exam_group %}  {% endifequal %}

{% endfor %}

			<button type="button">Edit Session</button>

			<button type="button">Create New Session</button>

Stats

{% if stats %}

{{ stats.finished_students_count }} student{{ stats.finished_students_count|pluralize:" has,s have" }} taken the test out of {{ stats.total_students_count }} student{{ stats.total_students_count|pluralize }} ({{ stats.finished_students_percentage|floatformat }}%). Currently, {{ stats.current_students_count }} student{{ stats.current_students_count|pluralize:" is,s are" }} taking the test right now.

The average score is {{ stats.average_score_percentage|floatformat }}% ({{ stats.average_score }} out of {{ stats.question_count }}).

The standard deviation is {{ stats.standard_deviation|floatformat|default:"not available" }}.

The highest score is {{ stats.high_score_percentage|floatformat }}% ({{ stats.high_score }} out of {{ stats.question_count }}).

The lowest score is {{ stats.low_score_percentage|floatformat }}% ({{ stats.low_score }} out of {{ stats.question_count }}).

{% else %}

This group has no questions or no students yet. To view statistics, you must have assigned both problems and students to this group.

{% endif %}

Grades

            Last Name
            Student ID
            Grade

	    {% for student in finished_students %}

	            {{ student.user.last_name }}
	            {{ student.user.get_profile.student_id }}
	            {{ student.score }}

	    {% endfor %}

Grade distribution

		# of students

		Grade

Question Distributions

This is a breakdown of student answers for all questions. Click any row to see the question and its answers.

            #
               A
               B
               C
               D
			    {% ifequal exam_group.answers_per_problem 5 %}
               E
				{% endifequal %}
               Unanswered

        {% for distribution in problem_distributions %}

        <tr class="problem_number_row" apprise_info="
{{ distribution.problem.text }}

																{% for answer in distribution.problem.sorted_answers %}

														        	{{ answer.letter|upper }})
														        	{{ answer.text }}

														    	{% endfor %}

">

                {{ distribution.problem.number }}

            {% for answer_distr in distribution.answers %}
            {{ answer_distr.chosen_percentage|floatformat }}% {% if answer_distr.answer.correct %}{% endif %} {% if answer_distr.chosen_count > 0 %}
({{ answer_distr.chosen_count }}) {% endif %}
            {% endfor %}

            {{ distribution.unanswered_percentage|floatformat }}% {% if distribution.unanswered_count > 0 %}
({{ distribution.unanswered_count }}) {% endif %}

        {% endfor %}

{% endblock %}


text:
package com.hp.ov.sdk.dto.alerts;

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

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

import com.hp.ov.sdk.dto.BaseModelResource;
import com.hp.ov.sdk.dto.servers.HealthStatus;

public class AlertResource extends BaseModelResource {

    private static final long serialVersionUID = 1L;

    private String activityUri;
    private AlertState alertState;
    private String alertTypeID;
    private String assignedToUser;
    private List<String> associatedEventUris = new ArrayList<String>();
    private AssociatedResource associatedResource;
    private List<ChangeLog> changeLog = new ArrayList<ChangeLog>();
    private List<String> childAlerts = new ArrayList<String>();
    private String clearedByUser;
    private String clearedTime;
    private String correctiveAction;
    private String healthCategory;
    private Boolean lifeCycle;
    private String parentAlert;
    private String physicalResourceType;
    private String resourceID;
    private String resourceUri;
    private ServiceEventData serviceEventDetails;
    private Boolean serviceEventSource;
    private HealthStatus severity;
    private AlertUrgency urgency;

    /**
     * @return the activityUri
     */
    public String getActivityUri() {
        return activityUri;
    }

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

    /**
     * @return the alertState
     */
    public AlertState getAlertState() {
        return alertState;
    }

    /**
     * @param alertState the alertState to set
     */
    public void setAlertState(AlertState alertState) {
        this.alertState = alertState;
    }

    /**
     * @return the alertTypeID
     */
    public String getAlertTypeID() {
        return alertTypeID;
    }

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

    /**
     * @return the assignedToUser
     */
    public String getAssignedToUser() {
        return assignedToUser;
    }

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

    /**
     * @return the associatedEventUris
     */
    public List<String> getAssociatedEventUris() {
        return associatedEventUris;
    }

    /**
     * @param associatedEventUris the associatedEventUris to set
     */
    public void setAssociatedEventUris(List<String> associatedEventUris) {
        this.associatedEventUris = associatedEventUris;
    }

    /**
     * @return the associatedResource
     */
    public AssociatedResource getAssociatedResource() {
        return associatedResource;
    }

    /**
     * @param associatedResource the associatedResource to set
     */
    public void setAssociatedResource(AssociatedResource associatedResource) {
        this.associatedResource = associatedResource;
    }

    /**
     * @return the changeLog
     */
    public List<ChangeLog> getChangeLog() {
        return changeLog;
    }

    /**
     * @param changeLog the changeLog to set
     */
    public void setChangeLog(List<ChangeLog> changeLog) {
        this.changeLog = changeLog;
    }

    /**
     * @return the childAlerts
     */
    public List<String> getChildAlerts() {
        return childAlerts;
    }

    /**
     * @param childAlerts the childAlerts to set
     */
    public void setChildAlerts(List<String> childAlerts) {
        this.childAlerts = childAlerts;
    }

    /**
     * @return the clearedByUser
     */
    public String getClearedByUser() {
        return clearedByUser;
    }

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

    /**
     * @return the clearedTime
     */
    public String getClearedTime() {
        return clearedTime;
    }

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

    /**
     * @return the correctiveAction
     */
    public String getCorrectiveAction() {
        return correctiveAction;
    }

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

    /**
     * @return the healthCategory
     */
    public String getHealthCategory() {
        return healthCategory;
    }

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

    /**
     * @return the lifeCycle
     */
    public Boolean getLifeCycle() {
        return lifeCycle;
    }

    /**
     * @param lifeCycle the lifeCycle to set
     */
    public void setLifeCycle(Boolean lifeCycle) {
        this.lifeCycle = lifeCycle;
    }

    /**
     * @return the parentAlert
     */
    public String getParentAlert() {
        return parentAlert;
    }

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

    /**
     * @return the physicalResourceType
     */
    public String getPhysicalResourceType() {
        return physicalResourceType;
    }

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

    /**
     * @return the resourceID
     */
    public String getResourceID() {
        return resourceID;
    }

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

    /**
     * @return the resourceUri
     */
    public String getResourceUri() {
        return resourceUri;
    }

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

    /**
     * @return the serviceEventDetails
     */
    public ServiceEventData getServiceEventDetails() {
        return serviceEventDetails;
    }

    /**
     * @param serviceEventDetails the serviceEventDetails to set
     */
    public void setServiceEventDetails(ServiceEventData serviceEventDetails) {
        this.serviceEventDetails = serviceEventDetails;
    }

    /**
     * @return the serviceEventSource
     */
    public Boolean getServiceEventSource() {
        return serviceEventSource;
    }

    /**
     * @param serviceEventSource the serviceEventSource to set
     */
    public void setServiceEventSource(Boolean serviceEventSource) {
        this.serviceEventSource = serviceEventSource;
    }

    /**
     * @return the severity
     */
    public HealthStatus getSeverity() {
        return severity;
    }

    /**
     * @param severity the severity to set
     */
    public void setSeverity(HealthStatus severity) {
        this.severity = severity;
    }

    /**
     * @return the urgency
     */
    public AlertUrgency getUrgency() {
        return urgency;
    }

    /**
     * @param urgency the urgency to set
     */
    public void setUrgency(AlertUrgency urgency) {
        this.urgency = urgency;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder()
                .append(activityUri)
                .append(alertState)
                .append(alertTypeID)
                .append(assignedToUser)
                .append(associatedEventUris)
                .append(associatedResource)
                .append(changeLog)
                .append(childAlerts)
                .append(clearedByUser)
                .append(clearedTime)
                .append(correctiveAction)
                .append(healthCategory)
                .append(lifeCycle)
                .append(parentAlert)
                .append(physicalResourceType)
                .append(resourceID)
                .append(resourceUri)
                .append(serviceEventDetails)
                .append(serviceEventSource)
                .append(severity)
                .append(urgency)
                .appendSuper(super.hashCode())
                .toHashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        }
        if ((other instanceof AlertResource) == false) {
            return false;
        }
        AlertResource rhs = ((AlertResource) other);
        return new EqualsBuilder()
                .append(activityUri, rhs.activityUri)
                .append(alertState, rhs.alertState)
                .append(alertTypeID, rhs.alertTypeID)
                .append(assignedToUser, rhs.assignedToUser)
                .append(associatedEventUris, rhs.associatedEventUris)
                .append(associatedResource, rhs.associatedResource)
                .append(changeLog, rhs.changeLog)
                .append(childAlerts, rhs.childAlerts)
                .append(clearedByUser, rhs.clearedByUser)
                .append(clearedTime, rhs.clearedTime)
                .append(correctiveAction, rhs.correctiveAction)
                .append(healthCategory, rhs.healthCategory)
                .append(lifeCycle, rhs.lifeCycle)
                .append(parentAlert, rhs.parentAlert)
                .append(physicalResourceType, rhs.physicalResourceType)
                .append(resourceID, rhs.resourceID)
                .append(resourceUri, rhs.resourceUri)
                .append(serviceEventDetails, rhs.serviceEventDetails)
                .append(serviceEventSource, rhs.serviceEventSource)
                .append(severity, rhs.severity)
                .append(urgency, rhs.urgency)
                .appendSuper(super.equals(other))
                .isEquals();
        }

}


text:
/**
 * @fileoverview Variable blocks for Blockly.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.Blocks.variables');

goog.require('Blockly.Blocks');

/**
 * Common HSV hue for all blocks in this category.
 */
Blockly.Blocks.variables.HUE = 330;

Blockly.Blocks['variables_get'] = {
  /**
   * Block for variable getter.
   * @this Blockly.Block
   */
  init: function() {
    this.setHelpUrl(Blockly.Msg.VARIABLES_GET_HELPURL);
    this.setColour(Blockly.Blocks.variables.HUE);
    this.appendDummyInput()
        .appendField(new Blockly.FieldVariable(
        Blockly.Msg.VARIABLES_DEFAULT_NAME), 'VAR');
    this.setOutput(true);
    this.setTooltip(Blockly.Msg.VARIABLES_GET_TOOLTIP);
  },
  /**
   * Return all variables referenced by this block.
   * @return {!Array.<string>} List of variable names.
   * @this Blockly.Block
   */
  getVars: function() {
    return [this.getFieldValue('VAR')];
  },
  /**
   * Notification that a variable is renaming.
   * If the name matches one of this block's variables, rename it.
   * @param {string} oldName Previous name of variable.
   * @param {string} newName Renamed variable.
   * @this Blockly.Block
   */
  renameVar: function(oldName, newName) {
    if (Blockly.Names.equals(oldName, this.getFieldValue('VAR'))) {
      this.setFieldValue(newName, 'VAR');
    }
  },
  contextMenuMsg_: Blockly.Msg.VARIABLES_GET_CREATE_SET,
  contextMenuType_: 'variables_set',
  /**
   * Add menu option to create getter/setter block for this setter/getter.
   * @param {!Array} options List of menu options to add to.
   * @this Blockly.Block
   */
  customContextMenu: function(options) {
    var option = {enabled: true};
    var name = this.getFieldValue('VAR');
    option.text = this.contextMenuMsg_.replace('%1', name);
    var xmlField = goog.dom.createDom('field', null, name);
    xmlField.setAttribute('name', 'VAR');
    var xmlBlock = goog.dom.createDom('block', null, xmlField);
    xmlBlock.setAttribute('type', this.contextMenuType_);
    option.callback = Blockly.ContextMenu.callbackFactory(this, xmlBlock);
    options.push(option);
  }
};

Blockly.Blocks['variables_set'] = {
  /**
   * Block for variable setter.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message": Blockly.Msg.VARIABLES_SET,
      "args": [
        {
          "type": "field_variable",
          "name": "VAR",
          "variable": Blockly.Msg.VARIABLES_DEFAULT_NAME
        },
        {
          "type": "input_value",
          "name": "VALUE"
        }
      ],
      "previousStatement": null,
      "nextStatement": null,
      "colour": Blockly.Blocks.variables.HUE,
      "tooltip": Blockly.Msg.VARIABLES_SET_TOOLTIP,
      "helpUrl": Blockly.Msg.VARIABLES_SET_HELPURL
    });
  },
  /**
   * Return all variables referenced by this block.
   * @return {!Array.<string>} List of variable names.
   * @this Blockly.Block
   */
  getVars: function() {
    return [this.getFieldValue('VAR')];
  },
  /**
   * Notification that a variable is renaming.
   * If the name matches one of this block's variables, rename it.
   * @param {string} oldName Previous name of variable.
   * @param {string} newName Renamed variable.
   * @this Blockly.Block
   */
  renameVar: function(oldName, newName) {
    if (Blockly.Names.equals(oldName, this.getFieldValue('VAR'))) {
      this.setFieldValue(newName, 'VAR');
    }
  },
  contextMenuMsg_: Blockly.Msg.VARIABLES_SET_CREATE_GET,
  contextMenuType_: 'variables_get',
  customContextMenu: Blockly.Blocks['variables_get'].customContextMenu
};


text: This is a fork of Dinesh's https://github.com/flexdinesh/dev-landing-page


text:
package org.apache.ode.dao.jpa;

import org.apache.ode.bpel.common.CorrelationKey;
import org.apache.ode.bpel.common.CorrelationKeySet;
import org.apache.ode.bpel.dao.MessageRouteDAO;
import org.apache.ode.bpel.dao.ProcessInstanceDAO;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

@Entity
@Table(name="ODE_MESSAGE_ROUTE")
@NamedQueries ({
	@NamedQuery(name=MessageRouteDAOImpl.DELETE_MESSAGE_ROUTES_BY_INSTANCE_IDS, query="delete from MessageRouteDAOImpl as r where r._instanceId in(:instanceIds)"),
	@NamedQuery(name=MessageRouteDAOImpl.DELETE_MESSAGE_ROUTES_BY_INSTANCE, query="delete from MessageRouteDAOImpl as r where r._processInst = :instance")
})
public class MessageRouteDAOImpl implements MessageRouteDAO {
	public final static String DELETE_MESSAGE_ROUTES_BY_INSTANCE = "DELETE_MESSAGE_ROUTES_BY_INSTANCE";
	public final static String DELETE_MESSAGE_ROUTES_BY_INSTANCE_IDS = "DELETE_MESSAGE_ROUTES_BY_INSTANCE_IDS";

	@Id @Column(name="MESSAGE_ROUTE_ID")
	@GeneratedValue(strategy=GenerationType.AUTO)
	private Long _id;
	@Basic @Column(name="GROUP_ID")
    private String _groupId;
	@Basic @Column(name="ROUTE_INDEX")
    private int _index;
	@Basic @Column(name="CORRELATION_KEY")
    private String _correlationKey;
	@Basic @Column(name="ROUTE_POLICY", length=16)
    private String _routePolicy;

	@SuppressWarnings("unused")
	@Basic @Column(name="PROCESS_INSTANCE_ID", insertable=false, updatable=false, nullable=true)
    private int _instanceId;
    @ManyToOne(fetch=FetchType.LAZY,cascade={CascadeType.PERSIST}) @Column(name="PROCESS_INSTANCE_ID")
    private ProcessInstanceDAOImpl _processInst;

    @ManyToOne(fetch= FetchType.LAZY,cascade={CascadeType.PERSIST}) @Column(name="CORR_ID")
    @SuppressWarnings("unused")
    private CorrelatorDAOImpl _correlator;

    public MessageRouteDAOImpl() {}
	public MessageRouteDAOImpl(CorrelationKeySet keySet, String groupId, int index,
                               ProcessInstanceDAOImpl processInst, CorrelatorDAOImpl correlator, String routePolicy) {
		_correlationKey = keySet.toCanonicalString();
		_groupId = groupId;
		_index = index;
		_processInst = processInst;
        _correlator = correlator;
        _routePolicy = routePolicy;
    }

    public Long getId() {
        return _id;
    }

    public CorrelationKey getCorrelationKey() {
		return new CorrelationKey(_correlationKey);
	}

    public void setCorrelationKey(CorrelationKey key) {
        _correlationKey = key.toCanonicalString();
    }

	public String getGroupId() {
		return _groupId;
	}

	public int getIndex() {
		return _index;
	}

	public ProcessInstanceDAO getTargetInstance() {
		return _processInst;
	}

	public String getRoute() {
		return _routePolicy;
	}

	public CorrelationKeySet getCorrelationKeySet() {
		return new CorrelationKeySet(_correlationKey);
	}

    public void setCorrelationKeySet(CorrelationKeySet keySet) {
        _correlationKey = keySet.toCanonicalString();
    }
}


text:
layout: page
title: Conner Chief Software Seminar
date: 2016-05-24
author: Amy Moody
tags: weekly links, java
status: published
summary: Ut sollicitudin semper luctus. Lorem.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 03/05/2018
  endDate: 03/08/2018
  ctyhocn: DALLSHX
  groupCode: CCSS
published: true
---
Aliquam erat volutpat. Donec et dui ac nunc dapibus cursus in at metus. Vivamus dignissim tellus sed porta suscipit. Vestibulum massa lectus, consequat sit amet orci consequat, hendrerit hendrerit velit. Cras mi augue, gravida et pretium sit amet, dictum vel eros. Cras imperdiet viverra lorem, vitae pulvinar urna ultrices ac. Donec non gravida felis. Donec euismod sit amet dolor sit amet hendrerit. Etiam massa ante, sagittis sed sodales quis, suscipit in magna. Pellentesque sit amet posuere urna. Suspendisse fermentum purus non consequat malesuada.
Fusce vehicula malesuada mi. Morbi sit amet arcu metus. Suspendisse semper finibus nibh, a ullamcorper metus cursus at. Nulla libero nisl, vestibulum et nunc vitae, rutrum tincidunt tellus. Etiam semper vehicula urna, vitae cursus elit finibus eget. Pellentesque pharetra quam a ultrices varius. Nam lobortis justo ut molestie dignissim. Sed a sem sed odio blandit consectetur. Aliquam placerat mauris ex, id interdum justo malesuada vitae. In a cursus nunc, in luctus dui. Donec commodo, lorem sit amet lacinia congue, arcu lectus dignissim neque, ut commodo elit eros nec felis. Cras libero lectus, lacinia a odio quis, lobortis bibendum velit.

* Vestibulum dignissim elit egestas, convallis mauris a, egestas nisl
* Nunc consequat est a ornare feugiat
* Phasellus id enim laoreet nisl congue porttitor
* Nam eget tellus nec enim consectetur facilisis.

Maecenas gravida sodales lacus vel efficitur. Duis eleifend tortor nec mi vehicula facilisis. Pellentesque sagittis aliquam nisi, eget ultricies enim ornare nec. Suspendisse sollicitudin est et lorem venenatis blandit. Duis quis hendrerit elit. Suspendisse potenti. Nam vel varius leo. Donec egestas tincidunt nulla, ut sollicitudin odio pretium ut. Nam a mattis purus.


text:
module ActiveRecord
  class Base
    def self.reset_pk_sequence
      adapter_name = ActiveRecord::Base.connection.adapter_name
      case adapter_name
      when 'SQLite'
        new_max = maximum(primary_key) || 0
        update_seq_sql = "update sqlite_sequence set seq = #{new_max} where name = '#{table_name}';"
        ActiveRecord::Base.connection.execute(update_seq_sql)
      when 'PostgreSQL'
        ActiveRecord::Base.connection.reset_pk_sequence!(table_name)
      when 'PostGIS'
        ActiveRecord::Base.connection.reset_pk_sequence!(table_name)
      else
        raise "Task not implemented for this DB adapter, #{adapter_name}"
      end
    end
  end
end


text:
@implementation DTCaptureViewUtils

+ (AVCaptureConnection *)connectionWithMediaType:(NSString *)mediaType fromConnections:(NSArray *)connections
{
	for (AVCaptureConnection *connection in connections) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:mediaType]) {
                return connection;
            }
        }
    }
    return nil;
}

+ (AVCaptureDeviceInput *)deviceInputWithPosition:(AVCaptureDevicePosition)position
{
	NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

	//Find device with given position
    for (AVCaptureDevice *device in devices) {
        if (device.position == position) {
			return [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
		}
    }

    return nil;
}

@end

#pragma mark - Functions
NSString* NSStringFromUIImageOrientation(UIImageOrientation orientation)
{
    switch (orientation) {
        case UIImageOrientationDown:
            return [NSString stringWithFormat:@"%@ [%d]", @"UIImageOrientationDown", UIImageOrientationDown];
        case UIImageOrientationDownMirrored:
            return [NSString stringWithFormat:@"%@ [%d]", @"UIImageOrientationDownMirrored", UIImageOrientationDownMirrored];
        case UIImageOrientationLeft:
            return [NSString stringWithFormat:@"%@ [%d]", @"UIImageOrientationLeft", UIImageOrientationLeft];
        case UIImageOrientationLeftMirrored:
            return [NSString stringWithFormat:@"%@ [%d]", @"UIImageOrientationLeftMirrored", UIImageOrientationLeftMirrored];
        case UIImageOrientationUp:
            return [NSString stringWithFormat:@"%@ [%d]", @"UIImageOrientationUp", UIImageOrientationUp];
        case UIImageOrientationUpMirrored:
            return [NSString stringWithFormat:@"%@ [%d]", @"UIImageOrientationUpMirrored", UIImageOrientationUpMirrored];
        case UIImageOrientationRight:
            return [NSString stringWithFormat:@"%@ [%d]", @"UIImageOrientationRight", UIImageOrientationRight];
        case UIImageOrientationRightMirrored:
            return [NSString stringWithFormat:@"%@ [%d]", @"UIImageOrientationRightMirrored", UIImageOrientationRightMirrored];
    }
}


text:
#ifndef CHECK_STRING_H
#define CHECK_STRING_H

/*

find tslibc/src/string -name 'check_*.c' | cut -d'_' -f2 | xargs -I% basename % .c

strrev
strrot
strrtok
strshift
strstrip
*/

TCase * tcase_strrev(void);
TCase * tcase_strrot(void);
TCase * tcase_strrtok(void);
TCase * tcase_strshift(void);
TCase * tcase_strstrip(void);

#endif /* CHECK_STRING_H */


text:
using System.Collections.Generic;
using Mond.Compiler.Expressions;

namespace Mond.Compiler.Parselets
{
    class CallParselet : IInfixParselet
    {
        public int Precedence => (int)PrecedenceValue.Postfix;

        public Expression Parse(Parser parser, Expression left, Token token)
        {
            var args = new List<Expression>();

            if (!parser.MatchAndTake(TokenType.RightParen))
            {
                do
                {
                    args.Add(parser.ParseExpression());
                } while (parser.MatchAndTake(TokenType.Comma));

                parser.Take(TokenType.RightParen);
            }

            return new CallExpression(token, left, args);
        }
    }
}


text:
namespace subtle {

ScopedUserPrefUpdateBase::ScopedUserPrefUpdateBase(PrefService* service,
                                                   const char* path)
    : service_(service),
      path_(path),
      value_(NULL) {}

ScopedUserPrefUpdateBase::~ScopedUserPrefUpdateBase() {
  Notify();
}

Value* ScopedUserPrefUpdateBase::GetValueOfType(base::Value::Type type) {
  if (!value_)
    value_ = service_->GetMutableUserPref(path_.c_str(), type);
  return value_;
}

void ScopedUserPrefUpdateBase::Notify() {
  if (value_) {
    service_->ReportUserPrefChanged(path_);
    value_ = NULL;
  }
}

}  // namespace subtle


text:
using NPOI.Util;
using System;
using System.IO;
using NPOI.HWPF.Model;
using System.IO.Compression;
using ICSharpCode.SharpZipLib.Zip;
namespace NPOI.HWPF.UserModel
{

    /**
     * Represents embedded picture extracted from Word Document
     * @author Dmitry Romanov
     */
    public partial class Picture: PictureDescriptor
    {
        //private static POILogger log = POILogFactory.GetLogger(Picture.class);

        //  public static int FILENAME_OFFSET = 0x7C;
        //  public static int FILENAME_SIZE_OFFSET = 0x6C;
        internal const int PICF_OFFSET = 0x0;
        internal const int PICT_HEADER_OFFSET = 0x4;
        internal const int MFPMM_OFFSET = 0x6;
        internal const int PICF_SHAPE_OFFSET = 0xE;
        internal const int PICMD_OFFSET = 0x1C;
        internal const int UNKNOWN_HEADER_SIZE = 0x49;

        public static byte[] IHDR = new byte[] { (byte)'I', (byte)'H', (byte)'D', (byte)'R' };

    public static byte[] COMPRESSED1 = { (byte) 0xFE, 0x78, (byte) 0xDA };
    public static byte[] COMPRESSED2 = { (byte) 0xFE, 0x78, (byte) 0x9C };

        private int dataBlockStartOfsset;
        private int pictureBytesStartOffset;
        private int dataBlockSize;
        private int size;
        //  private String fileName;
        private byte[] rawContent;
        private byte[] content;
        private byte[] _dataStream;
        private int height = -1;
        private int width = -1;

        public Picture(int dataBlockStartOfsset, byte[] _dataStream, bool fillBytes)
            :base(_dataStream, dataBlockStartOfsset)
            //: base(_dataStream, dataBlockStartOfsset)
        {

            this._dataStream = _dataStream;
            this.dataBlockStartOfsset = dataBlockStartOfsset;
            this.dataBlockSize = LittleEndian.GetInt(_dataStream, dataBlockStartOfsset);
            this.pictureBytesStartOffset = GetPictureBytesStartOffset(dataBlockStartOfsset, _dataStream, dataBlockSize);
            this.size = dataBlockSize - (pictureBytesStartOffset - dataBlockStartOfsset);

            if (fillBytes)
            {
                FillImageContent();
            }
        }

        public Picture(byte[] _dataStream) : base()
        {
            this._dataStream = _dataStream;
            this.dataBlockStartOfsset = 0;
            this.dataBlockSize = _dataStream.Length;
            this.pictureBytesStartOffset = 0;
            this.size = _dataStream.Length;
        }

        private void FillWidthHeight()
        {
            PictureType pictureType = SuggestPictureType();
            // trying to extract width and height from pictures content:
            if (pictureType == PictureType.JPEG)
            {
                FillJPGWidthHeight();
            }
            else if (pictureType == PictureType.PNG)
            {
                FillPNGWidthHeight();
            }
        }

       /**
         * Tries to suggest a filename: hex representation of picture structure offset in "Data" stream plus extension that
         * is tried to determine from first byte of picture's content.
         *
         * @return suggested file name
         */
        public String SuggestFullFileName()
        {
            String fileExt = SuggestFileExtension();
            return StringUtil.ToHexString(dataBlockStartOfsset) + (fileExt.Length > 0 ? "." + fileExt : "");
        }

        /**
         * Writes Picture's content bytes to specified OutputStream.
         * Is useful when there is need to write picture bytes directly to stream, omitting its representation in
         * memory as distinct byte array.
         *
         * @param out a stream to write to
         * @throws IOException if some exception is occured while writing to specified out
         */
        public void WriteImageContent(Stream out1)
        {
            if (rawContent != null && rawContent.Length > 0)
            {
                out1.Write(rawContent, 0, size);
            }
            else
            {
                out1.Write(_dataStream, dataBlockStartOfsset, size);
            }
        }

        /**
     * @return The offset of this picture in the picture bytes, used when
     *         matching up with {@link CharacterRun#getPicOffset()}
     */
    public int getStartOffset()
    {
        return dataBlockStartOfsset;
    }

    /**
         * @return picture's content as byte array
         */
        public byte[] GetContent()
        {
            if (content == null || content.Length <= 0)
            {
                FillImageContent();
            }
            return content;
        }

    /**
     * Returns picture's content as it stored in Word file, i.e. possibly in
     * compressed form.
     *
     * @return picture's content as it stored in Word file
     */
        public byte[] GetRawContent()
        {
                FillRawImageContent();
            return rawContent;
        }

        /**
         *
         * @return size in bytes of the picture
         */
        public int Size
        {
            get
            {
                return size;
            }
        }

        /**
         * returns horizontal aspect ratio for picture provided by user
         */
        public int AspectRatioX
        {
            get
            {
                return mx/10;
            }
        }

    /**
     * @return Horizontal scaling factor supplied by user expressed in .001%
     *         units
     */
    public int HorizontalScalingFactor
    {
get{
        return mx;
}
    }
        /**
         * returns vertical aspect ratio for picture provided by user
         */
        public int AspectRatioY
        {
            get
            {
                return my/10;
            }
        }

    /**
     * @return Vertical scaling factor supplied by user expressed in .001% units
     */
    public int VerticalScalingFactor
    {
get{
        return my;
}
    }

    /**
     * Gets the initial width of the picture, in twips, prior to cropping or
     * scaling.
     *
     * @return the initial width of the picture in twips
     */
    public int DxaGoal
    {
        get
        {
            return dxaGoal;
        }
    }

    /**
     * Gets the initial height of the picture, in twips, prior to cropping or
     * scaling.
     *
     * @return the initial width of the picture in twips
     */
    public int DyaGoal
    {
        get
        {
            return dyaGoal;
        }
    }

    /**
     * @return The amount the picture has been cropped on the left in twips
     */
    public int DxaCropLeft
    {
        get
        {
            return dxaCropLeft;
        }
    }

    /**
     * @return The amount the picture has been cropped on the top in twips
     */
    public int DyaCropTop
    {
        get
        {
            return dyaCropTop;
        }
    }

    /**
     * @return The amount the picture has been cropped on the right in twips
     */
    public int DxaCropRight
    {
        get
        {
            return dxaCropRight;
        }
    }

    /**
     * @return The amount the picture has been cropped on the bottom in twips
     */
    public int DyaCropBottom
    {
        get
        {
            return dyaCropBottom;
        }
    }
        /**
         * tries to suggest extension for picture's file by matching signatures of popular image formats to first bytes
         * of picture's contents
         * @return suggested file extension
         */
        public String SuggestFileExtension()
        {
            return SuggestPictureType().Extension;
        }

        public PictureType SuggestPictureType()
        {
            return PictureType.FindMatchingType(GetContent());
        }

        /**
         * Returns the mime type for the image
         */
        public String MimeType
        {
            get
            {
                return SuggestPictureType().Mime;
            }
        }

        private static bool MatchSignature(byte[] dataStream, byte[] signature, int pictureBytesOffset)
        {
            bool matched = pictureBytesOffset < dataStream.Length;
            for (int i = 0; (i + pictureBytesOffset) < dataStream.Length && i < signature.Length; i++)
            {
                if (dataStream[i + pictureBytesOffset] != signature[i])
                {
                    matched = false;
                    break;
                }
            }
            return matched;
        }

        //  public String GetFileName()
        //  {
        //    return fileName;
        //  }

        //  private static String extractFileName(int blockStartIndex, byte[] dataStream) {
        //        int fileNameStartOffset = blockStartIndex + 0x7C;
        //        int fileNameSizeOffset = blockStartIndex + FILENAME_SIZE_OFFSET;
        //        int fileNameSize = LittleEndian.GetShort(dataStream, fileNameSizeOffSet);
        //
        //        int fileNameIndex = fileNameStartOffSet;
        //        char[] fileNameChars = new char[(fileNameSize-1)/2];
        //        int charIndex = 0;
        //        while(charIndex<fileNameChars.Length) {
        //            short aChar = LittleEndian.GetShort(dataStream, fileNameIndex);
        //            fileNameChars[charIndex] = (char)aChar;
        //            charIndex++;
        //            fileNameIndex += 2;
        //        }
        //        String fileName = new String(fileNameChars);
        //        return fileName.Trim();
        //    }

        private void FillRawImageContent()
        {
            this.rawContent = new byte[size];
            Array.Copy(_dataStream, pictureBytesStartOffset, rawContent, 0, size);
        }

        private void FillImageContent()
          {
            byte[] rawContent = GetRawContent();

            // HACK: Detect compressed images.  In reality there should be some way to determine
            //       this from the first 32 bytes, but I can't see any similarity between all the
            //       samples I have obtained, nor any similarity in the data block contents.
            if (MatchSignature(rawContent, COMPRESSED1, 32) || MatchSignature(rawContent, COMPRESSED2, 32))
            {
              try
              {

                  ZipInputStream gzip = new ZipInputStream(new MemoryStream(rawContent, 33, rawContent.Length - 33));
                MemoryStream out1 = new MemoryStream();
                byte[] buf = new byte[4096];
                int readBytes;
                while ((readBytes = gzip.Read(buf,0,4096)) > 0)
                {
                    out1.Write(buf, 0, readBytes);
                }
                content = out1.ToArray();
              }
              catch (IOException)
              {
                // Problems Reading from the actual MemoryStream should never happen
                // so this will only ever be a ZipException.
                //log.log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
              }
            } else {
              // Raw data is not compressed.
              content = rawContent;
            }
          }

        private static int GetPictureBytesStartOffset(int dataBlockStartOffset, byte[] _dataStream, int dataBlockSize)
        {
            int realPicoffset = dataBlockStartOffset;
            int dataBlockEndOffset = dataBlockSize + dataBlockStartOffset;

            // Skip over the PICT block
            int PICTFBlockSize = LittleEndian.GetShort(_dataStream, dataBlockStartOffset + PICT_HEADER_OFFSET); // Should be 68 bytes

            // Now the PICTF1
            int PICTF1BlockOffset = PICTFBlockSize + PICT_HEADER_OFFSET;
            short MM_TYPE = LittleEndian.GetShort(_dataStream, dataBlockStartOffset + PICT_HEADER_OFFSET + 2);
            if (MM_TYPE == 0x66)
            {
                // Skip the stPicName
                int cchPicName = LittleEndian.GetUByte(_dataStream, PICTF1BlockOffset);
                PICTF1BlockOffset += 1 + cchPicName;
            }
            int PICTF1BlockSize = LittleEndian.GetShort(_dataStream, dataBlockStartOffset + PICTF1BlockOffset);

            int unknownHeaderOffset = (PICTF1BlockSize + PICTF1BlockOffset) < dataBlockEndOffset ? (PICTF1BlockSize + PICTF1BlockOffset) : PICTF1BlockOffset;
            realPicoffset += (unknownHeaderOffset + UNKNOWN_HEADER_SIZE);
            if (realPicoffset >= dataBlockEndOffset)
            {
                realPicoffset -= UNKNOWN_HEADER_SIZE;
            }
            return realPicoffset;
        }

        private void FillJPGWidthHeight()
        {
            /*
         * http://www.codecomments.com/archive281-2004-3-158083.html
         *
         * Algorhitm proposed by Patrick TJ McPhee:
         *
         * read 2 bytes make sure they are 'ffd8'x repeatedly: read 2 bytes make
         * sure the first one is 'ff'x if the second one is 'd9'x stop else if
         * the second one is c0 or c2 (or possibly other values ...) skip 2
         * bytes read one byte into depth read two bytes into height read two
         * bytes into width else read two bytes into length skip forward
         * length-2 bytes
         *
         * Also used Ruby code snippet from:
         * http://www.bigbold.com/snippets/posts/show/805 for reference
            */
            int pointer = pictureBytesStartOffset + 2;
            int firstByte = _dataStream[pointer];
            int secondByte = _dataStream[pointer + 1];

            int endOfPicture = pictureBytesStartOffset + size;
            while (pointer < endOfPicture - 1)
            {
                do
                {
                    firstByte = _dataStream[pointer];
                    secondByte = _dataStream[pointer + 1];
                    pointer += 2;
                } while (!(firstByte == (byte)0xFF) && pointer < endOfPicture - 1);

                if (firstByte == ((byte)0xFF) && pointer < endOfPicture - 1)
                {
                    if (secondByte == (byte)0xD9 || secondByte == (byte)0xDA)
                    {
                        break;
                    }
                    else if ((secondByte & 0xF0) == 0xC0 && secondByte != (byte)0xC4 && secondByte != (byte)0xC8 && secondByte != (byte)0xCC)
                    {
                        pointer += 5;
                        this.height = GetBigEndianShort(_dataStream, pointer);
                        this.width = GetBigEndianShort(_dataStream, pointer + 2);
                        break;
                    }
                    else
                    {
                        pointer++;
                        pointer++;
                        int length = GetBigEndianShort(_dataStream, pointer);
                        pointer += length;
                    }
                }
                else
                {
                    pointer++;
                }
            }
        }

        private void FillPNGWidthHeight()
        {
            /*
             Used PNG file format description from http://www.wotsit.org/download.asp?f=png
            */
            int HEADER_START = pictureBytesStartOffset + PictureType.PNG.Signatures[0].Length + 4;
            if (MatchSignature(_dataStream, IHDR, HEADER_START))
            {
                int IHDR_CHUNK_WIDTH = HEADER_START + 4;
                this.width = GetBigEndianInt(_dataStream, IHDR_CHUNK_WIDTH);
                this.height = GetBigEndianInt(_dataStream, IHDR_CHUNK_WIDTH + 4);
            }
        }

        /**
         * returns pixel width of the picture or -1 if dimensions determining was failed
         */
        public int Width
        {
            get
            {
                if (width == -1)
                {
                    FillWidthHeight();
                }
                return width;
            }
        }

        /**
         * returns pixel height of the picture or -1 if dimensions determining was failed
         */
        public int Height
        {
            get
            {
                if (height == -1)
                {
                    FillWidthHeight();
                }
                return height;
            }
        }

        private static int GetBigEndianInt(byte[] data, int offset)
        {
            return (((data[offset] & 0xFF) << 24) + ((data[offset + 1] & 0xFF) << 16) + ((data[offset + 2] & 0xFF) << 8) + (data[offset + 3] & 0xFF));
        }

        private static int GetBigEndianShort(byte[] data, int offset)
        {
            return (((data[offset] & 0xFF) << 8) + (data[offset + 1] & 0xFF));
        }

    }

}


text:
package terrastore.communication.protocol;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.msgpack.MessageTypeException;
import org.msgpack.Packer;
import org.msgpack.Unpacker;
import terrastore.communication.CommunicationException;
import terrastore.communication.Node;
import terrastore.communication.ProcessingException;
import terrastore.router.MissingRouteException;
import terrastore.router.Router;
import terrastore.store.Bucket;
import terrastore.store.Key;
import terrastore.store.Store;
import terrastore.store.StoreOperationException;
import terrastore.store.Value;
import terrastore.store.features.Predicate;
import terrastore.util.collect.Maps;
import terrastore.util.io.MsgPackUtils;

/**
 * @author Sergio Bossa
 */
public class PutValuesCommand extends AbstractCommand<Set<Key>> {

    private String bucketName;
    private Map<Key, Value> values;

    public PutValuesCommand(String bucketName, Map<Key, Value> values) {
        this.bucketName = bucketName;
        this.values = values;
    }

    public PutValuesCommand() {
    }

    @Override
    public Response<Set<Key>> executeOn(Router router) throws CommunicationException, MissingRouteException, ProcessingException {
        Map<Node, Set<Key>> nodeToKeys = router.routeToNodesFor(bucketName, values.keySet());
        Set<Key> result = new HashSet<Key>();
        for (Map.Entry<Node, Set<Key>> nodeToKeysEntry : nodeToKeys.entrySet()) {
            Node node = nodeToKeysEntry.getKey();
            Set<Key> nodeKeys = nodeToKeysEntry.getValue();
            PutValuesCommand command = new PutValuesCommand(bucketName, Maps.slice(values, nodeKeys));
            result.addAll(node.<Set<Key>>send(command));
        }
        return new KeysResponse(id, result);
    }

    public Response<Set<Key>> executeOn(Store store) throws StoreOperationException {
        Bucket bucket = store.getOrCreate(bucketName);
        Set<Key> insertedKeys = new HashSet<Key>();
        for (Map.Entry<Key, Value> entry : values.entrySet()) {
            bucket.put(entry.getKey(), entry.getValue());
            insertedKeys.add(entry.getKey());
        }
        return new KeysResponse(id, insertedKeys);
    }

    @Override
    protected void doSerialize(Packer packer) throws IOException {
        MsgPackUtils.packString(packer, bucketName);
        MsgPackUtils.packValues(packer, values);
    }

    @Override
    protected void doDeserialize(Unpacker unpacker) throws IOException, MessageTypeException {
        bucketName = MsgPackUtils.unpackString(unpacker);
        values = MsgPackUtils.unpackValues(unpacker);
    }
}


text:
package com.wanke.ui.activity;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;

import com.wanke.tv.R;
import com.wanke.ui.adapter.MyFragmentPagerAdapter;

public class MainActivity extends BaseActivity {
    MyFragmentPagerAdapter mMyFragmentPagerAdapter;
    private ViewPager mPager;

    @Override
    protected int getFlag() {
        return FLAG_SEARCH_VIEW | FLAG_DISABLE_HOME_AS_UP;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private View mRecommentBtn = null;
    private View mLiveBtn = null;
    private View mGameBtn = null;
    private View mAccountBtn = null;

    private MyFragmentPagerAdapter mFragmentPagerAdapter;

    /*
     * 初始化ViewPager
     */
    public void initView() {
        mPager = (ViewPager) findViewById(R.id.viewpager);

        // 给ViewPager设置适配器
        mFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
        mPager.setOffscreenPageLimit(mFragmentPagerAdapter.getCount());
        mPager.setAdapter(mFragmentPagerAdapter);
        mPager.setOnPageChangeListener(new MyOnPageChangeListener());
        //        mPager.setOnPageChangeListener(new MyOnPageChangeListener());// 页面变化时的监听器
        //        mPager.setOnDragListener(l);

        mRecommentBtn = findViewById(R.id.recomment_btn);
        mRecommentBtn.setOnClickListener(mBtnClickListener);
        mLiveBtn = findViewById(R.id.live_btn);
        mLiveBtn.setOnClickListener(mBtnClickListener);
        mGameBtn = findViewById(R.id.game_btn);
        mGameBtn.setOnClickListener(mBtnClickListener);
        mAccountBtn = findViewById(R.id.account_btn);
        mAccountBtn.setOnClickListener(mBtnClickListener);

        setCurrentPage(0);// 设置当前显示标签页为第一页
    }

    private OnClickListener mBtnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            int id = v.getId();
            int pageIndex = -1;
            switch (id) {
            case R.id.recomment_btn:
                pageIndex = 0;
                break;

            case R.id.live_btn:
                pageIndex = 1;
                break;

            case R.id.game_btn:
                pageIndex = 2;
                break;

            case R.id.account_btn:
                pageIndex = 3;
                break;

            default:
                break;
            }

            if (pageIndex >= 0 && pageIndex < mFragmentPagerAdapter.getCount()) {
                setCurrentPage(pageIndex);
            }
        }
    };

    private void setCurrentPage(int index) {
        if (index >= 0 && index < mFragmentPagerAdapter.getCount()) {
            mPager.setCurrentItem(index, true);

            mAccountBtn.setSelected(false);
            mGameBtn.setSelected(false);
            mLiveBtn.setSelected(false);
            mRecommentBtn.setSelected(false);

            switch (index) {
            case 0:
                mRecommentBtn.setSelected(true);
                break;

            case 1:
                mLiveBtn.setSelected(true);
                break;

            case 2:
                mGameBtn.setSelected(true);
                break;

            case 3:
                mAccountBtn.setSelected(true);
                break;

            default:
                break;
            }
        }
    }

    private class MyOnPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(
                int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            setCurrentPage(position);
        }

    }
    // /
    //    private int first = 0;
    //    private int second = 0;
    //    private int third = 0;
    //    private int currPosition = 0;
    //
    //    public class MyOnPageChangeListener implements OnPageChangeListener {
    //        private int one = mShiftP * 2 + mYwidth;// 两个相邻页面的偏移量
    //
    //        @Override
    //        public void onPageScrolled(int arg0, float arg1, int arg2) {
    //            // TODO Auto-generated method stub
    //        }
    //
    //        @Override
    //        public void onPageScrollStateChanged(int arg0) {
    //            // TODO Auto-generated method stub
    //        }
    //
    //        @Override
    //        public void onPageSelected(int arg0) {
    //            Log.d("onchanged", "onchanged " + arg0);
    //            TranslateAnimation ta = null;
    //            switch (arg0) {
    //            case 0:
    //                view1.setBackgroundResource(R.color.bisque);
    //                view2.setBackgroundResource(R.color.divider);
    //                if (currPosition == 1) {
    //                    view2.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(first, 0, 0, 0);
    //                }
    //                if (currPosition == 2) {
    //                    view3.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(second, 0, 0, 0);
    //                }
    //                if (currPosition == 3) {
    //                    view4.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(third, 0, 0, 0);
    //                }
    //                break;
    //
    //            case 1:
    //                view2.setBackgroundResource(R.color.bisque);
    //                view3.setBackgroundResource(R.color.divider);
    //                if (currPosition == 0) {
    //                    view1.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(0, first, 0, 0);
    //                }
    //                if (currPosition == 2) {
    //                    view3.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(second, first, 0, 0);
    //                }
    //                if (currPosition == 3) {
    //                    view4.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(third, first, 0, 0);
    //                }
    //                break;
    //
    //            case 2:
    //                view3.setBackgroundResource(R.color.bisque);
    //                view2.setBackgroundResource(R.color.divider);
    //                if (currPosition == 0) {
    //                    view1.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(0, second, 0, 0);
    //                }
    //                if (currPosition == 1) {
    //                    view2.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(first, second, 0, 0);
    //                }
    //                if (currPosition == 3) {
    //                    view4.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(third, second, 0, 0);
    //                }
    //                break;
    //
    //            case 3:
    //                view4.setBackgroundResource(R.color.bisque);
    //                view3.setBackgroundResource(R.color.divider);
    //                if (currPosition == 0) {
    //                    view1.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(0, third, 0, 0);
    //                }
    //                if (currPosition == 1) {
    //                    view2.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(first, third, 0, 0);
    //                }
    //                if (currPosition == 2) {
    //                    view3.setBackgroundResource(R.color.divider);
    //                    ta = new TranslateAnimation(second, third, 0, 0);
    //                }
    //                break;
    //
    //            }
    //            currPosition = arg0;
    //        }
    //    }

}


text:
/** @jsx React.DOM */
var TodoList3 = React.createClass({
  render: function() {
    var _this = this;
    var createItem = function(item, index) {
      return (

          { item.text }

            X

      );
    };
    return
{ this.props.items.map(createItem) }
;
  }
});

var TodoApp3 = React.createClass({
  mixins: [ReactFireMixin],

  getInitialState: function() {
    return {
      items: [],
      text: ''
    };
  },

  componentWillMount: function() {
    var firebaseRef = new Firebase('https://ReactFireTodoApp.firebaseio.com/items/');
    this.bindAsArray(firebaseRef.limitToLast(25), 'items');
  },

  onChange: function(e) {
    this.setState({text: e.target.value});
  },

  removeItem: function(key) {
    console.log('removeItem()', key);
    var firebaseRef = new Firebase('https://ReactFireTodoApp.firebaseio.com/items/');
    firebaseRef.child(key).remove();
  },

  handleSubmit: function(e) {
    e.preventDefault();
    if (this.state.text && this.state.text.trim().length !== 0) {
      this.firebaseRefs['items'].push({
        text: this.state.text
      });
      this.setState({
        text: ''
      });
    }
  },

  render: function() {
    return (

        <TodoList3 items={ this.state.items } removeItem={ this.removeItem } />
        <form onSubmit={ this.handleSubmit }>
          <input onChange={ this.onChange } value={ this.state.text } />
          <button>{ 'Add #' + (this.state.items.length + 1) }</button>
        </form>

    );
  }
});

React.render(<TodoApp3 />, document.getElementById('todoApp3'));


text:
package com.beust.jcommander.internal;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import com.beust.jcommander.ParameterException;

public class DefaultConsole implements Console {

    public void print(String msg) {
        System.out.print(msg);
    }

    public void println(String msg) {
        System.out.println(msg);
    }

    public char[] readPassword() {
        try {
            final InputStream is = System.in;
            char[] buf;
            char[] tempBuf;
            buf = tempBuf = new char[128];

            int c;
            int offset = 0;
            int bufferSpace = buf.length;

            // Wait for some data to become available
            waitForInputStreamData(is);

            while ((c = is.read()) != '\n') {
                if (--bufferSpace < 0) {
                    // Copy the data to the temporary buffer
                    tempBuf = buf;
                    // Increase the size of the buffer
                    buf = new char[offset + 128];
                    bufferSpace = buf.length - offset - 1;
                    // Copy the temp buffer back into the normal buffer
                    System.arraycopy(tempBuf, 0, buf, 0, offset);
                    // Clean out the temporary buffer
                    Arrays.fill(tempBuf, ' ');
                }
                buf[offset++] = (char) c;

                // No new line found yet so check and wait for the stream to have more data
                waitForInputStreamData(is);
            }

            char[] retValue = new char[offset];
            System.arraycopy(buf, 0, retValue, 0, offset);
            return retValue;
        } catch (IOException e) {
            throw new ParameterException(e);
        }
    }

    public String readLine() {
        try {
            final InputStream is = System.in;
            int c;
            final StringBuilder line = new StringBuilder();

            // Wait for some data to become available
            waitForInputStreamData(is);

            while ((c = is.read()) != '\n') {
                line.append((char) c);

                // No new line found yet so check and wait for the stream to have more data
                waitForInputStreamData(is);
            }
            return line.toString();
        } catch (IOException e) {
            throw new ParameterException(e);
        }
    }

    private void waitForInputStreamData(InputStream is) throws IOException {
        // Wait for some input if there is none available
        while (is.available() <= 0) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

}


text:
package org.apache.derbyTesting.functionTests.tests.storetests;

import org.apache.derby.iapi.services.sanity.SanityManager;

import org.apache.derbyTesting.functionTests.tests.store.BaseTest;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.derby.tools.ij;

/**

The purpose of this test is to reproduce JIRA DERBY-715:

Sometimes a deadlock would be incorrectly reported as a timeout.  The
bug seemed to always reproduce at least once if the following test
was run (at least one of the iterations in the loop would get an
incorrect timeout vs. a deadlock).

**/

public class st_derby715 extends BaseTest
{
    static boolean verbose = false;

    public st_derby715()
    {
    }

    /**
     * Create the base table that the 2 threads will use.
     **/
    private static void setup()
        throws Exception
    {
        Connection conn = ij.startJBMS();
        Statement  stmt = conn.createStatement();

        // drop table, ignore table does not exist error.

        try
        {
            stmt.executeUpdate("drop table a");
        }
        catch (Exception e)
        {
            // ignore drop table errors.
        }

        try
        {
            stmt.executeUpdate("drop table b");
        }
        catch (Exception e)
        {
            // ignore drop table errors.
        }

        stmt.executeUpdate("create table a (a integer)");
        stmt.executeUpdate("create table b (b integer)");
        stmt.close();
        conn.commit();
        conn.close();
    }

    public static class t1 implements Runnable
    {
        String[] argv;

        public t1(String[] argv)
        {
            argv = argv;
        }
        public void run()
        {
            try
            {
                ij.getPropertyArg(argv);
                Connection conn = ij.startJBMS();
                conn.setAutoCommit(false);
                conn.setTransactionIsolation(
                        Connection.TRANSACTION_SERIALIZABLE);

                Statement stmt = conn.createStatement();
                if (verbose)
                    System.out.println("Thread 1 before selecting from b");

                // get row locks on all rows in b
                ResultSet rs = stmt.executeQuery("select * from b");

                if (verbose)
                    System.out.println("Thread 1 before selecting next from b");

                while (rs.next())
                {
                    if (verbose)
                        System.out.println("Thread t1 got " + rs.getString(1));
                }
                if (verbose)
                    System.out.println("Thread 1 after all next.");

                // give thread 2 a chance to catch up.
                waitForLocks(conn, 2);

                if (verbose)
                    System.out.println("Thread 1 before inserting into a...");

                // now wait on lock inserting row into table a - either
                // thread 1 or thread 2 should get a deadlock, NOT a timeout.
                stmt.executeUpdate("insert into a values(1)");

                if (verbose)
                    System.out.println("Thread 1 after inserting into a...");

                conn.rollback();
            }
            catch (SQLException sqle)
            {
                if (sqle.getSQLState().equals("40001"))
                {
                    // only expected exception is a deadlock, we should
                    // get at least one deadlock, so print it to output.
                    // Don't know which thread will get the deadlock, so
                    // don't label it.
                    System.out.println("Got a Deadlock.");
                }
                else
                {
                    org.apache.derby.tools.JDBCDisplayUtil.ShowSQLException(
                        System.out, sqle);
                    sqle.printStackTrace(System.out);
                }
                if (verbose)
                    System.out.println("Thread 1 got exception:\n");
            }
            catch (Exception ex)
            {
                System.out.println("got unexpected exception: " + ex);
            }
        }
    }

    public static class t2 implements Runnable
    {
        String[] argv;
        public t2 (String[] argv)
        {
            argv = argv;
        }
        public void run()
        {
            try
            {
                ij.getPropertyArg(argv);
                Connection conn = ij.startJBMS();
                conn.setAutoCommit(false);
                conn.setTransactionIsolation(
                        Connection.TRANSACTION_SERIALIZABLE);

                Statement stmt = conn.createStatement();

                if (verbose)
                    System.out.println("Thread 2 before selecting from a");

                ResultSet rs = stmt.executeQuery("select * from a");

                if (verbose)
                    System.out.println("Thread 2 before selecting next from a");

                while (rs.next())
                {
                    if (verbose)
                        System.out.println("Thread t2 got " + rs.getString(1));
                }

                if (verbose)
                    System.out.println("Thread 2 after all next.");
                waitForLocks(conn,2);

                if (verbose)
                    System.out.println("Thread 2 before inserting into b");

                stmt.executeUpdate("insert into b values(2)");

                if (verbose)
                    System.out.println("Thread 2 after inserting into b");

                conn.rollback();
            }
            catch (SQLException sqle)
            {
                if (verbose)
                    System.out.println("Thread 1 got exception:\n");

                if (sqle.getSQLState().equals("40001"))
                {
                    // only expected exception is a deadlock, we should
                    // get at least one deadlock, so print it to output.
                    // Don't know which thread will get the deadlock, so
                    // don't label it.
                    System.out.println("Got a Deadlock.");
                }
                else
                {
                    org.apache.derby.tools.JDBCDisplayUtil.ShowSQLException(
                        System.out, sqle);
                    sqle.printStackTrace(System.out);
                }
            }
            catch (Exception ex)
            {
                System.out.println("got unexpected exception: " + ex);
            }
        }
    }

    /**
     * Wait for a specified number of locks before continuing
     *
     * @param conn Connection to use for lock query
     * @param num  Number of locks to check for
     */
    private static void waitForLocks(Connection conn, int num) throws InterruptedException, SQLException {
        int totalWait = 0;
        do {
            totalWait += 500;
            Thread.sleep(500);
        } while (numlocks(conn) < num && totalWait < 60000);

    }
    /**
     * Get the number of locks in the lock table
     * @return number of locks
     * @throws SQLException
     */
    private static int numlocks(Connection conn) throws SQLException {
        Statement s = conn.createStatement();
        ResultSet rs = s.executeQuery("SELECT count(*) from syscs_diag.lock_table");
        rs.next();
        int num = rs.getInt(1);
        rs.close();
        return num;
    }

    public void testList(Connection conn)
        throws SQLException
    {
    }

    public static void main(String[] argv)
        throws Throwable
    {
        ij.getPropertyArg(argv);

        st_derby715 setup_ddl = new st_derby715();
        setup_ddl.setup();
        setup_ddl = null;

        {
            for (int i = 0; i < 5; i++)
            {
                Thread test1 = new Thread(new t1(argv));
                Thread test2 = new Thread(new t2(argv));
                test1.start();
                test2.start();
                test1.join();
                test2.join();
            }
        }
        /*
        catch (SQLException sqle)
        {
			org.apache.derby.tools.JDBCDisplayUtil.ShowSQLException(
                System.out, sqle);
			sqle.printStackTrace(System.out);
		}
        */
    }
}


text:
oLua - Lua in more objective way
====

goals:

 - make Lua more objective (polymorphism, inheritance, encapsulation, abstraction) with respect of lua syntax (like "self", or ":")

 - no global variables (so I can avoid many mistakes I used to do) - only class definitions can be global

 - validation (since there is no static typing in lua, runtime validation is all you can get) - validation of methods' arguments and result

 - more validations (I still don't know what I mean by that)

check https://github.com/un1q/oLua/wiki for details

Known Issues
============

This is very first version of oLua, so don't expect to much. Actually I made it for my own purpose, so this is not well documented rough and it might doesn't work at all.

For sure:
 - enums validation is broken
 - encapsulation is not provided
 - validations cannot be disabled yet


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <Button
        android:id="@+id/plugin_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="@android:color/white"
        android:text="启动内置插件"
        android:textColor="@android:color/black" />

    <Button
        android:id="@+id/plugin_install"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/plugin_test"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:background="@android:color/white"
        android:padding="10dp"
        android:text="安装Assets下的新版本插件"
        android:textColor="@android:color/black" />

</RelativeLayout>


text:
<script>
  /** @polymerBehavior */
  const ChainedBehavior = {behaviors: [NotFoundBehavior]};
</script>


text:
import os

import dotenv

dotenv.load()

CLIENT_ID = os.environ.get('CLIENT_ID')
CLIENT_SECRET = os.environ.get('CLIENT_SECRET')

CHRONOS_FORCE_UPDATE = bool(os.environ.get('FORCE_UPDATE'))

SCOPE = ['https://www.googleapis.com/auth/calendar']
NB_RESULTS = 300

LOG_LEVEL = os.environ.get('LOG_LEVEL', 'debug')