text:
package types

import (
	"bytes"
	"encoding/json"
	"strings"
	"testing"

	"github.com/cosmos/gogoproto/proto"
	"github.com/stretchr/testify/assert"

	tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)

func TestMarshalJSON(t *testing.T) {
	b, err := json.Marshal(&ResponseDeliverTx{})
	assert.Nil(t, err)
	// include empty fields.
	assert.True(t, strings.Contains(string(b), "code"))
	r1 := ResponseCheckTx{
		Code:      1,
		Data:      []byte("hello"),
		GasWanted: 43,
		Events: []Event{
			{
				Type: "testEvent",
				Attributes: []EventAttribute{
					{Key: "pho", Value: "bo"},
				},
			},
		},
	}
	b, err = json.Marshal(&r1)
	assert.Nil(t, err)

	var r2 ResponseCheckTx
	err = json.Unmarshal(b, &r2)
	assert.Nil(t, err)
	assert.Equal(t, r1, r2)
}

func TestWriteReadMessageSimple(t *testing.T) {
	cases := []proto.Message{
		&RequestEcho{
			Message: "Hello",
		},
	}

	for _, c := range cases {
		buf := new(bytes.Buffer)
		err := WriteMessage(c, buf)
		assert.Nil(t, err)

		msg := new(RequestEcho)
		err = ReadMessage(buf, msg)
		assert.Nil(t, err)

		assert.True(t, proto.Equal(c, msg))
	}
}

func TestWriteReadMessage(t *testing.T) {
	cases := []proto.Message{
		&tmproto.Header{
			Height:  4,
			ChainID: "test",
		},
		// TODO: add the rest
	}

	for _, c := range cases {
		buf := new(bytes.Buffer)
		err := WriteMessage(c, buf)
		assert.Nil(t, err)

		msg := new(tmproto.Header)
		err = ReadMessage(buf, msg)
		assert.Nil(t, err)

		assert.True(t, proto.Equal(c, msg))
	}
}

func TestWriteReadMessage2(t *testing.T) {
	phrase := "hello-world"
	cases := []proto.Message{
		&ResponseCheckTx{
			Data:      []byte(phrase),
			Log:       phrase,
			GasWanted: 10,
			Events: []Event{
				{
					Type: "testEvent",
					Attributes: []EventAttribute{
						{Key: "abc", Value: "def"},
					},
				},
			},
		},
		// TODO: add the rest
	}

	for _, c := range cases {
		buf := new(bytes.Buffer)
		err := WriteMessage(c, buf)
		assert.Nil(t, err)

		msg := new(ResponseCheckTx)
		err = ReadMessage(buf, msg)
		assert.Nil(t, err)

		assert.True(t, proto.Equal(c, msg))
	}
}


text:
var parse = require('../lib/parse');

exports['parse line'] = function (test) {
    var result = parse("rule");

    test.deepEqual(result, [{ text: "rule" }]);
};

exports['parse line and indented line'] = function (test) {
    var result = parse("rule\n  when");

    test.deepEqual(result, [
        { text: "rule", elements: [
            { text: "when" }
        ]}
    ]);
};

exports['parse rule'] = function (test) {
    var result = parse("rule\n  when\n    model.temperature >= 37\n  then\n    facts.fever = true");

    test.deepEqual(result, [
        { text: "rule", elements: [
            { text: "when", elements: [
                { text: "model.temperature >= 37" }
            ] },
            { text: "then", elements: [
                { text: "facts.fever = true" }
            ] }
        ]}
    ]);
};

redpajama_set_name: RedPajamaGithub


text:
class Task < ActiveRecord::Base
  include EventStreamNotifier
  include TaskTypeRegistration
  include Commentable

  register_task default_title: "Ad-hoc", default_role: "user"

  cattr_accessor :metadata_types

  default_scope { order("completed ASC") }

  scope :completed,   -> { where(completed: true) }
  scope :metadata,    -> { where(type: metadata_types) }
  scope :incomplete,  -> { where(completed: false) }
  scope :admin,       -> { where(type: "StandardTasks::PaperAdminTask") }
  scope :on_journals, ->(journals) { joins(:journal).where("journals.id" => journals.map(&:id)) }
  scope :complete,    -> { where(completed: true) }
  scope :incomplete,  -> { where(completed: false) }

  has_one :paper, through: :phase
  has_one :journal, through: :paper
  has_many :attachments, as: :attachable
  has_many :questions, inverse_of: :task
  has_many :participations, inverse_of: :task, dependent: :destroy
  has_many :participants, through: :participations, source: :user

  validates :title, :role, presence: true
  validates :title, length: { maximum: 255 }

  belongs_to :phase, inverse_of: :tasks

  def self.assigned_to(*users)
    if users.empty?
      Task.none
    else
      joins(participations: :user).where("participations.user_id" => users)
    end
  end

  def self.unassigned
    includes(:participations).where(participations: { id: nil })
  end

  def self.admin_for_user(user)
    admin.joins(paper: :assigned_users).
      merge(PaperRole.admins.for_user(user))
  end

  def self.for_role(role)
    where(role: role)
  end

  def self.without(task)
    where.not(id: task.id)
  end

  def self.permitted_attributes
    [:completed, :title, :phase_id]
  end

  #TODO Research how task generation and templating can be simplified
  # https://www.pivotaltracker.com/story/show/81718250
  def journal_task_type
    journal.journal_task_types.find_by(kind: self.class.name)
  end

  def is_metadata?
    return false unless Task.metadata_types.present?
    Task.metadata_types.include?(self.class.name)
  end

  def manuscript_information_task?
    self.role == "author"
  end

  def array_attributes
    [:body]
  end

  def incomplete!
    update(completed: false)
  end

  def update_responder
    UpdateResponders::Task
  end

  def authorize_update?(params, user)
    true
  end
end


text:
package com.dseuss.deskclock;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.util.AttributeSet;
import android.view.View;

import com.dseuss.deskclock.R;
import com.dseuss.deskclock.provider.Alarm;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TreeMap;

/**
 * Renders a tree-like view of the next alarm times over the period of a week.
 * The timeline begins at the time of the next alarm, and ends a week after that time.
 * The view is currently only shown in the landscape mode of tablets.
 */
public class AlarmTimelineView extends View {

    private static final String TAG = "AlarmTimelineView";

    private static final String FORMAT_12_HOUR = "E h mm a";
    private static final String FORMAT_24_HOUR = "E H mm";

    private static final int DAYS_IN_WEEK = 7;

    private int mAlarmTimelineColor;
    private int mAlarmTimelineLength;
    private int mAlarmTimelineMarginTop;
    private int mAlarmTimelineMarginBottom;
    private int mAlarmNodeRadius;
    private int mAlarmNodeInnerRadius;
    private int mAlarmNodeInnerRadiusColor;
    private int mAlarmTextPadding;
    private int mAlarmTextSize;
    private int mAlarmMinDistance;

    private Paint mPaint;
    private ContentResolver mResolver;
    private SimpleDateFormat mDateFormat;
    private TreeMap<Date, AlarmTimeNode> mAlarmTimes = new TreeMap<Date, AlarmTimeNode>();
    private Calendar mCalendar;
    private AlarmObserver mAlarmObserver = new AlarmObserver(getHandler());
    private GetAlarmsTask mAlarmsTask = new GetAlarmsTask();
    private String mNoAlarmsScheduled;
    private boolean mIsAnimatingOut;

    /**
     * Observer for any changes to the alarms in the content provider.
     */
    private class AlarmObserver extends ContentObserver {

        public AlarmObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean changed) {
            if (mAlarmsTask != null) {
                mAlarmsTask.cancel(true);
            }
            mAlarmsTask = new GetAlarmsTask();
            mAlarmsTask.execute();
        }

        @Override
        public void onChange(boolean changed, Uri uri) {
            onChange(changed);
        }
    }

    /**
     * The data model for one node on the timeline.
     */
    private class AlarmTimeNode {
        public Date date;
        public boolean isRepeating;

        public AlarmTimeNode(Date date, boolean isRepeating) {
            this.date = date;
            this.isRepeating = isRepeating;
        }
    }

    /**
     * Retrieves alarms from the content provider and generates an alarm node tree sorted by date.
     */
    private class GetAlarmsTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected synchronized Void doInBackground(Void... params) {
            List<Alarm> enabledAlarmList = Alarm.getAlarms(mResolver, Alarm.ENABLED + "=1");
            final Date currentTime = mCalendar.getTime();
            mAlarmTimes.clear();
            for (Alarm alarm : enabledAlarmList) {
                int hour = alarm.hour;
                int minutes = alarm.minutes;
                HashSet<Integer> repeatingDays = alarm.daysOfWeek.getSetDays();

                // If the alarm is not repeating,
                if (repeatingDays.isEmpty()) {
                    mCalendar.add(Calendar.DATE, getDaysFromNow(hour, minutes));
                    mCalendar.set(Calendar.HOUR_OF_DAY, alarm.hour);
                    mCalendar.set(Calendar.MINUTE, alarm.minutes);
                    Date date = mCalendar.getTime();

                    if (!mAlarmTimes.containsKey(date)) {
                        // Add alarm if there is no other alarm with this date.
                        mAlarmTimes.put(date, new AlarmTimeNode(date, false));
                    }
                    mCalendar.setTime(currentTime);
                    continue;
                }

                // If the alarm is repeating, iterate through each alarm date.
                for (int day : alarm.daysOfWeek.getSetDays()) {
                    mCalendar.add(Calendar.DATE, getDaysFromNow(day, hour, minutes));
                    mCalendar.set(Calendar.HOUR_OF_DAY, alarm.hour);
                    mCalendar.set(Calendar.MINUTE, alarm.minutes);
                    Date date = mCalendar.getTime();

                    if (!mAlarmTimes.containsKey(date)) {
                        // Add alarm if there is no other alarm with this date.
                        mAlarmTimes.put(date, new AlarmTimeNode(mCalendar.getTime(), true));
                    } else {
                        // If there is another alarm with this date, make it
                        // repeating.
                        mAlarmTimes.get(date).isRepeating = true;
                    }
                    mCalendar.setTime(currentTime);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            requestLayout();
            AlarmTimelineView.this.invalidate();
        }

        // Returns whether this non-repeating alarm is firing today or tomorrow.
        private int getDaysFromNow(int hour, int minutes) {
            final int currentHour = mCalendar.get(Calendar.HOUR_OF_DAY);
            if (hour > currentHour ||
                    (hour == currentHour && minutes >= mCalendar.get(Calendar.MINUTE)) ) {
                return 0;
            }
            return 1;
        }

        // Returns the days from now of the next instance of this alarm, given the repeated day.
        private int getDaysFromNow(int day, int hour, int minute) {
            final int currentDay = mCalendar.get(Calendar.DAY_OF_WEEK);
            if (day != currentDay) {
                if (day < currentDay) {
                    day += DAYS_IN_WEEK;
                }
                return day - currentDay;
            }

            final int currentHour = mCalendar.get(Calendar.HOUR_OF_DAY);
            if (hour != currentHour) {
                return (hour < currentHour) ? DAYS_IN_WEEK : 0;
            }

            final int currentMinute = mCalendar.get(Calendar.MINUTE);
            return (minute < currentMinute) ? DAYS_IN_WEEK : 0;
        }
    }

    public AlarmTimelineView(Context context) {
        super(context);
        init(context);
    }

    public AlarmTimelineView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        mResolver = context.getContentResolver();

        final Resources res = context.getResources();

        mAlarmTimelineColor = res.getColor(R.color.alarm_timeline_color);
        mAlarmTimelineLength = res.getDimensionPixelOffset(R.dimen.alarm_timeline_length);
        mAlarmTimelineMarginTop = res.getDimensionPixelOffset(R.dimen.alarm_timeline_margin_top);
        mAlarmTimelineMarginBottom = res.getDimensionPixelOffset(R.dimen.footer_button_size) +
                2 * res.getDimensionPixelOffset(R.dimen.footer_button_layout_margin);
        mAlarmNodeRadius = res.getDimensionPixelOffset(R.dimen.alarm_timeline_radius);
        mAlarmNodeInnerRadius = res.getDimensionPixelOffset(R.dimen.alarm_timeline_inner_radius);
        mAlarmNodeInnerRadiusColor = res.getColor(R.color.blackish);
        mAlarmTextSize = res.getDimensionPixelOffset(R.dimen.alarm_text_font_size);
        mAlarmTextPadding = res.getDimensionPixelOffset(R.dimen.alarm_text_padding);
        mAlarmMinDistance = res.getDimensionPixelOffset(R.dimen.alarm_min_distance) +
                2 * mAlarmNodeRadius;
        mNoAlarmsScheduled = context.getString(R.string.no_upcoming_alarms);

        mPaint = new Paint();
        mPaint.setTextSize(mAlarmTextSize);
        mPaint.setStrokeWidth(res.getDimensionPixelOffset(R.dimen.alarm_timeline_width));
        mPaint.setAntiAlias(true);

        mCalendar = Calendar.getInstance();
        final Locale locale = Locale.getDefault();
        String formatString = DateFormat.is24HourFormat(context) ? FORMAT_24_HOUR : FORMAT_12_HOUR;
        String format = DateFormat.getBestDateTimePattern(locale, formatString);
        mDateFormat = new SimpleDateFormat(format, locale);

        mAlarmsTask.execute();
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        mResolver.registerContentObserver(Alarm.CONTENT_URI, true, mAlarmObserver);
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mResolver.unregisterContentObserver(mAlarmObserver);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int timelineHeight = !mAlarmTimes.isEmpty() ?  mAlarmTimelineLength : 0;
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
                timelineHeight + mAlarmTimelineMarginTop + mAlarmTimelineMarginBottom);
    }

    @Override
    public synchronized void onDraw(Canvas canvas) {

        // If the view is in the process of animating out, do not change the text or the timeline.
        if (mIsAnimatingOut) {
            return;
        }

        super.onDraw(canvas);

        final int x = getWidth() / 2;
        int y = mAlarmTimelineMarginTop;

        mPaint.setColor(mAlarmTimelineColor);

        // If there are no alarms, draw the no alarms text.
        if (mAlarmTimes == null || mAlarmTimes.isEmpty()) {
            mPaint.setTextAlign(Align.CENTER);
            canvas.drawText(mNoAlarmsScheduled, x, y, mPaint);
            return;
        }

        // Draw the timeline.
        canvas.drawLine(x, y, x, y + mAlarmTimelineLength, mPaint);

        final int xLeft = x - mAlarmNodeRadius - mAlarmTextPadding;
        final int xRight = x + mAlarmNodeRadius + mAlarmTextPadding;

        // Iterate through each of the alarm times chronologically.
        Iterator<AlarmTimeNode> iter = mAlarmTimes.values().iterator();
        Date firstDate = null;
        int prevY = 0;
        int i=0;
        final int maxY = mAlarmTimelineLength + mAlarmTimelineMarginTop;
        while (iter.hasNext()) {
            AlarmTimeNode node = iter.next();
            Date date = node.date;

            if (firstDate == null) {
                // If this is the first alarm, set the node to the top of the timeline.
                y = mAlarmTimelineMarginTop;
                firstDate = date;
            } else {
                // If this is not the first alarm, set the distance based upon the time from the
                // first alarm.  If a node already exists at that time, use the minimum distance
                // required from the last drawn node.
                y = Math.max(convertToDistance(date, firstDate), prevY + mAlarmMinDistance);
            }

            if (y > maxY) {
                // If the y value has somehow exceeded the timeline length, draw node on end of
                // timeline.  We should never reach this state.
                Log.wtf("Y-value exceeded timeline length.  Should never happen.");
                Log.wtf("alarm date=" + node.date.getTime() + ", isRepeating=" + node.isRepeating
                        + ", y=" + y + ", maxY=" + maxY);
                y = maxY;
            }

            // Draw the node.
            mPaint.setColor(Color.WHITE);
            canvas.drawCircle(x, y, mAlarmNodeRadius, mPaint);

            // If the node is not repeating, draw an inner circle to make the node "open".
            if (!node.isRepeating) {
                mPaint.setColor(mAlarmNodeInnerRadiusColor);
                canvas.drawCircle(x, y, mAlarmNodeInnerRadius, mPaint);
            }
            prevY = y;

            // Draw the alarm text.  Alternate left and right of the timeline.
            final String timeString = mDateFormat.format(date).toUpperCase();
            mPaint.setColor(mAlarmTimelineColor);
            if (i % 2 == 0) {
                mPaint.setTextAlign(Align.RIGHT);
                canvas.drawText(timeString, xLeft, y + mAlarmTextSize / 3, mPaint);
            } else {
                mPaint.setTextAlign(Align.LEFT);
                canvas.drawText(timeString, xRight, y + mAlarmTextSize / 3, mPaint);
            }
            i++;
        }
    }

    // This method is necessary to ensure that the view does not re-draw while it is being
    // animated out.  The timeline should remain on-screen as is, even though no alarms
    // are present, as the view moves off-screen.
    public void setIsAnimatingOut(boolean animatingOut) {
        mIsAnimatingOut = animatingOut;
    }

    // Convert the time difference between the date and the first date to a distance along the
    // timeline.
    private int convertToDistance(final Date date, final Date firstDate) {
        if (date == null || firstDate == null) {
            return 0;
        }
        return (int) ((date.getTime() - firstDate.getTime())
                * mAlarmTimelineLength / DateUtils.WEEK_IN_MILLIS + mAlarmTimelineMarginTop);
    }
}


text:
<?php

namespace Google\Service\Compute;

class NetworkEndpointGroupsListEndpointsRequest extends \Google\Model
{
  /**
   * @var string
   */
  public $healthStatus;

  /**
   * @param string
   */
  public function setHealthStatus($healthStatus)
  {
    $this->healthStatus = $healthStatus;
  }
  /**
   * @return string
   */
  public function getHealthStatus()
  {
    return $this->healthStatus;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(NetworkEndpointGroupsListEndpointsRequest::class, 'Google_Service_Compute_NetworkEndpointGroupsListEndpointsRequest');


text:
import DS from 'ember-data';

export default DS.Model.extend({
	content: DS.attr('string'),
	timestamp: DS.attr()
});


text:
{{ primary_releases.active.name }} {{ primary_releases.active.year }}

    {% if primary_releases.other %}

        Change release

        {% for release in primary_releases.other %}

{{ release.name }} {{ release.year }}

        {% endfor %}

    {% endif %}


text:
<?php

namespace Wei\Model;

/**
 * Add cache functions to the model
 */
trait CacheTrait
{
    /**
     * Remove the model cache
     *
     * @return $this
     */
    public function removeModelCache(): self
    {
        if ($this->getColumnValue('id')) {
            $this->cache->delete($this->getModelCacheKey());
        }
        return $this;
    }

    /**
     * Return the model cache key
     *
     * @param string|int|null $id
     * @return string
     */
    public function getModelCacheKey($id = null): string
    {
        return $this->getDb()->getDbname() . ':' . $this->getTable() . ':' . ($id ?: $this->getColumnValue('id'));
    }
}


text:
/*!
 * \file mkldnn_convolution-inl.h
 * \brief
*/

#ifndef MXNET_OPERATOR_NN_MKLDNN_MKLDNN_CONVOLUTION_INL_H_
#define MXNET_OPERATOR_NN_MKLDNN_MKLDNN_CONVOLUTION_INL_H_

#if MXNET_USE_MKLDNN == 1

#include <vector>
#include <utility>
#include "../convolution-inl.h"
#include "./mkldnn_ops-inl.h"
#include "./mkldnn_base-inl.h"

namespace mxnet {
namespace op {

struct MKLDNNConvParam : public dmlc::Parameter<MKLDNNConvParam> {
  bool with_bn;
  bool with_relu;
  bool with_sum;
  bool with_postsum_relu;
  bool quantized;
  bool weight_channelwise_scale;

  dmlc::optional<float> min_calib_range;  // min float value calculated from calibration dataset
  dmlc::optional<float> max_calib_range;  // max float value calculated from calibration dataset

  DMLC_DECLARE_PARAMETER(MKLDNNConvParam) {
    DMLC_DECLARE_FIELD(with_bn).set_default(false)
    .describe("Add post batchnorm.");
    DMLC_DECLARE_FIELD(with_relu).set_default(false)
    .describe("Add post relu");
    DMLC_DECLARE_FIELD(with_sum).set_default(false)
    .describe("Add post sum");
    DMLC_DECLARE_FIELD(with_postsum_relu).set_default(false)
    .describe("Add post relu after sum");
    DMLC_DECLARE_FIELD(quantized).set_default(false)
    .describe("enable quantization");
    DMLC_DECLARE_FIELD(weight_channelwise_scale).set_default(true)
    .describe("Quantize weight with channel wise scales.");
    DMLC_DECLARE_FIELD(min_calib_range)
    .set_default(dmlc::optional<float>())
    .describe("The minimum scalar value in the form of float32 obtained "
              "through calibration. If present, it will be used to by "
              "quantized convolution op to calculate primitive scale");
    DMLC_DECLARE_FIELD(max_calib_range)
    .set_default(dmlc::optional<float>())
    .describe("The maximum scalar value in the form of float32 obtained "
              "through calibration. If present, it will be used to by "
              "quantized convolution op to calculate primitive scale");
  }
};

struct MKLDNNConvFullParam {
  ConvolutionParam conv_param;
  MKLDNNConvParam mkldnn_param;
  float sum_scale;
  std::vector<float> requantize_scales;
};

static inline bool IsOutputUInt8(const MKLDNNConvParam &mkldnn_param) {
  return ((!mkldnn_param.with_sum) && mkldnn_param.with_relu) ||
         mkldnn_param.with_postsum_relu;
}

mkldnn::convolution_forward::primitive_desc
GetConvFwdImpl(const MKLDNNConvFullParam &param, const bool is_train,
               const NDArray &data, const NDArray &weights, const NDArray *bias,
               const NDArray &output);

class MKLDNNConvForward {
 public:
  mkldnn::convolution_forward::primitive_desc fwd_pd;

  MKLDNNConvForward(const MKLDNNConvFullParam &param, const bool is_train,
                    const NDArray &data, const NDArray &weights,
                    const NDArray *bias, const NDArray &output)
      : fwd_pd(GetConvFwdImpl(param, is_train, data, weights, bias, output)) {}

  void SetNewMem(const mkldnn::memory &data, const mkldnn::memory &weight,
                 const mkldnn::memory *bias, const mkldnn::memory &output);

  const mkldnn::convolution_forward &GetFwd() const {
    return *fwd_;
  }

 private:
  std::shared_ptr<mkldnn::convolution_forward> fwd_;
  std::shared_ptr<mkldnn::memory> data_;
  std::shared_ptr<mkldnn::memory> weight_;
  std::shared_ptr<mkldnn::memory> bias_;
  std::shared_ptr<mkldnn::memory> out_;
};

typedef ParamOpSign<ConvolutionParam> MKLDNNConvSignature;

MKLDNNConvForward &GetConvFwd(const ConvolutionParam &param,
                              const bool is_train, const NDArray &data,
                              const NDArray &weights, const NDArray *bias,
                              const NDArray &output);

void MKLDNNConvolutionForwardFullFeature(const MKLDNNConvFullParam &param,
                                         const OpContext &ctx,
                                         MKLDNNConvForward *fwd,
                                         const std::vector<NDArray> &in_data,
                                         const std::vector<OpReqType> &req,
                                         const std::vector<NDArray> &out_data);

}  // namespace op
}  // namespace mxnet

#endif  // MXNET_USE_MKLDNN == 1
#endif  // MXNET_OPERATOR_NN_MKLDNN_MKLDNN_CONVOLUTION_INL_H_


text:
package main

import (
	"time"

	"gopkg.in/kataras/iris.v6"
	"gopkg.in/kataras/iris.v6/adaptors/httprouter"
	"gopkg.in/kataras/iris.v6/middleware/basicauth"
)

func main() {
	app := iris.New()
	app.Adapt(iris.DevLogger()) // adapt a simple internal logger to print any errors
	app.Adapt(httprouter.New()) // adapt a router, you can use gorillamux too

	authConfig := basicauth.Config{
		Users:      map[string]string{"myusername": "mypassword", "mySecondusername": "mySecondpassword"},
		Realm:      "Authorization Required", // defaults to "Authorization Required"
		ContextKey: "mycustomkey",            // defaults to "user"
		Expires:    time.Duration(30) * time.Minute,
	}

	authentication := basicauth.New(authConfig)
	app.Get("/", func(ctx *iris.Context) { ctx.Redirect("/admin") })
	// to global app.Use(authentication) (or app.UseGlobal before the .Listen)
	// to routes
	/*
		app.Get("/mysecret", authentication, func(ctx *iris.Context) {
			username := ctx.GetString("mycustomkey") //  the Contextkey from the authConfig
			ctx.Writef("Hello authenticated user: %s ", username)
		})
	*/

	// to party

	needAuth := app.Party("/admin", authentication)
	{
		//http://localhost:8080/admin
		needAuth.Get("/", func(ctx *iris.Context) {
			username := ctx.GetString("mycustomkey") //  the Contextkey from the authConfig
			ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
		})
		// http://localhost:8080/admin/profile
		needAuth.Get("/profile", func(ctx *iris.Context) {
			username := ctx.GetString("mycustomkey") //  the Contextkey from the authConfig
			ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
		})
		// http://localhost:8080/admin/settings
		needAuth.Get("/settings", func(ctx *iris.Context) {
			username := authConfig.User(ctx) // shortcut for ctx.GetString("mycustomkey")
			ctx.Writef("Hello authenticated user: %s from: %s ", username, ctx.Path())
		})
	}

	// open http://localhost:8080/admin
	app.Listen(":8080")
}


text:
package com.amazonaws.services.iot.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.iot.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.SdkHttpUtils;
import com.amazonaws.protocol.json.*;

/**
 * CreatePolicyRequest Marshaller
 */
public class CreatePolicyRequestMarshaller implements
        Marshaller<Request<CreatePolicyRequest>, CreatePolicyRequest> {

    private static final String DEFAULT_CONTENT_TYPE = "application/x-amz-json-1.1";

    private final SdkJsonProtocolFactory protocolFactory;

    public CreatePolicyRequestMarshaller(SdkJsonProtocolFactory protocolFactory) {
        this.protocolFactory = protocolFactory;
    }

    public Request<CreatePolicyRequest> marshall(
            CreatePolicyRequest createPolicyRequest) {

        if (createPolicyRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<CreatePolicyRequest> request = new DefaultRequest<CreatePolicyRequest>(
                createPolicyRequest, "AWSIot");

        request.setHttpMethod(HttpMethodName.POST);

        String uriResourcePath = "/policies/{policyName}";

        uriResourcePath = uriResourcePath.replace(
                "{policyName}",
                (createPolicyRequest.getPolicyName() != null) ? SdkHttpUtils
                        .urlEncode(StringUtils.fromString(createPolicyRequest
                                .getPolicyName()), false) : "");
        request.setResourcePath(uriResourcePath);

        try {
            final StructuredJsonGenerator jsonGenerator = protocolFactory
                    .createGenerator();
            jsonGenerator.writeStartObject();

            if (createPolicyRequest.getPolicyDocument() != null) {
                jsonGenerator.writeFieldName("policyDocument").writeValue(
                        createPolicyRequest.getPolicyDocument());
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            if (!request.getHeaders().containsKey("Content-Type")) {
                request.addHeader("Content-Type", DEFAULT_CONTENT_TYPE);
            }
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
package com.obecto.gattakka

import akka.actor.ActorRef
import akka.event.{EventBus, LookupClassification, ActorEventBus}

class LookupBusImplementation(sendAs: ActorRef) extends EventBus with LookupClassification with ActorEventBus {
  type Event = Any
  type Classifier = Class[_]

  override protected def classify(event: Event): Classifier = event.getClass()

  override protected def publish(event: Event, subscriber: Subscriber): Unit = {
    subscriber.tell(event, sendAs)
  }

  override protected def mapSize: Int = 16

}


text:
using System;
using System.Reflection;
using System.Reflection.Emit;

namespace MyCouch.EntitySchemes.Reflections
{
    public class IlDynamicPropertyFactory : IDynamicPropertyFactory
    {
        protected static readonly Type VoidType = typeof(void);
        protected static readonly Type IlGetterType = typeof(Func<object, string>);
        protected static readonly Type IlSetterType = typeof(Action<object, string>);

        public virtual DynamicProperty PropertyFor(PropertyInfo property)
        {
            if (property == null)
                return new DynamicProperty();

            return new DynamicProperty(
                property.Name,
                CreateStringGetter(property),
                CreateStringSetter(property));
        }

        protected virtual IStringGetter CreateStringGetter(PropertyInfo property)
        {
            return property.CanRead
                ? new DynamicStringGetter(CreateIlGetter(property))
                : new FakeStringGetter() as IStringGetter;
        }

        protected virtual IStringSetter CreateStringSetter(PropertyInfo property)
        {
            return property.CanWrite
                ? new DynamicStringSetter(CreateIlSetter(property))
                : new FakeStringSetter() as IStringSetter;
        }

        protected virtual Func<object, string> CreateIlGetter(PropertyInfo property)
        {
            var propGetMethod = property.GetMethod;
            if (propGetMethod == null)
                return null;

            var getter = CreateDynamicGetMethod(property);

            var generator = getter.GetILGenerator();
            generator.DeclareLocal(typeof(object));
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Castclass, property.DeclaringType);
            generator.EmitCall(OpCodes.Callvirt, propGetMethod, null);

            if (!property.PropertyType.GetTypeInfo().IsClass)
                generator.Emit(OpCodes.Box, property.PropertyType);

            generator.Emit(OpCodes.Ret);

            return (Func<object, string>)getter.CreateDelegate(IlGetterType);
        }

        protected virtual DynamicMethod CreateDynamicGetMethod(PropertyInfo property)
        {
            var args = new[] { typeof(object) };
            var name = string.Format("_{0}{1}_", "Get", property.Name);
            var returnType = property.PropertyType;

            return !property.DeclaringType.GetTypeInfo().IsInterface
                ? new DynamicMethod(
                    name,
                    returnType,
                    args,
                    property.DeclaringType,
                    true)
                : new DynamicMethod(
                    name,
                    returnType,
                    args,
                    property.Module,
                    true);
        }

        protected virtual Action<object, string> CreateIlSetter(PropertyInfo property)
        {
            var propSetMethod = property.SetMethod;
            if (propSetMethod == null)
                return null;

            var setter = CreateDynamicSetMethod(property);

            var generator = setter.GetILGenerator();
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Castclass, property.DeclaringType);
            generator.Emit(OpCodes.Ldarg_1);

            generator.Emit(property.PropertyType.GetTypeInfo().IsClass
                ? OpCodes.Castclass
                : OpCodes.Unbox_Any,
                property.PropertyType);

            generator.EmitCall(OpCodes.Callvirt, propSetMethod, (Type[])null);
            generator.Emit(OpCodes.Ret);

            return (Action<object, string>)setter.CreateDelegate(IlSetterType);
        }

        protected virtual DynamicMethod CreateDynamicSetMethod(PropertyInfo property)
        {
            var args = new[] { typeof(object), property.PropertyType };
            var name = string.Format("_{0}{1}_", "Set", property.Name);
            var returnType = VoidType;

            return !property.DeclaringType.GetTypeInfo().IsInterface
                ? new DynamicMethod(
                    name,
                    returnType,
                    args,
                    property.DeclaringType,
                    true)
                : new DynamicMethod(
                    name,
                    returnType,
                    args,
                    property.Module,
                    true);
        }
    }
}


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

  angular.module('app.admin_users', ['datatables', 'datatables.tabletools']);
}());


text:
package modules

import javax.inject.{Inject, Singleton}

import com.google.maps.model.GeocodingResult
import models.{LineStation, StationGeo}
import play.api.{Configuration, Environment}
import play.api.inject.Module
import scalikejdbc._
import utils.{Config, GoogleMaps}

@Singleton
class LocationSetter @Inject() (config: Configuration, _p: PlayInitializer) {
  run()

  def run(): Unit = {
    new Thread(new LocationSetterThread(config)).start()
  }
}

object LocationSetter {
  val FindCount = 100
  val ReBranket = """\(.*\)""".r
  def normStationName(str: String) = ReBranket.replaceAllIn(str, "")

  def saveGeo(stationId: Long, geo: GeocodingResult)(implicit session: DBSession): Unit = {
    val loc = geo.geometry.location
    val sg = StationGeo(stationId, loc.lat, loc.lng)
    sg.save()(AutoSession)
  }

  def geoQuery(maps: GoogleMaps)(q: String): Option[GeocodingResult] = {
    val xs = maps.geocoding.request(q)
    if (xs.length == 1) Some(xs.head) else None
  }
}

class LocationSetterThread(config: Configuration) extends Runnable {
  import LocationSetter._
  val conf = new Config(config)
  val mapsOpt = conf.googleMapsKey.map(new GoogleMaps(_))

  override def run(): Unit = {
    println("Start LocationSetterThread")
    import models.DefaultAliases.{sg, ls}
    mapsOpt.foreach { maps =>
      Stream.from(0).map { idx =>
        val xs = LineStation.joins(LineStation.stationRef, LineStation.lineRef)
          .findAllWithLimitOffset(limit = FindCount, offset = idx * FindCount, orderings = Seq(ls.id.desc))
        xs.foreach { x =>
          val geo = StationGeo.findBy(sqls.eq(sg.stationId, x.stationId))
          if (geo.isEmpty) {
            for {
              station <- x.station
              line <- x.line
            } {
              val geo = geoQuery(maps)(s"${line.name} ${normStationName(station.name)}駅")
                .orElse(geoQuery(maps)(s"${normStationName(station.name)}駅"))
              Thread.sleep(1000L)
              geo.foreach(saveGeo(x.stationId, _)(AutoSession))
            }
          }
        }
        Thread.sleep(100)
        xs.nonEmpty
      }.takeWhile(identity).foreach(_ => ())
    }
  }
}

class LocationSetterModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration) =
    bind(classOf[LocationSetter]).toSelf.eagerly() :: Nil
}


text:
namespace Google.Cloud.Container.V1.Snippets
{
    // [START container_v1_generated_ClusterManager_RollbackNodePoolUpgrade_sync_flattened2]
    using Google.Cloud.Container.V1;

    public sealed partial class GeneratedClusterManagerClientSnippets
    {
        /// <summary>Snippet for RollbackNodePoolUpgrade</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void RollbackNodePoolUpgrade2()
        {
            // Create client
            ClusterManagerClient clusterManagerClient = ClusterManagerClient.Create();
            // Initialize request argument(s)
            string name = "";
            // Make the request
            Operation response = clusterManagerClient.RollbackNodePoolUpgrade(name);
        }
    }
    // [END container_v1_generated_ClusterManager_RollbackNodePoolUpgrade_sync_flattened2]
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="concept" name="DC.Type" />
<meta name="DC.Title" content="Dynamic parameters" />
<meta name="abstract" content="You can prepare statements that are allowed to have parameters for which the value is not specified when the statement is prepared using PreparedStatement methods in the JDBC API. These parameters are called dynamic parameters and are represented by a question mark (?)." />
<meta name="description" content="You can prepare statements that are allowed to have parameters for which the value is not specified when the statement is prepared using PreparedStatement methods in the JDBC API. These parameters are called dynamic parameters and are represented by a question mark (?)." />
<meta content="Dynamic parameters, IN (? or dynamic) parameters, Prepared statements, use of dynamic parameters in, ? (dynamic parameter), in prepared statements" name="DC.subject" />
<meta content="Dynamic parameters, IN (? or dynamic) parameters, Prepared statements, use of dynamic parameters in, ? (dynamic parameter), in prepared statements" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj19433.html" />
<meta scheme="URI" name="DC.Relation" content="rrefselectexpression.html" />
<meta scheme="URI" name="DC.Relation" content="rreftableexpression.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqljnextvaluefor.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj11277.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj1080779.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj23075.html" />
<meta scheme="URI" name="DC.Relation" content="rrefcase.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj1082953.html" />
<meta scheme="URI" name="DC.Relation" content="rrefsqlj1083019.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="crefsqlj29911" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>Dynamic parameters</title>

Dynamic parameters

You can prepare statements that are allowed to have parameters for
which the value is not specified when the statement is prepared using
PreparedStatement methods in the JDBC API. These parameters are called
dynamic parameters and are represented by a question mark
(<samp class="codeph">?</samp>).

The JDBC API documentation refers to dynamic parameters as IN, INOUT, or OUT
parameters. In SQL, they are always IN parameters.

You must specify values for dynamic parameters before executing the
statement. The values specified must match the types expected.

Dynamic parameters example

Where dynamic parameters are allowed

You can use dynamic parameters anywhere in an expression where their data type can be easily deduced.

Parent topic: SQL expressions

Related reference

selectExpression

tableExpression

NEXT VALUE FOR expression

VALUES expression

Expression precedence

Boolean expressions

CASE expression


text:
=======
Credits
=======

Development Lead
----------------

* Joakim Skoog <joakimskooog@gmail.com>

Contributors
------------

None yet. Why not be the first?


text:
<?php

namespace Magento\Sales\Controller\Adminhtml\Order;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use Magento\Sales\Api\OrderManagementInterface;

/**
 * Class MassHold
 */
class MassHold extends \Magento\Sales\Controller\Adminhtml\Order\AbstractMassAction
{
    /**
     * @var OrderManagementInterface
     */
    protected $orderManagement;

    /**
     * @param Context $context
     * @param Filter $filter
     * @param CollectionFactory $collectionFactory
     * @param OrderManagementInterface $orderManagement
     */
    public function __construct(
        Context $context,
        Filter $filter,
        CollectionFactory $collectionFactory,
        OrderManagementInterface $orderManagement
    ) {
        parent::__construct($context, $filter);
        $this->collectionFactory = $collectionFactory;
        $this->orderManagement = $orderManagement;
    }

    /**
     * Hold selected orders
     *
     * @param AbstractCollection $collection
     * @return \Magento\Backend\Model\View\Result\Redirect
     */
    protected function massAction(AbstractCollection $collection)
    {
        $countHoldOrder = 0;
        foreach ($collection->getItems() as $order) {
            if (!$order->canHold()) {
                continue;
            }
            $this->orderManagement->hold($order->getEntityId());
            $countHoldOrder++;
        }
        $countNonHoldOrder = $collection->count() - $countHoldOrder;

        if ($countNonHoldOrder && $countHoldOrder) {
            $this->messageManager->addError(__('%1 order(s) were not put on hold.', $countNonHoldOrder));
        } elseif ($countNonHoldOrder) {
            $this->messageManager->addError(__('No order(s) were put on hold.'));
        }

        if ($countHoldOrder) {
            $this->messageManager->addSuccess(__('You have put %1 order(s) on hold.', $countHoldOrder));
        }

        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath($this->getComponentRefererUrl());
        return $resultRedirect;
    }
}


text:
package erogenousbeef.core.multiblock;

/**
 * An exception thrown when trying to validate a multiblock. Requires a string describing why the multiblock
 * could not assemble.
 * @author Erogenous Beef
 */
public class MultiblockValidationException extends Exception {

	public MultiblockValidationException(String reason) {
		super(reason);
	}
}


text:
package net.ultrametrics.fractactor

/**
 * Ability to scale a point value with some transformation function.
 */
trait PointScaler {
  /**
   * Transform a point.
   * @param value the initial point
   * @return the scaled point
   */
  def transform(value: Int) = value
}


text:
package com.p1.mobile.p1android.ui.phone;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;

import com.p1.mobile.p1android.R;
import com.p1.mobile.p1android.ui.fragment.FeedItemViewFragment;
import com.p1.mobile.p1android.ui.listeners.ContextualBackListener;

public class FeedItemActivity extends FlurryFragmentActivity implements
        ContextualBackListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_feed_item_holder);
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Bundle extras = getIntent().getExtras();
        String pictureId = "";
        String shareId = "";
        if (extras != null) {
            pictureId = extras.getString("pictureId");
            shareId = extras.getString("shareId");
        }
        ft.replace(R.id.feed_item_holder,
                FeedItemViewFragment.newInstance(shareId, pictureId));
        ft.commit();
    }

    @Override
    public void onContextualBack() {
        finish();
    }
}


text:
package cn.jsprun.dao.impl;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import cn.jsprun.dao.SubscriptiosDao;
import cn.jsprun.domain.Subscriptions;
import cn.jsprun.utils.HibernateUtil;
public class SubscriptionsDaoImpl implements SubscriptiosDao {
	public boolean deleteSubscriptionByUid(int uid) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("delete from Subscriptions as s where s.id.uid=?");
			query.setParameter(0, uid);
			query.executeUpdate();
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
	@SuppressWarnings("unchecked")
	public List<Subscriptions> findSubscriptionsByUid(int uid) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			Query query = session.createQuery("from Subscriptions as s where s.id.uid=?");
			query.setParameter(0, uid);
			List<Subscriptions> list = query.list();
			tr.commit();
			return list;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return null;
	}
	public boolean insertSubscritption(Subscriptions subscrition) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.save(subscrition);
			tr.commit();
			return true;
		}catch(HibernateException e){
			if(tr!=null){
				tr.rollback();
			}
			e.printStackTrace();
		}
		return false;
	}
}


text:
<?php
/**
 * Util class
 *
 * Contains general purpose utilities
 *
 * Code is based on Symfony/translation package (Fabien Potencier)
 * https://github.com/symfony/translation
 *
 * @author Christophe Gosiau <christophe@tigron.be>
 * @author Gerry Demaret <gerry@tigron.be>
 * @author David Vandemaele <david@tigron.be>
 */

namespace Skeleton\I18n;

class Util {

	/**
	 * Load PO File
	 *
	 * @param string $filename
	 * @return array $strings
	 */
	public static function load($filename) {
		$strings = [];
		if (!file_exists($filename)) {
			return [];
		}
		$content = file_get_contents($filename);
		$lines = explode("\n", $content);

		$defaults = [
				   'ids' => [],
				   'translated' => null,
		];

		$item = $defaults;
		$flags = [];

		foreach ($lines as $line) {
		    $line = trim($line);
		    if ($line === '') {
		        // Whitespace indicated current item is done
		        if (!in_array('fuzzy', $flags)) {
		            self::add_message($strings, $item);
		        }
		        $item = $defaults;
		        $flags = array();
		    } elseif (substr($line, 0, 2) === '#,') {
		        $flags = array_map('trim', explode(',', substr($line, 2)));
		    } elseif (substr($line, 0, 7) === 'msgid "') {
		        // We start a new msg so save previous
		        // TODO: this fails when comments or contexts are added
		        self::add_message($strings, $item);
		        $item = $defaults;
		        $item['ids']['singular'] = substr($line, 7, -1);
		    } elseif (substr($line, 0, 8) === 'msgstr "') {
		        $item['translated'] = substr($line, 8, -1);
		    } elseif ($line[0] === '"') {
		        $continues = isset($item['translated']) ? 'translated' : 'ids';
		        if (is_array($item[$continues])) {
		            end($item[$continues]);
		            $item[$continues][key($item[$continues])] .= substr($line, 1, -1);
		        } else {
		            $item[$continues] .= substr($line, 1, -1);
		        }
		    } elseif (substr($line, 0, 14) === 'msgid_plural "') {
		        $item['ids']['plural'] = substr($line, 14, -1);
		    } elseif (substr($line, 0, 7) === 'msgstr[') {
		        $size = strpos($line, ']');
		        $item['translated'][(int) substr($line, 7, 1)] = substr($line, $size + 3, -1);
		    }
		}
		// save last item
		if (!in_array('fuzzy', $flags)) {
		    self::add_message($strings, $item);
		}

		return $strings;
	}

	/**
	 * Prepare a string for loading
	 *
	 * @access private
	 * @param string $string
	 * @return string $fixed_string
	 */
	public static function prepare_load_string($string) {
		$smap = ['/"\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\\"/'];
		$rmap = ['', "\n", "\r", "\t", '"'];
		return (string) preg_replace($smap, $rmap, $string);
	}

	/**
	 * Prepare a string to be written in a po file
	 *
	 * @access private
	 * @param string $string
	 * @return string $fixed_string
	 */
	public static function prepare_save_string($string) {
		$smap = ['"', "\n", "\t", "\r"];
		$rmap = ['\\"', '\\n"' . "\n" . '"', '\\t', '\\r'];
		return (string) str_replace($smap, $rmap, $string);
	}

	/**
	 * Save a po file, based on a translation array
	 *
	 * @access public
	 * @param string $filename
	 * @param array $strings
	 */
	public static function save($filename, $project, $language, $strings) {
		ksort($strings, SORT_STRING | SORT_FLAG_CASE);
		$dir = dirname($filename);
		if (!file_exists($dir)) {
			mkdir($dir, 0755, true);
		}

		// Guess the language string
		switch ($language->name_short) {
			case 'de':
			case 'es':
			case 'fr':
			case 'nl':
			case 'it':
			case 'fi':
				$language_string = $language->name_short;
				break;
			case 'se':
				$language_string = 'sv';
				break;
			case 'zh-chs':
				$language_string = 'zh_Hans';
				break;
			default:
				$language_string = $language->name_short;
		}

		$output = '';

		// Generate the file header
		$output .= '# .po file for project "' . $project . '" in ' . $language->name . "\n";
		$output .= '' . "\n";
		$output .= 'msgid ""' . "\n";
		$output .= 'msgstr ""' . "\n";
		$output .= '"Project-Id-Version: ' . $project . '-' . $language_string . '.' . time() . '\n"' . "\n";
		$output .= '"PO-Revision-Date: ' . date('Y-m-d H:iO')  . '\n"' . "\n";
		$output .= '"MIME-Version: 1.0\n"' . "\n";
		$output .= '"Content-Type: text/plain; charset=UTF-8\n"' . "\n";
		$output .= '"Content-Transfer-Encoding: 8bit\n"' . "\n";
		$output .= '"Language: ' . $language_string . '\n"' . "\n";

		$output .= "\n";

		foreach ($strings as $key => $value) {
			$output .= 'msgid "' . self::prepare_save_string($key) . '"' . "\n";
			$output .= 'msgstr "' . self::prepare_save_string($value) . '"' . "\n\n";
		}

		file_put_contents($filename, $output);
	}

	/**
	 * Merge 2 po files
	 *
	 * @access public
	 * @param array $strings1
	 * @param array $strings2
	 */
	public static function merge($base, $extra) {
		$base_strings = self::load($base);
		$extra_strings = self::load($extra);

		$extra_strings_keys = array_keys($extra_strings);
		foreach ($extra_strings_keys as $string) {
			if (isset($base_strings[$string]) AND $base_strings[$string] != '') {
				$extra_strings[$string] = $base_strings[$string];
			}
		}

		self::save($base, $extra_strings);
	}

	/**
	 * Get best matching language
	 *
	 * Borrowed from Drupal (https://github.com/drupal/core-utility)
	 *
	 * @access public
	 * @param string $http_accept_language
	 * @param array $langcodes
	 * @param array $mappings
	 * @return string $language
	 */
	public static function get_best_matching_language($http_accept_language, $langcodes, $mappings = []) {
		// The Accept-Language header contains information about the language
		// preferences configured in the user's user agent / operating system.
		// RFC 2616 (section 14.4) defines the Accept-Language header as follows:
		//		Accept-Language = "Accept-Language" ":"
		//						1#( language-range [ ";" "q" "=" qvalue ] )
		//		language-range	= ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
		// Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5"
		$ua_langcodes = [];
		if (preg_match_all('@(?<=[, ]|^)([a-zA-Z-]+|\\*)(?:;q=([0-9.]+))?(?:$|\\s*,\\s*)@', trim($http_accept_language), $matches, PREG_SET_ORDER)) {
			foreach ($matches as $match) {
				if ($mappings) {
					$langcode = strtolower($match[1]);
					foreach ($mappings as $ua_langcode => $standard_langcode) {
						if ($langcode == $ua_langcode) {
							$match[1] = $standard_langcode;
						}
					}
				}

				// We can safely use strtolower() here, tags are ASCII.
				// RFC2616 mandates that the decimal part is no more than three digits,
				// so we multiply the qvalue by 1000 to avoid floating point
				// comparisons.
				$langcode = strtolower($match[1]);
				$qvalue = isset($match[2]) ? (double) $match[2] : 1;

				// Take the highest qvalue for this langcode. Although the request
				// supposedly contains unique langcodes, our mapping possibly resolves
				// to the same langcode for different qvalues. Keep the highest.
				$ua_langcodes[$langcode] = max((int) ($qvalue * 1000), isset($ua_langcodes[$langcode]) ? $ua_langcodes[$langcode] : 0);
			}
		}

		// We should take pristine values from the HTTP headers, but Internet
		// Explorer from version 7 sends only specific language tags (eg. fr-CA)
		// without the corresponding generic tag (fr) unless explicitly configured.
		// In that case, we assume that the lowest value of the specific tags is the
		// value of the generic language to be as close to the HTTP 1.1 spec as
		// possible.
		// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 and
		// http://blogs.msdn.com/b/ie/archive/2006/10/17/accept-language-header-for-internet-explorer-7.aspx
		asort($ua_langcodes);
		foreach ($ua_langcodes as $langcode => $qvalue) {

			// For Chinese languages the generic tag is either zh-hans or zh-hant, so
			// we need to handle this separately, we can not split $langcode on the
			// first occurrence of '-' otherwise we get a non-existing language zh.
			// All other languages use a langcode without a '-', so we can safely
			// split on the first occurrence of it.
			if (strlen($langcode) > 7 && (substr($langcode, 0, 7) == 'zh-hant' || substr($langcode, 0, 7) == 'zh-hans')) {
				$generic_tag = substr($langcode, 0, 7);
			} else {
				$generic_tag = strtok($langcode, '-');
			}

			if (!empty($generic_tag) && !isset($ua_langcodes[$generic_tag])) {
				// Add the generic langcode, but make sure it has a lower qvalue as the
				// more specific one, so the more specific one gets selected if it's
				// defined by both the user agent and us.
				$ua_langcodes[$generic_tag] = $qvalue - 0.1;
			}
		}

		// Find the added language with the greatest qvalue, following the rules
		// of RFC 2616 (section 14.4). If several languages have the same qvalue,
		// prefer the one with the greatest weight.
		$best_match_langcode = FALSE;
		$max_qvalue = 0;
		foreach ($langcodes as $langcode_case_sensitive) {

			// Language tags are case insensitive (RFC2616, sec 3.10).
			$langcode = strtolower($langcode_case_sensitive);

			// If nothing matches below, the default qvalue is the one of the wildcard
			// language, if set, or is 0 (which will never match).
			$qvalue = isset($ua_langcodes['*']) ? $ua_langcodes['*'] : 0;

			// Find the longest possible prefix of the user agent supplied language
			// ('the language-range') that matches this site language ('the language
			// tag').
			$prefix = $langcode;
			do {
				if (isset($ua_langcodes[$prefix])) {
					$qvalue = $ua_langcodes[$prefix];
					break;
				}
			} while ($prefix = substr($prefix, 0, strrpos($prefix, '-')));

			// Find the best match.
			if ($qvalue > $max_qvalue) {
				$best_match_langcode = $langcode_case_sensitive;
				$max_qvalue = $qvalue;
			}
		}

		return $best_match_langcode;
	}

	/**
	 * Add message
	 *
	 * @access private
	 * @param array $strings
	 * @param array $item
	 */
	private static function add_message(array &$strings, array $item) {
        if (is_array($item['translated'])) {
            $strings[stripcslashes($item['ids']['singular'])] = stripcslashes($item['translated'][0]);
            if (isset($item['ids']['plural'])) {
                $plurals = $item['translated'];
                // PO are by definition indexed so sort by index.
                ksort($plurals);
                // Make sure every index is filled.
                end($plurals);
                $count = key($plurals);
                // Fill missing spots with '-'.
                $empties = array_fill(0, $count + 1, '-');
                $plurals += $empties;
                ksort($plurals);
                $strings[stripcslashes($item['ids']['plural'])] = stripcslashes(implode('|', $plurals));
            }
        } elseif (!empty($item['ids']['singular'])) {
            $strings[stripcslashes($item['ids']['singular'])] = stripcslashes($item['translated']);
        }
    }
}


text:
package org.traccar.protocol;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.traccar.BaseProtocolDecoder;
import org.traccar.DeviceSession;
import org.traccar.helper.BitUtil;
import org.traccar.helper.UnitsConverter;
import org.traccar.model.Position;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class ObdDongleProtocolDecoder extends BaseProtocolDecoder {

    public ObdDongleProtocolDecoder(ObdDongleProtocol protocol) {
        super(protocol);
    }

    public static final int MSG_TYPE_CONNECT = 0x01;
    public static final int MSG_TYPE_CONNACK = 0x02;
    public static final int MSG_TYPE_PUBLISH = 0x03;
    public static final int MSG_TYPE_PUBACK = 0x04;
    public static final int MSG_TYPE_PINGREQ = 0x0C;
    public static final int MSG_TYPE_PINGRESP = 0x0D;
    public static final int MSG_TYPE_DISCONNECT = 0x0E;

    private static void sendResponse(Channel channel, int type, int index, String imei, ChannelBuffer content) {
        if (channel != null) {
            ChannelBuffer response = ChannelBuffers.dynamicBuffer();
            response.writeShort(0x5555); // header
            response.writeShort(index);
            response.writeBytes(imei.getBytes(StandardCharsets.US_ASCII));
            response.writeByte(type);
            response.writeShort(content.readableBytes());
            response.writeBytes(content);
            response.writeByte(0); // checksum
            response.writeShort(0xAAAA);
            channel.write(response);
        }
    }

    @Override
    protected Object decode(
            Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

        ChannelBuffer buf = (ChannelBuffer) msg;

        buf.skipBytes(2); // header
        int index = buf.readUnsignedShort();

        String imei = buf.readBytes(15).toString(StandardCharsets.US_ASCII);
        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei);
        if (deviceSession == null) {
            return null;
        }

        int type = buf.readUnsignedByte();

        buf.readUnsignedShort(); // data length

        if (type == MSG_TYPE_CONNECT) {

            ChannelBuffer response = ChannelBuffers.dynamicBuffer();
            response.writeByte(1);
            response.writeShort(0);
            response.writeInt(0);
            sendResponse(channel, MSG_TYPE_CONNACK, index, imei, response);

        } else if (type == MSG_TYPE_PUBLISH) {

            int typeMajor = buf.readUnsignedByte();
            int typeMinor = buf.readUnsignedByte();

            buf.readUnsignedByte(); // event id

            Position position = new Position(getProtocolName());
            position.setDeviceId(deviceSession.getDeviceId());

            position.setTime(new Date(buf.readUnsignedInt() * 1000));

            int flags = buf.readUnsignedByte();

            position.setValid(!BitUtil.check(flags, 6));

            position.set(Position.KEY_SATELLITES, BitUtil.to(flags, 4));

            double longitude = ((BitUtil.to(buf.readUnsignedShort(), 1) << 24) + buf.readUnsignedMedium()) * 0.00001;
            position.setLongitude(BitUtil.check(flags, 5) ? longitude : -longitude);

            double latitude = buf.readUnsignedMedium() * 0.00001;
            position.setLatitude(BitUtil.check(flags, 4) ? latitude : -latitude);

            int speedCourse = buf.readUnsignedMedium();
            position.setSpeed(UnitsConverter.knotsFromMph(BitUtil.from(speedCourse, 10) * 0.1));
            position.setCourse(BitUtil.to(speedCourse, 10));

            ChannelBuffer response = ChannelBuffers.dynamicBuffer();
            response.writeByte(typeMajor);
            response.writeByte(typeMinor);
            sendResponse(channel, MSG_TYPE_PUBACK, index, imei, response);

            return position;

        }

        return null;
    }

}


text:
class Tweet < ActiveRecord::Base
  # Remember to create a migration!
  belongs_to :user
  belongs_to :original_user, class_name: 'User'#, foreign_key: :original_user_id

  validates_length_of :content, :within => 1..140,
    :too_long => "You may enter up to 140 characters",
    :too_short => "You must enter at least 1 character"

  default_scope { order('updated_at DESC') }
end


text:
//    (The MIT License)
//
//    Copyright (c) 2012 Richard S Allinson <rsa@mountainmansoftware.com>
//
//    Permission is hereby granted, free of charge, to any person obtaining
//    a copy of this software and associated documentation files (the
//    'Software'), to deal in the Software without restriction, including
//    without limitation the rights to use, copy, modify, merge, publish,
//    distribute, sublicense, and/or sell copies of the Software, and to
//    permit persons to whom the Software is furnished to do so, subject to
//    the following conditions:
//
//    The above copyright notice and this permission notice shall be
//    included in all copies or substantial portions of the Software.
//
//    THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
//    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//    CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//    TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//    SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';

/*
 * Module dependencies
 */

var utils = require('../utils');

/*
 * Functions and attributes to mock out
 */

var func = ['setEncoding', 'pause', 'resume'],
    attr = ['headers', 'trailers', 'httpVersion', 'connection'];

/*
 * The prototype for the request
 */

var request = {};

/*
 * Mock all ServerRequest functions
 */

func.forEach(function (func) {
    request[func] = function () {
        throw new Error('Function "' + func + '" not supported.');
    };
});

/*
 * Mock all ServerRequest attributes
 */

attr.forEach(function (attr) {
    request[attr] = '';
});

/*
 * Expose a create function for the Request
 */

exports.create = function (req) {

    var handler = {};

    utils.merge(handler, request);

    handler.method = req.method;
    handler.url = req.url;
    handler.body = req.body;

    return handler;
};


text:
/*
 * Custom Type Definitions
 * When including 3rd party modules you also need to include the type definition for the module
 * if they don't provide one within the module. You can try to install it with typings

typings install node --save

 * If you can't find the type definition in the registry we can make an ambient definition in
 * this file for now. For example

declare module "my-module" {
  export function doesSomething(value: string): string;
}

 *
 * If you're prototying and you will fix the types later you can also declare it as type any
 *

declare var assert: any;

 *
 * If you're importing a module that uses Node.js modules which are CommonJS you need to import as
 *

import * as _ from 'lodash'

 * You can include your type definitions in this file until you create one for the typings registry
 * see https://github.com/typings/registry
 *
 */

interface WebpackModule {
  hot: {
    data?: any,
    idle: any,
    accept(dependencies?: string | string[], callback?: (updatedDependencies?: any) => void): void;
    decline(dependencies?: string | string[]): void;
    dispose(callback?: (data?: any) => void): void;
    addDisposeHandler(callback?: (data?: any) => void): void;
    removeDisposeHandler(callback?: (data?: any) => void): void;
    check(autoApply?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void;
    apply(options?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void;
    status(callback?: (status?: string) => void): void | string;
    removeStatusHandler(callback?: (status?: string) => void): void;
  }
}

interface NodeModule extends WebpackModule {

}


text:
<?PHP

define('SED_CODE', TRUE);
define('SED_FORUMS', TRUE);
$location = 'Forums';
$z = 'forums';

require_once('./datas/config.php');
require_once($cfg['system_dir'].'/functions.php');
require_once($cfg['system_dir'].'/common.php');

sed_dieifdisabled($cfg['disable_forums']);

switch($m)
	{
	case 'topics':
	require_once($cfg['system_dir'].'/core/forums/forums.topics.inc.php');
	break;

	case 'posts':
	require_once($cfg['system_dir'].'/core/forums/forums.posts.inc.php');
	break;

	case 'editpost':
	require_once($cfg['system_dir'].'/core/forums/forums.editpost.inc.php');
	break;

	case 'newtopic':
	require_once($cfg['system_dir'].'/core/forums/forums.newtopic.inc.php');
	break;

	default:
	require_once($cfg['system_dir'].'/core/forums/forums.inc.php');
	break;
	}

?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">

	<title>SHTOOLS - List of routines</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="css/sh.css">
	<link rel="shortcut icon" type="image/vnd.microsoft.icon" href="images/favicon.ico">
	<link rel="icon" type="image/vnd.microsoft.icon" href="images/favicon.ico">
	<meta name="description" content="List of routines in the SHTOOLS software archive.">

				HOME
				DOWNLOAD
				DOCUMENTATION
				FAQ

>  Home > Documentation

Fortran 95 routines

Modules

Legendre functions

Spherical harmonic transformations

Spherical harmonic I/O, Storage, Conversions

Global spectral analysis

Localized spectral analysis

Spherical harmonic rotations

Gravity and Magnetics

Other routines

	>  Home > Documentation

			Institut de Physique du Globe de Paris
			University of Sorbonne Paris Cité
			© 2015 Mark Wieczorek


text:
@class NSString;

@interface EmoticonDownloadProxy : NSObject
{
    _Bool _needNotifyPartLen;
    NSObject *_m_userInfo;
    NSString *_m_productId;
    NSString *_m_designerId;
    NSString *_m_filePath;
}

@property(nonatomic) _Bool needNotifyPartLen; // @synthesize needNotifyPartLen=_needNotifyPartLen;
@property(retain, nonatomic) NSString *m_filePath; // @synthesize m_filePath=_m_filePath;
@property(retain, nonatomic) NSString *m_designerId; // @synthesize m_designerId=_m_designerId;
@property(retain, nonatomic) NSString *m_productId; // @synthesize m_productId=_m_productId;
@property(retain, nonatomic) NSObject *m_userInfo; // @synthesize m_userInfo=_m_userInfo;
- (void).cxx_destruct;
- (void)clearDelegate;
- (_Bool)isActive;
- (void)startRequest;
- (id)initWithMd5:(id)arg1;

@end


text:
namespace dfmc
{
  class IDemoData
  {
  public:
    virtual ~IDemoData() {}
  };
}
#endif


text:
import requests

WHEELMAP_API_URL = "http://wheelmap.org/api/"

class Wheelmap:
    def __init__(self, api_key):
        self.api_key = api_key

    def request(self, endpoint, method, params={}):
        """General function for all requests."""
        params["api_key"] = self.api_key
        endpoint_url = WHEELMAP_API_URL + endpoint
        r = requests.request(method, endpoint_url, params=params)
        return r.json()

    def nodes_collection(self, bbox=None, wheelchair=None, page=None, per_page=None):
        """Function for /api/nodes?bbox&wheelchair&page&per_page
        It returns a list of WheelmapNodes"""
        params={}

        if type(bbox) == str:
            params["bbox"] = bbox
        elif type(bbox) == tuple:
            params["bbox"] = "{},{},{},{}".format(*bbox)

        if wheelchair:
            params["wheelchair"] = wheelchair

        if page:
            params["page"] = page

        if per_page:
            params["per_page"] = per_page

        r = self.request("nodes", "GET", params)

        if "nodes" in r:
            nodes = []
            for node in r["nodes"]:
                nodes.append(WheelmapNode(node))

        return nodes

    def nodes_update_wheelchair(self, node=None, node_id=None, wheelchair=None):
        """/api/nodes/{node_id}/update_wheelchair"""

        if node:
            endpoint = "nodes/{}/update_wheelchair".format(node.node_id)
        else:
            endpoint = "nodes/{}/update_wheelchair".format(node_id)

        params = {'wheelchair': wheelchair}

        r = self.request(endpoint, "PUT", params=params)

        if "message" in r:
            return True
        else:
            return False

class WheelmapNode:
    def __init__(self, json_node):
        # id is node_id, because of python inbuild .id()
        self.node_id = json_node["id"]
        self.name = json_node["name"]
        self.lat = json_node["lat"]
        self.lng = json_node["lon"]
        self.wheelchair = json_node["wheelchair"]
        self.wheelchair_description = json_node["wheelchair_description"]
        self.street = json_node["street"]
        self.housenumber = json_node["housenumber"]
        self.city = json_node["city"]
        self.postcode = json_node["postcode"]
        self.website = json_node["website"]
        self.phone = json_node["phone"]
        self.node_type = json_node["node_type"]["identifier"]

    def get_wheelmap_node_url(self):
        return "http://wheelmap.org/nodes/%s" % self.wheelmap_id

    def get_wheelmap_map_url(self, zoom = 18):
        return "http://wheelmap.org/en/?lat=%s&lon=%szoom=%s" % (self.lat, self.lng, zoom)

    def get_openstreetmap_node_url(self):
        return "http://www.openstreetmap.org/browse/node/%s" % self.wheelmap_id

    def get_openstreetmap_map_url(self):
        return "http://www.openstreetmap.org/?node=%s" % self.wheelmap_id

    def get_color_coded_icon(self):
        return "http://wheelmap.org/marker/%s.png" % (self.wheelchair)

    def get_html_address(self):
        html = ""
        if self.street:
            html += self.street
            if self.housenumber:
                html += " " + self.housenumber
            html += "
"
        if self.city:
            if self.postcode:
                html += self.postcode + " "
            html += self.city
        return html

    def get_googlemaps_image(self, width = 200, height = 200):
        uri = "http://maps.googleapis.com/maps/api/staticmap?zoom=15&size=%sx%s&sensor=false" % (width, height)
        uri += "&markers=icon:%s|%s,%s" % (self.get_color_coded_icon(), self.lat, self.lng)
        return uri

    def get_mapquest_image(self, zoom = 16):
        (xtile, ytile) = deg2num(self.lat, self.lng, zoom)
        uri = "http://otile3.mqcdn.com/tiles/1.0.0/osm/%s/%s/%s.jpg" % (zoom, xtile, ytile)
        return uri

    def get_openstreetmap_image(self, zoom = 16):
        (xtile, ytile) = deg2num(self.lat, self.lng, zoom)
        uri = "http://b.tile.openstreetmap.org/%s/%s/%s.png" % (zoom, xtile, ytile)
        return uri

    def get_map_with_marker(self):
        html =  "
"
        html += "
"
        html += "" % self.get_color_coded_icon()
        html += "
"
        html += "" % self.get_openstreetmap_image(16)
        html += "
"
        return html


text:
namespace Jint.Tests.Runtime.Domain
{
    public class ClassWithStaticFields
    {
        public static string Get = "Get";
        public static string Set = "Set";

        public static string Getter { get { return "Getter"; } }
        public static string Setter { get; set; }

        public static readonly string Readonly = "Readonly";

        static ClassWithStaticFields()
        {
            Setter = "Setter";
        }
    }
}


text:
<?php

namespace Pimcore\Model\Metadata;

use Pimcore\Model;

class Resource extends Model\Resource\AbstractResource {

    public function getRawData(){
        $cid = $this->model->getCid();
        $type = $this->model->getType();
        $name = $this->model->getName();
        $raw = null;
        if($cid){
            $data = $this->db->fetchRow("SELECT * FROM assets_metadata_predefined WHERE type=? AND cid = ? AND name=?",array($type,$cid,$name) );
            $raw = $data['data'];
        }
        return $raw;
    }

    /**
     * Save object to database
     *
     * @return void
     */
    public function save() {

        $data = $this->model->getData();

        if ($this->model->getType() == "object" || $this->model->getType() == "asset" || $this->model->getType() == "document") {

            if ($data instanceof Model\Element\ElementInterface) {
                $data = $data->getId();
            }
            else {
                $data = null;
            }
        }

        if (is_array($data) || is_object($data)) {
            $data = \Pimcore\Tool\Serialize::serialize($data);
        }

        $saveData = array(
            "cid" => $this->model->getCid(),
            "ctype" => $this->model->getCtype(),
            "cpath" => $this->model->getCpath(),
            "name" => $this->model->getName(),
            "type" => $this->model->getType(),
            "inheritable" => (int)$this->model->getInheritable(),
            "data" => $data
        );

        $this->db->insertOrUpdate("properties", $saveData);
    }
}


text:
/* eslint-env mocha */

export default M => {
  const {string} = M.metadata()

  class Animal extends M.Base {
    speak() {
      return 'hello'
    }

    static innerTypes() {
      return Object.freeze({
        name: string()
      })
    }
  }

  return Object.freeze(Animal)
}


text:
package org.sidoh.song_recognition.audio_io;

import java.io.File;
import java.io.IOException;

/**
 * A frame buffer is an iterator across frames.
 *
 * @author chris
 *
 */
public abstract class FrameBuffer implements Iterable<double[]> {
	public static class Builder {
		private int frameSize;
		private double overlap;

		private Builder(int frameSize) {
			this.frameSize = frameSize;
			overlap = 0d;
		}

		public Builder sampleOverlap(double rate) {
			overlap = rate;
			return this;
		}

		public Builder frameSize(int size) {
			this.frameSize = size;
			return this;
		}

		public FrameBuffer fromWavFile(String filename) throws IOException, WavFileException {
			return fromWavFile(WavFile.openWavFile(new File(filename)));
		}

		public FrameBuffer fromWavFile(WavFile wav) {
			FrameBuffer buffer = new WavFrameBuffer(wav, frameSize);

			if (overlap != 0d) {
				buffer = new OverlappingFrameBuffer(buffer, overlap);
			}

			return buffer;
		}
	}

	/**
	 * Returns the size of the next frame
	 *
	 * @return
	 */
	public abstract int getFrameSize();

	/**
	 * Returns the number of frames in this buffer.
	 *
	 * @return
	 */
	public abstract int getNumFrames();

	/**
	 * Returns sample rate
	 *
	 * @return
	 */
	public abstract double getSampleRate();

	/**
	 * Returns # of frames in a second.
	 *
	 * @return
	 */
	public abstract double getFramesPerSecond();

	/**
	 * Create new builder with specified frame size
	 *
	 * @param size
	 * @return
	 */
	public static Builder frameSize(int size) {
		return new Builder(size);
	}
}


text:
import Ember from 'ember';
import layout from '../templates/components/mdl-checkbox';
import RippleUtil from '../util/ripple';
import FocusMixin from '../mixins/focusable';

const Constant_ = {
  TINY_TIMEOUT: 0.001
};

const CssClasses_ = {
  INPUT: 'mdl-checkbox__input',
  BOX_OUTLINE: 'mdl-checkbox__box-outline',
  FOCUS_HELPER: 'mdl-checkbox__focus-helper',
  TICK_OUTLINE: 'mdl-checkbox__tick-outline',
  RIPPLE_EFFECT: 'mdl-js-ripple-effect',
  RIPPLE_IGNORE_EVENTS: 'mdl-js-ripple-effect--ignore-events',
  RIPPLE_CONTAINER: 'mdl-checkbox__ripple-container',
  RIPPLE_CENTER: 'mdl-ripple--center',
  RIPPLE: 'mdl-ripple',
  IS_FOCUSED: 'is-focused',
  IS_DISABLED: 'is-disabled',
  IS_CHECKED: 'is-checked',
  IS_UPGRADED: 'is-upgraded'
};

/* global MaterialRadio */
export default Ember.Component.extend(FocusMixin, {
  layout: layout,
  classNames: ['mdl-checkbox', CssClasses_.IS_UPGRADED],
  classNameBindings: [
      'checked:is-checked'
  ],
  ripple: true,
  tagName: 'label',
  attributeBindings: ['controlId:for'],
  CssClasses: CssClasses_,
  controlId: Ember.computed(function () {
    return this.get('elementId') + '_control';
  }),
  onMouseUp_ (event) {
    window.setTimeout(function() {
      this.$().find('input').blur();
    }.bind(this), /** @type {number} */ (Constant_.TINY_TIMEOUT));
  },
  didInsertElement() {
    if (this.get('ripple')) {

      this.get('element').classList.add(CssClasses_.RIPPLE_IGNORE_EVENTS);
      this.rippleContainerElement_ = document.createElement('span');
      this.rippleContainerElement_.classList.add(CssClasses_.RIPPLE_CONTAINER);
      this.rippleContainerElement_.classList.add(CssClasses_.RIPPLE_EFFECT);
      this.rippleContainerElement_.classList.add(CssClasses_.RIPPLE_CENTER);
      this.boundRippleMouseUp = this.onMouseUp_.bind(this);
      this.rippleContainerElement_.addEventListener('mouseup', this.boundRippleMouseUp);

      var ripple = document.createElement('span');
      ripple.classList.add(CssClasses_.RIPPLE);

      this.rippleContainerElement_.appendChild(ripple);
      this.get('element').appendChild(this.rippleContainerElement_);
      new RippleUtil(this.get('element'));
      new RippleUtil(this.rippleContainerElement_);
    }
  }

});


text:
import os
from tableaudocumentapi import Datasource
from tableaudocumentapi import Workbook

path = os.path.realpath(os.getcwd())
print(path)
# sourceTDS = Datasource.from_file('{}/tableauworkbook.tds'.format(path))

############################################################
# Step 3)  Print out all of the fields and what type they are
############################################################
fname = '{}/tableauworkbook.twb'.format(path)
if fname.endswith('twb') or fname.endswith('twbx'): # or fname.endswith('tds'):

	    sourceWB = Workbook(fname)
	    for sourceTDS in sourceWB.datasources:

			print('--- Fields in {}'.format(sourceTDS.name))
			print('----------------------------------------------------------')
			print('--- {} total fields in this datasource'.format(len(sourceTDS.fields)))
			print('----------------------------------------------------------')
			for count, field in enumerate(sourceTDS.fields.values()):
			    print('{:>4}: {} is a {}'.format(count+1, field.name, field.datatype))
			    blank_line = False
			    if field.calculation:
			        print('      the formula is {}'.format(field.calculation.encode('utf-8').strip()))
			        blank_line = True
			    if field.default_aggregation:
			        print('      the default aggregation is {}'.format(field.default_aggregation))
			        blank_line = True
			    if field.description:
			        print('      the description is {}'.format(field.description))

			    if blank_line:
			        print('')
			# print('----------------------------------------------------------')