text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
    public class PDBTupleTests : CSharpPDBTestBase
    {
        [Fact]
        public void Local()
        {
            var source =
@"class C
{
    static void F()
    {
        (int A, int B, (int C, int), int, int, int G, int H, int I) t = (1, 2, (3, 4), 5, 6, 7, 8, 9);
    }
}";
            var comp = CreateStandardCompilation(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
            comp.VerifyPdb(
@"<symbols>
  <methods>
    <method containingType=""C"" name=""F"">
      <customDebugInfo>
        <using>
          <namespace usingCount=""0"" />
        </using>
        <tupleElementNames>
          <local elementNames=""|A|B||||G|H|I|C||"" slotIndex=""0"" localName=""t"" scopeStart=""0x0"" scopeEnd=""0x0"" />
        </tupleElementNames>
        <encLocalSlotMap>
          <slot kind=""0"" offset=""71"" />
        </encLocalSlotMap>
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" />
        <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""103"" />
        <entry offset=""0x1b"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0x1c"">
        <local name=""t"" il_index=""0"" il_start=""0x0"" il_end=""0x1c"" attributes=""0"" />
      </scope>
    </method>
  </methods>
</symbols>");
        }

        [Fact]
        public void Constant()
        {
            var source =
@"class C<T>
{
    static (int, int) F;
}
class C
{
    static void F()
    {
        const C<(int A, int B)> c = null;
    }
}";
            var comp = CreateStandardCompilation(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
            comp.VerifyPdb(
@"<symbols>
  <methods>
    <method containingType=""C"" name=""F"">
      <customDebugInfo>
        <using>
          <namespace usingCount=""0"" />
        </using>
        <tupleElementNames>
          <local elementNames=""|A|B"" slotIndex=""-1"" localName=""c"" scopeStart=""0x0"" scopeEnd=""0x2"" />
        </tupleElementNames>
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" />
        <entry offset=""0x1"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0x2"">
        <constant name=""c"" value=""null"" signature=""C`1{System.ValueTuple`2{Int32, Int32}}"" />
      </scope>
    </method>
  </methods>
</symbols>");
        }

        [Fact]
        public void TuplesAndDynamic()
        {
            var source =
@"class C<T>
{
}
class C
{
    static void F()
    {
        {
            (dynamic A, object B, object)[] x;
            const C<(object, dynamic, object C)> y = null;
        }
        {
            const C<(object A, object)> x = null;
        }
        {
            const C<(object, dynamic)> x = null;
            const C<(object, dynamic B)> y = null;
        }
    }
}";
            var comp = CreateStandardCompilation(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
            comp.VerifyPdb(
@"<symbols>
  <methods>
    <method containingType=""C"" name=""F"">
      <customDebugInfo>
        <using>
          <namespace usingCount=""0"" />
        </using>
        <dynamicLocals>
          <bucket flags=""00100"" slotId=""0"" localName=""x"" />
          <bucket flags=""00010"" slotId=""0"" localName=""y"" />
          <bucket flags=""0001"" slotId=""0"" localName=""x"" />
          <bucket flags=""0001"" slotId=""0"" localName=""y"" />
        </dynamicLocals>
        <tupleElementNames>
          <local elementNames=""|A|B|"" slotIndex=""0"" localName=""x"" scopeStart=""0x0"" scopeEnd=""0x0"" />
          <local elementNames=""|||C"" slotIndex=""-1"" localName=""y"" scopeStart=""0x1"" scopeEnd=""0x3"" />
          <local elementNames=""|A|"" slotIndex=""-1"" localName=""x"" scopeStart=""0x3"" scopeEnd=""0x5"" />
          <local elementNames=""||B"" slotIndex=""-1"" localName=""y"" scopeStart=""0x5"" scopeEnd=""0x7"" />
        </tupleElementNames>
        <encLocalSlotMap>
          <slot kind=""0"" offset=""58"" />
        </encLocalSlotMap>
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" />
        <entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""10"" />
        <entry offset=""0x2"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" />
        <entry offset=""0x3"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" />
        <entry offset=""0x4"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" />
        <entry offset=""0x5"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" />
        <entry offset=""0x6"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""10"" />
        <entry offset=""0x7"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0x8"">
        <scope startOffset=""0x1"" endOffset=""0x3"">
          <local name=""x"" il_index=""0"" il_start=""0x1"" il_end=""0x3"" attributes=""0"" />
          <constant name=""y"" value=""null"" signature=""C`1{System.ValueTuple`3{Object, Object, Object}}"" />
        </scope>
        <scope startOffset=""0x3"" endOffset=""0x5"">
          <constant name=""x"" value=""null"" signature=""C`1{System.ValueTuple`2{Object, Object}}"" />
        </scope>
        <scope startOffset=""0x5"" endOffset=""0x7"">
          <constant name=""x"" value=""null"" signature=""C`1{System.ValueTuple`2{Object, Object}}"" />
          <constant name=""y"" value=""null"" signature=""C`1{System.ValueTuple`2{Object, Object}}"" />
        </scope>
      </scope>
    </method>
  </methods>
</symbols>");
        }

        [Fact]
        public void MultiByteCharacters()
        {
            var source =
@"class C
{
    static void F()
    {
        (int \u1234, int, int \u005f\u1200\u005f) \u1200 = (1, 2, 3);
    }
}";
            var comp = CreateStandardCompilation(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
            comp.VerifyPdb(
string.Format(@"<symbols>
  <methods>
    <method containingType=""C"" name=""F"">
      <customDebugInfo>
        <using>
          <namespace usingCount=""0"" />
        </using>
        <tupleElementNames>
          <local elementNames=""|{0}||{1}"" slotIndex=""0"" localName=""{2}"" scopeStart=""0x0"" scopeEnd=""0x0"" />
        </tupleElementNames>
        <encLocalSlotMap>
          <slot kind=""0"" offset=""53"" />
        </encLocalSlotMap>
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" />
        <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""70"" />
        <entry offset=""0xa"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0xb"">
        <local name=""{2}"" il_index=""0"" il_start=""0x0"" il_end=""0xb"" attributes=""0"" />
      </scope>
    </method>
  </methods>
</symbols>",
    "\u1234",
    "_\u1200_",
    "\u1200"));
        }

        [Fact]
        public void DeconstructionForeach()
        {
            var source =
@"class C
{
    static void F(System.Collections.Generic.IEnumerable<(int a, int b)> ie)
    { //4,5
        foreach (         //5,9
            var (a, b)    //6,13
            in            //7,13
            ie)           //8,13
        { //9,9
        } //10,9
    } //11,5
}";
            var comp = CreateStandardCompilation(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
            comp.VerifyPdb(
string.Format(@"<symbols>
  <methods>
    <method containingType=""C"" name=""F"" parameterNames=""ie"">
      <customDebugInfo>
        <using>
          <namespace usingCount=""0"" />
        </using>
        <encLocalSlotMap>
          <slot kind=""5"" offset=""17"" />
          <slot kind=""0"" offset=""59"" />
          <slot kind=""0"" offset=""62"" />
          <slot kind=""temp"" />
        </encLocalSlotMap>
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""4"" startColumn=""5"" endLine=""4"" endColumn=""6"" />
        <entry offset=""0x1"" startLine=""5"" startColumn=""9"" endLine=""5"" endColumn=""16"" />
        <entry offset=""0x2"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""15"" />
        <entry offset=""0x9"" hidden=""true"" />
        <entry offset=""0xb"" startLine=""6"" startColumn=""13"" endLine=""6"" endColumn=""23"" />
        <entry offset=""0x20"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""10"" />
        <entry offset=""0x21"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""10"" />
        <entry offset=""0x22"" startLine=""7"" startColumn=""13"" endLine=""7"" endColumn=""15"" />
        <entry offset=""0x2c"" hidden=""true"" />
        <entry offset=""0x36"" hidden=""true"" />
        <entry offset=""0x37"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0x38"">
        <scope startOffset=""0xb"" endOffset=""0x22"">
          <local name=""a"" il_index=""1"" il_start=""0xb"" il_end=""0x22"" attributes=""0"" />
          <local name=""b"" il_index=""2"" il_start=""0xb"" il_end=""0x22"" attributes=""0"" />
        </scope>
      </scope>
    </method>
  </methods>
</symbols>"));
        }

        [Fact, WorkItem(17947, "https://github.com/dotnet/roslyn/issues/17947")]
        public void VariablesAndConstantsInUnreachableCode()
        {
            string source = @"
class C
{
    void F()
    {
        (int a, int b)[] v1 = null;
        const (int a, int b)[] c1 = null;

        throw null;

        (int a, int b)[] v2 = null;
        const (int a, int b)[] c2 = null;

        {
            (int a, int b)[] v3 = null;
            const (int a, int b)[] c3 = null;
        }
    }
}
";
            var c = CreateStandardCompilation(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
            var v = CompileAndVerify(c);
            v.VerifyIL("C.F", @"
{
  // Code size        5 (0x5)
  .maxstack  1
  .locals init ((int a, int b)[] V_0, //v1
                (int a, int b)[] V_1, //v2
                (int a, int b)[] V_2) //v3
  IL_0000:  nop
  IL_0001:  ldnull
  IL_0002:  stloc.0
  IL_0003:  ldnull
  IL_0004:  throw
}
");

            c.VerifyPdb(@"
<symbols>
  <methods>
    <method containingType=""C"" name=""F"">
      <customDebugInfo>
        <using>
          <namespace usingCount=""0"" />
        </using>
        <tupleElementNames>
          <local elementNames=""|a|b"" slotIndex=""0"" localName=""v1"" scopeStart=""0x0"" scopeEnd=""0x0"" />
          <local elementNames=""|a|b"" slotIndex=""1"" localName=""v2"" scopeStart=""0x0"" scopeEnd=""0x0"" />
          <local elementNames=""|a|b"" slotIndex=""-1"" localName=""c1"" scopeStart=""0x0"" scopeEnd=""0x5"" />
          <local elementNames=""|a|b"" slotIndex=""-1"" localName=""c2"" scopeStart=""0x0"" scopeEnd=""0x5"" />
        </tupleElementNames>
        <encLocalSlotMap>
          <slot kind=""0"" offset=""28"" />
          <slot kind=""0"" offset=""133"" />
          <slot kind=""0"" offset=""232"" />
        </encLocalSlotMap>
      </customDebugInfo>
      <sequencePoints>
        <entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" />
        <entry offset=""0x1"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""36"" />
        <entry offset=""0x3"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""20"" />
      </sequencePoints>
      <scope startOffset=""0x0"" endOffset=""0x5"">
        <local name=""v1"" il_index=""0"" il_start=""0x0"" il_end=""0x5"" attributes=""0"" />
        <local name=""v2"" il_index=""1"" il_start=""0x0"" il_end=""0x5"" attributes=""0"" />
        <constant name=""c1"" value=""null"" signature=""System.ValueTuple`2{Int32, Int32}[]"" />
        <constant name=""c2"" value=""null"" signature=""System.ValueTuple`2{Int32, Int32}[]"" />
      </scope>
    </method>
  </methods>
</symbols>

");
        }
    }
}


text:
__author__ = 'amaier1'

from simple import extract_entities

redpajama_set_name: RedPajamaGithub


text:
package com.raisepartner.chartfusion.api;

public class Categories extends com.raisepartner.chartfusion.api.Node {

	public final static String PARAMETER_FONTCOLOR = "fontColor";
	public final static String PARAMETER_FONTSIZE = "fontSize";
	public final static String PARAMETER_FONT = "font";

	public Categories() {
		super("categories");
	}

	/**
	 * Type: Color
	 * Range value: Hex Code
	 * Description :
	 * Lets you specify font color for the x-axis data labels.
	 */
	public void setFontColor(String value) {
		setAttribute(PARAMETER_FONTCOLOR, value);
	}

	/**
	 * Type: Number
	 * Range value:
	 * Description :
	 * Lets you specify font size for the x-axis data labels.
	 */
	public void setFontSize(String value) {
		setAttribute(PARAMETER_FONTSIZE, value);
	}

	/**
	 * Type:   String
	 * Range value:   Valid font face
	 * Description :
	 *   Lets you specify font face for the x-axis data labels.
	 */
	public void setFont(String value) {
		setAttribute(PARAMETER_FONT, value);
	}
}


text:
<?php
/**
 *
 * User: Windows
 * Date: 3/1/14
 * Time: 2:41 PM
 *
 */

namespace UserProfile\Domain\Concrete;

use Application\Domain\DbInterfaces\AggregateDbInterface;
use Zend\Db\Adapter\Adapter;

class ProfileQueryFactory {

    /**
     * @var UserAggregate
     */
    protected $aggregate;

    public function __construct(AggregateDbInterface $aggregate){
        $this->aggregate = $aggregate;
    }

    public function resolveUserProfile($username, $limit = 1){
        $result = null;
        $user_table = $this->aggregate->getTable('user');
        $profile_table = $this->aggregate->getTable('profile');
        $query = "select
                 $user_table.id,
                 $user_table.username,
                 $user_table.email,
                 $profile_table.first_name,
                 $profile_table.last_name,
                 $profile_table.user_id,
                 $profile_table.profile_picture
                 from $user_table
                 join $profile_table on ($user_table.id = $profile_table.user_id )
                 where $user_table.username = '$username'
                 Limit 1";
        $request = $this->aggregate->getDbAdapter()->query($query,Adapter::QUERY_MODE_EXECUTE)->toArray();
        if($limit == 1){
            $result = $request[0];
        }
        return $result;
    }
    public function resolveUserByEmail($email, $limit = 1){
        $result = null;
        $user_table = $this->aggregate->getTable('user');
        $profile_table = $this->aggregate->getTable('profile');
        $query = "select
                $user_table.id,
                $user_table.username,
                $user_table.email,
                $user_table.password,
                 $profile_table.first_name,
                 $profile_table.last_name,
                 $profile_table.user_id,
                 $profile_table.profile_picture
                 from $user_table
                 join $profile_table on ($user_table.id = $profile_table.user_id )
                 where $user_table.email = '$email'
                 Limit 1";
        $request = $this->aggregate->getDbAdapter()->query($query,Adapter::QUERY_MODE_EXECUTE)->toArray();
        if($limit == 1){
            $result = $request[0];
        }
        return $result;
    }

    public function resolveUserById($id){
        $result = null;
        $user_table = $this->aggregate->getTable('user');
        $profile_table = $this->aggregate->getTable('profile');
        $query = "select
                $user_table.id,
                $user_table.username,
                $user_table.email,
                $user_table.password,
                 $profile_table.first_name,
                 $profile_table.last_name,
                 $profile_table.user_id,
                 $profile_table.profile_picture
                 from $user_table
                 join $profile_table on ($user_table.id = $profile_table.user_id )
                 where $user_table.id = '$id'
                 Limit 1";
        $result = $this->aggregate->getDbAdapter()->query($query,Adapter::QUERY_MODE_EXECUTE)->toArray();

        if($result){
            return $result[0];
        }

        return $result;
    }

}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name=viewport content="width=device-width, initial-scale=.6">
    <link rel="stylesheet" type="text/css" href="./style/style.css">
    <link rel="stylesheet" type="text/css" href="./style/podcastit.css">
    <link rel="stylesheet" type="text/css" href="./icomoon/style.css">
    <link rel="icon" href="./assets/icon.ico" type="image/x-icon" />
    <link rel="shortcut icon" href="./assets/icon.ico" type="image/x-icon" />

    {{> tracking_code_script}}
    <title>PodCats | Live Lecture</title>

{{course}} | {{date}}

{{timeString}}

                <input type="text" id="text" maxlength="100" class="interval-comment" placeholder="Press here to begin a mark">

Begin mark

End mark

                Characters Left:
                100

            {{#if marks}}
            {{#each marks}}

                {{#if time}}

                    {{time}}

                {{else}}

                    {{start}}

                    {{end}}

{{{comment}}}

                {{/if}}

            {{/each}}
            {{else}}

No Comments Available!

            {{/if}}


text:
package example.ejb;

import javax.ejb.Local;

@Local
public interface ExampleModuleLocal {

  public int max(int ... numbers);

}


text:
[https://kujiy.000webhostapp.com/uop/apa.php?url=http%3A%2F%2Fexample.com%2F&sel=FEBRUARY+2%2C+2022+BY+AUTHOR+NAME](https://kujiy.000webhostapp.com/uop/apa.php?url=http%3A%2F%2Fexample.com%2F&sel=FEBRUARY+2%2C+2022+BY+AUTHOR+NAME)

### Bookmarklet
Drag `apatab` in this page to your bookmark bar.

[https://kujiy.github.io/uopeople/docs/](https://kujiy.github.io/uopeople/docs/)

### How to Use
1. Open your reference page
1. Select author and date texts with a drag
 1. Note: I recommend to select only an author name if the date is away from the author name.
1. Click `apatab` bookmarklet
1. Copy the citation when the new windows opened.


text:
package org.apache.cassandra.db.compaction;

import java.io.*;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.apache.cassandra.OrderedJUnit4ClassRunner;
import org.apache.cassandra.SchemaLoader;
import org.apache.cassandra.Util;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.columniterator.IdentityQueryFilter;
import org.apache.cassandra.db.columniterator.OnDiskAtomIterator;
import org.apache.cassandra.db.filter.QueryFilter;
import org.apache.cassandra.db.marshal.CompositeType;
import org.apache.cassandra.io.sstable.Component;
import org.apache.cassandra.io.sstable.SSTableReader;
import org.apache.cassandra.io.sstable.SSTableScanner;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Pair;

import static junit.framework.Assert.*;

@RunWith(OrderedJUnit4ClassRunner.class)
public class CompactionsTest extends SchemaLoader
{
    public static final String TABLE1 = "Keyspace1";

    public ColumnFamilyStore testSingleSSTableCompaction(String strategyClassName) throws Exception
    {
        Table table = Table.open(TABLE1);
        ColumnFamilyStore store = table.getColumnFamilyStore("Standard1");
        store.clearUnsafe();
        store.metadata.gcGraceSeconds(1);
        store.setCompactionStrategyClass(strategyClassName);

        // disable compaction while flushing
        store.disableAutoCompaction();

        long timestamp = System.currentTimeMillis();
        for (int i = 0; i < 10; i++)
        {
            DecoratedKey key = Util.dk(Integer.toString(i));
            RowMutation rm = new RowMutation(TABLE1, key.key);
            for (int j = 0; j < 10; j++)
                rm.add("Standard1", ByteBufferUtil.bytes(Integer.toString(j)),
                       ByteBufferUtil.EMPTY_BYTE_BUFFER,
                       timestamp,
                       j > 0 ? 3 : 0); // let first column never expire, since deleting all columns does not produce sstable
            rm.apply();
        }
        store.forceBlockingFlush();
        assertEquals(1, store.getSSTables().size());
        long originalSize = store.getSSTables().iterator().next().uncompressedLength();

        // wait enough to force single compaction
        TimeUnit.SECONDS.sleep(5);

        // enable compaction, submit background and wait for it to complete
        store.enableAutoCompaction();
        FBUtilities.waitOnFutures(CompactionManager.instance.submitBackground(store));
        while (CompactionManager.instance.getPendingTasks() > 0 || CompactionManager.instance.getActiveCompactions() > 0)
            TimeUnit.SECONDS.sleep(1);

        // and sstable with ttl should be compacted
        assertEquals(1, store.getSSTables().size());
        long size = store.getSSTables().iterator().next().uncompressedLength();
        assertTrue("should be less than " + originalSize + ", but was " + size, size < originalSize);

        // make sure max timestamp of compacted sstables is recorded properly after compaction.
        assertMaxTimestamp(store, timestamp);

        return store;
    }

    /**
     * Test to see if sstable has enough expired columns, it is compacted itself.
     */
    @Test
    public void testSingleSSTableCompactionWithSizeTieredCompaction() throws Exception
    {
        testSingleSSTableCompaction(SizeTieredCompactionStrategy.class.getCanonicalName());
    }

    @Test
    public void testSingleSSTableCompactionWithLeveledCompaction() throws Exception
    {
        ColumnFamilyStore store = testSingleSSTableCompaction(LeveledCompactionStrategy.class.getCanonicalName());
        LeveledCompactionStrategy strategy = (LeveledCompactionStrategy) store.getCompactionStrategy();
        // tombstone removal compaction should not promote level
        assert strategy.getLevelSize(0) == 1;
    }

    @Test
    public void testSuperColumnTombstones() throws IOException, ExecutionException, InterruptedException
    {
        Table table = Table.open(TABLE1);
        ColumnFamilyStore cfs = table.getColumnFamilyStore("Super1");
        cfs.disableAutoCompaction();

        DecoratedKey key = Util.dk("tskey");
        ByteBuffer scName = ByteBufferUtil.bytes("TestSuperColumn");

        // a subcolumn
        RowMutation rm = new RowMutation(TABLE1, key.key);
        rm.add("Super1", CompositeType.build(scName, ByteBufferUtil.bytes(0)),
               ByteBufferUtil.EMPTY_BYTE_BUFFER,
               FBUtilities.timestampMicros());
        rm.apply();
        cfs.forceBlockingFlush();

        // shadow the subcolumn with a supercolumn tombstone
        rm = new RowMutation(TABLE1, key.key);
        rm.deleteRange("Super1", SuperColumns.startOf(scName), SuperColumns.endOf(scName), FBUtilities.timestampMicros());
        rm.apply();
        cfs.forceBlockingFlush();

        CompactionManager.instance.performMaximal(cfs);
        assertEquals(1, cfs.getSSTables().size());

        // check that the shadowed column is gone
        SSTableReader sstable = cfs.getSSTables().iterator().next();
        SSTableScanner scanner = sstable.getScanner(new QueryFilter(null, "Super1", new IdentityQueryFilter()));
        scanner.seekTo(key);
        OnDiskAtomIterator iter = scanner.next();
        assertEquals(key, iter.getKey());
        assert iter.next() instanceof RangeTombstone;
        assert !iter.hasNext();
    }

    public static void assertMaxTimestamp(ColumnFamilyStore cfs, long maxTimestampExpected)
    {
        long maxTimestampObserved = Long.MIN_VALUE;
        for (SSTableReader sstable : cfs.getSSTables())
            maxTimestampObserved = Math.max(sstable.getMaxTimestamp(), maxTimestampObserved);
        assertEquals(maxTimestampExpected, maxTimestampObserved);
    }

    @Test
    public void testEchoedRow() throws IOException, ExecutionException, InterruptedException
    {
        // This test check that EchoedRow doesn't skipp rows: see CASSANDRA-2653

        Table table = Table.open(TABLE1);
        ColumnFamilyStore cfs = table.getColumnFamilyStore("Standard2");

        // disable compaction while flushing
        cfs.disableAutoCompaction();

        // Insert 4 keys in two sstables. We need the sstables to have 2 rows
        // at least to trigger what was causing CASSANDRA-2653
        for (int i=1; i < 5; i++)
        {
            DecoratedKey key = Util.dk(String.valueOf(i));
            RowMutation rm = new RowMutation(TABLE1, key.key);
            rm.add("Standard2", ByteBufferUtil.bytes(String.valueOf(i)), ByteBufferUtil.EMPTY_BYTE_BUFFER, i);
            rm.apply();

            if (i % 2 == 0)
                cfs.forceBlockingFlush();
        }
        Collection<SSTableReader> toCompact = cfs.getSSTables();
        assert toCompact.size() == 2;

        // Reinserting the same keys. We will compact only the previous sstable, but we need those new ones
        // to make sure we use EchoedRow, otherwise it won't be used because purge can be done.
        for (int i=1; i < 5; i++)
        {
            DecoratedKey key = Util.dk(String.valueOf(i));
            RowMutation rm = new RowMutation(TABLE1, key.key);
            rm.add("Standard2", ByteBufferUtil.bytes(String.valueOf(i)), ByteBufferUtil.EMPTY_BYTE_BUFFER, i);
            rm.apply();
        }
        cfs.forceBlockingFlush();
        SSTableReader tmpSSTable = null;
        for (SSTableReader sstable : cfs.getSSTables())
            if (!toCompact.contains(sstable))
                tmpSSTable = sstable;
        assert tmpSSTable != null;

        // Force compaction on first sstables. Since each row is in only one sstable, we will be using EchoedRow.
        Util.compact(cfs, toCompact);
        assertEquals(2, cfs.getSSTables().size());

        // Now, we remove the sstable that was just created to force the use of EchoedRow (so that it doesn't hide the problem)
        cfs.markObsolete(Collections.singleton(tmpSSTable), OperationType.UNKNOWN);
        assertEquals(1, cfs.getSSTables().size());

        // Now assert we do have the 4 keys
        assertEquals(4, Util.getRangeSlice(cfs).size());
    }

    @Test
    public void testDontPurgeAccidentaly() throws IOException, ExecutionException, InterruptedException
    {
        testDontPurgeAccidentaly("test1", "Super5");

        // Use CF with gc_grace=0, see last bug of CASSANDRA-2786
        testDontPurgeAccidentaly("test1", "SuperDirectGC");
    }

    @Test
    public void testUserDefinedCompaction() throws Exception
    {
        Table table = Table.open(TABLE1);
        final String cfname = "Standard3"; // use clean(no sstable) CF
        ColumnFamilyStore cfs = table.getColumnFamilyStore(cfname);

        // disable compaction while flushing
        cfs.disableAutoCompaction();

        final int ROWS_PER_SSTABLE = 10;
        for (int i = 0; i < ROWS_PER_SSTABLE; i++) {
            DecoratedKey key = Util.dk(String.valueOf(i));
            RowMutation rm = new RowMutation(TABLE1, key.key);
            rm.add(cfname, ByteBufferUtil.bytes("col"),
                   ByteBufferUtil.EMPTY_BYTE_BUFFER,
                   System.currentTimeMillis());
            rm.apply();
        }
        cfs.forceBlockingFlush();
        Collection<SSTableReader> sstables = cfs.getSSTables();

        assert sstables.size() == 1;
        SSTableReader sstable = sstables.iterator().next();

        int prevGeneration = sstable.descriptor.generation;
        String file = new File(sstable.descriptor.filenameFor(Component.DATA)).getName();
        // submit user defined compaction on flushed sstable
        CompactionManager.instance.forceUserDefinedCompaction(file);
        // wait until user defined compaction finishes
        do
        {
            Thread.sleep(100);
        } while (CompactionManager.instance.getPendingTasks() > 0 || CompactionManager.instance.getActiveCompactions() > 0);
        // CF should have only one sstable with generation number advanced
        sstables = cfs.getSSTables();
        assert sstables.size() == 1;
        assert sstables.iterator().next().descriptor.generation == prevGeneration + 1;
    }

    @Test
    public void testCompactionLog() throws Exception
    {
        SystemTable.discardCompactionsInProgress();

        String cf = "Standard4";
        ColumnFamilyStore cfs = Table.open(TABLE1).getColumnFamilyStore(cf);
        insertData(TABLE1, cf, 0, 1);
        cfs.forceBlockingFlush();

        Collection<SSTableReader> sstables = cfs.getSSTables();
        assert !sstables.isEmpty();
        Set<Integer> generations = Sets.newHashSet(Iterables.transform(sstables, new Function<SSTableReader, Integer>()
        {
            public Integer apply(SSTableReader sstable)
            {
                return sstable.descriptor.generation;
            }
        }));
        UUID taskId = SystemTable.startCompaction(cfs, sstables);
        SetMultimap<Pair<String, String>, Integer> compactionLogs = SystemTable.getUnfinishedCompactions();
        Set<Integer> unfinishedCompactions = compactionLogs.get(Pair.create(TABLE1, cf));
        assert unfinishedCompactions.containsAll(generations);

        SystemTable.finishCompaction(taskId);
        compactionLogs = SystemTable.getUnfinishedCompactions();
        assert !compactionLogs.containsKey(Pair.create(TABLE1, cf));
    }

    private void testDontPurgeAccidentaly(String k, String cfname) throws IOException, ExecutionException, InterruptedException
    {
        // This test catches the regression of CASSANDRA-2786
        Table table = Table.open(TABLE1);
        ColumnFamilyStore cfs = table.getColumnFamilyStore(cfname);

        // disable compaction while flushing
        cfs.clearUnsafe();
        cfs.disableAutoCompaction();

        // Add test row
        DecoratedKey key = Util.dk(k);
        RowMutation rm = new RowMutation(TABLE1, key.key);
        rm.add(cfname, CompositeType.build(ByteBufferUtil.bytes("sc"), ByteBufferUtil.bytes("c")), ByteBufferUtil.EMPTY_BYTE_BUFFER, 0);
        rm.apply();

        cfs.forceBlockingFlush();

        Collection<SSTableReader> sstablesBefore = cfs.getSSTables();

        QueryFilter filter = QueryFilter.getIdentityFilter(key, cfname);
        assert !(cfs.getColumnFamily(filter).getColumnCount() == 0);

        // Remove key
        rm = new RowMutation(TABLE1, key.key);
        rm.delete(cfname, 2);
        rm.apply();

        ColumnFamily cf = cfs.getColumnFamily(filter);
        assert cf == null || cf.getColumnCount() == 0 : "should be empty: " + cf;

        // Sleep one second so that the removal is indeed purgeable even with gcgrace == 0
        Thread.sleep(1000);

        cfs.forceBlockingFlush();

        Collection<SSTableReader> sstablesAfter = cfs.getSSTables();
        Collection<SSTableReader> toCompact = new ArrayList<SSTableReader>();
        for (SSTableReader sstable : sstablesAfter)
            if (!sstablesBefore.contains(sstable))
                toCompact.add(sstable);

        Util.compact(cfs, toCompact);

        cf = cfs.getColumnFamily(filter);
        assert cf == null || cf.getColumnCount() == 0 : "should be empty: " + cf;
    }
}


text:
Turma 2:
- Carlos Alves
- Mauro Rodrigues
- Ricardo Duarte

###Logical View

A perspectiva lógica do modelo 4+1 pretende divulgar as principais abstrações do sistema tais como classes e objetos. Para que tal objetivo seja conseguido, é comum o uso de diagramas de *packages*. Este tem como função descrever fragmentos do sistema divididos em agrupamentos lógicos, mostrando as dependências e relações entre estes. Desta forma, está presente a seguir um possível diagrama de *packages* referente ao sistema Jekyll:

[](https://github.com/)

Após uma análise ponderada ao esquema anterior, é possível constatar que o programa Jekyll apresenta dois packages principais, o jekyll e site_template. É no package jekyll que se encontra o código responsável pela conversão de texto simples em html e css. Este contém ainda dois packages importantes para a execução da sua função, sendo este o converters, que inclui todo o código necessário para a conversão dos ficheiros, e o commands, que processa os comandos dados pelo utilizador.
Por outro lado, também é importante realçar a importância do package site_template visto que é neste que ficará guardado todo o código html e css gerado pelo jekyll, ou seja, site_template contém o código de um website estático.

###Implementation View

A vista de implementação tem como objetivo mostrar, nomeadamente sob a forma de um diagrama de componentes, como os componentes de um sistema de software estão relacionados entre si.
Após uma discussão por parte dos elementos do grupo, chegou-se à conclusão que existem dois componentes principais. A componente de Parser, que recebe templates e conteúdo por parte do utilizador e interpreta-os, e a componente de render, que utiliza o conteúdo "parsed" para fazer o render e criar ficheiros html e css.

[](https://github.com/)

###Deployment View

A vista de deployment pretende ilustrar de que forma os elementos de software existentes no sistema em questão se relacionam com os módulos de hardware existentes. No programa Jekyll, o uso de um computador pessoal para executar o programa representa a única relação que o software de Jekyll possui com componentes hardware. Deste forma, o diagrama de deployment será tão simples como o seguinte:

[](https://github.com/)

###Process View

A vista de processo tem como objetivo mostrar os vários processos do sistema bem como as suas interações em run-time, utilizando-se para isso um diagrama de atividades.
De acordo com o site jekyllbootstrap (http://jekyllbootstrap.com/lessons/jekyll-introduction.html) existem quatro principais atividades :

>1- Jekyll collects data.
Jekyll scans the posts directory and collects all posts files as post objects. It then scans the layout assets and collects those and finally scans other directories in search of pages.

>2- Jekyll computes data.
Jekyll takes these objects, computes metadata (permalinks, tags, categories, titles, dates) from them and constructs one big site object that holds all the posts, pages, layouts, and respective metadata. At this stage your site is one big computed ruby object.

>3- Jekyll liquifies posts and templates.
Next jekyll loops through each post file and converts (through markdown or textile) and liquifies the post inside of its respective layout(s). Once the post is parsed and liquified inside the the proper layout structure, the layout itself is "liquified".
Liquification is defined as follows: Jekyll initiates a Liquid template, and passes a simpler hash representation of the ruby site object as well as a simpler hash representation of the ruby post object. These simplified data structures are what you have access to in the templates.

>4- Jekyll generates output.
Finally the liquid templates are "rendered", thereby processing any liquid syntax provided in the templates and saving the final, static representation of the file.

Por isso o grupo decidiu criar o seguinte diagrama para representar essas quatro atividades:

[](https://github.com/)

###Use case view

A vista de casos de uso está associada à relação que o utilizador possui com o programa em questão. Esta vista utiliza esquemas designados por diagramas de casos de uso para ilustrar quais as possibilidades que estão ao dispor do utilizador quando este usa a plataforma. Explicitando melhor, a vista de casos de uso representa todos os passos presentes na interação entre o utilizador e o programa.
Apresenta-se a seguir um possível diagrama de casos de uso referente ao Jekyll:

[](https://github.com/)

Como indica o diagrama acima representado, o utilizador pode fazer a edição de texto num editor à sua escolha, seguidamente, este executa o Jekyll e obterá uma pasta com os ficheiros representativos de um website, isto é, com extensões .html e .css. Por outro lado, o utilizador também tem a possibilidade de visualizar o resultado final do seu website estático. Para tal, este deve abrir o browser no localhost com valor indicado pelo programa. De seguida, os ficheiros serão carregados para o browser e o utilizador poderá visualizar o site que construiu com a ferramenta Jekyll.


text:
import esp

class PinSet:
    def __init__(self):
        esp.gpio.p16_init()
        esp.gpio.p16_write(1)

    def on(self):
        esp.gpio.p16_write(0)

    def off(self):
        esp.gpio.p16_write(1)

class Indicator:
    ON = 0
    OFF = 1

    def __init__(self, pin_setter=PinSet):
        self.pin_setter = pin_setter()
        self.timer = None
        self.state = self.OFF
        self.ons = 0

    def timer_target(self):
        if self.state == self.ON:
            self.pin_setter.off()
            self.state = self.OFF
        else:
            self.pin_setter.on()
            self.state = self.ON
            self.ons += 1

    def blink_cancel(self):
        if self.timer:
            self.timer.cancel()
            self.timer = None

    def blink(self, period=100):
        self.blink_cancel()
        self.timer = esp.os_timer(lambda timer: self.timer_target(),
                                  period=period)

    def on(self):
        self.blink_cancel()
        self.pin_setter.on()
        self.state = self.ON
        self.ons += 1

    def off(self):
        self.blink_cancel()
        self.pin_setter.off()
        self.state = self.OFF

    def indicate(self, state):
        if state:
            self.on()
        else:
            self.off()


text:
@interface PreferencesWindowController : NSWindowController <NSWindowDelegate>

#pragma mark - UI Bindings
#pragma mark - Settings
@property (weak              ) IBOutlet NSTextField   *staticPortNumberTextField;
@property (weak              ) IBOutlet NSButton      *allowAnimationsButton;
@property (weak              ) IBOutlet NSButton      *allowMessagesButton;
@property (weak              ) IBOutlet NSButton      *allowRemoteConnectionsButton;
@property (weak              ) IBOutlet NSTextField   *fastestField;
@property (weak              ) IBOutlet NSStepper     *fastestStepper;
@property (weak              ) IBOutlet NSTextField   *fasterField;
@property (weak              ) IBOutlet NSStepper     *fasterStepper;
@property (weak              ) IBOutlet NSTextField   *fastField;
@property (weak              ) IBOutlet NSStepper     *fastStepper;
@property (weak              ) IBOutlet NSTextField   *normalField;
@property (weak              ) IBOutlet NSStepper     *normalStepper;
@property (weak              ) IBOutlet NSTextField   *slowField;
@property (weak              ) IBOutlet NSStepper     *slowStepper;
@property (weak              ) IBOutlet NSTextField   *slowerField;
@property (weak              ) IBOutlet NSStepper     *slowerStepper;
@property (weak              ) IBOutlet NSTextField   *slowestField;
@property (weak              ) IBOutlet NSStepper     *slowestStepper;
@property (weak              ) IBOutlet NSButton      *restoreAnimationSpeeds;
@property (weak              ) IBOutlet NSButton      *saveAnimationSpeeds;

@property (weak              ) IBOutlet NSButton      *launchOnLoginButton;

#pragma mark - Appearance
@property (weak              ) IBOutlet NSButton      *toggleShapeLock;
@property (weak              ) IBOutlet NSView        *exampleView;

@property (weak              ) IBOutlet NSButton      *backgroundHiddenToggle;
@property (weak              ) IBOutlet NSPopUpButton *backgroundShapeList;
@property (weak              ) IBOutlet NSColorWell   *backgroundFillColor;
@property (weak              ) IBOutlet NSColorWell   *backgroundStrokeColor;
@property (weak              ) IBOutlet NSTextField   *backgroundLineWidthField;
@property (weak              ) IBOutlet NSStepper     *backgroundLineWidthStepper;

@property (weak              ) IBOutlet NSButton      *foregroundHiddenToggle;
@property (weak              ) IBOutlet NSPopUpButton *foregroundShapeList;
@property (weak              ) IBOutlet NSColorWell   *foregroundFillColor;
@property (weak              ) IBOutlet NSColorWell   *foregroundStrokeColor;
@property (weak              ) IBOutlet NSTextField   *foregroundLineWidthField;
@property (weak              ) IBOutlet NSStepper     *foregroundLineWidthStepper;

@property (weak              ) IBOutlet NSButton      *textHiddenToggle;
@property (weak              ) IBOutlet NSColorWell   *textForegroundColor;
@property (weak              ) IBOutlet NSTextField   *textStringField;
@property (weak              ) IBOutlet NSTextField   *textFontSizeField;
@property (weak              ) IBOutlet NSStepper     *textFontSizeStepper;
@property (weak              ) IBOutlet NSPopUpButton *textFontList;

@property (weak              ) IBOutlet NSTextField   *inputTextField;
@property (weak              ) IBOutlet NSTextField   *inputResultField;

@property (weak              ) IBOutlet NSButton      *resetButton;
@property (weak              ) IBOutlet NSButton      *acceptButton;

@end


text:
Fast, in memory work queue. `fastq` is API compatible with
[`async.queue`](https://github.com/caolan/async#queueworker-concurrency)

Benchmarks (1 million tasks):

* setImmediate: 1359ms
* fastq: 1492ms
* async.queue: 4039ms
* neoAsync.queue: 4476ms

Obtained on node 4.2.2, on a MacBook Pro 2014 (i7, 16GB of RAM).

If you need zero-overhead series function call, check out
[fastseries](http://npm.im/fastseries). For zero-overhead parallel
function call, check out [fastparallel](http://npm.im/fastparallel).

[![js-standard-style](https://raw.githubusercontent.com/feross/standard/master/badge.png)](https://github.com/feross/standard)

  * Installation
  * Basic Example
  * API
  * Licence & copyright

## Install

`npm i fastq --save`

## Usage

```js
'use strict'

var queue = require('fastq')(worker, 1)

queue.push(42, function (err, result) {
  if (err) { throw err }
  console.log('the result is', result)
})

function worker (arg, cb) {
  cb(null, 42 * 2)
}
```

### Setting this

```js
'use strict'

var that = { hello: 'world' }
var queue = require('fastq')(that, worker, 1)

queue.push(42, function (err, result) {
  if (err) { throw err }
  console.log(this)
  console.log('the result is', result)
})

function worker (arg, cb) {
  console.log(this)
  cb(null, 42 * 2)
}
```

## API

* fastqueue()
* queue#push()
* queue#unshift()
* queue#pause()
* queue#resume()
* queue#idle()
* queue#length()
* queue#kill()
* queue#killAndDrain()
* queue#concurrency
* queue#drain
* queue#empty
* queue#saturated

-------------------------------------------------------

### fastqueue([that], worker, concurrency)

Creates a new queue.

Arguments:

* `that`, optional context of the `worker` function.
* `worker`, worker function, it would be called with `that` as `this`,
  if that is specified.
* `concurrency`, number of concurrent tasks that could be executed in
  parallel.

-------------------------------------------------------

### queue.push(task, done)

Add a task at the end of the queue. `done(err, result)` will be called
when the task was processed.

-------------------------------------------------------

### queue.unshift(task, done)

Add a task at the beginning of the queue. `done(err, result)` will be called
when the task was processed.

-------------------------------------------------------

### queue.pause()

Pause the processing of tasks. Currently worked tasks are not
stopped.

-------------------------------------------------------

### queue.resume()

Resume the processing of tasks.

-------------------------------------------------------

### queue.idle()

Returns `false` if there are tasks being processed or waiting to be processed.
`true` otherwise.

-------------------------------------------------------

### queue.length()

Returns the number of tasks waiting to be processed (in the queue).

-------------------------------------------------------

### queue.kill()

Removes all tasks waiting to be processed, and reset `drain` to an empty
function.

-------------------------------------------------------

### queue.killAndDrain()

Same than `kill` but the `drain` function will be called before reset to empty.

-------------------------------------------------------

### queue.concurrency

Property that returns the number of concurrent tasks that could be executed in
parallel. It can be altered at runtime.

-------------------------------------------------------

### queue.drain

Function that will be called when the last
item from the queue has been processed by a worker.
It can be altered at runtime.

-------------------------------------------------------

### queue.empty

Function that will be called when the last
item from the queue has been assigned to a worker.
It can be altered at runtime.

-------------------------------------------------------

### queue.saturated

Function that will be called when the queue hits the concurrency
limit.
It can be altered at runtime.

## License

ISC


text:
import React from 'react';
import { StyleSheet, View } from 'react-native';
import distanceInWordsToNow from 'date-fns/distance_in_words_to_now';

import { Label, RawLabel } from '../common';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
  },
  text: {
    fontSize: 10,
    color: 'rgba(127, 127, 127, 0.75)',
  },
  tag: {
    paddingTop: 2,
    paddingRight: 4,
    paddingBottom: 2,
    paddingLeft: 4,
    marginLeft: 4,
    borderRadius: 2,
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
  }
});

export default class MessageTags extends React.PureComponent {
  render() {
    const { timestamp, starred } = this.props;

    if (timestamp === undefined && !starred) return null;

    const editedTime = distanceInWordsToNow(timestamp * 1000);

    return (
      <View style={styles.container}>
        {timestamp &&
          <View style={styles.tag}>
            <RawLabel style={styles.text} text={`edited ${editedTime} ago`} />
          </View>
        }
        {starred &&
          <View style={styles.tag}>
            <Label style={styles.text} text={'starred'} />
          </View>
        }
      </View>
    );
  }
}


text:
adsApp.directive('publicAds', function() {
    return {
        controller: 'PublicAdsCtrl',
        restrict: 'E',
        templateUrl: 'templates/public/public-ads.html',
        replace: true
    }
});


text:
(function() {
  var $, TextEditorView, View, _ref,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  _ref = require('space-pen'), View = _ref.View, $ = _ref.$;

  module.exports = TextEditorView = (function(_super) {
    __extends(TextEditorView, _super);

    function TextEditorView(params) {
      var attributes, editor, mini, name, placeholderText, value;
      if (params == null) {
        params = {};
      }
      mini = params.mini, placeholderText = params.placeholderText, attributes = params.attributes, editor = params.editor;
      if (attributes == null) {
        attributes = {};
      }
      if (mini != null) {
        attributes['mini'] = mini;
      }
      if (placeholderText != null) {
        attributes['placeholder-text'] = placeholderText;
      }
      if (editor != null) {
        this.element = atom.views.getView(editor);
      } else {
        this.element = document.createElement('atom-text-editor');
      }
      for (name in attributes) {
        value = attributes[name];
        this.element.setAttribute(name, value);
      }
      if (this.element.__spacePenView != null) {
        this.element.__spacePenView = this;
        this.element.__allowViewAccess = true;
      }
      TextEditorView.__super__.constructor.apply(this, arguments);
      this.setModel(this.element.getModel());
    }

    TextEditorView.prototype.setModel = function(model) {
      this.model = model;
    };

    TextEditorView.prototype.getModel = function() {
      return this.model;
    };

    TextEditorView.prototype.getText = function() {
      return this.model.getText();
    };

    TextEditorView.prototype.setText = function(text) {
      return this.model.setText(text);
    };

    TextEditorView.prototype.hasFocus = function() {
      return this.element.hasFocus();
    };

    return TextEditorView;

  })(View);

}).call(this);


text:
require 'webmock/rspec'
include WebMock::API


text:
/**
 * This file contains all necessary Angular controller definitions for 'frontend.admin.login-history' module.
 *
 * Note that this file should only contain controllers and nothing else.
 */
(function() {
    'use strict';

    angular.module('frontend.upstreams')
        .controller('AlertsModalController', [
            '_','$scope', '$rootScope','$q','$log','UserModel',
            'SocketHelperService','UserService','SettingsService','MessageService',
            '$state','DialogService','Upstream','$localStorage', 'DataModel',
            'ListConfig', '$uibModalInstance', '_upstreams',
            function controller(_,$scope, $rootScope,$q,$log,UserModel,
                                SocketHelperService, UserService,SettingsService, MessageService,
                                $state,DialogService,Upstream,$localStorage, DataModel,
                                ListConfig, $uibModalInstance, _upstreams ) {

                const Alert = new DataModel('api/upstreamalert', true);
                Alert.setScope($scope, false, 'items', 'itemCount');
                $scope = angular.extend($scope, angular.copy(ListConfig.getConfig('upstreamAlert',Alert)));
                $scope.user = UserService.user();

                $scope.close = () => {
                    $uibModalInstance.dismiss()
                }

                $scope.alertsCount = 0;

                $scope.openCreateItemModal = function() {

                    $uibModal.open({
                        animation: true,
                        ariaLabelledBy: 'modal-title',
                        ariaDescribedBy: 'modal-body',
                        templateUrl: 'js/app/upstreams/add-upstream-modal.html?v=' + $rootScope.konga_version,
                        controller: 'AddUpstreamModalController',
                        controllerAs: '$ctrl',
                        //size: 'lg',
                    });
                };

                $scope.openAlertsListModal = () => {
                    $uibModal.open({
                        animation: true,
                        ariaLabelledBy: 'modal-title',
                        ariaDescribedBy: 'modal-body',
                        templateUrl: 'js/app/upstreams/alerts/alerts-modal.html?v=' + $rootScope.konga_version,
                        controller: 'AddUpstreamModalController',
                        controllerAs: '$ctrl',
                        //size: 'lg',
                    });
                }

                function _fetchData(){
                    $scope.loading  = true;

                    Alert.load({
                        connection: _.get($scope.user,'node.id'),
                        populate: 'connection'
                    }).then(function(response){
                        response.forEach(item => {
                            item.upstream = _.find(_upstreams, upstream => item.upstream_id === upstream.id)
                        })
                        $scope.items = response
                        console.log("Loaded alerts =>", $scope.items);
                        $scope.loading  = false;
                    });
                }

                _fetchData();
            }
        ])
    ;
}());


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2013-2015 alladin-IT GmbH

  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.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="top"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="10dp"
    android:paddingLeft="12dp"
    android:paddingRight="12dp"
    android:paddingTop="8dp" >

    <TextView
        style="@style/blockHeader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="2dp"
        android:text="@string/terms" />

    <ScrollView
        style="@style/listViewResult"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="5dp"
        android:layout_weight="1"
        android:background="@color/transparent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <WebView
                android:id="@+id/termsCheckWebViewLong"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@color/transparent" />
        </LinearLayout>
    </ScrollView>

    <TextView
        style="@style/textSmallLight"
        android:id="@+id/termsAcceptText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        android:text="@string/terms_accept_text"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_marginTop="2dp"
        android:baselineAligned="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <RelativeLayout
            android:padding="5dp"
            android:layout_weight="1"
            android:id="@+id/termsButtonDecline"
            android:layout_width="0dp"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/termsDeclineButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:text="@string/terms_decline_button"
                android:background="@drawable/button_selector" />

        </RelativeLayout>

        <RelativeLayout
			android:padding="5dp"
            android:layout_weight="1"
            android:id="@+id/termsButtonAccept"
            android:layout_width="0dp"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/termsAcceptButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:text="@string/terms_accept_button"
                android:background="@drawable/button_selector" />
        </RelativeLayout>
    </LinearLayout>

</LinearLayout>


text:
/*
 * apei.h - ACPI Platform Error Interface
 */

#ifndef ACPI_APEI_H
#define ACPI_APEI_H

#include <linux/acpi.h>
#include <linux/cper.h>
#include <asm/ioctls.h>

#define APEI_ERST_INVALID_RECORD_ID	0xffffffffffffffffULL

#define APEI_ERST_CLEAR_RECORD		_IOW('E', 1, u64)
#define APEI_ERST_GET_RECORD_COUNT	_IOR('E', 2, u32)

#ifdef __KERNEL__

extern int hest_disable;
extern int erst_disable;
#ifdef CONFIG_ACPI_APEI_GHES
extern int ghes_disable;
#else
#define ghes_disable 1
#endif

#ifdef CONFIG_ACPI_APEI
void __init acpi_hest_init(void);
#else
static inline void acpi_hest_init(void) { return; }
#endif

typedef int (*apei_hest_func_t)(struct acpi_hest_header *hest_hdr, void *data);
int apei_hest_parse(apei_hest_func_t func, void *data);

int erst_write(const struct cper_record_header *record);
ssize_t erst_get_record_count(void);
int erst_get_record_id_begin(int *pos);
int erst_get_record_id_next(int *pos, u64 *record_id);
void erst_get_record_id_end(void);
ssize_t erst_read(u64 record_id, struct cper_record_header *record,
		  size_t buflen);
int erst_clear(u64 record_id);

#endif
#endif


text:
    {{abilityName}}

        {{character.abilities.get(ability)}}  0) ? 'text-success' : modifier === 0 ? '' : 'text-danger'">({{modifierText}})


text:
package iso20022

// Choice between a standard code or a proprietary code to specify the features that may apply to a corporate action option.
type OptionFeaturesFormat22Choice struct {

	// Standard code to specify the features that may apply to a corporate action option.
	Code *OptionFeatures10Code `xml:"Cd"`

	// Proprietary identification of the features that may apply to a corporate action option.
	Proprietary *GenericIdentification30 `xml:"Prtry"`
}

func (o *OptionFeaturesFormat22Choice) SetCode(value string) {
	o.Code = (*OptionFeatures10Code)(&value)
}

func (o *OptionFeaturesFormat22Choice) AddProprietary() *GenericIdentification30 {
	o.Proprietary = new(GenericIdentification30)
	return o.Proprietary
}


text:
import TextLimit from './text-limit';

var WORD = /\S+/g;

export default TextLimit.extend({
  _count: function(text) {
    var words = text.match(WORD);
    return words ? words.length : 0;
  }
});


text:
/* eslint-env jest */
import hasAccessibleChild from '../../../src/util/hasAccessibleChild';
import JSXElementMock from '../../../__mocks__/JSXElementMock';
import JSXAttributeMock from '../../../__mocks__/JSXAttributeMock';
import JSXExpressionContainerMock from '../../../__mocks__/JSXExpressionContainerMock';

describe('hasAccessibleChild', () => {
  describe('has no children and does not set dangerouslySetInnerHTML', () => {
    it('returns false', () => {
      expect(hasAccessibleChild(JSXElementMock('div', []))).toBe(false);
    });
  });

  describe('has no children and sets dangerouslySetInnerHTML', () => {
    it('Returns true', () => {
      const prop = JSXAttributeMock('dangerouslySetInnerHTML', true);
      const element = JSXElementMock('div', [prop], []);
      expect(hasAccessibleChild(element)).toBe(true);
    });
  });

  describe('has children', () => {
    it('Returns true for a Literal child', () => {
      const child = {
        type: 'Literal',
        value: 'foo',
      };
      const element = JSXElementMock('div', [], [child]);
      expect(hasAccessibleChild(element)).toBe(true);
    });

    it('Returns true for visible child JSXElement', () => {
      const child = JSXElementMock('div', []);
      const element = JSXElementMock('div', [], [child]);
      expect(hasAccessibleChild(element)).toBe(true);
    });

    it('Returns true for JSXText Element', () => {
      const child = {
        type: 'JSXText',
        value: 'foo',
      };
      const element = JSXElementMock('div', [], [child]);
      expect(hasAccessibleChild(element)).toBe(true);
    });

    it('Returns false for hidden child JSXElement', () => {
      const ariaHiddenAttr = JSXAttributeMock('aria-hidden', true);
      const child = JSXElementMock('div', [ariaHiddenAttr]);
      const element = JSXElementMock('div', [], [child]);
      expect(hasAccessibleChild(element)).toBe(false);
    });

    it('Returns true for defined JSXExpressionContainer', () => {
      const expression = {
        type: 'Identifier',
        name: 'foo',
      };
      const child = JSXExpressionContainerMock(expression);
      const element = JSXElementMock('div', [], [child]);
      expect(hasAccessibleChild(element)).toBe(true);
    });

    it('Returns false for undefined JSXExpressionContainer', () => {
      const expression = {
        type: 'Identifier',
        name: 'undefined',
      };
      const child = JSXExpressionContainerMock(expression);
      const element = JSXElementMock('div', [], [child]);
      expect(hasAccessibleChild(element)).toBe(false);
    });

    it('Returns false for unknown child type', () => {
      const child = {
        type: 'Unknown',
      };
      const element = JSXElementMock('div', [], [child]);
      expect(hasAccessibleChild(element)).toBe(false);
    });

    it('Returns true with children passed as a prop', () => {
      const children = JSXAttributeMock('children', true);
      const element = JSXElementMock('div', [children], []);
      expect(hasAccessibleChild(element)).toBe(true);
    });
  });
});


text:
<!-- This file was autogenerated via cilium cmdref, do not edit manually-->

## cilium endpoint health

View endpoint health

### Synopsis

View endpoint health

```
cilium endpoint health <endpoint id>
```

### Examples

```
cilium endpoint health 5421
```

### Options

```
  -o, --output string   json| jsonpath='{}'
```

### Options inherited from parent commands

```
      --config string   config file (default is $HOME/.cilium.yaml)
  -D, --debug           Enable debug messages
  -H, --host string     URI to server-side API
```

### SEE ALSO
* [cilium endpoint](../cilium_endpoint)	 - Manage endpoints


text:
Homebrew has begun gathering anonymous aggregate user behaviour analytics and reporting these to Google Analytics. You will be notified the first time you run `brew update` or install Homebrew.

## Why?
Homebrew is provided free of charge and run entirely by volunteers in their spare time. As a result, we do not have the resources to do detailed user studies of Homebrew users to decide on how best to design future features and prioritise current work. Anonymous aggregate user analytics allow us to prioritise fixes and features based on how, where and when people use Homebrew. For example:

- If a formula is widely used and is failing often it will enable us to prioritise fixing that formula over others.
- Collecting the OS version allows us to decide what versions of macOS to prioritise and support and identify build failures that occur only on single versions.

## What?
Homebrew's analytics record some shared information for every event:

- The Homebrew user agent, e.g. `Homebrew/0.9.9 (Macintosh; Intel macOS 10.12.0) curl/7.43.0`
- The Google Analytics version, i.e. `1` (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#v)
- The Homebrew analytics tracking ID, e.g. `UA-75654628-1` (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#tid)
- A Homebrew analytics user ID, e.g. `1BAB65CC-FE7F-4D8C-AB45-B7DB5A6BA9CB`. This is generated by `uuidgen` and stored in the repository-specific Git configuration variable `homebrew.analyticsuuid` within `$(brew --repository)/.git/config`. This does not allow us to track individual users but does enable us to accurately measure user counts vs. event counts (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#cid)
- If the Google Analytics anonymous IP setting is enabled, i.e. `1` (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#aip)
- The Homebrew application name, e.g. `Homebrew` (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#an)
- The Homebrew application version, e.g. `0.9.9` (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#av)
- The Homebrew analytics hit type, e.g. `screenview` (https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#t)

Homebrew's analytics records the following different events:

- a `screenview` hit type with the official Homebrew command you have run (with arguments stripped), e.g. `brew list` (not `brew list foo` or any external commands except `bundle` and `services`)
- an `event` hit type with the `install` event category and the Homebrew formula from a non-private GitHub tap you have requested to install plus any used options, e.g. `wget --with-pcre` as the action and an event label e.g. `macOS 10.12, non-/usr/local, CI` to indicate the OS version, non-standard installation location and invocation as part of CI. This allows us to identify the formulae that need fixing and where more easily.
- an `event` hit type with the `BuildError` event category and the Homebrew formula that failed to install, e.g. `wget` as the action and an event label e.g. `macOS 10.12`
- an `exception` hit type with the `exception` event category and exception description of the exception name, e.g. `FormulaUnavailableError` and whether the exception was fatal e.g. `1`

You can also view all the information that is sent by Homebrew's analytics by setting `HOMEBREW_ANALYTICS_DEBUG=1` in your environment. Please note this will also stop any analytics from being sent.

It is impossible for the Homebrew developers to match any particular event to any particular user, even if we had access to the Homebrew analytics user ID (which we do not). An example of the most user-specific information we can see from Google Analytics:

![Aggregate user analytics](img/docs/analytics.png)

As far as we can tell it would be impossible for Google to match the randomly generated Homebrew-only analytics user ID to any other Google Analytics user ID. If Google turned evil the only thing they could do would be to lie about anonymising IP addresses and attempt to match users based on IP addresses.

## When/Where?
Homebrew's analytics are sent throughout Homebrew's execution to Google Analytics over HTTPS.

## Who?
Homebrew's analytics are accessible to Homebrew's current maintainers. Contact @MikeMcQuaid if you are a maintainer and need access.

## How?
The code is viewable in [analytics.rb](https://github.com/Homebrew/brew/blob/master/Library/Homebrew/utils/analytics.rb) and [analytics.sh](https://github.com/Homebrew/brew/blob/master/Library/Homebrew/utils/analytics.sh). They are done in a separate background process and fail fast to avoid delaying any execution. They will fail immediately and silently if you have no network connection.

## Opting out
Homebrew analytics helps us maintainers and leaving it on is appreciated. However, if you want to opt out of Homebrew's analytics, you can set this variable in your environment:

```sh
export HOMEBREW_NO_ANALYTICS=1
```

Alternatively, this will prevent analytics from ever being sent:

```sh
brew analytics off
```


text:
from grail import BaseTest, step

class MyVeryFormattedTest(BaseTest):
    def test_some_feature(self):
        self.some_tricky_formatting('value', kwarg_to_format='kw_value', skip_this=100500)

    @step(description='Some info: {0}, another info: {kwarg_to_format}', format_description=True)
    def some_tricky_formatting(self, arg_to_format, kwarg_to_format, skip_this):
        print arg_to_format
        print kwarg_to_format
        print skip_this


text:
import BvEvent from './bv-event.class'

describe('utils/BvEvent class', () => {
  it('works', async () => {
    const evt = new BvEvent('foobar')
    expect(evt).toBeInstanceOf(BvEvent)
    expect(evt.type).toBe('foobar')
  })

  it('throws exception if no type given', async () => {
    let evt = null
    let failed = false
    try {
      evt = new BvEvent()
    } catch (e) {
      failed = true
    }
    expect(evt).not.toBeInstanceOf(BvEvent)
    expect(evt).toBe(null)
    expect(failed).toBe(true)
  })

  it('supports cancelable events', async () => {
    const evt = new BvEvent('foobar', {
      cancelable: true
    })
    expect(evt).toBeInstanceOf(BvEvent)
    expect(evt.type).toBe('foobar')
    expect(evt.cancelable).toBe(true)
    expect(evt.defaultPrevented).toBe(false)
    evt.preventDefault()
    expect(evt.defaultPrevented).toBe(true)
  })

  it('supports non cancelable events', async () => {
    const evt = new BvEvent('foobar', {
      cancelable: false
    })
    expect(evt).toBeInstanceOf(BvEvent)
    expect(evt.type).toBe('foobar')
    expect(evt.cancelable).toBe(false)
    expect(evt.defaultPrevented).toBe(false)
    evt.preventDefault()
    expect(evt.defaultPrevented).toBe(false)
  })

  it('supports built in properties', async () => {
    const evt = new BvEvent('foobar', {
      target: 'baz'
    })
    expect(evt).toBeInstanceOf(BvEvent)
    expect(evt.type).toBe('foobar')
    expect(evt.cancelable).toBe(true)
    expect(evt.target).toBe('baz')
  })

  it('supports custom properties', async () => {
    const evt = new BvEvent('foobar', {
      custom: 123
    })
    expect(evt).toBeInstanceOf(BvEvent)
    expect(evt.type).toBe('foobar')
    expect(evt.cancelable).toBe(true)
    expect(evt.custom).toBe(123)
  })
})


text:
import { element, by } from 'protractor';
import { AppPage } from './app.po';

describe('providers App', () => {
  let page: AppPage;

  beforeEach(async () => {
    page = new AppPage();
    await page.navigateTo();
  });

  it('should display header that says Users list', async () => {
    expect(await page.getTitleText()).toEqual('Users list');
  });

  it('shows a list of customers', async () => {
    const items = element.all(by.css('app-root li'));
    expect(await items.count()).toBe(10);
    expect(await items.get(0).getText()).toBe('1 Maria');
    expect(await items.get(9).getText()).toBe('10 Seth');
  });

});


text:
using NUnit.Framework;
using System.Collections.Generic;
using TAlex.MathCore.ExpressionEvaluation.Tokenize;
using FluentAssertions;

namespace TAlex.MathCore.ComplexExpressions.Tests.Tokenize
{
    [TestFixture]
    public class ComplexExpressionTokenizerTests
    {
        protected IExpressionTokenizer Tokenizer = new StandardExpressionTokenizer();

        [SetUp]
        public virtual void SetUp()
        {
            Tokenizer = new ComplexExpressionTokenizer();
        }

        [Test]
        public void GetTokensTest_ComplexNumber()
        {
            //arrange
            string expression = "1/2i";
            IList<Token> expectedTokens = new List<Token>()
            {
                new Token("1", TokenType.Scalar),
                new Token("/", TokenType.Operator),
                new Token("2", TokenType.Scalar),
                new Token("*", TokenType.Operator),
                new Token("1i", TokenType.Scalar),
                new Token("$", TokenType.End)
            };

            //action
            IEnumerable<Token> actualTokens = Tokenizer.GetTokens(expression);

            //assert
            actualTokens.Should().BeEquivalentTo(expectedTokens);
        }
    }
}


text:
@interface Bidder : MTLModel <MTLJSONSerializing>

@property (nonatomic, strong) NSString *bidderID;
@property (nonatomic, strong) NSString *saleID;

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


text:
package org.caleydo.view.parcoords;

import java.util.ArrayList;

import org.caleydo.core.data.datadomain.DataDomainManager;
import org.caleydo.data.loader.ResourceLoader;
import org.caleydo.data.loader.ResourceLocators;
import org.caleydo.data.loader.ResourceLocators.IResourceLocator;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {
	private static final String ID = "org.caleydo.view.parcoords";
	// The shared instance
	private static Activator plugin;

	@Override
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;

		registerDataDomains();
	}

	@Override
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	public static Activator getDefault() {
		return plugin;
	}

	private void registerDataDomains() {
		ArrayList<String> dataDomainTypes = new ArrayList<String>();
		dataDomainTypes.add("org.caleydo.datadomain.genetic");
		dataDomainTypes.add("org.caleydo.datadomain.generic");
		dataDomainTypes.add("org.caleydo.datadomain.clinical");

		DataDomainManager.get().getAssociationManager()
				.registerDatadomainTypeViewTypeAssociation(dataDomainTypes, GLParallelCoordinates.VIEW_TYPE);
	}

	public static ImageDescriptor getImageDescriptor(String path) {
		return AbstractUIPlugin.imageDescriptorFromPlugin(ID, path);
	}

	public static ResourceLoader getResourceLoader() {
		return new ResourceLoader(getResourceLocator());
	}

	public static IResourceLocator getResourceLocator() {
		return ResourceLocators.chain(
ResourceLocators.classLoader(Activator.class.getClassLoader()),
				ResourceLocators.DATA_CLASSLOADER,
				ResourceLocators.FILE);
	}
}


text:
/**
 * @author Pedro Sanders
 * @since v1
 *
 * Registry's properties
 */
module.exports = (stackName = 'routr', proxyAddr) => {
  const Properties = Java.type('java.util.Properties')
  const properties = new Properties()
  properties.setProperty('javax.sip.STACK_NAME', stackName)
  properties.setProperty('javax.sip.OUTBOUND_PROXY', proxyAddr)
  properties.setProperty('gov.nist.javax.sip.TRACE_LEVEL', 'LOG4J')
  properties.setProperty('gov.nist.javax.sip.DEBUG_LOG', 'etc/debug_log.txt')
  properties.setProperty('gov.nist.javax.sip.SERVER_LOG', 'etc/server_log.txt')
  // Guard against denial of service attack.
  properties.setProperty('gov.nist.javax.sip.MAX_MESSAGE_SIZE', '1048576')
  // Drop the client connection after we are done with the transaction.
  properties.setProperty('gov.nist.javax.sip.CACHE_CLIENT_CONNECTIONS', 'true')
  properties.setProperty(
    'gov.nist.javax.sip.MESSAGE_PROCESSOR_FACTORY',
    'gov.nist.javax.sip.stack.NioMessageProcessorFactory'
  )
  properties.setProperty(
    'gov.nist.javax.sip.PATCH_SIP_WEBSOCKETS_HEADERS',
    'false'
  )
  properties.setProperty('gov.nist.javax.sip.NIO_BLOCKING_MODE', 'NONBLOCKING')
  properties.setProperty('gov.nist.javax.sip.LOG_MESSAGE_CONTENT', 'false')
  properties.setProperty('gov.nist.javax.sip.TRACE_LEVEL', '0')
  properties.setProperty('gov.nist.javax.sip.THREAD_POOL_SIZE', '8')
  properties.setProperty('gov.nist.javax.sip.REENTRANT_LISTENER', 'true')
  properties.setProperty('javax.sip.AUTOMATIC_DIALOG_SUPPORT', 'OFF')
  return properties
}


text:
Pattern: Unspecified exception in `assert_raises`

Issue: -

## Description

Checks for a specified error in `assert_raises`.

## Examples

``` ruby
# bad
assert_raises { raise FooException }
assert_raises('This should have raised') { raise FooException }

# good
assert_raises(FooException) { raise FooException }
assert_raises(FooException, 'This should have raised') { raise FooException }
```

## Further Reading

- <https://minitest.rubystyle.guide#unspecified-exception>


text:
<?xml version="1.0" encoding="utf-8"?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
    <parameters>
        <parameter key="boekkooi.doctrine_event_store.model.class">Boekkooi\Bundle\DoctrineEventStoreBundle\Model\Event</parameter>
        <parameter key="boekkooi.doctrine_event_store.storage.class">Boekkooi\Bundle\DoctrineEventStoreBundle\Doctrine\ORM\Storage</parameter>
        <parameter key="boekkooi.doctrine_event_store.listener_resolver.class">Boekkooi\Bundle\DoctrineEventStoreBundle\Doctrine\ORM\EventListener\EventSourceListenerResolver</parameter>
        <parameter key="boekkooi.doctrine_event_store.listener.class">Boekkooi\Bundle\DoctrineEventStoreBundle\Doctrine\ORM\EventListener\EventSourceListener</parameter>
    </parameters>
    <services>
        <service id="boekkooi.doctrine_event_store.model.event_manager"
                 class="%doctrine.orm.entity_manager.class%"
                 factory-method="getManagerForClass"
                 factory-service="doctrine"
                 public="false">
            <argument>%boekkooi.doctrine_event_store.model.class%</argument>
        </service>
        <service id="boekkooi.doctrine_event_store.model.event_repository"
                 class="Doctrine\Common\Persistence\ObjectRepository"
                 factory-method="getRepository"
                 factory-service="boekkooi.doctrine_event_store.model.event_manager"
                 public="false">
            <argument>%boekkooi.doctrine_event_store.model.class%</argument>
        </service>
        <service id="boekkooi.doctrine_event_store.storage" class="%boekkooi.doctrine_event_store.storage.class%" public="false">
            <argument type="service" id="boekkooi.doctrine_event_store.model.event_manager"/>
            <argument type="service" id="boekkooi.doctrine_event_store.model.event_repository"/>
            <argument type="service" id="jms_serializer"/>
        </service>

        <service id="boekkooi.doctrine_event_store.listener_resolver" class="%boekkooi.doctrine_event_store.listener_resolver.class%">
            <argument type="service" id="service_container"/>
        </service>
        <service id="boekkooi.doctrine_event_store.listener" class="%boekkooi.doctrine_event_store.listener.class%">
            <argument type="service" id="service_container"/>
            <tag name="doctrine.event_subscriber"/>
        </service>
    </services>
</container>


text:
var isValidInterval = require('./Interval-asm').cwrap('isValidInterval', 'boolean', ['string'])
var SqlType = require('../lib/SqlType.js')
var inherits = require('util').inherits

module.exports = Interval

inherits(Interval, SqlType)
function Interval() {
  if ( !(this instanceof Interval) ) return new Interval()
  SqlType.call(this)
}

Interval.prototype.isValidValue = function(value) {
  if (typeof value !== 'string' || value === '') return false
  return !!isValidInterval(value)
}


text:
layout: post
author: [Phil]
title: Building an iTunes feed with Octopress
tags: [ruby]
excerpt: "Octopress is a great little CMS for hackers and it works on
  GitHub pages for free hosting, so a few PHP developers have been known to use it
  to smash together a basic site even thought it's using Ruby; Boo, hiss, etc. One
  site I've built with Octopress is for a new podcast I co-host with Ben Edmunds called
  PHP Town Hall. It needed an iTunes compatible RSS feed, so I built one. "
date: '2013-01-17 04:12:00'
comments: true
disqus_identifier: building-an-itunes-feed-with-octopress
---

Octopress is a great little CMS for hackers and it works on GitHub pages for free hosting, so a few PHP developers have been known to use it to smash together a basic site even thought it's using Ruby; Boo, hiss, etc.

One site I've built with Octopress is for a new podcast I co-host with Ben Edmunds called [PHP Town Hall](http://phptownhall.com/). It needed an iTunes compatible RSS feed, so I built one.

### source/itunes.rss

<script src="https://gist.github.com/4553431.js?file=itunes.rss"></script>

Some of this is obviously hardcoded, but I didn't care enough to change that and I don't see what benefit throwing some config options in would have made.

### plugins/octopress_filters.rb

Apple require you to use an RFC 2822 format for the date strings, which as far as I could tell was not built into Jekyll or Octopress. In this octopress_filters.rb file I added the following method towards the bottom:

<script src="https://gist.github.com/4553431.js?file=octopress_filters.rb"></script>

I've written a [pull request](https://github.com/imathis/octopress/pull/948) to add that in on the off-chance folks think its useful, but I'm fine with the hack. It works, and I'll be updating future versions with Git so I wont randomly loose the change.

### Posts

The last change to make is to give each of your blog posts some extra parameters. Below is an example of a PHP Town Hall post:

<script src="https://gist.github.com/4553431.js?file=All Posts"></script>

Here we add three new params to an average post, which are:

* **filename** - Will be inserted into the iTunes feed which has a link to an S3 bucket hardcoded, and have .mp3 appended.
* **length** - The file size in bytes.
* **summary** - A short summary just for display on the iTunes page.

That's all you need to do, so run rake preview to take a look at the URL then if it works publish it.


text:
void SphereShape::bind(lua_State *L)
{
	using namespace LuaIntf;

	LuaBinding(L).beginExtendClass<SphereShape, Object>("Sphere")
		.addConstructor(LUA_ARGS(const vec3&, float, _opt<Object*>))
		.addFunction("origin", &SphereShape::origin)
		.addFunction("radius", &SphereShape::radius)
	.endClass();
}


text:
package com.int8.diveguide;

import android.graphics.Color;
import android.location.Location;

public class PersistentTargetLocation extends Location {
	// The persistent location that's being used to store the information about this physical location.
	private PersistentLocation persistentLocation;

	public PersistentTargetLocation(PersistentLocation location) {
		super("PersistentTargetLocation");
		this.persistentLocation = location;
		// Need to also set the longitude and latitude for the parent location.
		super.setLatitude(PersistentTargetLocation.convertToDouble(location.latitude));
		super.setLongitude(PersistentTargetLocation.convertToDouble(location.longitude));
	}

	public PersistentTargetLocation(String name, double latitude, double longitude) {
		super("PersistentTargetLocation");
		super.setLatitude(latitude);
		super.setLongitude(longitude);
		// Create a new persistent location.
		this.persistentLocation = new PersistentLocation(name, PersistentTargetLocation.convertToLong(latitude),
				PersistentTargetLocation.convertToLong(longitude));
	}

	private static long convertToLong(double coordinate) {
		return Double.doubleToLongBits(coordinate);
	}

	private static double convertToDouble(long coordinate) {
		return Double.longBitsToDouble(coordinate);
	}

	public void setLatitude(long latitude) {
		super.setLatitude(latitude);
		// Set the location in the ORM object too.
		persistentLocation.setLatitude(PersistentTargetLocation.convertToLong(latitude));
	}

	public void setLongitude(double longitude) {
		super.setLatitude(longitude);
		// Set the location in the ORM object too.
		persistentLocation.setLongitude(PersistentTargetLocation.convertToLong(longitude));
	}

	public PersistentLocation getPersistentLocation() {
		return persistentLocation;
	}

	public int getColor() {
		// TODO(tgnourse): Calculate color somehow consistently with a reasonable set of mostly non repeating colors.
		// right now this just defaults to white.
		return Color.rgb(255, 255, 255);
	}
}


text:
require("lie/polyfill");
import readline = require("readline");
import assert = require("assert");
import { Evernote } from "evernote";
import { UserStore, NoteStore, promisifyUserStore, promisifyNoteStore } from "../index";

var readlineInterface = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

declare var Promise:PromiseConstructorLike;

var question = (q:string) => {
  return new Promise<string>((resolve, reject) => {
    readlineInterface.question(q, (answer:string) => {
      resolve(answer);
    })
  })
};

describe("integration", function () {
  this.timeout(60000);

  var userStore:UserStore;
  var noteStore:NoteStore;

  before(() => {
    return question("Please provide a valid evernote auth token: ").then(answer => {
      var client = new Evernote.Client({token: answer, sandbox: false});
      userStore = promisifyUserStore(client.getUserStore());
      noteStore = promisifyNoteStore(client.getNoteStore());
      return userStore.getUser();
    }).then(user => {
      console.log("running tests as ", user.username);
    });
  });

  it("can correctly call an api and provide a promise to its result", () => {
    var filter = new Evernote.NoteFilter();
    filter.order = Evernote.NoteSortOrder.CREATED;
    var resultSpec = new Evernote.NotesMetadataResultSpec();
    resultSpec.includeTitle = true;

    return noteStore.findNotesMetadata(filter, 10, 5, resultSpec).then(result => {
      console.log("Found", result.totalNotes, "total notes");
      console.log("Start index was", result.startIndex);
      console.log("Note titles were", result.notes.map(n => n.title).join(", "));
    })
  });

  context("when an api call fails", () => {
    it("correctly fails the promise with the expected error", () => {
      return noteStore.getNote("not-valid-uuid", false, false, false, false).then(() => {
        assert.ok(false, "Did not expect to succeed!")
      }, (e:Evernote.EDAMUserException) => {
        assert.ok(e instanceof Evernote.EDAMUserException);
        console.log("error code was", e.errorCode, "parameter that was problem:", e.parameter);
      })
    })
  })
});


text:
@interface GPSTripSummaryAnalyzer : NSObject

@property (nonatomic) CGFloat          total_dist;
@property (nonatomic) CGFloat          total_during;
@property (nonatomic) CGFloat          avg_speed;
@property (nonatomic) CGFloat          max_speed;

@property (nonatomic) CGFloat          traffic_jam_dist;
@property (nonatomic) CGFloat          traffic_jam_during;
@property (nonatomic) CGFloat          traffic_avg_speed;

@property (nonatomic) CGFloat          day_dist;
@property (nonatomic) CGFloat          day_during;
@property (nonatomic) CGFloat          day_avg_speed;
@property (nonatomic) CGFloat          day_max_speed;

@property (nonatomic) CGFloat          night_dist;
@property (nonatomic) CGFloat          night_during;
@property (nonatomic) CGFloat          night_avg_speed;
@property (nonatomic) CGFloat          night_max_speed;

@property (nonatomic, strong) CTRoute *         route;

- (void) updateGPSDataArray:(NSArray*)gpsLogs;

- (NSArray*) getTrafficJams;
- (NSString*) jsonRoute;

@end


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * String.prototype.toString() returns this string value
 *
 * @path ch15/15.5/15.5.4/S15.5.4.2_A1_T3.js
 * @description Create new String(string) and check it`s method toString()
 */

var __string__obj = new String("metal");

//////////////////////////////////////////////////////////////////////////////
//CHECK#
if (__string__obj.toString() !== "metal") {
  $ERROR('#1: __string__obj = new String("metal"); __string__obj.toString() === "metal". Actual: __string__obj.toString() ==='+__string__obj.toString() );
}
//
//////////////////////////////////////////////////////////////////////////////


text:
//#include "stdafx.h"
#include "NFLogPlugin.h"
#include "NFCLogModule.h"

#ifdef NF_DYNAMIC_PLUGIN

NF_EXPORT void DllStartPlugin(NFIPluginManager* pm)
{
    CREATE_PLUGIN(pm, NFLogPlugin)

};

NF_EXPORT void DllStopPlugin(NFIPluginManager* pm)
{
    DESTROY_PLUGIN(pm, NFLogPlugin)
};

#endif

//////////////////////////////////////////////////////////////////////////

const int NFLogPlugin::GetPluginVersion()
{
    return 0;
}

const std::string NFLogPlugin::GetPluginName()
{
    GET_CLASS_NAME(NFLogPlugin)
}

void NFLogPlugin::Install()
{
    REGISTER_MODULE(pPluginManager, NFCLogModule)
}

void NFLogPlugin::Uninstall()
{
    UNREGISTER_MODULE(pPluginManager, NFCLogModule)
}


text:
package org.sikuli.slides.api;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.junit.Test;
import org.sikuli.slides.api.io.PPTXSlidesReader;
import org.sikuli.slides.api.io.SlidesReader;
import org.sikuli.slides.api.models.Slide;

public class SlidesReaderTest {

	@Test
	public void testCanReadSlidesNormally() throws IOException{
		SlidesReader reader = new PPTXSlidesReader();
		URL url = getClass().getResource("click.pptx");
		List<Slide> slides = reader.read(url);
		assertEquals("# of slides", 1, slides.size());

		slides = reader.read(getClass().getResource("fivesteps.pptx"));
		assertEquals("# of slides", 5, slides.size());

		slides = reader.read(getClass().getResource("3blankslides.pptx"));
		assertEquals("# of slides", 3, slides.size());
	}

	@Test
	public void testCanReadSlidesRemotely() throws IOException{
		SlidesReader reader = new PPTXSlidesReader();
		URL url = new URL("http://slides.sikuli.org/pptx/helloworld.pptx");
		List<Slide> slides = reader.read(url);
		assertEquals("# of slides", 1, slides.size());
	}

	@Test
	public void testCanReadGoogleSlidesRemotely() throws IOException{
		SlidesReader reader = new PPTXSlidesReader();
		URL url = new URL("https://docs.google.com/presentation/d/1w48gExh5oLIT0J8xYXR1RxpqTrZTXJC8OR4UXxShTQ8/edit?usp=sharing");
		List<Slide> slides = reader.read(url);
		assertEquals("# of slides", 2, slides.size());
	}

	@Test(expected = IOException.class)
	public void testCanHandleNoSuchFile() throws IOException{
		SlidesReader reader = new PPTXSlidesReader();
		URL url = new URL("file:///none.pptx");
		reader.read(url);
	}

	@Test(expected = IOException.class)
	public void testCanHnadleBadFileExtension() throws IOException{
		SlidesReader reader = new PPTXSlidesReader();
		URL url = getClass().getResource("sikuli.png");
		reader.read(url);
	}

	@Test(expected = IOException.class)
	public void testCanHnadleBadURL() throws IOException{
		SlidesReader reader = new PPTXSlidesReader();
		URL url = new URL("http://does.not.exist/");
		reader.read(url);
	}

	@Test(expected = IOException.class)
	public void testCanHnadleBadGoogleDriveURL() throws IOException{
		SlidesReader reader = new PPTXSlidesReader();
		URL url = new URL("https://docs.google.com/presentation/d/badidbadidaksclaksdacklsldkaclksj/edit?usp=sharing");
		reader.read(url);
	}
}


text:
package xyz.kemix.java.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @author Kemix Koo <kemix_koo@163.com>
 *
 *         Created at 2017-10-27
 *
 */
public class ZipFileUtil {

	/**
	 *
	 * zip the source file or folder to target zip or folder, if source is folder,
	 * the folder name won't be used.
	 */
	public static void zip(File source, File target) throws IOException {
		if (source == null || target == null || !source.exists()) {
			throw new IOException("Parameter can't be null or not existed");
		}
		File targetZip = target;
		if (target.exists() && target.isDirectory()) {
			targetZip = new File(target, source.getName() + FileExts.ZIP.ext());
		}
		if (source.isDirectory()) {
			zip(source.listFiles(), targetZip);
		} else if (source.isFile()) {
			zip(new File[] { source }, targetZip);
		}
	}

	/**
	 * zip several files to target zip file
	 */
	public static void zip(File[] files, File target) throws IOException {
		if (files == null || files.length == 0) {
			throw new IOException("Can't zip empty list of files");
		}
		Map<String, File> map = new HashMap<String, File>();
		for (File f : files) {
			list(f, null, map);
		}
		if (map.isEmpty()) {
			throw new IOException("Can't zip empty list of files");
		}

		FileUtils.forceMkdir(target.getParentFile());

		boolean finished = false;
		ZipArchiveOutputStream zipArchiveOut = new ZipArchiveOutputStream(target);
		try {
			for (Map.Entry<String, File> entry : map.entrySet()) {
				File file = entry.getValue();
				ZipArchiveEntry zipEntry = new ZipArchiveEntry(file, entry.getKey());
				zipArchiveOut.putArchiveEntry(zipEntry);
				InputStream is = new FileInputStream(file);
				try {
					byte[] b = new byte[1024 * 5];
					int i = -1;
					while ((i = is.read(b)) != -1) {
						zipArchiveOut.write(b, 0, i);
					}
				} finally {
					IOUtils.closeQuietly(is);
				}
				zipArchiveOut.closeArchiveEntry();
			}
			zipArchiveOut.finish();
			finished = true;
		} finally {
			IOUtils.closeQuietly(zipArchiveOut);
			if (!finished) { // have error
				target.delete();
			}
		}
	}

	private static void list(File f, String parent, Map<String, File> map) {
		String name = f.getName();
		if (parent != null) {
			name = parent + '/' + name; // path in zip
		}
		if (f.isFile()) {
			map.put(name, f);
		} else if (f.isDirectory()) {
			for (File file : f.listFiles()) {
				list(file, name, map);
			}
		}
	}

	/**
	 * unzip the zip or jar to target folder
	 */
	public static final void unzip(File zip, File targetFolder) throws IOException {
		if (!zip.exists()) {
			throw new FileNotFoundException(zip.toString());
		}
		if (!zip.isFile()) {
			throw new IOException("Must be file:" + zip);
		}
		if (!FileExts.ZIP.of(zip.getName()) && !FileExts.JAR.of(zip.getName())) {
			throw new IOException("Invalid compress file:" + zip);
		}

		ZipFile zipfile = new ZipFile(zip);
		try {
			Enumeration<ZipArchiveEntry> entries = zipfile.getEntries();
			if (entries == null || !entries.hasMoreElements()) {
				throw new IOException("No any files in zip to unzip");
			}

			FileUtils.forceMkdir(targetFolder);

			while (entries.hasMoreElements()) {
				ZipArchiveEntry zipEntry = entries.nextElement();
				String fname = zipEntry.getName();

				if (zipEntry.isDirectory()) {
					String fpath = FilenameUtils.normalize(targetFolder + "/" + fname);
					FileUtils.forceMkdir(new File(fpath));
					continue;
				}

				if (StringUtils.contains(fname, "/")) {
					String tpath = StringUtils.substringBeforeLast(fname, "/");
					String fpath = FilenameUtils.normalize(targetFolder + "/" + tpath);
					FileUtils.forceMkdir(new File(fpath));
				}

				InputStream input = null;
				OutputStream output = null;
				try {
					input = zipfile.getInputStream(zipEntry);

					String file = FilenameUtils.normalize(targetFolder + "/" + fname);
					output = new FileOutputStream(file);

					IOUtils.copy(input, output);
				} finally {
					IOUtils.closeQuietly(input);
					IOUtils.closeQuietly(output);
				}
			}
		} finally {
			ZipFile.closeQuietly(zipfile);
		}
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<actions>
        <action>
            <actionName>build</actionName>
            <packagings>
                <packaging>*</packaging>
            </packagings>
            <goals>
                <goal>install</goal>
            </goals>
            <properties>
                <skipTests>true</skipTests>
            </properties>
        </action>
        <action>
            <actionName>rebuild</actionName>
            <packagings>
                <packaging>*</packaging>
            </packagings>
            <goals>
                <goal>clean</goal>
                <goal>install</goal>
            </goals>
            <properties>
                <skipTests>true</skipTests>
            </properties>
        </action>
    </actions>