text:
package ws.epigraph.data.pruning;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import ws.epigraph.data.*;
import ws.epigraph.data.traversal.DataTraversalContext;
import ws.epigraph.errors.ErrorValue;
import ws.epigraph.projections.req.*;
import ws.epigraph.types.DatumType;
import ws.epigraph.types.Field;
import ws.epigraph.types.Tag;
import ws.epigraph.types.TypeKind;
import ws.epigraph.util.HttpStatusCode;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Konstantin Sobolev
 * @see required flag for request projections
 */
public class ReqOutputRequiredDataPruner {
  private final DataTraversalContext context = new DataTraversalContext();

  public @NotNull DataPruningResult pruneData(
      @NotNull Data data,
      @NotNull ReqProjection<?, ?> projection,
      int pathSteps) {

    projection = projection.normalizedForType(data.type());

    final Map<@NotNull String, @NotNull ? extends Val> tagValues = data._raw().tagValues();
    final Map<String, Val> replacements = new HashMap<>();

    for (final Map.Entry<String, ReqTagProjectionEntry> entry : projection.tagProjections().entrySet()) {
      final String tagName = entry.getKey();
      final Tag tag = data.type().tagsMap().get(tagName);

      final ReqTagProjectionEntry tagProjectionEntry = entry.getValue();
      final ReqModelProjection<?, ?, ?> modelProjection = tagProjectionEntry.modelProjection();
      final boolean required = modelProjection.flag();

      Val val = tagValues.get(tagName);

      if (val != null) {
        final Datum datum = val.getDatum();

        if (datum != null) {
          final DatumPruningResult datumPruningResult = context.withStackItem(
              new DataTraversalContext.TagStackItem(tag),
              () -> pruneDatum(datum, modelProjection, Math.max(0, pathSteps - 1))
          );

          if (datumPruningResult instanceof Fail)
            return (Fail) datumPruningResult;

          if (datumPruningResult instanceof ReplaceDatum) {
            ReplaceDatum replaceDatum = (ReplaceDatum) datumPruningResult;
            replacements.put(tagName, replaceDatum.newDatum.asValue());
          } else {
            if (datumPruningResult instanceof UseError) {
              UseError useError = (UseError) datumPruningResult;
              replacements.put(tagName, tag.type.createValue(useError.error));
            } // else keep
          }
        }
      }

      if (replacements.containsKey(tagName))
        val = replacements.get(tagName);

      if (required) {
        final String name = data.type().kind() == TypeKind.ENTITY ? String.format("tag '%s'", tagName) : "data";
        if (val == null) {
          return new Fail(operationError(String.format("Required %s is missing", name)));
        } else {
          ErrorValue error = val.getError();
          if (error == null) {
            if (val.getDatum() == null)
              return new RemoveData(error(String.format("Required %s is null", name)));
          } else
            return new RemoveData(error(String.format(
                "Required %s is a [%d] error: %s",
                name,
                error.statusCode(),
                error.message()
            )));
        }
      } else if (data.type().kind() != TypeKind.ENTITY && replacements.containsKey(tagName)) {
        // if (single) tag in a self-var must be replaced by an error: kill the whole data
        assert val != null;
        ErrorValue error = val.getError();
        if (error == null) {
          if (val.getDatum() == null)
            return new RemoveData(error("Required data is null"));
        } else if (pathSteps == 0)
          return new RemoveData(error(String.format(
              "Required data is a [%d] error: %s",
              error.statusCode(),
              error.message()
          )));

      }
    }

    if (replacements.isEmpty())
      return Keep.INSTANCE;
    else {
      final Data.Builder builder = data.type().createDataBuilder();
      for (final Map.Entry<String, ? extends Val> entry : tagValues.entrySet()) {
        String tagName = entry.getKey();

        final Val val = replacements.containsKey(tagName) ? replacements.get(tagName) : entry.getValue();
        builder._raw().setValue(data.type().tagsMap().get(tagName), val);
      }
      return new ReplaceData(builder);
    }
  }

  public @NotNull DatumPruningResult pruneDatum(
      @NotNull Datum datum,
      @NotNull ReqModelProjection<?, ?, ?> projection,
      int pathSteps) {

    projection = projection.normalizedForType(datum.type());

    switch (datum.type().kind()) {
      case RECORD:
        return pruneRecordDatum((RecordDatum) datum, (ReqRecordModelProjection) projection, pathSteps);
      case MAP:
        return pruneMapDatum((MapDatum) datum, (ReqMapModelProjection) projection, pathSteps);
      case LIST:
        return pruneListDatum((ListDatum) datum, (ReqListModelProjection) projection, pathSteps);
      default:
        return Keep.INSTANCE;
    }
  }

  private @NotNull DatumPruningResult pruneRecordDatum(
      @NotNull RecordDatum datum,
      @NotNull ReqRecordModelProjection projection,
      int pathSteps) {

    final Map<@NotNull String, @NotNull ? extends Data> fieldsData = datum._raw().fieldsData();
    final Map<String, Data> replacements = new HashMap<>();

    for (final Map.Entry<String, ReqFieldProjectionEntry> entry : projection.fieldProjections().entrySet()) {
      final String fieldName = entry.getKey();
      final Field field = datum.type().fieldsMap().get(fieldName);

      final ReqFieldProjectionEntry fieldProjectionEntry = entry.getValue();
      final ReqFieldProjection fieldProjection = fieldProjectionEntry.fieldProjection();
      final boolean required = fieldProjection.flag();
      final ReqProjection<?, ?> dataProjection = fieldProjection.projection();

      Data data = fieldsData.get(fieldName);

      if (data != null) {
        final Data data0 = data;
        final DataPruningResult dataPruningResult = context.withStackItem(
            new DataTraversalContext.FieldStackItem(field),
            () -> pruneData(data0, dataProjection, Math.max(0, pathSteps - 1))
        );

        if (dataPruningResult instanceof Fail)
          return (Fail) dataPruningResult;

        if (dataPruningResult instanceof ReplaceData) {
          ReplaceData replaceData = (ReplaceData) dataPruningResult;
          replacements.put(fieldName, replaceData.newData);
        } else if (dataPruningResult instanceof RemoveData) {
          RemoveData removeData = (RemoveData) dataPruningResult;
          if (required)
            return new UseError(
                removeData.reason,
                new ErrorValue(HttpStatusCode.PRECONDITION_FAILED, removeData.reason.toString())
            );
          else
            replacements.put(fieldName, null);
        } // else keep
      }

      if (replacements.containsKey(fieldName))
        data = replacements.get(fieldName);

      if (required) {
        DatumPruningResult fieldBasedResult = checkRequiredData(data, "field", "'" + fieldName + "'");
        if (fieldBasedResult != Keep.INSTANCE)
          return fieldBasedResult;
      }
    }

    if (replacements.isEmpty())
      return Keep.INSTANCE;
    else {
      final RecordDatum.Builder builder = datum.type().createBuilder();
      for (final Map.Entry<String, ? extends Data> entry : fieldsData.entrySet()) {
        String fieldName = entry.getKey();
        final Field field = datum.type().fieldsMap().get(fieldName);

        final Data data = replacements.containsKey(fieldName) ? replacements.get(fieldName) : entry.getValue();
        builder._raw().setData(field, data);
      }
      return new ReplaceDatum(builder);
    }
  }

  private @NotNull DatumPruningResult pruneMapDatum(
      @NotNull MapDatum datum,
      @NotNull ReqMapModelProjection projection,
      int pathSteps) {

    final ReqProjection<?, ?> itemsProjection = projection.itemsProjection();
    final boolean keysRequired = projection.keysRequired();
    final Map<Datum.Imm, Data> replacements = new HashMap<>();

    List<ReqKeyProjection> projectionKeys = projection.keys();
    Collection<Datum.Imm> keys =
        projectionKeys == null
        ? datum._raw().elements().keySet()
        : projectionKeys.stream().map(pk -> pk.value().toImmutable()).collect(Collectors.toList());

    for (Datum.Imm key : keys) {
      @Nullable Data data = datum._raw().elements().get(key);

      if (data != null) {
        final Data data0 = data;
        final DataPruningResult prunedData =
            context.withStackItem(
                new DataTraversalContext.MapKeyStackItem(key),
                () -> pruneData(data0, itemsProjection, Math.max(0, pathSteps - 1))
            );

        if (prunedData instanceof RemoveData) {
          RemoveData removeData = (RemoveData) prunedData;
          if (keysRequired)
            return new UseError(
                removeData.reason,
                new ErrorValue(HttpStatusCode.PRECONDITION_FAILED, removeData.reason.toString())
            );
          else
            replacements.put(key, null);
        } else if (prunedData instanceof ReplaceData) {
          ReplaceData replaceData = (ReplaceData) prunedData;
          replacements.put(key, replaceData.newData);
        } else if (prunedData instanceof Fail)
          return (Fail) prunedData;
        // else keep
      }

      if (replacements.containsKey(key))
        data = replacements.get(key);

      if (keysRequired) {
        DataTraversalContext.MapKeyStackItem keyItem = new DataTraversalContext.MapKeyStackItem(key);
        DatumPruningResult itemBasedResult = checkRequiredData(data, "key", keyItem);
        if (itemBasedResult != Keep.INSTANCE)
          return itemBasedResult;
      }
    }

    if (replacements.isEmpty())
      return Keep.INSTANCE;
    else {
      final MapDatum.Builder builder = datum.type().createBuilder();
      for (final Map.Entry<Datum.Imm, ? extends Data> entry : datum._raw().elements().entrySet()) {
        final Datum.Imm key = entry.getKey();
        @Nullable Data data = replacements.containsKey(key) ? replacements.get(key) : entry.getValue();
        if (data != null)
          builder._raw().elements().put(key, data);
      }
      return new ReplaceDatum(builder);
    }

  }

  private @NotNull DatumPruningResult pruneListDatum(
      @NotNull ListDatum datum,
      @NotNull ReqListModelProjection projection,
      int pathSteps) {

    if (pathSteps > 1)
      throw new IllegalArgumentException("Lists can't be in the path");

    final ReqProjection<?, ?> itemsProjection = projection.itemsProjection();
    final Map<Integer, Data> replacements = new HashMap<>();

    int index = 0;

    for (Data data : datum._raw().elements()) {

      final Data data0 = data;
      final DataPruningResult prunedData =
          context.withStackItem(
              new DataTraversalContext.ListIndexStackItem(index),
              () -> pruneData(data0, itemsProjection, 0)
          );

      if (prunedData instanceof RemoveData) {
        replacements.put(index, null);
      } else if (prunedData instanceof ReplaceData) {
        ReplaceData replaceData = (ReplaceData) prunedData;
        replacements.put(index, replaceData.newData);
      } else if (prunedData instanceof Fail)
        return (Fail) prunedData;
      // else keep

      index++;
    }

    if (replacements.isEmpty())
      return Keep.INSTANCE;
    else {
      final ListDatum.Builder builder = datum.type().createBuilder();

      index = 0;
      for (@Nullable Data data : datum._raw().elements()) {
        if (replacements.containsKey(index))
          data = replacements.get(index);

        if (data != null)
          builder._raw().elements().add(data);

        index++;
      }

      return new ReplaceDatum(builder);
    }

  }

  private @NotNull DatumPruningResult checkRequiredData(@Nullable Data data, @NotNull String name, @NotNull Object id) {
    if (data == null) {
      return new Fail(operationError(String.format("Required %s %s is missing", name, id)));
    } else if (data.type().kind() != TypeKind.ENTITY) {
      final Val val = data._raw().tagValues().get(DatumType.MONO_TAG_NAME);

      if (val == null) {
        return new Fail(operationError(String.format("Required %s %s is missing", name, id)));
      } else {
        final ErrorValue error = val.getError();
        if (error == null) {
          if (val.getDatum() == null) {
            final Reason reason = error(String.format("Required %s %s is null", name, id));
            return new UseError(
                reason,
                new ErrorValue(HttpStatusCode.PRECONDITION_FAILED, reason.toString())
            );
          }
        } else {
          Reason reason = error(String.format("Required %s %s is an error: '%s'", name, id, error.message()));
          return new UseError(reason, new ErrorValue(error.statusCode(), reason.toString()));
        }
      }
    }

    return Keep.INSTANCE;
  }

  private @NotNull Reason operationError(String message) { return new Reason(true, message, location()); }

  private @NotNull Reason error(String message) { return new Reason(false, message, location()); }

  private @NotNull ArrayList<DataTraversalContext.StackItem> location() {
    final ArrayList<DataTraversalContext.StackItem> items = new ArrayList<>(context.stack());
    Collections.reverse(items);
    return items;
  }

  public interface DataPruningResult {}

  public static class ReplaceData implements DataPruningResult {
    public final @NotNull Data newData;

    ReplaceData(final @NotNull Data data) {newData = data;}
  }

  public static class RemoveData implements DataPruningResult { // remove field or map entry
    public final @NotNull Reason reason;

    RemoveData(final @NotNull Reason reason) {this.reason = reason;}

    @Override
    public String toString() { return String.format("RemoveData{reason=%s}", reason); }
  }

  public interface DatumPruningResult {}

  public static class Keep implements DatumPruningResult, DataPruningResult {
    public static final Keep INSTANCE = new Keep();
  }

  public static class ReplaceDatum implements DatumPruningResult {
    final @NotNull Datum newDatum;

    ReplaceDatum(final @NotNull Datum data) {newDatum = data;}
  }

  public static class UseError implements DatumPruningResult {
    final @NotNull Reason reason;
    final @NotNull ErrorValue error;

    UseError(@NotNull Reason reason, @NotNull ErrorValue error) {
      this.reason = reason;
      this.error = error;
    }

    @Override
    public String toString() { return String.format("UseError{reason=%s | error=%s}", reason, error); }
  }

  public static class Fail implements DatumPruningResult, DataPruningResult {
    public final @NotNull Reason reason;

    Fail(final @NotNull Reason reason) {this.reason = reason;}

    @Override
    public String toString() { return String.format("Fail{reason=%s}", reason); }
  }

  public static class Reason {
    public final boolean isOperationError;
    public final @NotNull String message;
    public final @NotNull List<DataTraversalContext.StackItem> location;

    Reason(
        boolean isOperationError,
        @NotNull String message,
        @NotNull List<DataTraversalContext.StackItem> location) {
      this.isOperationError = isOperationError;
      this.message = message;
      this.location = location;
    }

    @Override
    public @NotNull String toString() {
      String location =
          this.location.stream().map(DataTraversalContext.StackItem::toString).collect(Collectors.joining());

      return location.trim().isEmpty() ?
             message :
             location + " : " + message;
    }
  }
}


text:
module Gisele
  class VM
    class Kernel < Component
      include Robustness

      def self.bytecode
        @kernelbc ||= Bytecode.parse(Path.dir/'kernel/macros.gvm')
      end

      def_delegators :vm, :pick,
                          :fetch,
                          :save,
                          :event

      def start(at, input)
        at    = valid_label!(at)
        input = valid_input!(input)

        runner(nil) do |k|
          stack = k.run(:start, [ input, at ])
          stack.first
        end
      end

      def resume(puid, input)
        prog  = Prog===puid ? puid : fetch(puid)
        prog  = valid_prog!(puid, :world)
        input = valid_input!(input)

        runner(prog) do |k|
          k.run(:resume, [ input ])
        end
      end

      def progress(puid)
        prog = valid_prog!(puid, :enacter)

        runner(prog) do |k|
          k.run(:progress, [ ])
        end
      end

    private

      def runner(prog = nil)
        if block_given?
          yield Runner.new(vm, prog)
        else
          Runner.new(vm, prog)
        end
      end

    end # class Kernel
  end # class VM
end # module Gisele
require_relative 'kernel/opcodes'
require_relative 'kernel/runner'

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.sql.tree;

import com.google.common.collect.ImmutableList;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.google.common.base.MoreObjects.toStringHelper;

public class Table
        extends QueryBody
{
    private final QualifiedName name;

    public Table(QualifiedName name)
    {
        this(Optional.empty(), name);
    }

    public Table(NodeLocation location, QualifiedName name)
    {
        this(Optional.of(location), name);
    }

    private Table(Optional<NodeLocation> location, QualifiedName name)
    {
        super(location);
        this.name = name;
    }

    public QualifiedName getName()
    {
        return name;
    }

    @Override
    public <R, C> R accept(AstVisitor<R, C> visitor, C context)
    {
        return visitor.visitTable(this, context);
    }

    @Override
    public List<Node> getChildren()
    {
        return ImmutableList.of();
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .addValue(name)
                .toString();
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Table table = (Table) o;
        return Objects.equals(name, table.name);
    }

    @Override
    public int hashCode()
    {
        return name.hashCode();
    }

    @Override
    public boolean shallowEquals(Node other)
    {
        if (!sameClass(this, other)) {
            return false;
        }

        Table otherTable = (Table) other;
        return name.equals(otherTable.name);
    }
}


text:
namespace Yu_Gi_Oh.Save_File
{
    public enum BattlePackType
    {
        Drafted_BattlePackEpicDawn = 0,
        Sealed_BattlePackEpicDawn = 1,
        Drafted_BattlePack2WaroftheGiants = 2,
        Sealed_BattlePack2WaroftheGiants = 3,
        Drafted_BattlePack2WaroftheGiantsRound2 = 4
    }
}


text:
using content::WebContents;

const char FullscreenControllerTest::kFullscreenMouseLockHTML[] =
    "/fullscreen_mouselock/fullscreen_mouselock.html";

void FullscreenControllerTest::RequestToLockMouse(
    bool user_gesture,
    bool last_unlocked_by_target) {
  WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
  MouseLockController* mouse_lock_controller =
      GetExclusiveAccessManager()->mouse_lock_controller();
  mouse_lock_controller->set_fake_mouse_lock_for_test(true);
  browser()->RequestToLockMouse(tab, user_gesture,
      last_unlocked_by_target);
  mouse_lock_controller->set_fake_mouse_lock_for_test(false);
}

FullscreenController* FullscreenControllerTest::GetFullscreenController() {
  return GetExclusiveAccessManager()->fullscreen_controller();
}

ExclusiveAccessManager* FullscreenControllerTest::GetExclusiveAccessManager() {
  return browser()->exclusive_access_manager();
}

void FullscreenControllerTest::LostMouseLock() {
  browser()->LostMouseLock();
}

bool FullscreenControllerTest::SendEscapeToFullscreenController() {
  content::NativeWebKeyboardEvent event;
  event.windowsKeyCode = ui::VKEY_ESCAPE;
  return GetExclusiveAccessManager()->HandleUserKeyPress(event);
}

bool FullscreenControllerTest::IsFullscreenForBrowser() {
  return GetFullscreenController()->IsFullscreenForBrowser();
}

bool FullscreenControllerTest::IsWindowFullscreenForTabOrPending() {
  return GetFullscreenController()->IsWindowFullscreenForTabOrPending();
}

ExclusiveAccessBubbleType
FullscreenControllerTest::GetExclusiveAccessBubbleType() {
  return GetExclusiveAccessManager()->GetExclusiveAccessExitBubbleType();
}

bool FullscreenControllerTest::IsFullscreenBubbleDisplayed() {
  return GetExclusiveAccessBubbleType() != EXCLUSIVE_ACCESS_BUBBLE_TYPE_NONE;
}

void FullscreenControllerTest::GoBack() {
  content::TestNavigationObserver observer(
      browser()->tab_strip_model()->GetActiveWebContents(), 1);
  chrome::GoBack(browser(), CURRENT_TAB);
  observer.Wait();
}

void FullscreenControllerTest::Reload() {
  content::TestNavigationObserver observer(
      browser()->tab_strip_model()->GetActiveWebContents(), 1);
  chrome::Reload(browser(), CURRENT_TAB);
  observer.Wait();
}

void FullscreenControllerTest::SetPrivilegedFullscreen(bool is_privileged) {
  GetFullscreenController()->SetPrivilegedFullscreenForTesting(is_privileged);
}


text:
Solid::Solid(){
  direction = Off;
}

void Solid::run(Sign &sign, EffectData &data){

  for(uint8_t i=0; i<LED_COUNT; i++){
    sign.pixel(i) -> direction[0] = direction;
  }

}

void Solid::push(IrInput input){
  Effect::push(input);
  switch(input){
    case UP:   direction = Up; break;
    case RIGHT: direction = Off; break;
    case DOWN: direction = Down; break;
  }
}

void Solid::setConfig(uint8_t kConfig){
  switch(kConfig){
    case SOLID_FADE_CONFIG: direction = Off; break;
  }
}


text:
// T3000View.h : interface of the CT3000View class
//

#pragma once

#include "MainFrm.h"
#include "afxwin.h"
#include "afxcmn.h"

#include "msflexgrid1.h"

#include "SetPtDayDlg.h"
#include "OfficeStPtDlg.h"

#include "singleslider/MacSliderCtrl.h"
#include "AutoRichEditCtrl.h"
#include "CM5/CStatic/staticex.h"
#include "cslidercontrol0.h"
//#include "TemcoDataGrid.h"
#define WM_FRESHVIEW WM_USER + 1100

//#define  DaySP		0  //address 345
//#define  DcoolDB	1  //address 346
//#define  DheatDB	2  //address 347
//#define  DcoolSP	3  //address 348
//#define  DheatSP	4  //address 349
//#define  NightSP	5  //address 350
//#define  NheatDB	6  //address 352
//#define  NcoolDB	7  //address 353
//#define  NheatSP	8  //address 354
//#define  NcoolSP	9  //address 355
//#define  Max		10  //address 365
//#define  Min		11  //address 366

class CT3000View : public CFormView
{
public: // create from serialization only
	CT3000View();
	DECLARE_DYNCREATE(CT3000View)

public:
	enum{ IDD = IDD_T3000_FORM };

// Attributes
public:
	CT3000Doc* GetDocument() const;

// Operations
public:

	CString	g_strIpAdress;
	CMFCTabCtrl	m_wndTab;
	CSetPtDayDlg* m_pSetPtDayDlg;
	CRect m_rcTabCtrl;
	COfficeStPtDlg* m_pSetPtOffceDlg;
	CWinThread* m_pFreshBackground;
	//CEdit		m_wnd1;
	//CEdit		m_wnd2;

public:

void Read_SliderData();

public:

// Overrides
public:
	virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	virtual void OnInitialUpdate(); // called first time after construct

	void UpdateDayControls();
	void UpdateNightControls();

	void CreateFlexSilde();
// Implementation
public:
	virtual ~CT3000View();
#ifdef _DEBUG
	virtual void AssertValid() const;
	virtual void Dump(CDumpContext& dc) const;
#endif

//protected:
////	CMFCStatusBar& GetStatusBar () const
//	{
//		return ((CMainFrame*) AfxGetMainWnd ())->GetStatusBar ();
//	}
// Generated message map functions
protected:
	afx_msg void OnFilePrintPreview();
	afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
	afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
	DECLARE_MESSAGE_MAP()
public:
	void OnFileOpen();

	void OnConnect();
	void OnDisconnect();
	void OnAddBuildingConfig();

	void Fresh();
	void Fresh_T3000View();
	void FreshCtrl();

     int get_real_fan_select();
	 int set_real_fan_select();
	// Õâ¸öº¯ÊýÊÇΪÁËÓë֮ǰµÄ°æ±¾¼æÈÝ
	// ʹÓÃеÄSlider£¬µ«ÊǼĴæÆ÷Âß¼Ê¹ÓÃÔÀ´µÄ
	void InitSliderBars2();

	void InitFlexSliderBars();
	void Fresh_In();
	void Fresh_Out();
	void Initial_Max_Min();
	void FreshIOGridTable();
    void FreshIOGridTable_Tstat6();
    int GetRoundMM(BOOL is_max,int num1,int num2,float rate);
	int GetRoundNumber(int number);

	void DayFeedBackNewSliderFor5ABCD();
	void NightFeedBackNewSliderFor5ABCD();
	void InitFanSpeed();
	int m_InRanges[10];
	int m_OutRanges[10];
public:
	// scan Tstats in database
	void ScanTstatInDB(void);
	afx_msg void OnNMCustomdrawSlider1(NMHDR *pNMHDR, LRESULT *pResult);
	afx_msg void OnBnClickedCoolRadio();
	afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
	afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
	BOOL OnToolTipNotify(UINT id, NMHDR * pNMHDR, LRESULT * pResult);

	HANDLE m_hSerial;//´®¿Ú¾ä±ú
	SOCKET m_hSocket;

	int m_nID;
	float m_fFirmwareVersion;
	UINT m_nSerialNumber;
	int m_nHardwareVersion;
	CString m_strModelName;
	float m_fTemperature;
	CComboBox m_FanComBox;
	int m_iCurFanSpeed;
	int m_nOverrideTime;
	int m_nTimeLeft;
	CString m_nstrPID1;
	CString m_nstrPID2;

	CButton m_CoolCtrl;
	CButton m_HeatCtrl;
	CButton m_OcupaCtrl;
	CButton	m_UnOcupaCtrl;
	BOOL m_bOccupied;
	CButton m_OcupiedBtn;
	CString m_strFreeCool;
	CString m_strFreeCoolFN;

// 	CMacSliderCtrl m_TemperaureSlider;
// 	CMacSliderCtrl m_daySlider;
// 	CMacSliderCtrl m_nightSlider;
// 	CMacSliderCtrl m_nightHeatSlider;

	int m_outRows;
	int m_inRows;
	CWinThread* pMainUIBackFreshThread;

	CMsflexgrid m_Output_Grid;
	CMsflexgrid m_Input_Grid;

	CTabCtrl m_SetPtTabCtrl;

	/*
	 *  something about slider
	 *  1.if you want to use the slider

	*/
	CSliderControl0  m_nightSlider;
	CSliderControl0  m_daySlider;

	CStatic m_SetptStatic;

	CEdit m_inNameEdt;
	CEdit m_outNameEdt;

    int m_new_deadband;
    int m_old_deadband;
    int m_slider_Type;
	afx_msg void OnBnClickedGrapgicbutton();
	afx_msg void OnBnClickedParameterbtn();
	//	afx_msg void OnBnClickedOutputbtn();

	DECLARE_EVENTSINK_MAP()
	afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
	void ClickInputMsflexgrid();
	void ClickOutputMsflexgrid();
	afx_msg void OnEnKillfocusInputnameedit();
	afx_msg void OnEnKillfocusOutputnameedit();
	virtual BOOL PreTranslateMessage(MSG* pMsg);
	afx_msg void OnTimer(UINT_PTR nIDEvent);
	afx_msg void OnDestroy();
	afx_msg void OnBnClickedTrendlogview();

	afx_msg void OnBnClickedOccupacheck();
	afx_msg void OnCbnSelchangeFanspeedcombo();
	LRESULT OnFreshView(WPARAM wParam, LPARAM lParam);
//	static void EnableToolTips(BOOL bEnable);
protected:
	virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);

public:
	afx_msg void OnSize(UINT nType, int cx, int cy);
	afx_msg void OnMove(int x, int y);
	afx_msg void OnWindowPosChanging(WINDOWPOS* lpwndpos);
	afx_msg void OnMoving(UINT fwSide, LPRECT pRect);
	afx_msg void OnBnClickedBtnSynctime();
	afx_msg void OnBnClickedButtonSchedule();

	afx_msg void OnBnClickedUnoccupiedMark();

//tstat6
	unsigned short tempchange[512];//for tstat6
	unsigned short temptstat6[512];
//tstat6

	void HandleSliderSetPos(BOOL bRight);
	BOOL				m_bSliderSetPosWarning;
	void InitFlexSliderBars_tstat6();//tsat6
    void SetFlexSliderBars_tstat6();

	void TemperatureSlider();

    int Round_SetPoint_Max(int spvalue);
	int Round_SetPoint_Min(int spvalue);
	int m_daysetpoint;//0907
	afx_msg void OnEnKillfocusEditCurSp();
	int m_nightpot;//0907

	afx_msg void OnCbnSelchangeStaticunint();
	CComboBox m_gUnit;
	CMacSliderCtrl m_currentTemp;

   afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
    afx_msg void OnBnClickedHelp();
//	afx_msg void OnBnClickedBtnTopological();

	 afx_msg void OnBnClickedHelpHelp();

	 afx_msg LRESULT  ResumeMessageCallBackForT3000View(WPARAM wParam, LPARAM lParam);
	 afx_msg LRESULT  ReadDataCallBack(WPARAM wParam, LPARAM lParam);
    // BOOL OnToolTipNotify(UINT id, NMHDR * pNMHDR, LRESULT * pResult);
	 int DayMax;
	 int DayMin;
    // CStaticEx m_isp;
     CToolTipCtrl m_tooltips;
     afx_msg void OnEnKillfocusDayEdit();

	 BOOL m_offline;
	 BOOL m_StartFirst;
     //afx_msg void OnBnClickedTestSlider();
//	 void ValuesChangedDaySlider(const VARIANT& sender, float newValue);
//	 void ValuesChangedNightSlider(const VARIANT& sender, float newValue);

	 void DayHandleMovedSlidercontrol1(const VARIANT& sender, float newValue);
	 void NightHandleMovedSlidercontrol1(const VARIANT& sender, float newValue);
	 /*void ClickSlidercontrol1(const VARIANT& sender, LPDISPATCH e);*/
     afx_msg void OnCbnSelchangeComboSysMode();
     afx_msg void OnBnClickedButtonSetpointDetail();
};

#ifndef _DEBUG  // debug version in T3000View.cpp
inline CT3000Doc* CT3000View::GetDocument() const
   { return reinterpret_cast<CT3000Doc*>(m_pDocument); }
#endif


text:
//
//  HUIPatternLockView.m
//  HUIPatternLockView
//
//  Created by ZhangTinghui on 13-7-17.
//  Copyright (c) 2013年 ZhangTinghui. All rights reserved.
//

#if !__has_feature(objc_arc)
#error This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
#endif

#import "HUIPatternLockView.h"

#pragma mark - @class HUIPatternLockViewDot
@interface HUIPatternLockViewDot : NSObject
@property (nonatomic, assign) NSUInteger    number;
@property (nonatomic, assign) CGRect        frame;
@property (nonatomic, assign) CGPoint       center;

+ (instancetype)dotWithNumber:(NSUInteger)number frame:(CGRect)frame;
@end

@implementation HUIPatternLockViewDot

+ (instancetype)dotWithNumber:(NSUInteger)number frame:(CGRect)frame {
    HUIPatternLockViewDot *dot = [[self alloc] init];
    dot.number  = number;
    dot.frame   = frame;
    dot.center  = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame));
    return dot;
}

@end

#pragma mark - @class HUIPatternLockView
static const NSInteger  kDefaultNumberOfRowsOrColumns   = 3;
static const CGFloat    kDefaultDotWidth                = 60.00f;
static const CGFloat    kDefaultLineWidth               = 8.0f;
#define kDefaultLineColor   [UIColor colorWithRed:248.00/255.00 green:200.0/255.00 blue:79.0/255.00 alpha:1.0]

@interface HUIPatternLockView ()
@property (nonatomic, strong) NSMutableArray *normalDots;
@property (nonatomic, strong) NSMutableArray *highlightedDots;
@property (nonatomic, strong) NSMutableArray *linePath;

@property (nonatomic, assign) BOOL needRecalculateDotsFrame;
@end

@implementation HUIPatternLockView

- (void)dealloc {
    [self _removeKVOObserverOnSelfPropertiesWhichEffectsDotsFrames];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self != nil) {
        [self _loadDefaultConfiguration];
        [self _addKVOObserverOnSelfPropertiesWhichEffectsDotsFrames];
        [self setNeedsDisplay];
    }

    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self != nil) {
        [self _loadDefaultConfiguration];
        [self _addKVOObserverOnSelfPropertiesWhichEffectsDotsFrames];
        [self setNeedsDisplay];
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [super encodeWithCoder:aCoder];
}

#pragma mark - Draw Rect
- (void)_loadDefaultConfiguration {
    self.numberOfRows               = kDefaultNumberOfRowsOrColumns;
    self.numberOfColumns            = kDefaultNumberOfRowsOrColumns;
    self.lineColor                  = kDefaultLineColor;
    self.lineWidth                  = kDefaultLineWidth;
    self.dotWidth                   = kDefaultDotWidth;
    self.contentInset               = UIEdgeInsetsZero;
    self.needRecalculateDotsFrame   = YES;
}

- (void)resetDotsState {
    self.normalDots = [NSMutableArray array];
    self.highlightedDots = [NSMutableArray array];
    self.linePath   = [NSMutableArray array];

    //calculate dot width with bounds
    CGFloat dotsAreaWidth = CGRectGetWidth(self.bounds) - self.contentInset.left - self.contentInset.right;
    CGFloat dotsAreaHeight = CGRectGetHeight(self.bounds) - self.contentInset.top - self.contentInset.bottom;
    //throw exception if dots is too big
    if (self.dotWidth * self.numberOfColumns > dotsAreaWidth
        || self.dotWidth * self.numberOfRows > dotsAreaHeight) {
        @throw [NSException exceptionWithName:NSInvalidArgumentException
                                       reason:@"The dot is too big to be layout in content area"
                                     userInfo:nil];
        return;
    }

    CGFloat widthPerDots = dotsAreaWidth / self.numberOfColumns;
    CGFloat heightPerDots = dotsAreaHeight / self.numberOfRows;

    NSInteger number = 0;
    for (NSInteger i = 0; i < self.numberOfRows; i++) {
        for (NSInteger j = 0; j < self.numberOfColumns; j++) {

            CGPoint dotCenter = CGPointMake(self.contentInset.left + (j + 0.5) * widthPerDots,
                                          self.contentInset.top + (i + 0.5) * heightPerDots);

            CGRect dotFrame = CGRectMake(dotCenter.x - self.dotWidth * 0.5,
                                         dotCenter.y - self.dotWidth * 0.5,
                                         self.dotWidth,
                                         self.dotWidth);
            [self.normalDots addObject:[HUIPatternLockViewDot dotWithNumber:(number++) frame:dotFrame]];
        }
    }
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();

    //recalculate dots' frame if needed
    if (self.needRecalculateDotsFrame) {
        [self resetDotsState];
        self.needRecalculateDotsFrame = NO;
    }

    //draw line
    CGContextSetStrokeColorWithColor(context, [self.lineColor CGColor]);
    CGContextSetLineWidth(context, self.lineWidth);
    CGContextSetLineJoin(context, kCGLineJoinRound);
    if ([self.linePath count] > 0) {
        NSValue *firstValue = self.linePath[0];
        for (NSValue *pointValue in self.linePath) {
            CGPoint point = [pointValue CGPointValue];
            if (pointValue == firstValue) {
                CGContextMoveToPoint(context, point.x, point.y);
            }
            else {
                CGContextAddLineToPoint(context, point.x, point.y);
            }
        }
    }
    CGContextDrawPath(context, kCGPathStroke);

    //draw dot images
    if (self.normalDotImage != nil) {
        for (HUIPatternLockViewDot *dot in self.normalDots) {
            [self.normalDotImage drawInRect:dot.frame];
        }
    }

    if (self.highlightedDotImage != nil) {
        for (HUIPatternLockViewDot *dot in self.highlightedDots) {
            [self.highlightedDotImage drawInRect:dot.frame];
        }
    }
}

#pragma mark - Properties
- (void)setNumberOfRows:(NSInteger)numberOfRows {
    if (numberOfRows <= 0) {
        @throw [NSException exceptionWithName:NSInvalidArgumentException
                                       reason:@"numberOfRows should not less or equal to Zero"
                                     userInfo:nil];
        return;
    }

    _numberOfRows = numberOfRows;
}

- (void)setNumberOfColumns:(NSInteger)numberOfColumns {
    if (numberOfColumns <= 0) {
        @throw [NSException exceptionWithName:NSInvalidArgumentException
                                       reason:@"numberOfColumns should not less or equal to Zero"
                                     userInfo:nil];
        return;
    }

    _numberOfColumns = numberOfColumns;
}

- (void)setDotWidth:(CGFloat)dotWidth {
    if (dotWidth <= 10.00) {
        @throw [NSException exceptionWithName:NSInvalidArgumentException
                                       reason:@"dotWidth should not less or equal to 10pt, too small make\
                it hard to been touch"
                                     userInfo:nil];
        return;
    }

    _dotWidth = dotWidth;
}

- (void)setLineColor:(UIColor *)lineColor {
    if (_lineColor == lineColor) {
        return;
    }

    _lineColor = lineColor;
    [self setNeedsDisplay];
}

- (void)setLineWidth:(CGFloat)lineWidth {
    _lineWidth = lineWidth;
    [self setNeedsDisplay];
}

#pragma mark - KVO
- (NSArray *)_propertyKeyPathesWhichEffectsDotsFrames {
    return @[NSStringFromSelector(@selector(frame)),
             NSStringFromSelector(@selector(numberOfRows)),
             NSStringFromSelector(@selector(numberOfColumns)),
             NSStringFromSelector(@selector(dotWidth)),
             NSStringFromSelector(@selector(contentInset))];
}

- (BOOL)_isKVOKeyPathIsThePropertyWhichEffectsDotsFrames:(NSString *)KVOKeyPath {
    return [[self _propertyKeyPathesWhichEffectsDotsFrames] containsObject:KVOKeyPath];
}

- (void)_removeKVOObserverOnSelfPropertiesWhichEffectsDotsFrames {
    NSArray *keyPathes = [self _propertyKeyPathesWhichEffectsDotsFrames];
    for (NSString *keyPath in keyPathes) {
        [self removeObserver:self forKeyPath:keyPath];
    }
}

- (void)_addKVOObserverOnSelfPropertiesWhichEffectsDotsFrames {
    NSArray *keyPathes = [self _propertyKeyPathesWhichEffectsDotsFrames];
    for (NSString *keyPath in keyPathes) {
        [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:nil];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    if (object != self || ![self _isKVOKeyPathIsThePropertyWhichEffectsDotsFrames:keyPath]) {
        return;
    }

    self.needRecalculateDotsFrame = YES;
    [self setNeedsDisplay];
}

#pragma mark - Record Line Path
- (HUIPatternLockViewDot *)_normalDotContainsPoint:(CGPoint)point {
    for (HUIPatternLockViewDot * dot in self.normalDots){
        if (CGRectContainsPoint(dot.frame, point)) {
            return dot;
        }
    }
    return nil;
}

- (void)_updateLinePathWithPoint:(CGPoint)point {
    HUIPatternLockViewDot *dot = [self _normalDotContainsPoint:point];
    NSInteger linePathPointsCount = [self.linePath count];

    if (dot != nil) {
        NSValue *pointValue = [NSValue valueWithCGPoint:dot.center];
        if (linePathPointsCount <= 0) {
            //if no any points in linePath. use this dot's center to be the linePath start and end point
            [self.linePath addObject:pointValue];
            [self.linePath addObject:pointValue];
        }
        else {
            //else insert a new point into the path
            [self.linePath insertObject:pointValue atIndex:linePathPointsCount-1];
        }

        //mark this dot as highlighted
        [self.normalDots removeObject:dot];
        [self.highlightedDots addObject:dot];
    }
    else {

        NSValue *pointValue = [NSValue valueWithCGPoint:point];
        if (linePathPointsCount == 0) {
            //linePath must start with a dot's center
            return;
        }
        else if (linePathPointsCount == 1) {
            //if linePath has a start point, this point is treat as end point
            [self.linePath addObject:pointValue];
        }
        else {
            //else if line path has at least two points. always use this point to update the end point
            self.linePath[linePathPointsCount-1] = pointValue;
        }
    }
}

- (void)_endLinePathWithPoint:(CGPoint)point {
    HUIPatternLockViewDot *dot = [self _normalDotContainsPoint:point];
    if (dot != nil) {
        [self.normalDots removeObject:dot];
        [self.highlightedDots addObject:dot];
    }

    //finally linePath is the center of all highlighted dots.
    NSMutableArray *array = [NSMutableArray array];
    for (HUIPatternLockViewDot *dot in self.highlightedDots) {
        [array addObject:[NSValue valueWithCGPoint:dot.center]];
    }
    self.linePath = array;
}

#pragma mark Touches
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self resetDotsState];
    [self _updateLinePathWithPoint:[[touches anyObject] locationInView:self]];
    [self setNeedsDisplay];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [self _updateLinePathWithPoint:[[touches anyObject] locationInView:self]];
    [self setNeedsDisplay];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    /*  end the line path and get the password
     */
    [self _endLinePathWithPoint:[[touches anyObject] locationInView:self]];
    [self setNeedsDisplay];

    /*  get the pattern info
     */
    NSUInteger dotCounts = [self.highlightedDots count];
    NSMutableString *password = [NSMutableString string];
    for (HUIPatternLockViewDot *dot in self.highlightedDots) {
        [password appendFormat:@"[%lu]", (unsigned long)dot.number];
    }

    /*  Notify the delegate
     */
    if (dotCounts <= 0) {
        return;
    }

    if (self.didDrawPatternWithPassword) {
        self.didDrawPatternWithPassword(self, dotCounts, password);
    }

    if ([self.delegate respondsToSelector:@selector(patternLockView:didDrawPatternWithDotCounts:password:)]) {
        [self.delegate patternLockView:self didDrawPatternWithDotCounts:dotCounts password:password];
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self resetDotsState];
    [self setNeedsDisplay];
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Authors:
* Envlh
* Pupsik-ipa
* Андрей
-->
<resources>
  <string name="menu_settings">Архиарақәа</string>
  <string name="username">Ахархәаҩ ихьӡ</string>
  <string name="password">Ажәамаӡа</string>
  <string name="login">Аҭаларҭа</string>
  <string name="signup">Иҟаҵатәуп арегистрациа</string>
  <string name="logging_in_title">Асистемахь аҭаларҭа</string>
  <string name="logging_in_message">Шәааԥшы ԥыҭрак...</string>
  <string name="login_success">Аҭалара қәҿиарала имҩаԥысит!</string>
  <string name="login_failed">Асистемахь аҭалараан агха!</string>
  <string name="upload_failed">Афаил ԥшаам. Даҽа фаилк шәахәаԥш.</string>
  <string name="authentication_failed" fuzzy="true">Аутентификациа агха!</string>
  <string name="uploading_started">Аҭагалара иалагоуп!</string>
  <string name="upload_completed_notification_title">%1$s иҭагалоуп!</string>
  <string name="upload_completed_notification_text">Шәақәыӷәӷәа иҭагалоу афаил ахәаԥшраз</string>
  <string name="upload_progress_notification_title_start" fuzzy="true">Аҭагалара %1$s иалагоуп</string>
  <string name="upload_progress_notification_title_in_progress">%1$s иаҿуп аҭагалара</string>
  <string name="upload_progress_notification_title_finishing">Аҭагалара ахыркәшамҭа %1$s</string>
  <string name="upload_failed_notification_title">Аҭагалара %1$s амуӡеит</string>
  <string name="upload_failed_notification_subtitle">Шәақәыӷәӷәа ахәаԥшразы</string>
  <string name="contribution_state_failed">Аҭагалара агха.</string>
  <string name="contribution_state_in_progress">Инагӡоуп %1$d%%</string>
  <string name="contribution_state_starting">Аҭагалара</string>
  <string name="menu_from_gallery">Агалереиа аҟынтәи</string>
  <string name="menu_from_camera">Афото ҭыхтәуп</string>
  <string name="provider_contributions">Сара сҭагаламҭақәа</string>
  <string name="share_title_hint" fuzzy="true">Ахьӡ</string>
  <string name="share_description_hint">Ахҳәаа</string>
  <string name="login_failed_generic">Асистемахь аҭалара агха!</string>
  <string name="share_upload_button">Аҭагалара</string>
  <string name="provider_modifications">Аԥсахрақәа</string>
  <string name="menu_upload_single">Аҭагалара</string>
  <string name="categories_search_text_hint">Актегориа алхра</string>
  <string name="menu_save_categories">Еиқәырхатәуп</string>
  <string name="refresh_button">Ирҿыцтәуп</string>
  <string name="contributions_subtitle_zero" fuzzy="true">Аҭагаламҭақәа макьана иҟам</string>
  <string name="categories_activity_title">Акатегориақәа</string>
  <string name="title_activity_settings">Архиарақәа</string>
  <string name="title_activity_signup">Арегистрациа ҟаҵатәуп</string>
  <string name="menu_retry_upload">Еиҭаҟаҵатәуп</string>
  <string name="menu_cancel_upload">Аҟәыхра</string>
  <string name="menu_download">Иҭыгатәуп</string>
  <string name="preference_license" fuzzy="true">Алицензиа</string>
  <string name="preference_theme" fuzzy="true">Уахынлатәи арежим</string>
  <string name="license_name_cc_by_sa_four"> Attribution-ShareAlike 4.0</string>
  <string name="license_name_cc_by_four">Attribution 4.0</string>
  <string name="license_name_cc_by_sa">Attribution-ShareAlike 3.0</string>
  <string name="license_name_cc_by">Attribution 3.0</string>
  <string name="license_name_cc0">CC0</string>
  <string name="license_name_cc_by_sa_3_0">CC BY-SA 3.0</string>
  <string name="license_name_cc_by_3_0">CC BY 3.0</string>
  <string name="license_name_cc_by_sa_4_0">CC BY-SA 4.0</string>
  <string name="license_name_cc_by_4_0">CC BY 4.0</string>
  <string name="tutorial_4_text">Аҭагалара аҿырԥштәы:</string>
  <string name="welcome_final_text">Ари шәара еилышәкаама?</string>
  <string name="welcome_final_button_text">Ааи!</string>
  <string name="detail_panel_cats_label">Акатегориақәа</string>
  <string name="detail_panel_cats_loading">Аҭагалара...</string>
  <string name="detail_panel_cats_none">Акагь алхӡам</string>
  <string name="detail_description_empty">Иҟам ахҳәаа</string>
  <string name="detail_license_empty">Идырым алицензиа</string>
  <string name="menu_refresh">Ирҿыцтәуп</string>
  <string name="ok">OK</string>
  <string name="warning">Агәаҽанҵара</string>
  <string name="yes">Ааи</string>
  <string name="no">Мап</string>
  <string name="media_detail_title">Ахьӡ</string>
  <string name="media_detail_description">Ахҳәаа</string>
  <string name="media_detail_license">Алицензиа</string>
  <string name="media_detail_coordinates">Акоординатқәа</string>
  <string name="_2fa_code">2ФА Акод</string>
  <string name="welcome_image_mount_zao">Ашьха Зао</string>
  <string name="welcome_image_tulip">Атиульпан</string>
  <string name="welcome_image_welcome_wikipedia">Бзиала шәаабеит Википедиа ахь</string>
  <string name="welcome_image_sydney_opera_house">Сиднеи аопера атеатр</string>
  <string name="cancel">Аҟәыхра</string>
  <string name="navigation_drawer_open">Иаарттәуп</string>
  <string name="navigation_drawer_close">Иарктәуп</string>
  <string name="navigation_item_upload">Иҭагалатәуп</string>
  <string name="navigation_item_settings">Архиарақәа</string>
  <string name="navigation_item_logout">Иҭыҵтәуп</string>
  <string name="no_description_found">ахҳаа ԥшаам</string>
</resources>


text:
public class NoBooleanCastsFrom {

  public static void main(String[] args) {

    int a = (int) true;

  }

}


text:
package org.eclipse.ceylon.compiler.java.test.interop.access;

public class JavaSealed<T> {

    JavaSealed() {}
    private JavaSealed(int i) {}

}


text:
'use strict';

var tap = require('tap');
var test = tap.test;

var cls = require('../context.js');

test("nested contexts on a single namespace", function (t) {
  t.plan(7);

  var namespace = cls.createNamespace("namespace");
  namespace.run(function () {
    namespace.set("value", 1);

    t.equal(namespace.get("value"), 1,
            "namespaces have associated data even without contexts.");

    namespace.run(function () {
      t.equal(namespace.get("value"), 1, "lookup will check enclosing context");
      namespace.set("value", 2);
      t.equal(namespace.get("value"), 2, "setting works on top-level context");

      namespace.run(function () {
        t.equal(namespace.get("value"), 2, "lookup will check enclosing context");
        namespace.set("value", 3);
        t.equal(namespace.get("value"), 3, "setting works on nested context");
      });

      t.equal(namespace.get("value"), 2,
              "should revert to value set in top-level context");
    });

    t.equal(namespace.get("value"), 1, "namespace retains its outermost value.");
  });
});

test("the example from the docs", function (t) {
  var writer = cls.createNamespace('writer');
  writer.set('value', 0);

  t.equal(writer.get('value'), 0, "outer hasn't been entered yet");
  function requestHandler() {
    writer.run(function (outer) {
      t.equal(writer.active, outer, "writer.active == outer");

      writer.set('value', 1);
      t.equal(writer.get('value'), 1, "writer.active == outer");
      t.equal(outer.value, 1, "outer is active");

      process.nextTick(function () {
        t.equal(writer.active, outer, "writer.active == outer");
        t.equal(writer.get('value'), 1, "inner has been entered");
        writer.run(function (inner) {
          t.equal(writer.active, inner, "writer.active == inner");

          writer.set('value', 2);
          t.equal(outer.value, 1, "outer is unchanged");
          t.equal(inner.value, 2, "inner is active");
          t.equal(writer.get('value'), 2, "writer.active == inner");
        });
      });
    });

    setTimeout(function () {
      t.equal(writer.get('value'), 0, "writer.active == global");
      t.end();
    }, 100);
  }

  requestHandler();
});


text:
import currentScene from '../computed/currentScene';

function setLoadedCourseSnackbar({state}) {
  if (Boolean(state.get(currentScene).recording)) {
    state.merge('snackbar', {
      text: 'Laster video og lyd...',
      show: true,
      persist: true
    });
    state.set('course.isLoadingMedia', true);
  } else {
    state.merge('snackbar', {
      text: 'Kurset er lastet!',
      show: true,
      persist: false
    });
  }
}

export default setLoadedCourseSnackbar;


text:
package it.univaq.mwt.fastmarket.business;

import java.util.List;

public class ResponseGrid<R> implements java.io.Serializable {

	private String sEcho;
	private long iTotalRecords;
	private long iTotalDisplayRecords;
	private List<R> rows;

	public ResponseGrid(String sEcho, long iTotalRecords, long iTotalDisplayRecords, List<R> rows) {
		super();
		this.sEcho = sEcho;
		this.iTotalRecords = iTotalRecords;
		this.iTotalDisplayRecords = iTotalDisplayRecords;
		this.rows = rows;
	}
	public String getsEcho() {
		return sEcho;
	}
	public void setsEcho(String sEcho) {
		this.sEcho = sEcho;
	}
	public long getiTotalRecords() {
		return iTotalRecords;
	}
	public void setiTotalRecords(long iTotalRecords) {
		this.iTotalRecords = iTotalRecords;
	}
	public long getiTotalDisplayRecords() {
		return iTotalDisplayRecords;
	}
	public void setiTotalDisplayRecords(long iTotalDisplayRecords) {
		this.iTotalDisplayRecords = iTotalDisplayRecords;
	}
	public List<R> getRows() {
		return rows;
	}
	public void setRows(List<R> rows) {
		this.rows = rows;
	}

}


text:
title: Teaching Assistant
season: Fall
year: 2014
meta:
 - CS 5630 / 6630 Visualization
 - University of Utah, Salt Lake City, UT
reference: "with Dr. Miriah Meyer, using Processing"
links:
  Course page: https://www.cs.utah.edu/~miriah/teaching/cs6630/
---


text:
ItemBomb = class(Item)

function ItemBomb:throwTo(x, y)
    self.throw = true
    self.toX   = x
    self.toY   = y
    self.moveX = x - self.x
    self.moveY = y - self.y
    if self.moveY ~= 0 then
        self.flyAngle = math.atan(self.moveX / self.moveY)
    else
        self.flyAngle = math.pi / 2
    end
    self.delayCollide = 16
end

function ItemBomb:moveRateX()
    if self.x == self.toX and self.y == self.toY then
        self.throw = false
        self.delayCollide = 0
    end
    self.delayCollide = self.delayCollide - 1
    if self.throw then
        if self.moveY > 0 then
            if math.sin(self.flyAngle) > 0 then
                return math.min(self.toX - self.x, 10 * math.sin(self.flyAngle))
            else
                return math.max(self.toX - self.x, 10 * math.sin(self.flyAngle))
            end
        else
            if math.sin(self.flyAngle) > 0 then
                return math.max(self.toX - self.x, -10 * math.sin(self.flyAngle))
            else
                return math.min(self.toX - self.x, -10 * math.sin(self.flyAngle))
            end
        end
    else
        return 0
    end
end

function ItemBomb:moveRateY()
    if self.x == self.toX and self.y == self.toY then
        self.throw = false
    end
    if self.throw then
        if self.moveY > 0 then
            if math.cos(self.flyAngle) > 0 then
                return math.min(self.toY - self.y, 10 * math.cos(self.flyAngle))
            else
                return math.max(self.toY - self.y, 10 * math.cos(self.flyAngle))
            end
        else
            if math.cos(self.flyAngle) > 0 then
                return math.max(self.toY - self.y, -10 * math.cos(self.flyAngle))
            else
                return math.min(self.toY - self.y, -10 * math.cos(self.flyAngle))
            end
        end
    else
        return 4
    end
end

function ItemBomb:spriteClass()
    return SpriteItemBomb
end

function ItemBomb:spriteLayer()
    return "scene"
end

function ItemBomb:spriteName()
    return "item_bomb"
end

function ItemBomb:collideEffect(player)
    if self.delayCollide <= 0 then
        player:addItem(self)
    end
end

function ItemBomb:applyEffect(player)
    local layer  = self:spriteLayer()
    local name   = "bombeffect"
    local class  = SpriteBomb
    local cutin  = nil

    if love.char == 0 then
        cutin = LayerManager:addSprite(layer, "cutin", CutinBombRyuko)
    elseif love.char == 1 then
        cutin = LayerManager:addSprite(layer, "cutin", CutinBombSatsuki)
    end

    cutin.callback = function()
        local sprite = LayerManager:addSprite(layer, name, class, true)

        local useSE = SoundManager:addSound("Using Bomb.wav")
        useSE:play()

        sprite.x = 0
        sprite.y = 440

        local explosionSE = SoundManager:addSound("Bomb Explosion.mp3")
        explosionSE:play()

        sprite:frameCallback(3, function()
            local layer  = self:spriteLayer()
            local name   = "boosteffect"
            local class  = SpriteBomb
            local sprite = LayerManager:addSprite(layer, name, class, true)

            local explosionSE = SoundManager:addSound("Bomb Explosion.mp3")
            explosionSE:play()

            sprite.x = 0
            sprite.y = 320

            sprite:frameCallback(3, function()
                local layer  = self:spriteLayer()
                local name   = "boosteffect"
                local class  = SpriteBomb
                local sprite = LayerManager:addSprite(layer, name, class, true)

                local explosionSE = SoundManager:addSound("Bomb Explosion.mp3")
                explosionSE:play()

                sprite.x = 0
                sprite.y = 200

                sprite:frameCallback(3, function()
                    local layer  = self:spriteLayer()
                    local name   = "boosteffect"
                    local class  = SpriteBomb
                    local sprite = LayerManager:addSprite(layer, name, class, true)

                    local explosionSE = SoundManager:addSound("Bomb Explosion.mp3")
                    explosionSE:play()

                    sprite.x = 0
                    sprite.y = 80

                    sprite:frameCallback(3, function()
                        local layer  = self:spriteLayer()
                        local name   = "boosteffect"
                        local class  = SpriteBomb
                        local sprite = LayerManager:addSprite(layer, name, class, true)

                        local explosionSE = SoundManager:addSound("Bomb Explosion.mp3")
                        explosionSE:play()

                        sprite.x = 0
                        sprite.y = -40

                        sprite:autoDestroy(1)
                    end)

                    sprite:autoDestroy(1)
                end)

                sprite:autoDestroy(1)
            end)

            sprite:autoDestroy(1)
        end)

        local enemies = ModelManager:getModel("enemyCharacter")
        for k,v in pairs(enemies) do
            v:applyDamage(300, false)
        end

        sprite:autoDestroy(1)

        self:destroy()
    end

end


text:
require 'spec_helper'

describe "Exchange::Helper" do
  subject { Exchange::Helper }
  describe "assure_time" do
    before(:each) do
      time = Time.now
      allow(Time).to receive(:now).and_return time
    end
    context "with a time object" do
      it "should return that time object" do
        expect(Exchange::Helper.assure_time(Time.now - 3400)).to eq(Time.now - 3400)
      end
    end
    context "with a string" do
      it "should send to Time.gm" do
        expect(Time).to receive(:gm).with('2011','09','09').once.and_return('TIME')
        expect(Exchange::Helper.assure_time('2011-09-09')).to eq('TIME')
      end
    end
    context "with nil" do
      it "should return nil if no default is defined" do
        expect(Exchange::Helper.assure_time(nil)).to be_nil
      end
      it "should return the default if the default is defined" do
        expect(Exchange::Helper.assure_time(nil, :default => :now)).to eq(Time.now)
      end
    end
  end
end


text:
import { Config } from '@stencil/core'
import { sass } from '@stencil/sass'

export const config: Config = {
  namespace: 'mattailes',
  globalStyle: 'src/global/app.scss',
  plugins: [sass()],
  outputTargets: [{ type: 'dist' }, { type: 'www', serviceWorker: null }],
}


text:
<?HH
/**
 * Hack Fast Algos
 *
 * Implementation of a stack
 * @Learn more @link https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
 */

namespace HackFastAlgos\DataStructure;

class StackInvalidIndexException extends \Exception{}

class Stack implements \Countable
{
	private Vector<T> $stackData = Vector{};

	public function count() : int
	{
		return $this->stackData->count();
	}

	public function push<T>(T $item)
	{
		$this->stackData[] = $item;
	}

	public function pop<T>() : T
	{
		// Manual pop
		$count = $this->stackData->count();

		if ($count === 0) {
			throw new StackInvalidIndexException();
		}

		$last = $this->stackData[$count-1];
		$this->stackData->removeKey($count-1);

		return $last;
	}
}


text:
using Data_Manager;
using Logging;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TUMCampusAppAPI.DBTables;
using TUMCampusAppAPI.TUMOnline;
using Windows.ApplicationModel.Appointments;
using Windows.Data.Xml.Dom;

namespace TUMCampusAppAPI.Managers
{
    public class CalendarDBManager : AbstractTumDBManager
    {
        //--------------------------------------------------------Attributes:-----------------------------------------------------------------\\
        #region --Attributes--
        public static CalendarDBManager INSTANCE;

        #endregion
        //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
        #region --Constructors--
        /// <summary>
        /// Basic Constructor
        /// </summary>
        /// <history>
        /// 20/01/2017 Created [Fabian Sauter]
        /// </history>
        public CalendarDBManager()
        {
            this.refreshingTask = null;
        }

        #endregion
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--
        /// <summary>
        /// Returns the next calendar entry.
        /// </summary>
        /// <returns>Returns the next calendar entry.</returns>
        public TUMOnlineCalendarTable getNextEntry()
        {
            List<TUMOnlineCalendarTable> list = getEntries();
            if (list == null || list.Count <= 0)
            {
                return null;
            }
            TUMOnlineCalendarTable entry = null;
            foreach (TUMOnlineCalendarTable e in list)
            {
                if (entry == null)
                {
                    if (e != null && e.dTEnd.CompareTo(DateTime.Now) > 0)
                    {
                        entry = e;
                    }
                    continue;
                }
                if (e != null && e.dTEnd.CompareTo(DateTime.Now) > 0 && e.dTEnd.CompareTo(entry.dTEnd) < 0)
                {
                    entry = e;
                }
            }
            return entry;
        }

        /// <summary>
        /// Returns all calendar entries, the db contains.
        /// </summary>
        /// <returns>Returns all calendar entries.</returns>
        public List<TUMOnlineCalendarTable> getEntries()
        {
            List<TUMOnlineCalendarTable> list = dB.Query<TUMOnlineCalendarTable>(true, "SELECT * FROM " + DBTableConsts.TUM_ONLINE_CALENDAR_TABLE + ";");
            return list;
        }

        #endregion
        //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
        #region --Misc Methods (Public)--
        public override void initManager()
        {
            Task.Run(() => syncCalendar(false, true));
        }

        /// <summary>
        /// Creates a new Task and starts syncing the calendar in the background.
        /// </summary>
        /// <param name="force">Force sync calendar.</param>
        /// <param name="insertInCalendar">Add downloaded entries to the system calendar.</param>
        /// <returns>Returns the sync task or null if not syncing.</returns>
        public Task syncCalendar(bool force, bool insertInCalendar)
        {
            if (!force && Settings.getSettingBoolean(SettingsConsts.ONLY_USE_WIFI_FOR_UPDATING) && !DeviceInfo.isConnectedToWifi())
            {
                return null;
            }

            waitForSyncToFinish();
            REFRESHING_TASK_SEMA.Wait();
            refreshingTask = syncCalendarTaskAsync(force, insertInCalendar);
            REFRESHING_TASK_SEMA.Release();

            return refreshingTask;
        }

        /// <summary>
        /// Deletes all calendars created by this app.
        /// </summary>
        public async Task deleteCalendarAsync()
        {
            AppointmentStore aS = await AppointmentManager.RequestStoreAsync(AppointmentStoreAccessType.AppCalendarsReadWrite);
            IReadOnlyList<AppointmentCalendar> cal = await aS.FindAppointmentCalendarsAsync();
            foreach (AppointmentCalendar c in cal)
            {
                await c.DeleteAsync();
            }
            Logger.Info("Deleted all existing calendars.");
        }

        /// <summary>
        /// Resets the calendar, creates a new one and inserts all given TUMOnlineCalendarEntries into it.
        /// </summary>
        /// <param name="list">A list with all TUMOnlineCalendarTable entries that should get added to the calendar.</param>
        public async Task insterInCalendarAsync(List<TUMOnlineCalendarTable> list)
        {
            // 1. Get access to appointmentstore:
            AppointmentStore aS = await AppointmentManager.RequestStoreAsync(AppointmentStoreAccessType.AppCalendarsReadWrite);

            // 2. Delete the calendar if one exists:
            await deleteCalendarAsync();

            // 3. Request a new one:
            AppointmentCalendar calendar = null;
            calendar = await aS.CreateAppointmentCalendarAsync(Consts.CALENDAR_NAME);

            // 4. Insert appointments:
            if (calendar != null)
            {
                calendar.DisplayColor = Windows.UI.Color.FromArgb(0, 101, 189, 1);
                foreach (TUMOnlineCalendarTable entry in list)
                {
                    await calendar.SaveAppointmentAsync(entry.getAppointment());
                }
            }
            Logger.Info("Finished loading calendar.");
        }

        #endregion

        #region --Misc Methods (Private)--
        /// <summary>
        /// Refreshes the whole calendar if needed or force == true.
        /// </summary>
        /// <param name="force">Force sync calendar.</param>
        /// <param name="insertInCalendar">Add downloaded entries to the system calendar.</param>
        /// <returns></returns>
        private async Task syncCalendarTaskAsync(bool force, bool insertInCalendar)
        {
            if (!DeviceInfo.isConnectedToInternet() || (!force && Settings.getSettingBoolean(SettingsConsts.ONLY_USE_WIFI_FOR_UPDATING) && !DeviceInfo.isConnectedToWifi()))
            {
                return;
            }
            if (force || SyncDBManager.INSTANCE.needSync(DBTableConsts.TUM_ONLINE_CALENDAR_TABLE, Consts.VALIDITY_ONE_DAY).NEEDS_SYNC)
            {
                long time = SyncDBManager.GetCurrentUnixTimestampMillis();
                List<TUMOnlineCalendarTable> list = null;
                XmlDocument doc = null;
                try
                {
                    doc = await getCalendarEntriesDocumentAsync();
                }
                catch (Exception e)
                {
                    Logger.Error("Unable to sync Calendar! Unable to request a document.");
                    SyncDBManager.INSTANCE.Update(new SyncTable(this, e));
                    return;
                }

                if (doc == null)
                {
                    Logger.Error("Unable to sync Calendar! Unable to request a document.");
                    SyncDBManager.INSTANCE.Update(new SyncTable("News", SyncResult.STATUS_ERROR_UNKNOWN, "Unable to sync Calendar! Unable to request a document."));
                    return;
                }
                list = parseToList(doc);

                if (force)
                {
                    dB.DeleteAll<TUMOnlineCalendarTable>();
                }

                // Do not use insertAll, because insertAll is unable to replace entries => Exception:
                for (int i = 0; i < list.Count; i++)
                {
                    dB.InsertOrReplace(list[i]);
                }

                if (insertInCalendar && !Settings.getSettingBoolean(SettingsConsts.DISABLE_CALENDAR_INTEGRATION))
                {
                    await insterInCalendarAsync(list);
                }
                SyncDBManager.INSTANCE.Update(new SyncTable(DBTableConsts.TUM_ONLINE_CALENDAR_TABLE));
                Logger.Info("Finished syncing calendar in: " + (SyncDBManager.GetCurrentUnixTimestampMillis() - time) + " ms");
            }
        }

        /// <summary>
        /// Parses a xml document into a list of TUMOnlineCalendarEntries.
        /// </summary>
        /// <param name="doc">The XmlDocument that should get parsed.</param>
        /// <returns>Returns a list of TUMOnlineCalendarTable.</returns>
        private List<TUMOnlineCalendarTable> parseToList(XmlDocument doc)
        {
            List<TUMOnlineCalendarTable> list = new List<TUMOnlineCalendarTable>();
            foreach (var element in doc.SelectNodes("/events/event"))
            {
                try
                {
                    addEntryToList(list, new TUMOnlineCalendarTable(element));
                }
                catch (Exception e)
                {
                    Logger.Error("Error during parsing calendar entry (" + (element == null ? "NULL" : element.GetXml() + ')'), e);
                }
            }
            return list;
        }

        /// <summary>
        /// Adds a given TUMOnlineCalendarTable to the given list. Checks before adding whether the entity is valid.
        /// </summary>
        private void addEntryToList(List<TUMOnlineCalendarTable> list, TUMOnlineCalendarTable entry)
        {
            for (var i = 0; i < list.Count; i++)
            {
                if (entry.status.Equals("CANCEL"))
                {
                    return;
                }
                if (list[i].Equals(entry))
                {
                    list[i].location += ",\n" + entry.location;
                    return;
                }
            }
            list.Add(entry);
        }

        /// <summary>
        /// Creates a TUMOnlineRequest to request the personal calendar.
        /// </summary>
        /// <returns>Returns the personal calendar in form of a xml document.</returns>
        private async Task<XmlDocument> getCalendarEntriesDocumentAsync()
        {
            TUMOnlineRequest req = new TUMOnlineRequest(TUMOnlineConst.CALENDAR);
            req.addToken();
            req.addParameter(Consts.P_MONTH_AHEAD, "2");
            req.addParameter(Consts.P_MONTH_BACK, "5");
            return await req.doRequestDocumentAsync();
        }

        #endregion

        #region --Misc Methods (Protected)--
        protected override void DropTables()
        {
            dB.DropTable<TUMOnlineCalendarTable>();
        }

        protected override void CreateTables()
        {
            dB.CreateTable<TUMOnlineCalendarTable>();
        }

        #endregion
        //--------------------------------------------------------Events:---------------------------------------------------------------------\\
        #region --Events--

        #endregion
    }
}


text:
#pragma once
#include <ostream>
#include <spdlog/fmt/fmt.h>
#include <Eigen/SparseCore>

namespace Faunus {

/**
 * @brief Save Matrix Market sparse matrix
 * @note File format description: https://math.nist.gov/MatrixMarket/formats.html
 * @param mat Sparse matrix
 * @param out Output stream
 * @param symmetric Set to true if symmetric matrix (half storage)
 *
 * Mainly copied from Eigen's unsupported `SparseExtra/MarketIO.h`
 *
 * @warning Untested for symmetric matrices with non-zero diagonal
 */
template <typename SparseMatrixType>
bool streamMarket(const SparseMatrixType& mat, std::ostream& out, bool symmetric = false) {
    using Scalar = Eigen::SparseMatrix<double>::Scalar;
    if (!out) {
        return false;
    }
    out << fmt::format("%%MatrixMarket matrix coordinate  {} {}\n", "real", symmetric ? "symmetric" : "general")
        << mat.rows() << " " << mat.cols() << " " << mat.nonZeros() / (symmetric ? 2 : 1) << "\n";

    for (int col = 0; col < mat.outerSize(); ++col) {
        for (Eigen::SparseMatrix<Scalar>::InnerIterator it(mat, col); it; ++it) {
            if (symmetric && col > it.row()) {
                continue;
            }
            out << fmt::format("{} {} {:.6E}\n", it.row() + 1, it.col() + 1, it.value());
        }
    }
    return true;
}
} // namespace Faunus


text:
<?php

namespace SBD\Softbd\Models;

use Illuminate\Database\Eloquent\Model;

class Translation extends Model
{
    protected $table = 'translations';

    protected $fillable = ['table_name', 'column_name', 'foreign_key', 'locale', 'value'];
}


text:
/**
 * Created by Michel Koolwaaij on 26-09-16.
 */
public interface IMicStudent {
    public String getVoornaam();
    public String getAchternaam();
    public String getEmail();
    public int getId();
}


text:
/*jshint camelcase: false */
/*jshint newcap: false */

'use strict';

var util = require('util');
var common = require('../../common');
var resourceGroup = require('../../common/resourceGroup-client');
var msRestRequest = require('../../common/msRestRequest');
var HttpStatus = require('http-status-codes');

var API_VERSIONS;
var environment;
var azureProperties;
var namespaceUrlTemplate = '%s/subscriptions/%s/resourceGroups/%s/providers/Microsoft.ServiceBus/namespaces/%s';
  //Params needed: resourceManagerEndpointUrl, subscriptionId, resourceGroupName, namespaceName
exports.init = function(azure) {
  azureProperties = azure;

  var environmentName = azureProperties.environment;
  environment = common.getEnvironment(environmentName);

  API_VERSIONS = common.API_VERSION[environmentName];
};

exports.createResourceGroup = function(azureConfig, callback) {
  resourceGroup.createOrUpdate(
    'ServiceBus',
    azureProperties,
    azureConfig.resourceGroupName,
    { 'location': azureConfig.location },
    callback
  );
};

exports.createNamespace = function(azureConfig, callback) {
  msRestRequest.PUT(
    util.format(
      namespaceUrlTemplate,
      environment.resourceManagerEndpointUrl,
      azureProperties.subscriptionId,
      azureConfig.resourceGroupName,
      azureConfig.namespaceName),
    common.mergeCommonHeaders('ServiceBus - createNamespace', {}),
    {
      'location': azureConfig.location,
      'kind': azureConfig.sbType,
      'sku': {
        'name': 'StandardSku',
        'tier': azureConfig.sbTier
      },
      'tags': azureConfig.tags,
      'properties': {
      }
    },
    API_VERSIONS.SERVICE_BUS_NAMESPACE,
    function(err, response, body) {
      common.logHttpResponse(response, 'ServiceBus - createNamespace', true);
      if (err) {
        callback(err);
      } else {
        if (response.statusCode == HttpStatus.OK) {
          callback(null);
        } else {
          return common.formatErrorFromRes(response, callback);
        }
      }
    }
  );
};

function getNamespace(azureConfig, callback) {
  msRestRequest.GET(
    util.format(
      namespaceUrlTemplate,
      environment.resourceManagerEndpointUrl,
      azureProperties.subscriptionId,
      azureConfig.resourceGroupName,
      azureConfig.namespaceName),
    common.mergeCommonHeaders('ServiceBus - getNamespace', {}),
    API_VERSIONS.SERVICE_BUS_NAMESPACE,
    callback
  );
}

exports.checkNamespaceAvailability = function(azureConfig, callback) {
  getNamespace(azureConfig, function(err, response, body) {
    common.logHttpResponse(response, 'Check namespace availability', true);
    if (err) {
      callback(err);
    } else {
      switch (response.statusCode) {
        case HttpStatus.NOT_FOUND:
          callback(null);
          break;
        case HttpStatus.OK:
          var error = new Error('The namespace name is not available.');
          error.statusCode = HttpStatus.CONFLICT;
          callback(error);
          break;
        default:
          return common.formatErrorFromRes(response, callback);
      }
    }
  });
};

exports.checkNamespaceStatus = function(azureConfig, callback) {
  getNamespace(azureConfig, function(err, response, body) {
    common.logHttpResponse(response, 'Check namespace Status', true);
    if(err) {
      callback(err);
    } else {
      if (response.statusCode == HttpStatus.OK) {
        var b = JSON.parse(body);
        callback(null, b.properties.provisioningState);
      } else {
        return common.formatErrorFromRes(response, callback);
      }
    }
  });
};

exports.listNamespaceKeys = function(azureConfig, callback) {
  msRestRequest.POST(
    util.format(
      namespaceUrlTemplate + '/authorizationRules/RootManageSharedAccessKey/ListKeys',
      environment.resourceManagerEndpointUrl,
      azureProperties.subscriptionId,
      azureConfig.resourceGroupName,
      azureConfig.namespaceName),
    common.mergeCommonHeaders('ServiceBus - listNamespaceKeys', {}),
    null,
    API_VERSIONS.SERVICE_BUS_NAMESPACE,
    function(err, response, body) {
      common.logHttpResponse(response, 'ServiceBus - listNamespaceKeys', false);
      if (err) {
        callback(err);
      } else {
        if (response.statusCode == HttpStatus.OK) {
          var b = JSON.parse(body);
          callback(null, 'RootManageSharedAccessKey', b.primaryKey);
        } else {
          return common.formatErrorFromRes(response, callback);
        }
      }
    }
  );
};

exports.delNamespace = function(azureConfig, callback) {
  msRestRequest.DELETE(
    util.format(
      namespaceUrlTemplate,
      environment.resourceManagerEndpointUrl,
      azureProperties.subscriptionId,
      azureConfig.resourceGroupName,
      azureConfig.namespaceName),
    common.mergeCommonHeaders('ServiceBus - deleteNamespace', {}),
    API_VERSIONS.SERVICE_BUS_NAMESPACE,
    function(err, response, body) {
      common.logHttpResponse(response, 'ServiceBus - deleteNamespace', true);
      if (err) {
        callback(err);
      } else {
        if (response.statusCode == HttpStatus.ACCEPTED || response.statusCode == HttpStatus.NO_CONTENT) {
          callback(null);
        } else {
          return common.formatErrorFromRes(response, callback);
        }
      }
    }
  );
};


text:
<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 *
	 * @return void
	 */
	public function run()
	{
		Model::unguard();

		$this->call('AdminSeeder');
		$this->command->info('Admin Users table seeded.');

		Model::reguard();
	}

}


text:
use std::collections::HashMap;

pub struct Brackets {
    raw_brackets: Vec<char>,
    pairs: MatchingBrackets,
}

impl<'a> From<&'a str> for Brackets {
    fn from(i: &str) -> Self {
        Brackets::new(String::from(i), None)
    }
}

impl Brackets {
    pub fn new(s: String, pairs: Option<Vec<(char, char)>>) -> Self {
        let p = match pairs {
            Some(x) => MatchingBrackets::from(x),
            None => MatchingBrackets::from(vec![('[', ']'), ('{', '}'), ('(', ')')]),
        };

        Brackets {
            raw_brackets: s.chars().filter(|c| p.contains(&c)).collect::<Vec<char>>(),
            pairs: p,
        }
    }

    pub fn are_balanced(&self) -> bool {
        let mut unclosed: Vec<char> = Vec::new();

        for &bracket in self.raw_brackets.iter() {
            if let Some(last_unclosed) = unclosed.pop() {
                unclosed.extend(self.pairs.unmatched(last_unclosed, bracket));
            } else {
                unclosed.push(bracket);
            }
        }

        unclosed.is_empty()
    }
}

pub struct MatchingBrackets {
    collection: HashMap<char, char>,
}

impl From<Vec<(char, char)>> for MatchingBrackets {
    fn from(v: Vec<(char, char)>) -> Self {
        MatchingBrackets { collection: v.into_iter().collect::<HashMap<char, char>>() }
    }
}

impl MatchingBrackets {
    fn contains(&self, other: &char) -> bool {
        let known = self.collection.keys().chain(self.collection.values()).collect::<Vec<_>>();
        known.contains(&other)
    }

    fn closer_for(&self, k: &char) -> Option<&char> {
        self.collection.get(k)
    }

    fn closed_by(&self, l: char, r: char) -> bool {
        match self.closer_for(&l) {
            Some(&x) => r == x,
            None => false,
        }
    }

    fn unmatched(&self, open: char, potential_close: char) -> Vec<char> {
        let mut ret: Vec<char> = Vec::new();

        if !self.closed_by(open, potential_close) {
            ret.push(open);
            ret.push(potential_close);
        }

        ret
    }
}


text:
					<input type="text" placeholder="Enter Product Name" class="productName" ng-model="product.name">

					Brand: <input type="text" placeholder="eg. Banana Republic" class="productName" ng-model="product.company">
					ProductID: <input type="text" placeholder="eg. 124567002" class="productName" ng-model="product.productId" ng-blur="updateImage()">

					Size:

						<button ng-repeat="size in sizes" ng-click="selectSize(size)" ng-class="{'active': size == product.size}">{{size}}</button>

					Gender:

						<button ng-repeat="gender in genders" ng-click="selectGender(gender)"  ng-class="{'active': gender == product.gender}">{{gender}}</button>

					Category:

						<button ng-repeat="category in categories" ng-click="selectCategory(category)" ng-class="{'active': category == product.category}">{{category}}</button>

					Price: $<input type="text" placeholder="30" class="productName" ng-model="product.price">

Enter a brief description about your product

					<textarea ng-model="product.description">
					</textarea>

					<button class="btn btnPrimary" ng-click="submitProduct()">Submit</button>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- see http://mojo.codehaus.org/clirr-maven-plugin/examples/ignored-differences.html -->
<differences>
  <difference>
    <className>com/google/api/services/file/v1beta1/model/GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion</className>
    <method>java.lang.String getExclusionDuration()</method>
    <differenceType>7002</differenceType>
  </difference>
  <difference>
    <className>com/google/api/services/file/v1beta1/model/GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion</className>
    <method>java.lang.String getExclusionStartTime()</method>
    <differenceType>7002</differenceType>
  </difference>
  <difference>
    <className>com/google/api/services/file/v1beta1/model/GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion</className>
    <method>com.google.api.services.file.v1beta1.model.GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion setExclusionDuration(java.lang.String)</method>
    <differenceType>7002</differenceType>
  </difference>
  <difference>
    <className>com/google/api/services/file/v1beta1/model/GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion</className>
    <method>com.google.api.services.file.v1beta1.model.GoogleCloudSaasacceleratorManagementProvidersV1SloExclusion setExclusionStartTime(java.lang.String)</method>
    <differenceType>7002</differenceType>
  </difference>
</differences>


text:
package consulo.csharp.lang.psi.impl.source.resolve.type.wrapper;

import com.intellij.pom.Navigatable;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiNameIdentifierOwner;
import com.intellij.psi.impl.light.LightElement;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import consulo.annotation.access.RequiredReadAction;
import consulo.annotation.access.RequiredWriteAction;
import consulo.csharp.lang.CSharpLanguage;
import consulo.csharp.lang.psi.*;
import consulo.csharp.lang.psi.impl.light.builder.CSharpLightFieldDeclarationBuilder;
import consulo.dotnet.psi.*;
import consulo.dotnet.resolve.DotNetTypeRef;
import consulo.util.dataholder.Key;
import org.jetbrains.annotations.NonNls;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * @author VISTALL
 * @since 26-Nov-16.
 */
public class CSharpTupleTypeDeclaration extends LightElement implements CSharpTypeDeclaration
{
	public static final Key<PsiNameIdentifierOwner> TUPLE_ELEMENT = Key.create("tuple.element");

	private final CSharpTypeDeclaration myType;
	private final DotNetNamedElement[] myMembers;

	@RequiredReadAction
	public CSharpTupleTypeDeclaration(DotNetTypeDeclaration type, PsiNameIdentifierOwner[] variables, DotNetTypeRef[] typeRefs)
	{
		super(type.getManager(), CSharpLanguage.INSTANCE);

		myType = (CSharpTypeDeclaration) type;

		final DotNetNamedElement[] members = type.getMembers();
		DotNetNamedElement[] targetMembers = members;
		for(int i = 0; i < variables.length; i++)
		{
			PsiNameIdentifierOwner variable = variables[i];
			String name = variable.getName();
			if(name == null)
			{
				continue;
			}
			CSharpLightFieldDeclarationBuilder builder = new CSharpLightFieldDeclarationBuilder(type.getProject())
			{
				@Override
				public void navigate(boolean requestFocus)
				{
					PsiElement element = getUserData(TUPLE_ELEMENT);
					if(element instanceof Navigatable)
					{
						((Navigatable) element).navigate(true);
					}
				}

				@Override
				public boolean isEquivalentTo(PsiElement another)
				{
					if(another == getUserData(TUPLE_ELEMENT))
					{
						return true;
					}
					return super.isEquivalentTo(another);
				}

				@Override
				public PsiFile getContainingFile()
				{
					return getUserData(TUPLE_ELEMENT).getContainingFile();
				}
			};
			builder.putUserData(TUPLE_ELEMENT, variable);
			builder.withParent(this);
			builder.withTypeRef(typeRefs[i]);
			builder.addModifier(CSharpModifier.PUBLIC);
			builder.withName(name);
			String real = "Item" + (i + 1);

			DotNetNamedElement element = ContainerUtil.find(members, it -> real.equals(it.getName()));
			if(element != null)
			{
				builder.setNavigationElement(ToNativeElementTransformers.transform(element));
			}

			targetMembers = ArrayUtil.append(targetMembers, builder, DotNetNamedElement[]::new);
		}
		myMembers = targetMembers;
	}

	@Override
	public boolean isEquivalentTo(PsiElement another)
	{
		return myType.isEquivalentTo(another);
	}

	@Override
	public boolean isInterface()
	{
		return myType.isInterface();
	}

	@Override
	public boolean isStruct()
	{
		return myType.isStruct();
	}

	@Override
	public boolean isEnum()
	{
		return myType.isEnum();
	}

	@Override
	public boolean isNested()
	{
		return myType.isNested();
	}

	@Override
	@Nullable
	public DotNetTypeList getExtendList()
	{
		return myType.getExtendList();
	}

	@Override
	@RequiredReadAction
	@Nonnull
	public DotNetTypeRef[] getExtendTypeRefs()
	{
		return myType.getExtendTypeRefs();
	}

	@Override
	@RequiredReadAction
	public boolean isInheritor(@Nonnull String s, boolean b)
	{
		return myType.isInheritor(s, b);
	}

	@Override
	@RequiredReadAction
	@Nonnull
	public DotNetTypeRef getTypeRefForEnumConstants()
	{
		return myType.getTypeRefForEnumConstants();
	}

	@Override
	@RequiredReadAction
	@Nullable
	public String getVmQName()
	{
		return myType.getVmQName();
	}

	@Override
	@RequiredReadAction
	@Nullable
	public String getVmName()
	{
		return myType.getVmName();
	}

	@Override
	@RequiredReadAction
	@Nullable
	public String getPresentableParentQName()
	{
		return myType.getPresentableParentQName();
	}

	@Override
	@RequiredReadAction
	@Nullable
	public String getPresentableQName()
	{
		return myType.getPresentableQName();
	}

	@Override
	@NonNls
	public String toString()
	{
		return myType.toString();
	}

	@Override
	@RequiredWriteAction
	public PsiElement setName(@NonNls @Nonnull String s) throws IncorrectOperationException
	{
		return myType.setName(s);
	}

	@Override
	@RequiredReadAction
	public boolean hasModifier(@Nonnull DotNetModifier dotNetModifier)
	{
		return myType.hasModifier(dotNetModifier);
	}

	@Override
	@RequiredReadAction
	@Nullable
	public DotNetModifierList getModifierList()
	{
		return myType.getModifierList();
	}

	@Override
	@Nullable
	public DotNetGenericParameterList getGenericParameterList()
	{
		return myType.getGenericParameterList();
	}

	@Override
	@Nonnull
	public DotNetGenericParameter[] getGenericParameters()
	{
		return myType.getGenericParameters();
	}

	@Override
	public int getGenericParametersCount()
	{
		return myType.getGenericParametersCount();
	}

	@Override
	@RequiredReadAction
	@Nullable
	public PsiElement getNameIdentifier()
	{
		return myType.getNameIdentifier();
	}

	@Override
	@RequiredReadAction
	@Nonnull
	public DotNetNamedElement[] getMembers()
	{
		return myMembers;
	}

	@Override
	@Nullable
	public CSharpGenericConstraintList getGenericConstraintList()
	{
		return myType.getGenericConstraintList();
	}

	@Override
	@Nonnull
	public CSharpGenericConstraint[] getGenericConstraints()
	{
		return myType.getGenericConstraints();
	}

	@Override
	@RequiredReadAction
	public PsiElement getLeftBrace()
	{
		return myType.getLeftBrace();
	}

	@Override
	@RequiredReadAction
	public PsiElement getRightBrace()
	{
		return myType.getRightBrace();
	}

	@RequiredReadAction
	@Override
	public String getName()
	{
		return myType.getName();
	}
}


text:
<?php

namespace Oro\Component\Layout\Tests\Unit\Extension\Theme\Model;

use Oro\Component\Layout\Extension\Theme\Model\PageTemplate;
use Oro\Component\Layout\Extension\Theme\Model\Theme;
use Oro\Component\Layout\Extension\Theme\Model\ThemeFactory;

class ThemeFactoryTest extends \PHPUnit_Framework_TestCase
{
    /** @var ThemeFactory */
    protected $factory;

    protected function setUp()
    {
        $this->factory = new ThemeFactory();
    }

    protected function tearDown()
    {
        unset($this->factory);
    }

    /**
     * @dataProvider themeDefinitionDataProvider
     *
     * @param string $name
     * @param array  $definition
     * @param mixed  $expectedResult
     */
    public function testCreate($name, array $definition, $expectedResult)
    {
        $result = $this->factory->create($name, $definition);

        $this->assertEquals($expectedResult, $result);
    }

    /**
     * @return array
     */
    public function themeDefinitionDataProvider()
    {
        $minimalDefinition = new Theme('base');

        $fullDefinition = new Theme('oro-black', 'base');
        $fullDefinition->setIcon('oro-black-icon.ico');
        $fullDefinition->setLogo('oro-black-logo.png');
        $fullDefinition->setScreenshot('oro-black-screenshot.png');
        $fullDefinition->setLabel('Oro Black Theme');
        $fullDefinition->setDirectory('OroBlack');
        $fullDefinition->setGroups(['main', 'frontend']);
        $fullDefinition->setDescription('description');

        $config = [
            'key' => 'value',
            'page_templates' => [
                'templates' => [
                    [
                        'label' => 'Some label',
                        'key' => 'some_key',
                        'route_name' => 'some_route_name',
                        'screenshot' => 'some_screenshot',
                        'description' => 'Some description'
                    ],
                    [
                        'label' => 'Some label (disabled)',
                        'key' => 'some_key_disabled',
                        'route_name' => 'some_route_name_disabled',
                        'enabled' => false,
                    ]
                ],
                'titles' => [
                    'some_route_name' => 'Title for some route name'
                ]
            ]
        ];

        $fullDefinition->setConfig($config);

        $fullDefinition->addPageTemplateTitle('some_route_name', 'Title for some route name');

        $pageTemplate = new PageTemplate('Some label', 'some_key', 'some_route_name');
        $pageTemplate->setDescription('Some description')
            ->setScreenshot('some_screenshot');
        $fullDefinition->addPageTemplate($pageTemplate);

        $pageTemplate = new PageTemplate('Some label (disabled)', 'some_key_disabled', 'some_route_name_disabled');
        $pageTemplate->setEnabled(false);
        $fullDefinition->addPageTemplate($pageTemplate);

        return [
            'minimal definition given' => [
                '$name'           => 'base',
                '$definition'     => [],
                '$expectedResult' => $minimalDefinition,
            ],
            'full definition given'    => [
                '$name'           => 'oro-black',
                '$definition'     => [
                    'parent'     => 'base',
                    'groups'     => ['main', 'frontend'],
                    'label'      => 'Oro Black Theme',
                    'screenshot' => 'oro-black-screenshot.png',
                    'icon'       => 'oro-black-icon.ico',
                    'logo'       => 'oro-black-logo.png',
                    'directory'  => 'OroBlack',
                    'description' => 'description',
                    'config' => $config
                ],
                '$expectedResult' => $fullDefinition,
            ]
        ];
    }
}