text:
<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/model/event_set.html">
<link rel="import" href="/tracing/ui/analysis/analysis_link.html">
<link rel="import" href="/tracing/ui/analysis/analysis_sub_view.html">
<link rel="import" href="/tracing/ui/analysis/generic_object_view.html">
<link rel="import" href="/tracing/ui/analysis/object_instance_view.html">
<link rel="import" href="/tracing/ui/analysis/object_snapshot_view.html">
<link rel="import" href="/tracing/ui/analysis/single_event_sub_view.html">
<link rel="import" href="/tracing/value/ui/time_stamp_span.html">

<polymer-element name="tr-ui-a-single-object-snapshot-sub-view"
    extends="tr-ui-a-sub-view">
  <template>
    <style>
    #args {
      white-space: pre;
    }

    :host {
      overflow: auto;
      display: flex;
    }

    ::content * {
      -webkit-user-select: text;
    }

    ::content .title {
      border-bottom: 1px solid rgb(128, 128, 128);
      font-size: 110%;
      font-weight: bold;
    }

    ::content td, th {
      font-family: monospace;
      vertical-align: top;
    }
    </style>
    <content></content>
  </template>
  <script>
  'use strict';

  Polymer({
    created: function() {
      this.currentSelection_ = undefined;
    },

    get requiresTallView() {
      if (this.children.length === 0)
        return false;
      if (this.children[0] instanceof tr.ui.analysis.ObjectSnapshotView)
        return this.children[0].requiresTallView;
    },

    get selection() {
      return this.currentSelection_;
    },

    set selection(selection) {
      if (selection.length !== 1)
        throw new Error('Only supports single item selections');
      if (!(selection[0] instanceof tr.model.ObjectSnapshot))
        throw new Error('Only supports object instances');

      this.textContent = '';
      this.currentSelection_ = selection;

      var snapshot = selection[0];

      var typeInfo = tr.ui.analysis.ObjectSnapshotView.getTypeInfo(
          snapshot.objectInstance.category, snapshot.objectInstance.typeName);
      if (typeInfo) {
        var customView = new typeInfo.constructor();
        this.appendChild(customView);
        customView.modelEvent = snapshot;
      } else {
        this.appendGenericAnalysis_(snapshot);
      }
    },

    appendGenericAnalysis_: function(snapshot) {
      var instance = snapshot.objectInstance;

      this.textContent = '';

      var titleEl = document.createElement('div');
      titleEl.classList.add('title');
      titleEl.appendChild(document.createTextNode('Snapshot of '));
      this.appendChild(titleEl);

      var instanceLinkEl = document.createElement('tr-ui-a-analysis-link');
      instanceLinkEl.selection = new tr.model.EventSet(instance);
      titleEl.appendChild(instanceLinkEl);

      titleEl.appendChild(document.createTextNode(' @ '));

      titleEl.appendChild(tr.v.ui.createTimeStampSpan(
          snapshot.ts, {ownerDocument: this.ownerDocument}));

      var tableEl = document.createElement('table');
      this.appendChild(tableEl);

      var rowEl = document.createElement('tr');
      tableEl.appendChild(rowEl);

      var labelEl = document.createElement('td');
      labelEl.textContent = 'args:';
      rowEl.appendChild(labelEl);

      var argsEl = document.createElement('td');
      argsEl.id = 'args';
      rowEl.appendChild(argsEl);

      var objectViewEl = document.createElement('tr-ui-a-generic-object-view');
      objectViewEl.object = snapshot.args;
      argsEl.appendChild(objectViewEl);
    }
  });
  </script>
</polymer-element>


text:
package org.apache.pig.test;

import static org.apache.pig.ExecType.LOCAL;
import static org.apache.pig.ExecType.MAPREDUCE;

import java.io.IOException;
import java.util.Properties;

import junit.framework.TestCase;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.pig.PigServer;
import org.apache.pig.ExecType;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil;
import org.apache.pig.builtin.mock.Storage;
import org.apache.pig.builtin.mock.Storage.Data;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class TestParser extends TestCase {

protected final Log log = LogFactory.getLog(getClass());

    protected ExecType execType = MAPREDUCE;

    private static MiniCluster cluster;
    protected PigServer pigServer;

    @Before
    @Override
    public void setUp() throws Exception {

        String execTypeString = System.getProperty("test.exectype");
        if(execTypeString!=null && execTypeString.length()>0){
            execType = ExecType.fromString(execTypeString);
        }
        if(execType == MAPREDUCE) {
            cluster = MiniCluster.buildCluster();
            pigServer = new PigServer(MAPREDUCE, cluster.getProperties());
        } else {
            pigServer = new PigServer(LOCAL);
        }
    }

    @Override
    @After
    public void tearDown() throws Exception {
        pigServer.shutdown();
    }

    @AfterClass
    public static void oneTimeTearDown() throws Exception {
        if(cluster != null)
            cluster.shutDown();
    }

    @Test
    public void testLoadingNonexistentFile() throws ExecException, IOException {
        try {
            // FIXME : this should be tested in all modes
            if(execType == ExecType.LOCAL)
                return;
            pigServer.registerQuery("vals = load 'nonexistentfile';");
            pigServer.openIterator("vals");
            fail("Loading a  nonexistent file should throw an IOException at parse time");
        } catch (IOException io) {
        }
    }

    @Test
    public void testRemoteServerList() throws ExecException, IOException {
        try {
            Properties pigProperties = pigServer.getPigContext().getProperties();
            pigProperties.setProperty("fs.default.name", "hdfs://a.com:8020");
            Configuration conf;

            pigServer.registerQuery("a = load '/user/pig/1.txt';");
            conf = ConfigurationUtil.toConfiguration(pigProperties);
            assertTrue(conf.get("mapreduce.job.hdfs-servers")==null||
                    conf.get("mapreduce.job.hdfs-servers").equals("hdfs://a.com:8020"));

            pigServer.registerQuery("a = load 'hdfs://a.com/user/pig/1.txt';");
            conf = ConfigurationUtil.toConfiguration(pigProperties);
            assertTrue(pigProperties.getProperty("mapreduce.job.hdfs-servers")==null||
                    conf.get("mapreduce.job.hdfs-servers").equals("hdfs://a.com:8020"));

            pigServer.registerQuery("a = load 'har:///1.txt';");
            conf = ConfigurationUtil.toConfiguration(pigProperties);
            assertTrue(pigProperties.getProperty("mapreduce.job.hdfs-servers")==null||
                    conf.get("mapreduce.job.hdfs-servers").equals("hdfs://a.com:8020"));

            pigServer.registerQuery("a = load 'hdfs://b.com/user/pig/1.txt';");
            conf = ConfigurationUtil.toConfiguration(pigProperties);
            assertTrue(conf.get("mapreduce.job.hdfs-servers")!=null &&
                    conf.get("mapreduce.job.hdfs-servers").contains("hdfs://b.com"));

            pigServer.registerQuery("a = load 'har://hdfs-c.com/user/pig/1.txt';");
            conf = ConfigurationUtil.toConfiguration(pigProperties);
            assertTrue(conf.get("mapreduce.job.hdfs-servers")!=null &&
                    conf.get("mapreduce.job.hdfs-servers").contains("hdfs://c.com"));

            pigServer.registerQuery("a = load 'hdfs://d.com:8020/user/pig/1.txt';");
            conf = ConfigurationUtil.toConfiguration(pigProperties);
            assertTrue(conf.get("mapreduce.job.hdfs-servers")!=null &&
                    conf.get("mapreduce.job.hdfs-servers").contains("hdfs://d.com:8020"));

        } catch (IOException io) {
        }
    }

    @Test
    public void testRemoteServerList2() throws ExecException, IOException {

        Properties pigProperties = pigServer.getPigContext().getProperties();
        pigProperties.setProperty("fs.default.name", "hdfs://a.com:8020");
        Configuration conf;

        pigServer.setBatchOn();

        Data data = Storage.resetData(pigServer.getPigContext());
        data.set("/user/pig/1.txt");// no data

        pigServer.registerQuery("a = load '/user/pig/1.txt' using mock.Storage;");
        pigServer.registerQuery("store a into '/user/pig/1.txt';");

        System.out.println("hdfs-servers: " + pigProperties.getProperty("mapreduce.job.hdfs-servers"));
        conf = ConfigurationUtil.toConfiguration(pigProperties);
        assertTrue(conf.get("mapreduce.job.hdfs-servers")==null||
                conf.get("mapreduce.job.hdfs-servers").equals("hdfs://a.com:8020"));

        pigServer.registerQuery("store a into 'hdfs://b.com/user/pig/1.txt';");
        System.out.println("hdfs-servers: " + pigProperties.getProperty("mapreduce.job.hdfs-servers"));
        conf = ConfigurationUtil.toConfiguration(pigProperties);
        assertTrue(conf.get("mapreduce.job.hdfs-servers")!=null &&
                conf.get("mapreduce.job.hdfs-servers").contains("hdfs://b.com"));

        pigServer.registerQuery("store a into 'har://hdfs-c.com:8020/user/pig/1.txt';");
        System.out.println("hdfs-servers: " + pigProperties.getProperty("mapreduce.job.hdfs-servers"));
        conf = ConfigurationUtil.toConfiguration(pigProperties);
        assertTrue(conf.get("mapreduce.job.hdfs-servers")!=null &&
                conf.get("mapreduce.job.hdfs-servers").contains("hdfs://c.com:8020"));

        pigServer.registerQuery("store a into 'hdfs://d.com:8020/user/pig/1.txt';");
        System.out.println("hdfs-servers: " + pigProperties.getProperty("mapreduce.job.hdfs-servers"));
        conf = ConfigurationUtil.toConfiguration(pigProperties);
        assertTrue(conf.get("mapreduce.job.hdfs-servers")!=null &&
                conf.get("mapreduce.job.hdfs-servers").contains("hdfs://d.com:8020"));

    }
}

redpajama_set_name: RedPajamaGithub


text:
package gov.va.cpe.vpr;

import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import gov.va.cpe.vpr.DrugTherapy.MedStatus;
import gov.va.cpe.vpr.DrugTherapy.MedType;
import gov.va.cpe.vpr.pom.AbstractPOMObject;
import gov.va.cpe.vpr.pom.IGenericPOMObjectDAO;
import gov.va.cpe.vpr.pom.JSONViews;
import gov.va.cpe.vpr.pom.POMUtils;
import gov.va.hmp.healthtime.CPRSDateTimePrinterSet;
import gov.va.hmp.healthtime.HealthTimePrinterSet;
import gov.va.hmp.healthtime.MSCUIDateTimePrinterSet;
import gov.va.hmp.healthtime.PointInTime;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Ignore;
import org.mockito.Matchers;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

/*
 * This class tests a snapshot of avivapatient 6's medication history and
 * tests the structure of the DrugTherapy derivative objects
 */
public class DrugTherapyTest {

	private static HealthTimePrinterSet FORMATTER = new CPRSDateTimePrinterSet();
	private static Map<String,DrugTherapy> data = new HashMap<>();
	private static int medCount=0;
	private static List<Medication> meds = null;
	private static IGenericPOMObjectDAO DAO = mock(IGenericPOMObjectDAO.class);
	private static Map<String,DrugTherapy> DAO_DATA = new HashMap<>();
	private static POMObjectTester<Medication> LOADER = new POMObjectTester<Medication>() {
		@Override
		protected Medication handle(Medication med) {
	        // get the default type/category classification
	        MedType type = DrugTherapy.MedType.typeOf(med);
	        String dispName = med.getQualifiedName();
	        String key = type.getGroup() + ":" + dispName;

	        // Initialize a new DrugTherapy if we don't have one yet and add the med to it
	        DrugTherapy dt = data.get(key);
	        if (dt == null) {
	        	data.put(key, dt = new DrugTherapy(type, dispName));
	        }
	        dt.addMed(med);
	        med.save(DAO);
	        medCount++;
	        return med;
		}
	};

	@BeforeClass
	public static void setup() throws URISyntaxException, IOException {

		// setup mock methods for save/find
		when(DAO.findByUID((Class<DrugTherapy>) any(), anyString())).thenAnswer(new Answer<DrugTherapy>() {
			@Override
			public DrugTherapy answer(InvocationOnMock invocation) throws Throwable {
				String uid = (String) invocation.getArguments()[1];
				return DAO_DATA.get(uid);
			}
		});

		when(DAO.save(Matchers.any(DrugTherapy.class))).thenAnswer(new Answer<DrugTherapy>() {
			@Override
			public DrugTherapy answer(InvocationOnMock invocation) throws Throwable {
				DrugTherapy dt = (DrugTherapy) invocation.getArguments()[0];
				DAO_DATA.put(dt.getUid(), dt);
				return dt;
		}});

		// load all the data
		if (data.isEmpty()) {
			File file = new File(DrugTherapyTest.class.getResource("avivapatient.six.20140304.zip").toURI());
			meds = LOADER.loadZipFile(file, "5000000346","med");
		}
	}

	@Test
	public void testBasicGroups() {
		// PT 6 has 183 records collapsed into 64 therapy objects
		assertEquals(183, medCount);
		assertEquals(52, data.size());

		// check for one med that should be in each of 5 categories
		assertTrue(data.containsKey("Inpatient Meds:MORPHINE INJ"));
		assertTrue(data.containsKey("Outpatient Meds:ACETAMINOPHEN TAB"));
		assertTrue(data.containsKey("Non-VA Meds:ACETAMINOPHEN TAB"));
		assertTrue(data.containsKey("Clinic Orders:MORPHINE INJ"));
	}

	@Test
	public void testClinicOrder() {
		// clinic order: morphine has 1 order
		DrugTherapy dt = data.get("Clinic Orders:MORPHINE INJ");
		assertEquals("MORPHINE INJ", dt.getName());
		assertTrue(dt.hasMeds());
		assertEquals(1, dt.getMeds().size());
		assertEquals(DrugTherapy.MedType.IMO, dt.getType());
		assertFalse(dt.isRecent());
		assertTrue(dt.getPrimary().isIMO());
	}

	@Test
	public void testExternalMeds() {
		// external meds has 2 groups, one of which is ACETAMINOPHEN TAB
		DrugTherapy dt = data.get("Non-VA Meds:ACETAMINOPHEN TAB");
		assertTrue(dt.hasMeds());
		assertEquals(1, dt.getMeds().size());
		assertEquals(DrugTherapy.MedType.NonVA, dt.getType());
		assertTrue(dt.getPrimary().isNonVA());
	}

	@Test
	public void testOutpatientMeds() {
		// outpatient meds has 15, one of which is ACETAMINOPHEN TAB
		DrugTherapy dt = data.get("Outpatient Meds:ACETAMINOPHEN TAB");
		assertTrue(dt.hasMeds());
		assertEquals(1, dt.getMeds().size());
		assertEquals(DrugTherapy.MedType.OutPRN, dt.getType());
		assertTrue(dt.getPrimary().isOutPatient());
		assertTrue(dt.getPrimary().isPRN());
	}

	@Test
	public void testInpatientMORPHINE() {
		// there are 2 inpatient MORPHINE TAB orders, 1 is current, 1 is old
		DrugTherapy dt = data.get(MedType.InPT.getGroup() + ":MORPHINE INJ");
		assertTrue(dt.hasMeds());
		assertEquals(2, dt.getMeds().size());
		assertEquals(DrugTherapy.MedType.PRN, dt.getType());
		assertTrue(dt.getPrimary().isInPatient());
		assertTrue(dt.getPrimary().isPRN());
		assertEquals(new PointInTime("201307091500"), dt.getTherapyStart());
		assertEquals(new PointInTime("201407211400"), dt.getTherapyStop());

		// min/max dose is 2mg Q6H=12mg/daily
		Float[] vals = dt.calcDoseRange();
		assertNotNull(vals);
		assertEquals(4, vals.length);
		assertEquals(12.0f, vals[0], 0);
		assertEquals(12.0f, vals[1], 0);
		assertEquals(2.0f, vals[2], 0);
		assertEquals(2.0f, vals[3], 0);
	}

	@Test
	public void testOutpatientVENLAFAXINE() {
		// there are 5 outpatient VENLAFAXINE CAP,SA orders
		DrugTherapy dt = data.get(MedType.OutPT.getGroup() + ":VENLAFAXINE CAP,SA");

		assertTrue(dt.hasMeds());
		assertEquals(5, dt.getMeds().size());
		assertEquals(DrugTherapy.MedType.OutPT, dt.getType());
		assertTrue(dt.getPrimary().isOutPatient());
		assertEquals(8, dt.getAllFills().size());
		assertEquals(new PointInTime("20081119"), dt.getTherapyStart());
		assertEquals(new PointInTime("20140722"), dt.getTherapyStop());

		// 2 doses in this history: 75mg BID (150mg/day) and and 225mg daily (225/day)
		Float[] vals = dt.calcDoseRange();
		assertNotNull(vals);
		assertEquals(4, vals.length);
		assertEquals(150.0f, vals[0], 0); // minDD
		assertEquals(225.0f, vals[1], 0); // maxDD
		assertEquals(75f, vals[2], 0); // minDose
		assertEquals(225f, vals[3], 0); // maxDose

	}

	@Test
	@Ignore
	public void testInpatientGeneric() {
		// loop through all recent inpatient DrugTherapy groups
		for (String key : data.keySet()) {
//			System.out.println("TEsting: " + dt.getPrimary().getUid());
			DrugTherapy dt = data.get(key);
			assertNotNull(dt);
			assertTrue(dt.hasMeds());
			assertEquals(dt.getName(), key.split(":")[1]);

			if (key.startsWith("Inpatient Meds")) {
				assertTrue(dt.getPrimary().isInPatient());
			} else if (key.startsWith("External Meds")) {
				assertTrue(dt.getPrimary().isNonVA());
			} else if (key.startsWith("Outpatient Meds")) {
				assertTrue(dt.getPrimary().isOutPatient());
			}

			testGeneric(dt);
		}
	}

	private void testGeneric(DrugTherapy dt) {
		// meds are sorted by date desc, therefore meds.first() == therapystop and meds.last() == therapystart
		// TODO: this isn't always true, need to re-evaluate
//		assertEquals(dt.getTherapyStop(), dt.getMeds().first().getOverallStop());
//		assertEquals(dt.getTherapyStart(), dt.getMeds().last().getOverallStart());

		// test the map
		Medication prim = dt.getPrimary();
		MedType type = dt.getType();
		Map<String,Object> map = dt.buildRow(new HashMap<String,Object>(), new MSCUIDateTimePrinterSet());
		assertEquals(dt.getName(), map.get("name"));
		assertEquals(type.getGroup(), map.get("groupName"));
		assertEquals(prim.getUid(), map.get("uid"));
		assertEquals(DrugTherapy.MedStatus.statusOf(prim).displayName(), map.get("vaStatus"));

		// not inpatient? Should never have a last admin
		if (!prim.isInPatient()) {
			assertNull(dt.getLastAdmin());
		}

		// if it does have last admin, ensure its the latest admin ever
		if (dt.getLastAdmin() != null) {
			int adminCount = 0;
			for (Medication med : dt.getMeds()) {
				for (MedicationAdministration admin : med.getAdministrations()) {
					assertTrue(admin.getDateTime().equals(dt.getLastAdmin()) ||
							admin.getDateTime().before(dt.getLastAdmin()));
					adminCount++;
				}
			}
			assertEquals(adminCount, dt.getAllAdmins().size());
		} else {
			// if no last admin, should have no admins
			assertTrue(dt.getAllAdmins().isEmpty());
			assertTrue(prim.getAdministrations().isEmpty());
		}

		// not outpatient? should never have a last fill
		if (!prim.isOutPatient()) {
			assertNull(dt.getLastFill());
		}

		// if it does have a last fill, ensure its the lastest fill ever
		if (dt.getLastFill() != null) {
			int fillCount = 0;
			for (Medication med : dt.getMeds()) {
				for (MedicationFill fill : med.getFills()) {
					fillCount++;
					Object partial = fill.getProperty("partial");
					if (partial != null && partial.equals(1)) continue; // skip this
					assertTrue(fill.getDispenseDate().equals(dt.getLastFill()) ||
							fill.getDispenseDate().before(dt.getLastFill()));
				}
			}
			assertEquals(fillCount, dt.getAllFills().size());
		} else {
			// if no last fill, should have no fills anywhere
			assertTrue(dt.getAllFills().isEmpty());
			assertTrue(prim.getFills().isEmpty());
		}

		// test daily dose
		testGenericDailyDose(dt);

		// TODO: How to test
		// tagline
		// status
		// doseStr
		// doseScheduleStr
		// svg
		// selfLink
	}

	private void testGenericDailyDose(DrugTherapy dt) {
		// nothing should have daily dose b/c they are all old
		Number dd = dt.getDailyDose();
		if (dd != null) {
			// check all the meds/doses
			int activeCnt = 0;
			String units = dt.getPrimary().getUnits();
			for (Medication med : dt.getMeds()) {
				if (med.isActive()) {
					activeCnt++;
				}

				// all units should be the same
				assertEquals(units, med.getUnits());
				for (MedicationDose dose : med.getDosages()) {
					assertEquals(units, dose.getUnits());

					// must have > daily dose frequencies
					Integer freq = dose.getScheduleFreq();
					if (freq != null) {
						assertTrue(freq < 1440);
					}
				}
			}

			// must have active meds
			assertTrue(activeCnt > 0);

			// must be different than main dose value
			assertFalse(dd.equals(dt.getPrimary().getDosages().get(0).calcDailyDose()));
		}

	}

	@Test
	public void testDailyDose() {

		// create a DrugTherapy with 2 active orders for Warfarin representing 7MG daily

		// m1 dose = 2MG DAILY
		Medication m1 = new Medication();
		m1.setData("uid", "urn:foo:bar:warfarin:AAA");
		m1.setData("vaType", "O");
		m1.setData("vaStatus", "ACTIVE");
		m1.setData("overallStart", PointInTime.today());
		m1.setData("overallStop", PointInTime.today().addDays(7));

		Medication m2 = new Medication();
		m2.setData("uid", "urn:foo:bar:warfarin:BBB");
		m2.setData("vaType", "O");
		m2.setData("vaStatus", "ACTIVE");
		m2.setData("overallStart", PointInTime.today());
		m2.setData("overallStop", PointInTime.today().addDays(7));

		Map<String, Object> d1 = new HashMap<>();
		d1.put("doseVal", 2);
		d1.put("units", "MG");
		d1.put("scheduleFreq", 1440);
		m1.setData("dosages", Arrays.asList(d1));

		// m2 dose = 5MG DAILY
		Map<String, Object> d2 = new HashMap<>();
		d2.put("doseVal", 5);
		d2.put("units", "MG");
		d2.put("scheduleFreq", 1440);
		m2.setData("dosages", Arrays.asList(d2));

		// setup our test
		MedicationDose dose1 = m1.getDosages().get(0);
		MedicationDose dose2 = m2.getDosages().get(0);
		DrugTherapy dt = new DrugTherapy(MedType.OutPT, "Warfarin");
		dt.addMed(m1);
		assertEquals(2, m1.getDailyDose());

		// total daily dose with just the first med should be 2, but will
		// return null since its <= daily frequency
		assertNull(dt.getDailyDose());

		dt.addMed(m2);
		assertEquals(5, m2.getDailyDose());

		// total daily dose should be 7MG (and even though they are both <= daily, they
		// should return since there are two orders)
		assertEquals(7, dt.getDailyDose());

		// should be not null if greater than daily
		dose1.setData("scheduleFreq", 720);
		dose2.setData("scheduleFreq", 720);
		assertEquals(14, dt.getDailyDose());

		// prefix should initially be total daily
		assertEquals("Total daily", dt.getDailyDosePrefix());

		// prefix should change to max daily for PRN
		dose1.setData("scheduleName", "BID PRN");
		assertEquals("Max daily", dt.getDailyDosePrefix());
	}

	@Test
	public void testStatusCounts() {

		/* uncomment to list
		for (String key : data.keySet()) {
			DrugTherapy dt = data.get(key);
			System.out.println("KEY=" + key);

			for (MedStatus ms : MedStatus.values()) {
				System.out.printf("\t%s=%s\n", ms.name(), dt.getStatusCount(ms));
			}
		}
		*/

		// Outpatient Meds:CALCIUM CARBONATE TAB has 1 pending
		assertEquals(1, data.get("Outpatient Meds:CALCIUM CARBONATE TAB").getStatusCount(MedStatus.PENDING));

		// Inpatient Meds:SIMVASTATIN TAB has 1 active
		assertEquals(1, data.get("Inpatient Meds:SIMVASTATIN TAB").getStatusCount(MedStatus.ACTIVE));

		// Outpatient Meds:GLYBURIDE TAB has 9 DISCONTINUED
		assertEquals(9, data.get("Outpatient Meds:GLYBURIDE TAB").getStatusCount(MedStatus.DISCONTINUED));

		// Outpatient Meds:ASPIRIN TAB,EC has 2 EXPIRED
		assertEquals(2, data.get("Outpatient Meds:ASPIRIN TAB,EC").getStatusCount(MedStatus.EXPIRED));
	}

	@Test
	public void testIsRecent() {
		// bulk testing isRecent by creating a new DrugTherapy for each individual Medication record
		// and comparing DrugTherapy.isRecent() to Medication.isRecent()

		for (Medication med : meds) {
			DrugTherapy dt = new DrugTherapy(MedType.typeOf(med), "FOO");
			dt.addMed(med);
			assertEquals(med.isRecent(), dt.isRecent());
		}
	}

	@Test
	public void testMedStatus() {
		Medication med = new Medication();
		assertSame(MedStatus.OTHER, MedStatus.statusOf(med));

		med.setData("vaStatus", "ACTIVE");
		assertSame(MedStatus.ACTIVE, MedStatus.statusOf(med));

		med.setData("vaStatus", "CANCELED");
		assertSame(MedStatus.CANCELED, MedStatus.statusOf(med));

		med.setData("vaStatus", "DISCONTINUED");
		assertSame(MedStatus.DISCONTINUED, MedStatus.statusOf(med));

		med.setData("vaStatus", "DISCONTINUED/EDIT");
		assertSame(MedStatus.DISCONTINUEDEDIT, MedStatus.statusOf(med));

		med.setData("vaStatus", "EXPIRED");
		assertSame(MedStatus.EXPIRED, MedStatus.statusOf(med));

		med.setData("vaStatus", "HOLD");
		assertSame(MedStatus.HOLD, MedStatus.statusOf(med));

		med.setData("vaStatus", "foo");
		assertSame(MedStatus.OTHER, MedStatus.statusOf(med));

		med.setData("vaStatus", "PENDING");
		assertSame(MedStatus.PENDING, MedStatus.statusOf(med));

		med.setData("vaStatus", "SUSPEND");
		assertSame(MedStatus.SUSPEND, MedStatus.statusOf(med));
	}

	@Test
	public void testMedType() {
		Medication med = new Medication();

		assertSame(MedType.Other, MedType.typeOf(med));
	}

//	@Test // broken, work in progress
	public void testSerialization() {
		// how does DrugTherapy.getType() serialize?
		Map<String,Object> map = data.get("Outpatient Meds:ACETAMINOPHEN TAB").getData();
		assertNotNull(map.get("type"));
		assertNotNull(map.get("statusCounts"));
		assertEquals("OutPRN", map.get("type"));

		// should serialize ok
		DrugTherapy dt = new DrugTherapy(map);
		assertEquals(dt.getType(), MedType.OutPRN);
		System.out.println(map);
	}

	public void testCompareAll() {
		assertEquals(data.size(), DAO_DATA.size());
		for (DrugTherapy dt1 : data.values()) {
			// compare that the two objects
			DrugTherapy dt2 = DAO_DATA.get(DrugTherapy.getDrugTherapyUID(dt1.getPrimary()));
			assertNotNull(dt2);
			assertNotSame(dt1,dt2);

			assertEquals(dt1.getName(), dt2.getName());
			assertEquals(dt1.getTherapyStart(), dt2.getTherapyStart());
			assertEquals(dt1.getTherapyStop(), dt2.getTherapyStop());
			assertEquals(dt1.getMeds().size(), dt2.getMeds().size());

			// check the fields that go to the ViewDefGridPanel for consistency
			Map<String,Object> data1=dt1.buildRow(new HashMap<String,Object>(), FORMATTER), data2=dt2.getData();

			assertNotEquals(data1.get("uid"), data2.get("uid"));
			assertEquals(data1.get("name"), data2.get("name"));
			assertEquals(data1.get("groupName"), data2.get("groupName"));
			assertEquals(nvl(data1.get("lastAdmin")), data2.get("lastAdmin"));
			assertEquals(nvl(data1.get("lastFill")), data2.get("lastFill"));

			// fields in MedsPanel.js (need to be serialized): name,groupName,tagline(lastFill,fillsRemain,fillDays,cssClass),doseStr,dailyDose,dailyDosePrefix,dailyDoseUnits,doseScheduleStr,status,svg
			// fields in medicationhistory.vm (not serialized): lastAdmin,lastFill,overallStart,overallStop,.....

			// TODO: check additional fields that will be stored in JDS

			// fields in buildRow() not in getData(): renewBy
			//doseScheduleStr,svg,status,vaStatus,selfLink,orderCount,doseStr,vaType,dailyDosePrefix,dailyDoseUnits,medType,tagline

//			assertEquals(data1.size(), data2.size());
//			for (String key : data1.keySet()) {
//				Object val1 = data1.get(key), val2 = data2.get(key);
//				assertEquals(val1,val2);
//			}

//			SortedSet<Medication> meds1 = dt1.getMeds();
//			SortedSet<Medication> meds2 = dt2.getMeds();

		}
	}

	private static String nvl(Object val) {
		return nvl(val, null);
	}

	private static String nvl(Object val, String ifnull) {
		return (val == null) ? ifnull : val.toString();
	}
}


text:
testing how github works
[2]adding new content to readme file


text:
/**
 *
 */
package ca.phon.opgraph.io;

import java.io.*;

import ca.phon.opgraph.*;

/**
 * An interface for any class providing OpGraph serialization services.
 */
public interface OpGraphSerializer {

	/**
	 * Validate a graph
	 *
	 * @param file
	 *
	 * @throws IOException if a validation error occurs
	 */
	public abstract void validate(File file) throws IOException;

	/**
	 * Validate a graph
	 *
	 * @param stream
	 *
	 * @throws IOException if a validation error occurs
	 */
	public abstract void validate(InputStream stream) throws IOException;

	/**
	 * Writes a graph to a file.
	 *
	 * @param graph  the graph to write
	 * @param file  the stream to write to
	 *
	 * @throws IOException  if any I/O errors occur
	 */
	public abstract void write(OpGraph graph, File file) throws IOException;

	/**
	 * Writes a graph to a stream.
	 *
	 * @param graph  the graph to write
	 * @param stream  the stream to write to
	 *
	 * @throws IOException  if any I/O errors occur
	 */
	public abstract void write(OpGraph graph, OutputStream stream) throws IOException;

	/**
	 * Reads a graph from a given file.
	 *
	 * @param file  the stream to read from
	 *
	 * @return the {@link OpGraph} that was read from the given stream
	 *
	 * @throws IOException  if any I/O errors occur
	 */
	public abstract OpGraph read(File file) throws IOException;

	/**
	 * Reads a graph from a given stream.
	 *
	 * @param stream  the stream to read from
	 *
	 * @return the {@link OpGraph} that was read from the given stream
	 *
	 * @throws IOException  if any I/O errors occur
	 */
	public abstract OpGraph read(InputStream stream) throws IOException;
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM /home/vbox/tinderbox/4.3-sdk/src/libs/xpcom18a4/xpcom/io/nsIAsyncOutputStream.idl
 */

#ifndef __gen_nsIAsyncOutputStream_h__
#define __gen_nsIAsyncOutputStream_h__

#ifndef __gen_nsIOutputStream_h__
#include "nsIOutputStream.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIOutputStreamCallback; /* forward declaration */

class nsIEventTarget; /* forward declaration */

/* starting interface:    nsIAsyncOutputStream */
#define NS_IASYNCOUTPUTSTREAM_IID_STR "10dc9c94-8aff-49c6-8af9-d7fdb7339dae"

#define NS_IASYNCOUTPUTSTREAM_IID \
  {0x10dc9c94, 0x8aff, 0x49c6, \
    { 0x8a, 0xf9, 0xd7, 0xfd, 0xb7, 0x33, 0x9d, 0xae }}

/**
 * If an output stream is non-blocking, it may return NS_BASE_STREAM_WOULD_BLOCK
 * when written to.  The caller must then wait for the stream to become
 * writable.  If the stream implements nsIAsyncOutputStream, then the caller can
 * use this interface to request an asynchronous notification when the stream
 * becomes writable or closed (via the AsyncWait method).
 *
 * While this interface is almost exclusively used with non-blocking streams, it
 * is not necessary that nsIOutputStream::isNonBlocking return true.  Nor is it
 * necessary that a non-blocking nsIOutputStream implementation also implement
 * nsIAsyncOutputStream.
 */
class NS_NO_VTABLE nsIAsyncOutputStream : public nsIOutputStream {
 public:

  NS_DEFINE_STATIC_IID_ACCESSOR(NS_IASYNCOUTPUTSTREAM_IID)

  /**
     * This method closes the stream and sets its internal status.  If the
     * stream is already closed, then this method is ignored.  Once the stream
     * is closed, the stream's status cannot be changed.  Any successful status
     * code passed to this method is treated as NS_BASE_STREAM_CLOSED, which
     * is equivalent to nsIInputStream::close.
     *
     * NOTE: this method exists in part to support pipes, which have both an
     * input end and an output end.  If the output end of a pipe is closed, then
     * reads from the input end of the pipe will fail.  The error code returned
     * when an attempt is made to read from a "closed" pipe corresponds to the
     * status code passed in when the output end of the pipe is closed, which
     * greatly simplifies working with pipes in some cases.
     *
     * @param aStatus
     *        The error that will be reported if this stream is accessed after
     *        it has been closed.
     */
  /* void closeWithStatus (in nsresult reason); */
  NS_IMETHOD CloseWithStatus(nsresult reason) = 0;

  /**
     * Asynchronously wait for the stream to be writable or closed.  The
     * notification is one-shot, meaning that each asyncWait call will result
     * in exactly one notification callback.  After the OnOutputStreamReady event
     * is dispatched, the stream releases its reference to the
     * nsIOutputStreamCallback object.  It is safe to call asyncWait again from the
     * notification handler.
     *
     * This method may be called at any time (even if write has not been called).
     * In other words, this method may be called when the stream already has
     * room for more data.  It may also be called when the stream is closed.  If
     * the stream is already writable or closed when AsyncWait is called, then the
     * OnOutputStreamReady event will be dispatched immediately.  Otherwise, the
     * event will be dispatched when the stream becomes writable or closed.
     *
     * @param aCallback
     *        This object is notified when the stream becomes ready.
     * @param aFlags
     *        This parameter specifies optional flags passed in to configure
     *        the behavior of this method.  Pass zero to specify no flags.
     * @param aRequestedCount
     *        Wait until at least this many bytes can be written.  This is only
     *        a suggestion to the underlying stream; it may be ignored.  The
     *        caller may pass zero to indicate no preference.
     * @param aEventTarget
     *        Specify NULL to receive notification on ANY thread (possibly even
     *        recursively on the calling thread -- i.e., synchronously), or
     *        specify that the notification be delivered to a specific event
     *        target.
     */
  /* void asyncWait (in nsIOutputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsIEventTarget aEventTarget); */
  NS_IMETHOD AsyncWait(nsIOutputStreamCallback *aCallback, PRUint32 aFlags, PRUint32 aRequestedCount, nsIEventTarget *aEventTarget) = 0;

  /**
     * If passed to asyncWait, this flag overrides the default behavior,
     * causing the OnOutputStreamReady notification to be suppressed until the
     * stream becomes closed (either as a result of closeWithStatus/close being
     * called on the stream or possibly due to some error in the underlying
     * stream).
     */
  enum { WAIT_CLOSURE_ONLY = 1U };

};

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIASYNCOUTPUTSTREAM \
  NS_IMETHOD CloseWithStatus(nsresult reason); \
  NS_IMETHOD AsyncWait(nsIOutputStreamCallback *aCallback, PRUint32 aFlags, PRUint32 aRequestedCount, nsIEventTarget *aEventTarget); \

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIASYNCOUTPUTSTREAM(_to) \
  NS_IMETHOD CloseWithStatus(nsresult reason) { return _to CloseWithStatus(reason); } \
  NS_IMETHOD AsyncWait(nsIOutputStreamCallback *aCallback, PRUint32 aFlags, PRUint32 aRequestedCount, nsIEventTarget *aEventTarget) { return _to AsyncWait(aCallback, aFlags, aRequestedCount, aEventTarget); } \

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIASYNCOUTPUTSTREAM(_to) \
  NS_IMETHOD CloseWithStatus(nsresult reason) { return !_to ? NS_ERROR_NULL_POINTER : _to->CloseWithStatus(reason); } \
  NS_IMETHOD AsyncWait(nsIOutputStreamCallback *aCallback, PRUint32 aFlags, PRUint32 aRequestedCount, nsIEventTarget *aEventTarget) { return !_to ? NS_ERROR_NULL_POINTER : _to->AsyncWait(aCallback, aFlags, aRequestedCount, aEventTarget); } \

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsAsyncOutputStream : public nsIAsyncOutputStream
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIASYNCOUTPUTSTREAM

  nsAsyncOutputStream();

private:
  ~nsAsyncOutputStream();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsAsyncOutputStream, nsIAsyncOutputStream)

nsAsyncOutputStream::nsAsyncOutputStream()
{
  /* member initializers and constructor code */
}

nsAsyncOutputStream::~nsAsyncOutputStream()
{
  /* destructor code */
}

/* void closeWithStatus (in nsresult reason); */
NS_IMETHODIMP nsAsyncOutputStream::CloseWithStatus(nsresult reason)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void asyncWait (in nsIOutputStreamCallback aCallback, in unsigned long aFlags, in unsigned long aRequestedCount, in nsIEventTarget aEventTarget); */
NS_IMETHODIMP nsAsyncOutputStream::AsyncWait(nsIOutputStreamCallback *aCallback, PRUint32 aFlags, PRUint32 aRequestedCount, nsIEventTarget *aEventTarget)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

/* starting interface:    nsIOutputStreamCallback */
#define NS_IOUTPUTSTREAMCALLBACK_IID_STR "40dbcdff-9053-42c5-a57c-3ec910d0f148"

#define NS_IOUTPUTSTREAMCALLBACK_IID \
  {0x40dbcdff, 0x9053, 0x42c5, \
    { 0xa5, 0x7c, 0x3e, 0xc9, 0x10, 0xd0, 0xf1, 0x48 }}

class NS_NO_VTABLE nsIOutputStreamCallback : public nsISupports {
 public:

  NS_DEFINE_STATIC_IID_ACCESSOR(NS_IOUTPUTSTREAMCALLBACK_IID)

  /**
 * This is a companion interface for nsIAsyncOutputStream::asyncWait.
 */
/**
     * Called to indicate that the stream is either writable or closed.
     *
     * @param aStream
     *        The stream whose asyncWait method was called.
     */
  /* void onOutputStreamReady (in nsIAsyncOutputStream aStream); */
  NS_IMETHOD OnOutputStreamReady(nsIAsyncOutputStream *aStream) = 0;

};

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIOUTPUTSTREAMCALLBACK \
  NS_IMETHOD OnOutputStreamReady(nsIAsyncOutputStream *aStream);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIOUTPUTSTREAMCALLBACK(_to) \
  NS_IMETHOD OnOutputStreamReady(nsIAsyncOutputStream *aStream) { return _to OnOutputStreamReady(aStream); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIOUTPUTSTREAMCALLBACK(_to) \
  NS_IMETHOD OnOutputStreamReady(nsIAsyncOutputStream *aStream) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnOutputStreamReady(aStream); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsOutputStreamCallback : public nsIOutputStreamCallback
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIOUTPUTSTREAMCALLBACK

  nsOutputStreamCallback();

private:
  ~nsOutputStreamCallback();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsOutputStreamCallback, nsIOutputStreamCallback)

nsOutputStreamCallback::nsOutputStreamCallback()
{
  /* member initializers and constructor code */
}

nsOutputStreamCallback::~nsOutputStreamCallback()
{
  /* destructor code */
}

/* void onOutputStreamReady (in nsIAsyncOutputStream aStream); */
NS_IMETHODIMP nsOutputStreamCallback::OnOutputStreamReady(nsIAsyncOutputStream *aStream)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIAsyncOutputStream_h__ */


text:
using ExtendedXmlSerializer.Core.Specifications;
using System.Reflection;

namespace ExtendedXmlSerializer.ContentModel.Members
{
	sealed class PropertyMemberSpecification : ISpecification<PropertyInfo>
	{
		public static PropertyMemberSpecification Default { get; } = new PropertyMemberSpecification();

		PropertyMemberSpecification() {}

		public bool IsSatisfiedBy(PropertyInfo parameter)
		{
			var getMethod = parameter.GetGetMethod(true);
			var result = parameter.CanRead && !getMethod.IsStatic && getMethod.IsPublic
			             &&
			             !(!parameter.GetSetMethod(true)?.IsPublic ?? false)
			             &&
			             parameter.GetIndexParameters().Length <= 0;
			return result;
		}
	}
}


text:
require 'digest/sha1'

module Globalize
  module ActiveRecord
    module Migration
      attr_reader :globalize_migrator

      def globalize_migrator
        @globalize_migrator ||= Migrator.new(self)
      end

      delegate :create_translation_table!, :add_translation_fields!, :drop_translation_table!,
        :translation_index_name, :translation_locale_index_name,
        to: :globalize_migrator

      class Migrator
        include Globalize::ActiveRecord::Exceptions

        attr_reader :model, :fields
        delegate :translated_attribute_names, :connection, :table_name,
          :table_name_prefix, :translations_table_name, :columns, to: :model

        def initialize(model)
          @model = model
        end

        def create_translation_table!(fields = {}, options = {})
          @fields = fields
          # If we have fields we only want to create the translation table with those fields
          complete_translated_fields if fields.blank?
          validate_translated_fields

          create_translation_table
          add_translation_fields!(fields, options)
          create_translations_index
          clear_schema_cache!
        end

        def add_translation_fields!(fields, options = {})
          @fields = fields
          validate_translated_fields

          add_translation_fields
          clear_schema_cache!
          move_data_to_translation_table if options[:migrate_data]
          remove_source_columns if options[:remove_source_columns]
          clear_schema_cache!
        end

        def remove_source_columns
          connection.remove_columns(table_name, *fields.keys)
        end

        def drop_translation_table!(options = {})
          move_data_to_model_table if options[:migrate_data]
          drop_translations_index
          drop_translation_table
          clear_schema_cache!
        end

        # This adds all the current translated attributes of the model
        # It's a problem because in early migrations would add all the translated attributes
        def complete_translated_fields
          translated_attribute_names.each do |name|
            fields[name] = column_type(name) unless fields[name]
          end
        end

        def create_translation_table
          connection.create_table(translations_table_name) do |t|
            t.references table_name.sub(/^#{table_name_prefix}/, '').singularize
            t.string :locale
            t.timestamps
          end
        end

        def add_translation_fields
          connection.change_table(translations_table_name) do |t|
            fields.each do |name, options|
              if options.is_a? Hash
                t.column name, options.delete(:type), options
              else
                t.column name, options
              end
            end
          end
        end

        def create_translations_index
          connection.add_index(
            translations_table_name,
            "#{table_name.sub(/^#{table_name_prefix}/, "").singularize}_id",
            name: translation_index_name
          )
          # index for select('DISTINCT locale') call in translation.rb
          connection.add_index(
            translations_table_name,
            :locale,
            name: translation_locale_index_name
          )
        end

        def drop_translation_table
          connection.drop_table(translations_table_name)
        end

        def drop_translations_index
          connection.remove_index(translations_table_name, name: translation_index_name)
        end

        def move_data_to_translation_table
          model.find_each do |record|
            translation = record.translation_for(I18n.default_locale) || record.translations.build(locale: I18n.default_locale)
            fields.each do |attribute_name, attribute_type|
              translation[attribute_name] = record.read_attribute(attribute_name, {translated: false})
            end
            translation.save!
          end
        end

        def move_data_to_model_table
          add_missing_columns

          # Find all of the translated attributes for all records in the model.
          all_translated_attributes = @model.all.collect{|m| m.attributes}
          all_translated_attributes.each do |translated_record|
            # Create a hash containing the translated column names and their values.
            translated_attribute_names.inject(fields_to_update={}) do |f, name|
              f.update({name.to_sym => translated_record[name.to_s]})
            end

            # Now, update the actual model's record with the hash.
            @model.where(id: translated_record['id']).update_all(fields_to_update)
          end
        end

        def validate_translated_fields
          fields.each do |name, options|
            raise BadFieldName.new(name) unless valid_field_name?(name)
            if options.is_a? Hash
              raise BadFieldType.new(name, options[:type]) unless valid_field_type?(name, options[:type])
            else
              raise BadFieldType.new(name, options) unless valid_field_type?(name, options)
            end
          end
        end

        def column_type(name)
          columns.detect { |c| c.name == name.to_s }.try(:type)
        end

        def valid_field_name?(name)
          translated_attribute_names.include?(name)
        end

        def valid_field_type?(name, type)
          !translated_attribute_names.include?(name) || [:string, :text].include?(type)
        end

        def translation_index_name
          index_name = "index_#{translations_table_name}_on_#{table_name.singularize}_id"
          index_name.size < connection.index_name_length ? index_name :
            "index_#{Digest::SHA1.hexdigest(index_name)}"[0, connection.index_name_length]
        end

        def translation_locale_index_name
          index_name = "index_#{translations_table_name}_on_locale"
          index_name.size < connection.index_name_length ? index_name :
            "index_#{Digest::SHA1.hexdigest(index_name)}"[0, connection.index_name_length]
        end

        def clear_schema_cache!
          connection.schema_cache.clear! if connection.respond_to? :schema_cache
          model::Translation.reset_column_information
          model.reset_column_information
        end

        private

        def add_missing_columns
          translated_attribute_names.map(&:to_s).each do |attribute|
            unless model.column_names.include?(attribute)
              connection.add_column(table_name, attribute, model::Translation.columns_hash[attribute].type)
            end
          end
        end
      end
    end
  end
end


text:
\textbf{Входные параметры:}

 VHML\_ResultVector --- указатель на массив;

 Left --- левые границы интервалов (размер VHML\_N);

 Right --- правые границы интервалов (размер VHML\_N)

 VHML\_N --- размер массива.

\textbf{Возвращаемое значение:}
Отсутствует.


text:
from __future__ import unicode_literals

from django.apps.registry import Apps
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.timezone import now

class MigrationRecorder(object):
    """
    Deals with storing migration records in the database.

    Because this table is actually itself used for dealing with model
    creation, it's the one thing we can't do normally via syncdb or migrations.
    We manually handle table creation/schema updating (using schema backend)
    and then have a floating model to do queries with.

    If a migration is unapplied its row is removed from the table. Having
    a row in the table always means a migration is applied.
    """

    @python_2_unicode_compatible
    class Migration(models.Model):
        app = models.CharField(max_length=255)
        name = models.CharField(max_length=255)
        applied = models.DateTimeField(default=now)

        class Meta:
            apps = Apps()
            app_label = "migrations"
            db_table = "django_migrations"

        def __str__(self):
            return "Migration %s for %s" % (self.name, self.app)

    def __init__(self, connection):
        self.connection = connection

    @property
    def migration_qs(self):
        return self.Migration.objects.using(self.connection.alias)

    def ensure_schema(self):
        """
        Ensures the table exists and has the correct schema.
        """
        # If the table's there, that's fine - we've never changed its schema
        # in the codebase.
        if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
            return
        # Make the table
        with self.connection.schema_editor() as editor:
            editor.create_model(self.Migration)

    def applied_migrations(self):
        """
        Returns a set of (app, name) of applied migrations.
        """
        self.ensure_schema()
        return set(tuple(x) for x in self.migration_qs.values_list("app", "name"))

    def record_applied(self, app, name):
        """
        Records that a migration was applied.
        """
        self.ensure_schema()
        self.migration_qs.create(app=app, name=name)

    def record_unapplied(self, app, name):
        """
        Records that a migration was unapplied.
        """
        self.ensure_schema()
        self.migration_qs.filter(app=app, name=name).delete()

    def flush(self):
        """
        Deletes all migration records. Useful if you're testing migrations.
        """
        self.migration_qs.all().delete()


text:
#include "Core.h"

#define LLOG(x)

#include <plugin/bz2/bz2.h>

String LocalHost::GetEnvironment()
{
	return environment;
}

String LocalHost::GetHostPath(const String& path)
{
	return path;
}

String LocalHost::GetLocalPath(const String& path)
{
	return path;
}

String LocalHost::NormalizePath(const String& path)
{
	return ::NormalizePath(path);
}

Vector<Host::FileInfo> LocalHost::GetFileInfo(const Vector<String>& path)
{
	Vector<FileInfo> fi;
	for(int i = 0; i < path.GetCount(); i++) {
		FindFile ff(path[i]);
		FileInfo& f = fi.Add();
		if(ff) {
			(Time&)f = ff.GetLastWriteTime();
#ifdef PLATFORM_WIN32
			f.second = f.second & ~1; // FAT vs NTFS accuracy fix
#endif
			f.length = ff.IsFile() ? (int)ff.GetLength() : -1;
		}
		else {
			(Time&)f = Time::Low();
			f.length = Null;
		}
	}
	return fi;
}

void LocalHost::DeleteFile(const Vector<String>& path)
{
	for(int i = 0; i < path.GetCount(); i++)
		::DeleteFile(path[i]);
}

void LocalHost::DeleteFolderDeep(const String& folder)
{
	::DeleteFolderDeep(folder);
}

void LocalHost::ChDir(const String& path)
{
#ifdef PLATFORM_WIN32
	SetCurrentDirectory(path);
#endif
#ifdef PLATFORM_POSIX
	IGNORE_RESULT( chdir(path) );
#endif
	if(cmdout)
		*cmdout << "cd \"" << GetHostPath(path) << "\"\n";
}

void LocalHost::DoDir(const String& dir)
{
	if(dir.GetLength() > 3) {
		DoDir(GetFileFolder(dir));
		*cmdout << "mkdir \"" << dir << "\"\n";
	}
}

void LocalHost::RealizeDir(const String& path)
{
	RealizeDirectory(path);
	if(cmdout)
		DoDir(path);
}

void    LocalHost::SaveFile(const String& path, const String& data)
{
	::SaveFile(path, data);
}

String  LocalHost::LoadFile(const String& path)
{
	return ::LoadFile(path);
}

int LocalHost::Execute(const char *cmdline)
{
	if(cmdout)
		*cmdout << cmdline << '\n';
	PutVerbose(cmdline);
	int q = IdeConsoleExecute(FindCommand(exedirs, cmdline), NULL, environment, false);
	PutVerbose(Format("Exitcode: %d", q));
	return q;
}

int LocalHost::ExecuteWithInput(const char *cmdline)
{
	if(cmdout)
		*cmdout << cmdline << '\n';
	PutVerbose(cmdline);
	int q = IdeConsoleExecuteWithInput(FindCommand(exedirs, cmdline), NULL, environment, false);
	PutVerbose(Format("Exitcode: %d", q));
	return q;
}

int LocalHost::Execute(const char *cmdline, Stream& out)
{
	PutVerbose(cmdline);
	int q = IdeConsoleExecute(FindCommand(exedirs, cmdline), &out, environment, true);
	PutVerbose(Format("Exitcode: %d", q));
	return q;
}

int LocalHost::AllocSlot()
{
	return IdeConsoleAllocSlot();
}

bool LocalHost::Run(const char *cmdline, int slot, String key, int blitz_count)
{
	return IdeConsoleRun(FindCommand(exedirs, cmdline), NULL, environment, false, slot, key, blitz_count);
}

bool LocalHost::Run(const char *cmdline, Stream& out, int slot, String key, int blitz_count)
{
	return IdeConsoleRun(FindCommand(exedirs, cmdline), &out, environment, true, slot, key, blitz_count);
}

bool LocalHost::Wait()
{
	return IdeConsoleWait();
}

One<AProcess> LocalHost::StartProcess(const char *cmdline)
{
	try {
		PutVerbose(cmdline);
		One<AProcess> p;
		if(p.Create<LocalProcess>().Start(FindCommand(exedirs, cmdline), environment))
			return p;
	}
	catch(...) {
	}
	return NULL;
}

#ifdef PLATFORM_POSIX
//#BLITZ_APPROVE
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

static Vector<int>& sPid()
{
	static Vector<int> q;
	return q;
}

void sCleanZombies(int signal_number)
{
	Vector<int>& pid = sPid();
	int i = 0;
	while(i < pid.GetCount())
		if(pid[i] && waitpid(pid[i], 0, WNOHANG | WUNTRACED) > 0)
			pid.Remove(i);
		else
			i++;
}
#endif

String LinuxHostConsole = "/usr/bin/xterm -e";

void LocalHost::Launch(const char *_cmdline, bool console)
{
	String cmdline = FindCommand(exedirs, _cmdline);
	PutVerbose(cmdline);
#ifdef PLATFORM_WIN32
	if(console)
		cmdline = GetExeFilePath() + " ! " + cmdline;
	int n = cmdline.GetLength() + 1;
	Buffer<char> cmd(n);
	memcpy(cmd, cmdline, n);
	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;
	PROCESS_INFORMATION pi;
	STARTUPINFO si;
	ZeroMemory(&si, sizeof(STARTUPINFO));
	si.cb = sizeof(STARTUPINFO);
	String ev = ToSystemCharset(environment);
	Buffer<char> env(ev.GetCount() + 1);
	memcpy(env, ev, ev.GetCount() + 1);
	if(CreateProcess(NULL, cmd, &sa, &sa, TRUE,
		             NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE,
	                ~env, NULL, &si, &pi)) {
		CloseHandle(pi.hProcess);
		CloseHandle(pi.hThread);
	}
	else
		PutConsole("Unable to launch " + String(_cmdline));
#endif
#ifdef PLATFORM_POSIX
	String script = ConfigFile("console-script-" + AsString(getpid()) + ".tmp");
	String lc;
	static const char *term[] = {
		"/usr/bin/mate-terminal -x",
		"/usr/bin/gnome-terminal -x",
		"/usr/bin/konsole -e",
		"/usr/bin/xterm -e",
	};
	int ii = 0;
	for(;;) { // If (pre)defined terminal emulator is not available, try to find one
		int c = LinuxHostConsole.FindFirstOf(" ");
		lc = c < 0 ? LinuxHostConsole : LinuxHostConsole.Left(c);
		if(ii >= __countof(term) || FileExists(lc))
			break;
		LinuxHostConsole = term[ii++];
	}
	if(FileExists(lc)) {
		if(console) {
			FileStream out(script, FileStream::CREATE, 0777);
			out << "#!/bin/sh\n"
			    << cmdline << '\n'
			    << "echo \"<--- Finished, press any key to close the window --->\"\nread dummy\n";
			cmdline = LinuxHostConsole + " sh " + script;
		}
	}
	else
	if(LinuxHostConsole.GetCount())
		PutConsole("Warning: Terminal '" + lc + "' not found, executing in background.");
	Buffer<char> cmd_buf(strlen(cmdline) + 1);
	char *cmd_out = cmd_buf;
	Vector<char *> args;
	const char *p = cmdline;
	const char *b = p;
	while(*p && (byte)*p > ' ')
		if(*p++ == '\"')
			while(*p && *p++ != '\"')
				;
	args.Add(cmd_out);
	memcpy(cmd_out, b, p - b);
	cmd_out += p - b;
	*cmd_out++ = '\0';

	while(*p)
		if((byte)*p <= ' ')
			p++;
		else {
			args.Add(cmd_out);
			b = p;
			while(*p && (byte)*p > ' ')
				if(*p++ == '\"')
				{
					memcpy(cmd_out, b, p - b - 1);
					cmd_out += p - b - 1;
					b = p;
					while(*p && *p != '\"')
						p++;
					memcpy(cmd_out, b, p - b);
					cmd_out += p - b;
					if(*p == '\"')
						p++;
					b = p;
				}
			memcpy(cmd_out, b, p - b);
			cmd_out += p - b;
			*cmd_out++ = '\0';
		}

	args.Add(NULL);

	ONCELOCK {
		struct sigaction sigchld_action;
		memset(&sigchld_action, 0, sizeof(sigchld_action));
		sigchld_action.sa_handler = sCleanZombies;
		sigaction(SIGCHLD, &sigchld_action, NULL);
	}

	pid_t pid = fork();
	if(pid == 0)
	{
		const char *from = environment;
		Vector<const char *> env;
		while(*from) {
			env.Add(from);
			from += strlen(from) + 1;
		}
		env.Add(NULL);
		const char **envp = env.Begin();
		execve(args[0], args, (char *const *)envp);
		abort();
	}
	LLOG("Launch pid: " << pid);
	sPid().Add(pid);
#endif
}

void LocalHost::AddFlags(Index<String>& cfg)
{
#if   defined(PLATFORM_WIN32)
	cfg.Add("WIN32");
#endif

#ifdef PLATFORM_LINUX
	cfg.Add("LINUX");
#endif

#ifdef PLATFORM_POSIX
	cfg.Add("POSIX");
#endif

#ifdef PLATFORM_BSD
	cfg.Add("BSD");
#endif

#ifdef PLATFORM_FREEBSD
	cfg.Add("FREEBSD");
#endif

#ifdef PLATFORM_OPENBSD
	cfg.Add("OPENBSD");
#endif

#ifdef PLATFORM_NETBSD
	cfg.Add("NETBSD");
#endif

#ifdef PLATFORM_SOLARIS
	cfg.Add("SOLARIS");
#endif

#ifdef PLATFORM_OSX11
	cfg.Add("OSX11");
#endif
}

#if 0
static bool IsSamePath(const char *a, const char *b, int count) {
	for(; --count >= 0; a++, b++)
		if(a != b && ToLower(*a) != ToLower(*b) && !((*a == '\\' || *a == '/') && (*b == '\\' || *b == '/')))
			return false;
	return true;
}

String RemoteHost::GetEnvironment()
{
	return environment;
}

String RemoteHost::GetHostPath(const String& path)
{
	bool slash = (os_type != "WINDOWS");
	for(int i = 0; i < path_map_local.GetCount(); i++) {
		String lc = path_map_local[i];
		if(path.GetLength() >= lc.GetLength() && IsSamePath(path, lc, lc.GetLength()))
		{
			String r = CatAnyPath(path_map_remote[i], path.Mid(lc.GetLength()));
			return slash ? UnixPath(r) : WinPath(r);
		}
	}
	return slash ? UnixPath(path) : WinPath(path);
}

String RemoteHost::GetLocalPath(const String& path)
{
	for(int i = 0; i < path_map_remote.GetCount(); i++) {
		String rc = path_map_remote[i];
		if(path.GetLength() >= rc.GetLength() && IsSamePath(path, rc, rc.GetLength()))
		   return path_map_local[i] + path.Mid(rc.GetLength());
	}
	if(!memcmp(path, "/cygdrive/", 10))
	{
		const char *s = path.Begin() + 10;
		String out;
		if(*s)
			out << *s++ << ':';
		out << s;
		return out;
	}
	return NativePath(path);
}

String RemoteHost::NormalizePath(const String& path)
{
	return path;
}

String RemoteHost::RemoteExec(String cmd)
{
	Socket socket;
	String sockerr;
/*
	String hostname = host;
	int port = 2346;
	int ppos = hostname.Find(':');
	if(ppos >= 0)
	{
		port = atoi(host.GetIter(ppos + 1));
		hostname.Trim(ppos);
	}
*/
	if(!ClientSocket(socket, host, port, true, NULL, 2000)) {
		PutConsole(NFormat("Error connecting to '%s', port %d: %s", host, port, Socket::GetErrorText()));
		return String::GetVoid();
	}
	socket.Write(cmd);
	socket.Write("\0", 1);
	return socket.ReadUntil('\0', Null, 10000000);
}

Vector<Host::FileInfo> RemoteHost::GetFileInfo(const Vector<String>& path)
{
	VectorMap<String, FileInfo> out;
	out.Reserve(path.GetCount());
	String request;
	request << "@" << (int)(GetSysTime() - TimeBase()) << ":";
	for(int i = 0; i < path.GetCount(); i++)
	{
		String hp = GetHostPath(path[i]);
		request << hp << "\n";
		FileInfo& fi = out.Add(hp);
		(Time&)fi = Time::Low();
		fi.length = Null;
	}
	String result = RemoteExec(request);
	const char *p = result;
	while(*p)
	{
		const char *b = p;
		while(*p && *p != '\n' && *p != '\t')
			p++;
		String fn(b, p);
		Time time = Time::Low();
		int size = Null;
		if(*p == '\t')
		{
			int t = ScanInt(p + 1, &p);
			if(!IsNull(t))
				time = TimeBase() + t;
			if(*p == '\t')
				size = ScanInt(p + 1, &p);
		}
		int ifn = out.Find(fn);
		if(ifn >= 0)
		{
			(Time&)out[ifn] = time;
			out[ifn].length = size;
		}
		while(*p && *p++ != '\n')
			;
	}
	return out.PickValues();
}

void RemoteHost::DeleteFile(const Vector<String>& path)
{
	String request = "-";
	for(int i = 0; i < path.GetCount(); i++)
		request << GetHostPath(path[i]) << "\n";
	String out = RemoteExec(request);
	if(!IsNull(out) && out != "OK")
		PutVerbose(out);
}

void RemoteHost::DeleteFolderDeep(const String& folder)
{
	String out = RemoteExec("~" + GetHostPath(folder));
	if(out != "OK")
		PutConsole(out);
}

void RemoteHost::ChDir(const String& path)
{
	chdir_path = GetHostPath(path);
}

void RemoteHost::RealizeDir(const String& path)
{
	RemoteExec("*" + GetHostPath(path));
}

void RemoteHost::SaveFile(const String& path, const String& data)
{
	String request;
	request << ">" << GetHostPath(path)
		<< "\t" << int(GetSysTime() - TimeBase())
		<< "\t" << data.GetLength()
		<< "\t" << ASCII85Encode(BZ2Compress(data))
		<< "\n";
	String out = RemoteExec(request);
	if(out != "OK")
		PutConsole(out);
}

String  RemoteHost::LoadFile(const String& path)
{
	String hpath = GetHostPath(path);
	String request = "^" + hpath;
	String out = RemoteExec(request);
	const char *p = out;
	while(*p && *p != '\n' && *p != '\t')
		p++;
	if(*p++ != '\t')
		return String::GetVoid();
	int len = ScanInt(p, &p);
	if(IsNull(len) || len <= 0 || *p++ != '\t')
		return String::GetVoid();
	String data = BZ2Decompress(ASCII85Decode(p));
	if(data.GetLength() != len)
	{
		PutConsole(NFormat("%s: decompressed length (%d) doesn't match length in header (%d)",
			hpath, data.GetLength(), len));
		return String::GetVoid();
	}
	return data;
}

int RemoteHost::Execute(const char *cmdline)
{
	int q = IdeConsoleExecute(StartProcess(cmdline), cmdline);
	PutVerbose(Format("Exitcode: %d", q));
	return q;
}

int RemoteHost::ExecuteWithInput(const char *cmdline)
{
	int q = IdeConsoleExecute(StartProcess(cmdline), cmdline);
	PutVerbose(Format("Exitcode: %d", q));
	return q;
}

int RemoteHost::Execute(const char *cmdline, Stream& out)
{
	int q = IdeConsoleExecute(StartProcess(cmdline), cmdline, &out, true);
	PutVerbose(Format("Exitcode: %d", q));
	return q;
}

int RemoteHost::AllocSlot()
{
	return IdeConsoleAllocSlot();
}

bool RemoteHost::Run(const char *cmdline, int slot, String key, int blitz_count)
{
	return IdeConsoleRun(StartProcess(cmdline), cmdline, NULL, false, slot, key, blitz_count);
}

bool RemoteHost::Run(const char *cmdline, Stream& out, int slot, String key, int blitz_count)
{
	return IdeConsoleRun(StartProcess(cmdline), cmdline, &out, false, slot, key, blitz_count);
}

bool RemoteHost::Wait()
{
	return IdeConsoleWait();
}

One<AProcess> RemoteHost::StartProcess(const char *cmdline)
{
	try {
		PutVerbose(cmdline);
		return StartRemoteProcess(host, port, cmdline, environment, REMOTE_TIMEOUT);
	}
	catch(...) {
		return NULL;
	}
}

void RemoteHost::Launch(const char *_cmdline, bool)
{
}

void RemoteHost::AddFlags(Index<String>& cfg)
{
	cfg.Add(os_type);
}
#endif


text:
The ReSharper test environment will use default values for settings. If your test needs particular values in the settings, you need to set them yourself in the test, and they should be reset at the end of the test. This is important because ReSharper will try to reuse the current project and solution for future tests.

The `BaseTest` class provides two methods to help with this:

```cs
public class BaseTest : BaseTestNoShell
{
  public void ExecuteWithinSettingsTransaction( Action<IContextBoundSettingsStore> action);
  public ChangeSettingsTemporarilyCore ChangeSettingsTemporarily(Lifetime lifetime);

  // […snip…]
}
```

Normally, you would use the `ExecuteWithinSettingsTransaction` method. This takes an action that receives an instance of `IContextBoundSettingsStore`, and your code will use this settings store to temporarily change the settings. Once the action is complete, the changes to the settings are automatically undone.

```cs
[Test]
public void MyTest()
{
  ExecuteWithinSettingsTransaction(store => {

    // Update settings
    store.SetValue((CSharpLanguageProjectSettings s) => {
      s.LanguageLevel = CSharpLanguageLevel.CSharp50
    });

    // Do test
    // […snip…]
  });
}
```

## Advanced Usage

The `ChangeSettingsTemporarily` method does all of the work. It creates an instance of `ChangeSettingsTemporarilyCore` using the `Lifetime` you pass in. It creates a new in-memory settings layer with a very high priority, which means it overrides all other layers (project, solution, global), and any writes against the settings store will go to this temporary layer. The layer is created with the given `Lifetime` instance, and when the `Lifetime` terminates, the layer is automatically removed and cleaned up. Should you need it, you can get access to the layer's storage from the returned instance of `ChangeSettingsTemporarilyCore`.

The `ExecuteWithinSettingsTransaction` method makes this an easier API to consume. It creates a new `Lifetime` instance, calls `ChangeSettingsTemporarily` and then gets a bound settings store accessor which it uses in a call to the passed in action. Once the action completes, the `Lifetime` is terminated, which cleans up the store accessor, and the instance of `ChangeSettingsTemporarilyCore`, and therefore removes the temporary settings layer.


text:
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * @fileoverview: The NaCl plugin leans on its host to provide some basic
 * stream-like objects for /dev/random. The interface is likely to change
 * in the near future, so documentation in this file is a bit sparse.
 */

/**
 * Base class for streams required by the plugin.
 */
nassh.Stream = function(fd, path) {
  this.fd_ = fd;
  this.path = path;
  this.open = false;
};

/**
 * Errors we may raise.
 */
nassh.Stream.ERR_STREAM_CLOSED = 'Stream closed';
nassh.Stream.ERR_STREAM_OPENED = 'Stream opened';
nassh.Stream.ERR_FD_IN_USE = 'File descriptor in use';
nassh.Stream.ERR_NOT_IMPLEMENTED = 'Not implemented';

/**
 * Collection of currently open stream instances.
 */
nassh.Stream.openStreams_ = {};

/**
 * Look up a stream instance.
 */
nassh.Stream.getStreamByFd = function(fd) {
  return this.openStreams_[fd];
};

/**
 * Open a new stream of a given class.
 */
nassh.Stream.openStream = function(streamClass, fd, arg, onOpen) {
  if (fd in this.openStreams_)
    throw nassh.Stream.ERR_FD_IN_USE;

  var stream = new streamClass(fd, arg);
  var self = this;

  stream.asyncOpen_(arg, function(success) {
      if (success) {
        self.openStreams_[fd] = stream;
        stream.open = true;
      }

      onOpen(success);
    });

  return stream;
};

/**
 * Clean up after a stream is closed.
 */
nassh.Stream.onClose_ = function(stream) {
  if (stream.open)
    throw nassh.Stream.ERR_STREAM_OPENED;

  delete this.openStreams_[stream.fd_];
};

/**
 * Open a stream, calling back when complete.
 */
nassh.Stream.prototype.asyncOpen_ = function(path, onOpen) {
  setTimeout(function() { onOpen(false) }, 0);
};

/**
 * Read from a stream, calling back with the result.
 */
nassh.Stream.prototype.asyncRead = function(size, onRead) {
  throw nassh.Stream.ERR_NOT_IMPLEMENTED;
};

/**
 * Write to a stream.
 */
nassh.Stream.prototype.asyncWrite = function(data, onSuccess) {
  throw nassh.Stream.ERR_NOT_IMPLEMENTED;
};

/**
 * Close a stream.
 */
nassh.Stream.prototype.close = function(reason) {
  if (!this.open)
    return;

  this.open = false;

  if (this.onClose)
    this.onClose(reason || 'closed');

  nassh.Stream.onClose_(this);
};

/**
 * The /dev/random stream.
 *
 * This special case stream just returns random bytes when read.
 */
nassh.Stream.Random = function(fd) {
  nassh.Stream.apply(this, [fd]);
};

nassh.Stream.Random.prototype = {
  __proto__: nassh.Stream.prototype
};

nassh.Stream.Random.prototype.asyncOpen_ = function(path, onOpen) {
  this.path = path;
  setTimeout(function() { onOpen(true) }, 0);
};

nassh.Stream.Random.prototype.asyncRead = function(size, onRead) {
  if (!this.open)
    throw nassh.Stream.ERR_STREAM_CLOSED;

  var bytes = new Uint8Array(size);
  crypto.getRandomValues(bytes);
  Array.prototype.map.apply(
      bytes, [function(el) { return String.fromCharCode(el) }]);

  var b64bytes = btoa(Array.prototype.join.apply(bytes, ['']));

  setTimeout(function() { onRead(b64bytes) }, 0);
};


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

<TITLE>
Constant Field Values
</TITLE>

<META NAME="date" CONTENT="2011-08-11">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Constant Field Values

Contents

lizardSpock.*

players.*

lizardSpock.*

lizardSpock.SLArena

public final boolean
DEBUG
false

protected final int
pauseDuration
10

public final boolean
SOUND_TEST
true

players.*

players.DrSequence

private final int
LENGTH
100

players.SLPlayer

public static final int
ERROR
-1

public static final int
LIZARD
4

public static final int
PAPER
1

public static final int
ROCK
0

public static final int
SCISSORS
2

public static final int
SPOCK
3

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
import getModalities from './getModalities';

describe('getModalities', () => {
  test('should return an empty object when Modality and ModalitiesInStudy are not present', () => {
    const Modality = null;
    const ModalitiesInStudy = null;

    expect(getModalities(Modality, ModalitiesInStudy)).toEqual({});
  });

  test('should return an empty object when Modality and ModalitiesInStudy are not present', () => {
    const Modality = null;
    const ModalitiesInStudy = null;

    expect(getModalities(Modality, ModalitiesInStudy)).toEqual({});
  });

  test('should return modalities in Study when Modality is not defined', () => {
    const Modality = null;

    const ModalitiesInStudy = {
      Value: ['MOCKED_VALUE'],
      vr: 'MOCKED_VALUE',
    };

    expect(getModalities(Modality, ModalitiesInStudy)).toEqual(
      ModalitiesInStudy
    );
  });

  test('should return only the modalitues that exists in ModalitiesInStudy', () => {
    const Modality = {
      Value: ['DESIRED_VALUE'],
      vr: 'DESIRED_VR',
    };

    const ModalitiesInStudy = {
      Value: ['DESIRED_VALUE', 'NOT_DESIRED_VALUE'],
      vr: 'DESIRED_VR',
    };

    expect(getModalities(Modality, ModalitiesInStudy)).toEqual(Modality);
  });

  test('should return the seek Modality when the desired Modality does not exist in ModalitiesInStudy', () => {
    const Modality = {
      Value: ['DESIRED_VALUE'],
      vr: 'DESIRED_VR',
    };

    const ModalitiesInStudy = {
      Value: ['NOT_DESIRED_VALUE'],
      vr: 'DESIRED_VR',
    };

    expect(getModalities(Modality, ModalitiesInStudy)).toEqual(Modality);
  });

  test('should return the seek Modality when the desired Modality does not exist in ModalitiesInStudy VR', () => {
    const Modality = {
      Value: ['DESIRED_VALUE'],
      vr: 'DESIRED_VR',
    };

    const ModalitiesInStudy = {
      Value: ['NOT_DESIRED_VALUE'],
      vr: 'ANOTHER_VR',
    };

    expect(getModalities(Modality, ModalitiesInStudy)).toEqual(
      ModalitiesInStudy
    );
  });
});


text:
use std::error;
use std::fmt;

/// Th error for parsing a JSON record.
#[derive(Debug, PartialEq)]
pub struct Error {
    kind: ErrorKind,
}

impl Error {
    #[inline]
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }
}

impl From<ErrorKind> for Error {
    #[inline]
    fn from(kind: ErrorKind) -> Error {
        Error { kind: kind }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", self.kind.as_str())
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        self.kind.as_str()
    }

    fn cause(&self) -> Option<&error::Error> {
        None
    }
}

/// The error kind of error for parsing a JSON record.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ErrorKind {
    InvalidQuery,
    InvalidRecord,
}

impl ErrorKind {
    #[inline]
    fn as_str(&self) -> &'static str {
        match *self {
            ErrorKind::InvalidQuery => "invalid query",
            ErrorKind::InvalidRecord => "invalid record",
        }
    }
}


text:
package com.lucadev.mcprotocol.protocol.network.connection.impl;

import com.lucadev.mcprotocol.protocol.network.connection.Connection;
import com.lucadev.mcprotocol.protocol.network.connection.ConnectionFactory;

import javax.net.SocketFactory;

/**
 * Factory that returns key securing connections that can be used by the Minecraft protocol.
 * The secure connections can be cast to KeySecuredConnection
 *
 * @author Luca Camphuisen < Luca.Camphuisen@hva.nl >
 * @see ConnectionFactory
 * @see KeySecuredConnection
 */
public class UnsecuredConnectionFactory extends ConnectionFactory {

    /**
     * Creates a new connection that cannot be secured.
     *
     * @return a new connection.
     */
    @Override
    public Connection createConnection() {
        return new UnsecuredConnection();
    }

    /**
     * Create a new connection that cannot be secured with the specified socket factory.
     *
     * @param socketFactory the socketfactory to use for the connection being created.
     * @return
     */
    @Override
    public Connection createConnection(SocketFactory socketFactory) {
        return new UnsecuredConnection(socketFactory);
    }
}


text:
namespace Wilson.Web.Areas.Admin.Models.ControlPanelViewModels
{
    public class ShortUserViewModel
    {
        public string Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Email { get; set; }

        public string PhoneNumber { get; set; }

        public bool IsActive { get; set; }
    }
}


text:
<?php

namespace G4\CleanCore\Exception;

class Validation extends \Exception
{
    protected $meta;

    protected $name;

    protected $value;

    public function __construct($name, $value, $meta)
    {
        $this->name  = $name;
        $this->value = $value;
        $this->meta  = $meta;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getValue()
    {
        return $this->value;
    }
}


text:
package net.onrc.openvirtex.messages;

import net.onrc.openvirtex.elements.datapath.PhysicalSwitch;

public interface Virtualizable {
	public void virtualize(PhysicalSwitch sw);
}


text:
## To Install

Type:

```
make
```

## To Run

Type:

```
java -jar WinterWolf.jar
```

## About

December 2010

In my second year at university I built a web browser for a Graphical User Interfaces module. Unfortunately it had to be written in Java, and even more unfortunately it had to use a JEditorPane as the rendering engine with the consequence that it only supports HTML 3.2.

Given these drawbacks, it's not a very practical application. However, the focus was on the user interface, and I feel I managed to design it well. No prizes for guessing where I got my inspiration.

I have decided to release the source code in case anyone is interested in how to build a simple web browser in Java. I've given it the MIT licence, so feel free to mess around and redistribute - just leave the copyright notice intact.


text:
description("This tests that the methods on CSSPrimitiveValue throw exceptions ");

div = document.createElement('div');
div.style.width = "10px";
div.style.height = "90%";
div.style.content = "counter(dummy, square)";
div.style.clip = "rect(0, 0, 1, 1)";
div.style.color = "rgb(0, 0, 0)";

var invalidAccessError = "InvalidAccessError: A parameter or an operation was not supported by the underlying object.";

// Test passing invalid unit to getFloatValue
shouldThrow("div.style.getPropertyCSSValue('width').getFloatValue(CSSPrimitiveValue.CSS_UNKNOWN)", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('width').getFloatValue(CSSPrimitiveValue.CSS_STRING)", "invalidAccessError");

// Test invalid unit conversions in getFloatValue
shouldThrow("div.style.getPropertyCSSValue('width').getFloatValue(CSSPrimitiveValue.CSS_HZ)", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('width').getFloatValue(CSSPrimitiveValue.CSS_S)", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('width').getFloatValue(CSSPrimitiveValue.CSS_RAD)", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('width').getFloatValue(CSSPrimitiveValue.CSS_PERCENTAGE)", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('height').getFloatValue(CSSPrimitiveValue.CSS_PX)", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('height').getFloatValue(CSSPrimitiveValue.CSS_DEG)", "invalidAccessError");

// Test calling get*Value for CSSPrimitiveValue of the wrong type
shouldBe("div.style.getPropertyCSSValue('clip').primitiveType", "CSSPrimitiveValue.CSS_RECT");
shouldThrow("div.style.getPropertyCSSValue('clip').getFloatValue(CSSPrimitiveValue.CSS_PX)", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('clip').getStringValue()", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('clip').getCounterValue()", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('clip').getRGBColorValue()", "invalidAccessError");

shouldBe("div.style.getPropertyCSSValue('color').primitiveType", "CSSPrimitiveValue.CSS_RGBCOLOR");
shouldThrow("div.style.getPropertyCSSValue('color').getFloatValue(CSSPrimitiveValue.CSS_PX)", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('color').getStringValue()", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('color').getCounterValue()", "invalidAccessError");
shouldThrow("div.style.getPropertyCSSValue('color').getRectValue()", "invalidAccessError");


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import HeaderComponent from './component';
import LogoComponent from './components/logo';
import MenuLeftComponent from './components/menu-left';
import MenuRightComponent from './components/menu-right';

@NgModule({
  declarations: [
    HeaderComponent,
    LogoComponent,
    MenuLeftComponent,
    MenuRightComponent
  ],
  imports: [
    CommonModule,
    RouterModule
  ],
  exports: [
    HeaderComponent
  ]
})

export default class HeaderModule { }


text:
html {
    color: #000080;
}
.line {
    border-top: black solid 1px;
    height: 10px;
    width: 99%;
    margin: 0;
    padding: 0;
    margin-top: 20px;
    clear: both;
}
a {
    color: #800080;
}
a:visited {
    color: red;
}
header {
    text-align: center;
    line-height: .95em;
}
.name {
    text-transform: uppercase;
    font-weight: bold;
    margin-bottom: -15px;
}
.first-letter {
    font-size: 200%;
}
.small-text {
    font-size: 75%;
}
.address {
    font-size: 75%;
}
.homepage {
    font-size: 90%;
}
.columns-left {
    float: left;
    max-width: 40%;
    margin-left: 25px;
}
.columns-right {
    float: right;
    max-width: 40%;
    margin-right: 25px;
}
li {
    padding: .5em;
}
.bottom {
    clear:both;
    font-size:.6em;
}
.link-text {
    font-size: 75%;
}
.geico {
    text-align: center;
}
.questions {
    font-size: 1.4em;
}
.legal{
    font-size: 1.7em;
}
/*
What is important to know when linking an external file (like a stylesheet) to an HTML file?

    First, if this is a stylesheet, the link needs to go in the head. This has to do with how
    the information will be read by browsers and such. So it's stored up there with all the other
    metadata.

    It must include a link tag (self closing) as well as the following attributes:
        href: used to indicate the path to the file
        type: techincally this is optional, but it's used to specify the media
        rel: if this is a stylesheet, this used to define the relationship of the doc to the html

    Most of this can be obliviously copy pasted like this *kablam*:
    <link type="text/css" rel="stylesheet" href="path.css"/>
    But the tricky part is nailing down that href portion. If I'm struggling to get the right
    relative path, I play around - I might /'s and ..'s, look for typos, or go up/down a directory.

What tricks did you use to help you with positioning? How hard was it to get the site as you
wanted it?

    The original used table with two td's per row in order to create a two column effect. Our
    html wasn't quite organized that way, so we decided to use floats and margins instead. It
    was broken up into two chunks, one for the left column, and one for the right. I think it
    was a clever solution even though it doesn't look exaclty the same. as the original.
    Namely, there's a bigger gap between the columns if zoomed out since the columns are
    hugging right and left sides of the screen.

    The hardest things often involved positioning something via margin, display, or position.
    Often there are multiple methods that might work, but each creates its own issues.

What CSS did you use to modify the element style (like size, color, etc.)

    Stylistic choices either involved font-size or color (for font-color).  Color was pretty
    straight forward. Size was finicky since there were so many font-sizes used. We ended up
    leaving that stuff to do after the pairing session since we both knew how to do it and it
    seemed time consuming. The tricky thing with font sizes was sectioning off the text that
    needed to be targeted. For that I used classes.

Did you modify the HTML to include classes or ids? If so, which did you choose and why? If you
didn't, how would you know which one to add to your HTML?

    We used classes since I remembered hearing something about avoiding ids - though I can't
    remember where. I think it had something to do with ids being tricky once things get more
    complicated. In any case, classes seemed to do just fine. And, even though we didn't do it,
    they could have been used multiple times (unlike ids).

When you compared your site to the actual code base, which do you think had cleaner code that
followed best practices and why?

    I don't feel confident in my code enough to declare it a winner. However, as far as the html
    is concerned I don't see as many semantic elements in the original. That might have to do with
    when it was written more than anything else. There are also a ton of nested items - <p>'s and
    <div>'s. Whereas our use of classes makes it a bit more apparent to me what each section is for.
    The CSS is a tough call. Since we were trying to replicate the original, and we failed in that
    aim, so the original of course did it better. Our CSS seems a bit lengthy to me too. I wonder
    how lengthy the original was.

*/


text:
package com.github.groovylabs.lyre.domain.exceptions;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

public class ConflictException extends WebApplicationException {

    public ConflictException(String message) {
        super(Response.status(Response.Status.CONFLICT).entity(message).type(MediaType.TEXT_PLAIN).build());
    }

}


text:
<?php

namespace Routelandia;

// Include the Respect/Relational "style" for the portal database
require_once 'PortalStyle.php';

// Require our database models
// note that the path has to be ../ because the execution context will be
// in public/
foreach (glob("../entities/*.php") as $filename)
{
    require_once $filename;
}

// Make "Mapper" easily accessible locally.
use Respect\Relational\Mapper;

use \PDO;

/**
 * Represents a connection to our application database.
 *
 * Allows you to easily access the database using a singleton
 * method, preventing the same script from opening multiple
 * connections to the database.
 * (This also makes configuration easy to change.)
 */
class DB {
  // The internal variable used to track the database handle
  private static $database_handle;
  private static $sql;
  private static $mapper;

  /**
   * A singleton to get a database handle.
   */
  private static function get_database_handle() {
    if(DB::$database_handle == NULL) {
      /* Attempt to include the local config file which is not
       * in git. (So that we don't check in configuration stuff
       * such as database passwords.
       *
       * If the file does not exist we can't continue until it
       * has been created on the machine this script is running
       * on.
       *
       * Local config is expected to set the following:
       *
       *   $DB_HOST = "";
       *   $DB_NAME = "";
       *   $DB_USER = "";
       *   $DB_PASSWORD = "";
       *
       * NOTE: We have to go up a directory to ../local_config.php because
       * database.php will be called from some script that lives in public/
       * therefore the current execution context will be in public/
       * Also note that this is included inside the instance call because
       * PHP includes the contenst of the includes in a literal sense, so
       * this maintains correct variable scope.
       *
       * We're going to do a check to see if the local url is "/api-test".
       * To do testing we'll need to set up a second configuration in the local
       * machine's apache config, to mount this SAME DIRECTORY with a different
       * database config file.
       * Creating the local_test_config with the details to connect to a testing
       * database will ensure that we can run our tests without risking damage
       * to the local database.
       */
      // Check if we're using the testing url, use a different database config
      if(strpos($_SERVER['REQUEST_URI'], "/api-test/") === false){
        if (!file_exists('../local_config.php'))
          throw new Exception ('local_config.php does not exist and must be created!');
        else
          require_once('../local_config.php' );
      }
      else
      {
        if (!file_exists('../local_test_config.php'))
          throw new Exception ('local_test_config.php does not exist and must be created!');
        else
          require_once('../local_test_config.php' );
      }

      //try {
        DB::$database_handle = new PDO("pgsql:host='$DB_HOST';dbname='$DB_NAME';user='$DB_USER';password='$DB_PASSWORD'");
      //} catch (PDOException e) {
      //  throw new DatabaseErrorException($e->getMessage());
      //}
    }
    return DB::$database_handle;
  }

  /**
   * A singleton method to get the database as a Mapper object
   *
   * Note that we do the check for null because that seems to help POST requests actually get the mapper
   * set up correctly. Not entirely certain *WHY* POST requests manage to get a handle without setting up the
   * mapper, but this way seems to work so we're going with it.
   */
  public static function mapper() {
    $h = DB::$database_handle;
    if($h == null) {
      $h = DB::get_database_handle();
    }
    DB::$mapper = new Mapper($h);
    DB::$mapper->setStyle(new \Routelandia\Data\Styles\PortalStyle);
    DB::$mapper->entityNamespace = 'Routelandia\\Entities\\';

    return DB::$mapper;
  }

  /**
   * A singleton method to get the database as a SQL object
   */
  public static function sql() {
    if(DB::$sql == null) {
      $h = DB::get_database_handle();

      DB::$sql = new \Respect\Relational\Db($h);
    }

    return DB::$sql;
  }

}


text:
"use strict";
var dependencyInjector = require("../core/utils/dependency_injector");
module.exports = dependencyInjector({
    locale: function() {
        var currentLocale = "en";
        return function(locale) {
            if (!locale) {
                return currentLocale
            }
            currentLocale = locale
        }
    }()
});


text:
<?php

namespace Namespaced;

class FooBar
{
    public static $loaded = true;
}


text:
package com.azure.core.implementation.serializer.jsonwrapper;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Date;

public class Entry {

    @JsonProperty
    Date date;

    public Date date() {
        return date;
    }

    public void date(Date date) {
        this.date = date;
    }
}


text:
@interface LoadWebViewController ()<WKNavigationDelegate>

@property(nonatomic,strong)WKWebView *webView;
@property(nonatomic,strong)dispatch_semaphore_t managentS;
@property(nonatomic,strong)dispatch_queue_t myQeue;
@property(nonatomic,strong)NSString* playPath;
//@property(nonatomic,assign)

@end

@implementation LoadWebViewController

-(void)viewWillAppear:(BOOL)animated{
    if (self.netWorkingUrl) {
        [self.navigationController setNavigationBarHidden:YES animated:NO];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    if (self.netWorkingUrl) {
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    _webView.navigationDelegate = self;
    [self.view addSubview:_webView];

    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

    if (self.netWorkingUrl) {
        _myQeue = dispatch_queue_create("loadWebQueue", DISPATCH_QUEUE_SERIAL);
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.netWorkingUrl]];
        [_webView loadRequest:request];
        [_webView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view);
            make.left.and.right.mas_equalTo(0);
            make.bottom.equalTo(self.view).mas_equalTo(-50);
        }];

        WebViewNavBar *navbar = [[WebViewNavBar alloc] initWithFrame:CGRectZero];
        @weakify(self);
        [navbar.backBtn addTargetWithBlock:^(UIButton *sender) {
            @strongify(self);
            if (self.webView.canGoBack) {
                [self.webView goBack];
            }else{
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];

        [navbar.scrapyBtn addTargetWithBlock:^(UIButton *sender) {
//            @strongify(self);
            //NSString *htmlString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.hao123.com/gaoxiao?pn=1"] encoding:NSUTF8StringEncoding error:nil];

//            NSURL *ulr = self.webView.URL;
//            [MBProgressHUD showMessage:@"正在抓取磁力链...."];
//            dispatch_async(dispatch_get_global_queue(0, 0), ^{
//
//                NSData *data = [NSData dataWithContentsOfURL:ulr];
//                NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//
//                NSString *retStr = [[NSString alloc] initWithData:data encoding:enc];
//                //^(magnet:\?xt=urn:btih:)[0-9a-fA-F]{40}.*$
//                //magnet:?[^\"]+
//                NSArray *magnetArr = [retStr matches:RX(@"magnet:?[^\"]+")];
//                [GCDQueue executeInMainQueue:^{
//                    [MBProgressHUD hideHUD];
//                    if (magnetArr.count >= 1) {
//                        [MBProgressHUD showSuccess:@"抓取成功"];
//                        NSString *playPath = magnetArr.firstObject;
//                        [self setMangnet:playPath];
//
//                    }else{
//                        [MBProgressHUD showError:@"失败了...."];
//                    }
//
//                }];
//
//            });
        }];

        navbar.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [self.view addSubview:navbar];

        [navbar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.and.left.equalTo(self.view);
            make.bottom.equalTo(self.view);
            make.size.height.mas_equalTo(50);
        }];

    }else{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.label.text = @"正在加载....";
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:self.model.fullPath]];
        [_webView loadRequest:request];
    }
}

-(void)setMangnet:(NSString *)path{

//    [MBProgressHUD showMessage:@"正在同步本地列表..." toView:self.view];
//    @weakify(self);
//    dispatch_async(self.myQeue, ^{
//        @strongify(self);
//        [TYZTorMagentTools getTrackers:^(id result) {
//            NSLog(@"===》%@",result);
//        }];
//
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [MBProgressHUD hideHUDForView:self.view];
//            [MBProgressHUD showMessage:@"正在开启服务..." toView:self.view];
//        });
//    });
//
//    dispatch_async(self.myQeue, ^{
//
//        self.managentS = dispatch_semaphore_create(0);
//        [TYZTorMagentTools startServer:^(id result) {
//            dispatch_semaphore_signal(self.managentS);
//            [GCDQueue executeInMainQueue:^{
//                [MBProgressHUD hideHUDForView:self.view];
//                if ([result isKindOfClass:[NSString class]]) {
//                    // 开启成功
//                    [MBProgressHUD showMessage:@"正在解析服务(需要花费一点时间)..." toView:self.view];
//                }else{
//                    [MBProgressHUD showError:@"开启失败..."];
//                }
//            }];
//        }];
//        dispatch_semaphore_wait(self.managentS, DISPATCH_TIME_FOREVER);
//
//    });
//
//    dispatch_async(self.myQeue, ^{
//
//        NSString *trackersList = (NSString *)[[NSUserDefaults standardUserDefaults]objectForKey:@"trackersList"];
//        self.managentS = dispatch_semaphore_create(0);
//        [TYZTorMagentTools reuqest:TYZMagentState_START magentLink:path trackers:trackersList handler:^(id result) {
//            dispatch_semaphore_signal(self.managentS);
//        }];
//        dispatch_semaphore_wait(self.managentS, DISPATCH_TIME_FOREVER);
//
//    });
//
//    dispatch_async(self.myQeue, ^{
//
//        //哪里需要,加在哪里
//        [TYZTorMagentTools getCurrentState:^(id result) {
//            NSLog(@"==》%@",result);
//
//            NSString *resultS = (NSString *)result;
//            NSData *jsonData = [resultS dataUsingEncoding:NSUTF8StringEncoding];
//            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
//
//            if (![[resultDic objectForKey:@"videoUrl"] isKindOfClass:[NSNull class]]) {
//
//                if (self.playPath) {
//                    return ;
//                }
//                [GCDQueue executeInMainQueue:^{
//
//                    [MBProgressHUD hideHUDForView:self.view];
//
//                    self.playPath = resultDic[@"videoUrl"];
//                    PlayVideoViewController *vc = [[PlayVideoViewController alloc] init];
//                    vc.path = self.playPath;
//                    APPPresentViewController(vc);
//                }];
//
//            }
//
//        }];
//
//    });
//
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{

    [self hidenMessage];
}

-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{

}

//-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
//    //如果是跳转一个新页面
//    if (navigationAction.targetFrame == nil) {
//        [webView loadRequest:navigationAction.request];
//    }
//    decisionHandler(WKNavigationActionPolicyAllow);
//}

@end


text:
class SessionsController < ApplicationController
  skip_before_action :authorize
  before_action :already_signed_in, only: [:new, :create]

  def new
  end

  def create
  	user = User.find_by(name: params[:name])
    if user and user.authenticate(params[:password])
      session[:user_id] = user.id
      redirect_to dashboard_url
    else
      redirect_to login_url, alert: "Invalid user/password combination"
    end
  end

  def destroy
  	session[:user_id] = nil
    redirect_to login_url, notice: "Logged out"
  end
end