text:
use log::{error, info, trace, warn};
use std::{
    fs, io,
    mem::{replace, swap},
};

use super::{index::*, segment::*, LogOptions, Offset};
use std::collections::BTreeMap;

pub struct FileSet {
    active: (Index, Segment),
    closed: BTreeMap<u64, (Index, Segment)>,
    opts: LogOptions,
}

impl FileSet {
    pub fn load_log(opts: LogOptions) -> io::Result<FileSet> {
        let mut segments = BTreeMap::new();
        let mut indexes = BTreeMap::new();

        let files = fs::read_dir(&opts.log_dir)?
            // ignore Err results
            .filter_map(|e| e.ok())
            // ignore directories
            .filter(|e| e.metadata().map(|m| m.is_file()).unwrap_or(false));

        for f in files {
            match f.path().extension() {
                Some(ext) if SEGMENT_FILE_NAME_EXTENSION.eq(ext) => {
                    let segment = match Segment::open(f.path(), opts.log_max_bytes) {
                        Ok(seg) => seg,
                        Err(e) => {
                            error!("Unable to open segment {:?}: {}", f.path(), e);
                            return Err(e);
                        }
                    };

                    let offset = segment.starting_offset();
                    segments.insert(offset, segment);
                }
                Some(ext) if INDEX_FILE_NAME_EXTENSION.eq(ext) => {
                    let index = match Index::open(f.path()) {
                        Ok(ind) => ind,
                        Err(e) => {
                            error!("Unable to open index {:?}: {}", f.path(), e);
                            return Err(e);
                        }
                    };

                    let offset = index.starting_offset();
                    indexes.insert(offset, index);
                    // TODO: fix missing index updates (crash before write to
                    // index)
                }
                _ => {}
            }
        }

        // pair up the index and segments (there should be an index per segment)
        let mut closed = segments
            .into_iter()
            .map(move |(i, s)| {
                match indexes.remove(&i) {
                    Some(v) => (i, (v, s)),
                    None => {
                        // TODO: create the index from the segment
                        panic!("No index found for segment starting at {}", i);
                    }
                }
            })
            .collect::<BTreeMap<u64, (Index, Segment)>>();

        // try to reuse the last index if it is not full. otherwise, open a new index
        // at the correct offset
        let last_entry = closed.keys().next_back().cloned();
        let (ind, seg) = match last_entry {
            Some(off) => {
                info!("Reusing index and segment starting at offset {}", off);
                closed.remove(&off).unwrap()
            }
            None => {
                info!("Starting new index and segment at offset 0");
                let ind = Index::new(&opts.log_dir, 0, opts.index_max_bytes)?;
                let seg = Segment::new(&opts.log_dir, 0, opts.log_max_bytes)?;
                (ind, seg)
            }
        };

        // mark all closed indexes as readonly (indexes are not opened as readonly)
        for &mut (ref mut ind, _) in closed.values_mut() {
            ind.set_readonly()?;
        }

        Ok(FileSet {
            active: (ind, seg),
            closed,
            opts,
        })
    }

    pub fn active_segment_mut(&mut self) -> &mut Segment {
        &mut self.active.1
    }

    pub fn active_index_mut(&mut self) -> &mut Index {
        &mut self.active.0
    }

    pub fn active_index(&self) -> &Index {
        &self.active.0
    }

    pub fn find(&self, offset: u64) -> &(Index, Segment) {
        let active_seg_start_off = self.active.0.starting_offset();
        if offset < active_seg_start_off {
            trace!(
                "Index is contained in the active index for offset {}",
                offset
            );
            if let Some(entry) = self.closed.range(..=offset).next_back().map(|p| p.1) {
                return entry;
            }
        }
        &self.active
    }

    pub fn roll_segment(&mut self) -> io::Result<()> {
        self.active.0.set_readonly()?;
        self.active.1.flush_sync()?;

        let next_offset = self.active.0.next_offset();

        info!("Starting new segment and index at offset {}", next_offset);

        // set the segment and index to the new active index/seg
        let mut p = {
            let seg = Segment::new(&self.opts.log_dir, next_offset, self.opts.log_max_bytes)?;
            let ind = Index::new(&self.opts.log_dir, next_offset, self.opts.index_max_bytes)?;
            (ind, seg)
        };
        swap(&mut p, &mut self.active);
        self.closed.insert(p.1.starting_offset(), p);
        Ok(())
    }

    pub fn remove_after(&mut self, offset: u64) -> Vec<(Index, Segment)> {
        if offset >= self.active.0.starting_offset() {
            return vec![];
        }

        // find the midpoint
        //
        // E.g:
        //    offset = 6
        //    [0 5 10 15] => split key 5
        //
        // midpoint  is then used as the active index/segment pair
        let split_key = match self
            .closed
            .range(..=offset)
            .next_back()
            .map(|p| p.0)
            .cloned()
        {
            Some(key) => {
                trace!("File set split key for truncation {}", key);
                key
            }
            None => {
                warn!("Split key before offset {} found", offset);
                return vec![];
            }
        };

        // split off the range of close segment/index pairs including
        // the midpoint (which will become the new active index/segment)
        let mut after = self.closed.split_off(&split_key);

        let mut active = after.remove(&split_key).unwrap();
        trace!(
            "Setting active to segment starting {}",
            active.0.starting_offset()
        );
        assert!(active.0.starting_offset() <= offset);

        swap(&mut active, &mut self.active);

        let mut pairs = after.into_iter().map(|p| p.1).collect::<Vec<_>>();
        pairs.push(active);
        pairs
    }

    pub fn remove_before(&mut self, offset: u64) -> Vec<(Index, Segment)> {
        // split such that self.closed contains [..offset), suffix=[offset,...]
        let split_point = {
            match self
                .closed
                .range(..=offset)
                .next_back()
                .map(|e| e.0)
                .cloned()
            {
                Some(off) => off,
                None => return vec![],
            }
        };

        let suffix = self.closed.split_off(&split_point);

        // put the suffix back into the closed segments
        let prefix = replace(&mut self.closed, suffix);
        prefix.into_values().collect()
    }

    pub fn log_options(&self) -> &LogOptions {
        &self.opts
    }

    /// First offset written. This may not be 0 due to removal of the start of
    /// the log
    pub fn min_offset(&self) -> Option<Offset> {
        if let Some(v) = self.closed.keys().next() {
            Some(*v)
        } else if !self.active.0.is_empty() {
            Some(self.active.0.starting_offset())
        } else {
            None
        }
    }
}


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

using System.Globalization;
using DbLinq.Language.Implementation;

namespace DbMetal.Language
{
    /// <summary>
    /// German support
    /// </summary>
#if !MONO_STRICT
    public
#endif
    class GermanWords : AbstractEndPluralWords
    {
        /// <summary>
        /// Loads the words (operation may be slow, so it is excluded from ctor)
        /// </summary>
        public override void Load()
        {
            if (WordsWeights == null)
                Load("GermanWords.txt");
        }

        /// <summary>
        /// Returns true if the required culture is supported
        /// </summary>
        /// <param name="cultureInfo"></param>
        /// <returns></returns>
        public override bool Supports(CultureInfo cultureInfo)
        {
            return cultureInfo.ThreeLetterISOLanguageName == "deu";
        }

        protected override SingularPlural[] SingularsPlurals
        {
            get { return singularsPlurals; }
        }

        // important: keep this from most specific to less specific
        private static readonly SingularPlural[] singularsPlurals =
            {
                new SingularPlural { Singular="e", Plural="en" },
                new SingularPlural { Singular="", Plural="e" },
            };
    }
}

redpajama_set_name: RedPajamaGithub


text:
package github

type Error struct {
	Message string `json:"message"`
}

func (e Error) Error() string  { return e.Message }
func (e Error) String() string { return e.Message }

type Branch struct {
	Protection struct {
		Enabled bool `json:"enabled"`
		Checks  struct {
			Enforcement string   `json:"enforcement_level"`
			Contexts    []string `json:"contexts"`
		} `json:"required_status_checks"`
	} `json:"protection"`
}

// commentHook represents a subset of the issue_comment payload.
type commentHook struct {
	Issue struct {
		Link   string `json:"html_url"`
		Number int    `json:"number"`
		User   struct {
			Login string `json:"login"`
		} `json:"user"`

		PullRequest struct {
			Link string `json:"html_url"`
		} `json:"pull_request"`
	} `json:"issue"`

	Comment struct {
		Body string `json:"body"`
		User struct {
			Login string `json:"login"`
		} `json:"user"`
	} `json:"comment"`

	Repository struct {
		Name     string `json:"name"`
		FullName string `json:"full_name"`
		Desc     string `json:"description"`
		Private  bool   `json:"private"`
		Owner    struct {
			Login  string `json:"login"`
			Type   string `json:"type"`
			Avatar string `json:"avatar_url"`
		} `json:"owner"`
	} `json:"repository"`
}


text:
/*=========================================================================

  Copyright 2004 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
  license for use of this work by or on behalf of the
  U.S. Government. Redistribution and use in source and binary forms, with
  or without modification, are permitted provided that this Notice and any
  statement of authorship are reproduced on all copies.

=========================================================================*/

/*========================================================================
 For general information about using VTK and Qt, see:
 http://www.trolltech.com/products/3rdparty/vtksupport.html
=========================================================================*/

#ifndef Q_VTK_INTERACTOR_INTERNAL_H
#define Q_VTK_INTERACTOR_INTERNAL_H

#include <QtCore/QObject>

#include <map>
class QVTKInteractor;
class QSignalMapper;
class QTimer;

// internal class, do not use
class QVTKInteractorInternal : public QObject
{
  Q_OBJECT
public:
  QVTKInteractorInternal(QVTKInteractor* p);
  ~QVTKInteractorInternal();
public Q_SLOTS:
  void TimerEvent(int id);
public:
  QSignalMapper* SignalMapper;
  typedef std::map<int, QTimer*> TimerMap;
  TimerMap Timers;
  QVTKInteractor* Parent;
};

#endif


text:
package org.rocksdb;

import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;

public class KeyMayExistTest {

  @ClassRule
  public static final RocksNativeLibraryResource ROCKS_NATIVE_LIBRARY_RESOURCE =
      new RocksNativeLibraryResource();

  @Rule
  public TemporaryFolder dbFolder = new TemporaryFolder();

  @Test
  public void keyMayExist() throws RocksDBException {
    final List<ColumnFamilyDescriptor> cfDescriptors = Arrays.asList(
        new ColumnFamilyDescriptor(RocksDB.DEFAULT_COLUMN_FAMILY),
        new ColumnFamilyDescriptor("new_cf".getBytes())
    );

    final List<ColumnFamilyHandle> columnFamilyHandleList = new ArrayList<>();
    try (final DBOptions options = new DBOptions()
        .setCreateIfMissing(true)
        .setCreateMissingColumnFamilies(true);
         final RocksDB db = RocksDB.open(options,
             dbFolder.getRoot().getAbsolutePath(),
             cfDescriptors, columnFamilyHandleList)) {
      try {
        assertThat(columnFamilyHandleList.size()).
            isEqualTo(2);
        db.put("key".getBytes(UTF_8), "value".getBytes(UTF_8));
        // Test without column family
        final Holder<byte[]> holder = new Holder<>();
        boolean exists = db.keyMayExist("key".getBytes(UTF_8), holder);
        assertThat(exists).isTrue();
        assertThat(holder.getValue()).isNotNull();
        assertThat(new String(holder.getValue(), UTF_8)).isEqualTo("value");

        exists = db.keyMayExist("key".getBytes(UTF_8), null);
        assertThat(exists).isTrue();

        // Slice key
        final StringBuilder builder = new StringBuilder("prefix");
        final int offset = builder.toString().length();
        builder.append("slice key 0");
        final int len = builder.toString().length() - offset;
        builder.append("suffix");

        final byte[] sliceKey = builder.toString().getBytes(UTF_8);
        final byte[] sliceValue = "slice value 0".getBytes(UTF_8);
        db.put(sliceKey, offset, len, sliceValue, 0, sliceValue.length);

        exists = db.keyMayExist(sliceKey, offset, len, holder);
        assertThat(exists).isTrue();
        assertThat(holder.getValue()).isNotNull();
        assertThat(holder.getValue()).isEqualTo(sliceValue);

        exists = db.keyMayExist(sliceKey, offset, len, null);
        assertThat(exists).isTrue();

        // Test without column family but with readOptions
        try (final ReadOptions readOptions = new ReadOptions()) {
          exists = db.keyMayExist(readOptions, "key".getBytes(UTF_8), holder);
          assertThat(exists).isTrue();
          assertThat(holder.getValue()).isNotNull();
          assertThat(new String(holder.getValue(), UTF_8)).isEqualTo("value");

          exists = db.keyMayExist(readOptions, "key".getBytes(UTF_8), null);
          assertThat(exists).isTrue();

          exists = db.keyMayExist(readOptions, sliceKey, offset, len, holder);
          assertThat(exists).isTrue();
          assertThat(holder.getValue()).isNotNull();
          assertThat(holder.getValue()).isEqualTo(sliceValue);

          exists = db.keyMayExist(readOptions, sliceKey, offset, len, null);
          assertThat(exists).isTrue();
        }

        // Test with column family
        exists = db.keyMayExist(columnFamilyHandleList.get(0), "key".getBytes(UTF_8),
            holder);
        assertThat(exists).isTrue();
        assertThat(holder.getValue()).isNotNull();
        assertThat(new String(holder.getValue(), UTF_8)).isEqualTo("value");

        exists = db.keyMayExist(columnFamilyHandleList.get(0), "key".getBytes(UTF_8),
            null);
        assertThat(exists).isTrue();

        // Test slice sky with column family
        exists = db.keyMayExist(columnFamilyHandleList.get(0), sliceKey, offset, len,
            holder);
        assertThat(exists).isTrue();
        assertThat(holder.getValue()).isNotNull();
        assertThat(holder.getValue()).isEqualTo(sliceValue);

        exists = db.keyMayExist(columnFamilyHandleList.get(0), sliceKey, offset, len,
            null);
        assertThat(exists).isTrue();

        // Test with column family and readOptions
        try (final ReadOptions readOptions = new ReadOptions()) {
          exists = db.keyMayExist(columnFamilyHandleList.get(0), readOptions,
              "key".getBytes(UTF_8), holder);
          assertThat(exists).isTrue();
          assertThat(holder.getValue()).isNotNull();
          assertThat(new String(holder.getValue(), UTF_8)).isEqualTo("value");

          exists = db.keyMayExist(columnFamilyHandleList.get(0), readOptions,
              "key".getBytes(UTF_8), null);
          assertThat(exists).isTrue();

          // Test slice key with column family and read options
          exists = db.keyMayExist(columnFamilyHandleList.get(0), readOptions,
              sliceKey, offset, len, holder);
          assertThat(exists).isTrue();
          assertThat(holder.getValue()).isNotNull();
          assertThat(holder.getValue()).isEqualTo(sliceValue);

          exists = db.keyMayExist(columnFamilyHandleList.get(0), readOptions,
              sliceKey, offset, len, null);
          assertThat(exists).isTrue();
        }

        // KeyMayExist in CF1 must return null value
        exists = db.keyMayExist(columnFamilyHandleList.get(1),
            "key".getBytes(UTF_8), holder);
        assertThat(exists).isFalse();
        assertThat(holder.getValue()).isNull();
        exists = db.keyMayExist(columnFamilyHandleList.get(1),
            "key".getBytes(UTF_8), null);
        assertThat(exists).isFalse();

        // slice key
        exists = db.keyMayExist(columnFamilyHandleList.get(1),
            sliceKey, 1, 3, holder);
        assertThat(exists).isFalse();
        assertThat(holder.getValue()).isNull();
        exists = db.keyMayExist(columnFamilyHandleList.get(1),
            sliceKey, 1, 3, null);
        assertThat(exists).isFalse();
      } finally {
        for (final ColumnFamilyHandle columnFamilyHandle :
            columnFamilyHandleList) {
          columnFamilyHandle.close();
        }
      }
    }
  }

  @Test
  public void keyMayExistNonUnicodeString() throws RocksDBException {
    try (final Options options = new Options()
        .setCreateIfMissing(true)
        .setCreateMissingColumnFamilies(true);
         final RocksDB db = RocksDB.open(options,
             dbFolder.getRoot().getAbsolutePath())) {
      final byte key[] = "key".getBytes(UTF_8);
      final byte value[] = { (byte)0x80 };  // invalid unicode code-point
      db.put(key, value);

      final byte buf[] = new byte[10];
      final int read = db.get(key, buf);
      assertThat(read).isEqualTo(1);
      assertThat(buf).startsWith(value);

      final Holder<byte[]> holder = new Holder<>();
      boolean exists = db.keyMayExist("key".getBytes(UTF_8), holder);
      assertThat(exists).isTrue();
      assertThat(holder.getValue()).isNotNull();
      assertThat(holder.getValue()).isEqualTo(value);

      exists = db.keyMayExist("key".getBytes(UTF_8), null);
      assertThat(exists).isTrue();
    }
  }
}


text:
var _ = require('lodash');
var sync = require('synchronize');
var request = require('request');

sync(request, 'get');

var cache = {};

module.exports = {
  fetch: function (url, params) {
    var headers = _.extend({
      'User-Agent': 'request'
    }, params.headers);

    if (cache[url]) {
      var res = cache[url];
    }

    else {
      var res = request.get(url, { headers: headers });
      cache[url] = res;
    }

    return {
      getContentText: function () {
        if (res.statusCode !== 200) {
          console.error(res.body);
        }

        return res.body;
      },
      getResponseCode: function () { return res.statusCode; }
    };
  }
};


text:
"""The tests for the Logentries component."""

import pytest

import homeassistant.components.logentries as logentries
from homeassistant.const import EVENT_STATE_CHANGED, STATE_OFF, STATE_ON
from homeassistant.setup import async_setup_component

from tests.async_mock import MagicMock, call, patch

async def test_setup_config_full(hass):
    """Test setup with all data."""
    config = {"logentries": {"token": "secret"}}
    hass.bus.listen = MagicMock()
    assert await async_setup_component(hass, logentries.DOMAIN, config)
    assert hass.bus.listen.called
    assert EVENT_STATE_CHANGED == hass.bus.listen.call_args_list[0][0][0]

async def test_setup_config_defaults(hass):
    """Test setup with defaults."""
    config = {"logentries": {"token": "token"}}
    hass.bus.listen = MagicMock()
    assert await async_setup_component(hass, logentries.DOMAIN, config)
    assert hass.bus.listen.called
    assert EVENT_STATE_CHANGED == hass.bus.listen.call_args_list[0][0][0]

@pytest.fixture
def mock_dump():
    """Mock json dumps."""
    with patch("json.dumps") as mock_dump:
        yield mock_dump

@pytest.fixture
def mock_requests():
    """Mock requests."""
    with patch.object(logentries, "requests") as mock_requests:
        yield mock_requests

async def test_event_listener(hass, mock_dump, mock_requests):
    """Test event listener."""
    mock_dump.side_effect = lambda x: x
    mock_post = mock_requests.post
    mock_requests.exceptions.RequestException = Exception
    config = {"logentries": {"token": "token"}}
    hass.bus.listen = MagicMock()
    assert await async_setup_component(hass, logentries.DOMAIN, config)
    handler_method = hass.bus.listen.call_args_list[0][0][1]

    valid = {"1": 1, "1.0": 1.0, STATE_ON: 1, STATE_OFF: 0, "foo": "foo"}
    for in_, out in valid.items():
        state = MagicMock(state=in_, domain="fake", object_id="entity", attributes={})
        event = MagicMock(data={"new_state": state}, time_fired=12345)
        body = [
            {
                "domain": "fake",
                "entity_id": "entity",
                "attributes": {},
                "time": "12345",
                "value": out,
            }
        ]
        payload = {
            "host": "https://webhook.logentries.com/noformat/logs/token",
            "event": body,
        }
        handler_method(event)
        assert mock_post.call_count == 1
        assert mock_post.call_args == call(payload["host"], data=payload, timeout=10)
        mock_post.reset_mock()


text:
layout: relation
title: 'obj'
shortdef: 'object'
udver: '2'
---

The object of a verb (`obj`) is one of two core arguments of the verb together with the subject. This relation is typically used for nouns or nominal phrases which represent the affected object of the action, that is, the entity which undergoes some change of state or position (**the direct object**). In Slovene, this role is most often—but not exclusively—performed by objects in the accusative and genitive (in the case of negation) cases.
~~~ sdparse
Andreja Burin pa je dobila posebno pohvalo \n Andreja Burin CONJ aux-PAST got a-special commendation
obj(dobila,pohvalo)
obj(got,commendation)
~~~
~~~ sdparse
Neznosna teža nahrbtnika me je vlekla v globino \n Immense weight of-backpack me aux-PAST pulled to depths
obj(vlekla,me-4)
obj(pulled,me-13)
~~~
~~~ sdparse
Trojka ni upoštevala opozorila poročevalca Specialeja \n Troika did-not consider warning of-reporter Speciale
obj(upoštevala,opozorila)
obj(consider,warning)
~~~

The `obj` relation is also used for objects of adjectival and (less often) nominal subject complements.
~~~ sdparse
Mladi gasilci so prav željni vaj . \n Young firefighters are really eager for-exercises .
obj(željni,vaj)
nsubj(željni,gasilci)
cop(željni,so)
obj(eager,for-exercises)
nsubj(eager,firefighters)
cop(eager,are)
~~~
~~~ sdparse
K sreči niste zapisani samo šahu . \n Luckily you-are-not committed only to-chess .
obj(zapisani,šahu)
cop(zapisani,niste)
obj(committed,to-chess)
cop(committed,you-are-not)
~~~
~~~ sdparse
Župančič je bil domači učitelj grofiču Manfredu Attemsu \n Župančič aux-PAST was home teacher to-count Manfred Attems
obj(učitelj,grofiču)
cop(učitelj,bil)
obj(teacher,to-count)
cop(teacher,was)
~~~

In accordance with the general guidelines, the SSJ-UD treebank also follows the following strict rule: if the sentence contains **only one object**, this object is always marked as a direct object (`obj`), regardless of its grammatical case or semantic role. An example of this is the above sentence *suho listje jima je šelestelo*. See also the `iobj` relation explanation.

The `obj` relation is not used for prepositional phrases, even if they are syntactically or semantically necessary and cannot be omitted from the sentence (e.g., *veliko se je govorilo o hladni vojni*). Regardless of their meaning and omissibility, prepositional phrases are always treated as peripheral objects (`obl`).


text:
package org.apache.lucene.analysis.commongrams;

import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.TestStopFilter;
import org.apache.lucene.analysis.util.BaseTokenStreamFactoryTestCase;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.analysis.util.ClasspathResourceLoader;
import org.apache.lucene.analysis.util.ResourceLoader;

import java.io.StringReader;

/**
 * Tests pretty much copied from StopFilterFactoryTest We use the test files
 * used by the StopFilterFactoryTest TODO: consider creating separate test files
 * so this won't break if stop filter test files change
 **/
public class TestCommonGramsQueryFilterFactory extends BaseTokenStreamFactoryTestCase {

  public void testInform() throws Exception {
    ResourceLoader loader = new ClasspathResourceLoader(TestStopFilter.class);
    assertTrue("loader is null and it shouldn't be", loader != null);
    CommonGramsQueryFilterFactory factory = (CommonGramsQueryFilterFactory) tokenFilterFactory("CommonGramsQuery", TEST_VERSION_CURRENT, loader,
        "words", "stop-1.txt",
        "ignoreCase", "true");
    CharArraySet words = factory.getCommonWords();
    assertTrue("words is null and it shouldn't be", words != null);
    assertTrue("words Size: " + words.size() + " is not: " + 2,
        words.size() == 2);
    assertTrue(factory.isIgnoreCase() + " does not equal: " + true, factory
        .isIgnoreCase() == true);

    factory = (CommonGramsQueryFilterFactory) tokenFilterFactory("CommonGramsQuery", TEST_VERSION_CURRENT, loader,
        "words", "stop-1.txt, stop-2.txt",
        "ignoreCase", "true");
    words = factory.getCommonWords();
    assertTrue("words is null and it shouldn't be", words != null);
    assertTrue("words Size: " + words.size() + " is not: " + 4,
        words.size() == 4);
    assertTrue(factory.isIgnoreCase() + " does not equal: " + true, factory
        .isIgnoreCase() == true);

    factory = (CommonGramsQueryFilterFactory) tokenFilterFactory("CommonGramsQuery", TEST_VERSION_CURRENT, loader,
        "words", "stop-snowball.txt",
        "format", "snowball",
        "ignoreCase", "true");
    words = factory.getCommonWords();
    assertEquals(8, words.size());
    assertTrue(words.contains("he"));
    assertTrue(words.contains("him"));
    assertTrue(words.contains("his"));
    assertTrue(words.contains("himself"));
    assertTrue(words.contains("she"));
    assertTrue(words.contains("her"));
    assertTrue(words.contains("hers"));
    assertTrue(words.contains("herself"));
  }

  /**
   * If no words are provided, then a set of english default stopwords is used.
   */
  public void testDefaults() throws Exception {
    CommonGramsQueryFilterFactory factory = (CommonGramsQueryFilterFactory) tokenFilterFactory("CommonGramsQuery");
    CharArraySet words = factory.getCommonWords();
    assertTrue("words is null and it shouldn't be", words != null);
    assertTrue(words.contains("the"));
    Tokenizer tokenizer = whitespaceMockTokenizer("testing the factory");
    TokenStream stream = factory.create(tokenizer);
    assertTokenStreamContents(stream,
        new String[] { "testing_the", "the_factory" });
  }

  /** Test that bogus arguments result in exception */
  public void testBogusArguments() throws Exception {
    try {
      tokenFilterFactory("CommonGramsQuery", "bogusArg", "bogusValue");
      fail();
    } catch (IllegalArgumentException expected) {
      assertTrue(expected.getMessage().contains("Unknown parameters"));
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/ChallengeApp.iml" filepath="$PROJECT_DIR$/ChallengeApp.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/libraries/facebook/facebook.iml" filepath="$PROJECT_DIR$/libraries/facebook/facebook.iml" />
      <module fileurl="file://$PROJECT_DIR$/libraries/volley/volley.iml" filepath="$PROJECT_DIR$/libraries/volley/volley.iml" />
    </modules>
  </component>
</project>


text:
<?php

/**
 * Model class
 */

namespace PHPRedmineAPI\models;

use PHPRedmineAPI\models\baseModel;

/**
 * Contacts model
 *
 * @author Muriano <jamuriano@gmail.com>
 */
class Contact extends baseModel {}


text:
@interface HRToolbar ()
{
    NSMutableArray * _matrices;
}
@end

@implementation HRToolbar
@synthesize startColor = _startColor;
@synthesize endColor = _endColor;
@synthesize delegate = _delegate;

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.startColor = [NSColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
        self.endColor = nil;
    }
    return self;
}
-(void)setDelegate:(id<HRToolbarDelegate>)delegate
{
    if(self.delegate != delegate)
    {
        _delegate = delegate;
        [self reloadItems];
    }
}
-(void)setStartColor:(NSColor *)startColor
{
    _startColor = startColor;
    [self setNeedsDisplay:YES];
}
-(void)reloadItems
{
    if(_matrices)
    {
        [_matrices makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [_matrices removeAllObjects];
    }
    _matrices = [[NSMutableArray alloc] init];
    NSInteger groups = [self.delegate numberOfGroup:self];

    CGFloat w = 28, h = 25;
    CGFloat x = 10, y = 5;
    CGFloat span = 10;

    for(NSInteger i = 0 ;i  < groups ; ++i)
    {
        NSInteger items = [self.delegate numberOfItemInGroup:self group:i];
        for(NSInteger j = 0; j < items; ++ j)
        {
            NSRect frame = NSMakeRect(x, y, w, h);
            HRToolbarButton * button = [[HRToolbarButton alloc] initWithFrame:frame];
            [button setGroupIndex:i];
            [button setItemIndex:j];
            NSImage * icon = [self.delegate iconForItem:self group:i item:j];
            [button setImage:icon];
            [button setButtonType:NSMomentaryChangeButton];
            [button setBezelStyle:NSTexturedRoundedBezelStyle];
            [button setImagePosition:NSImageOnly];
            [button setBordered:NO];
            [button setTarget:self];
            [button setAction:@selector(buttonClicked:)];
            [self addSubview:button];

            [_matrices addObject:button];

            x+= w + span;

            if(j == items-1 && i != groups-1) // last
            {
                BOOL seperate = [self.delegate shouldSeperatorAfterGroup:self group:i];
                if(seperate)
                {

                    HRLineView * line = [[HRLineView alloc] initWithFrame:NSMakeRect(x, 0, 3, self.bounds.size.height)];
                    [self addSubview:line];
                    [_matrices addObject:line];
                    x+= span;

                }

            }
        }
    }
}
-(void)buttonClicked:(HRToolbarButton*)sender
{
    [self.delegate toolbarItemSelected:self group:sender.groupIndex item:sender.itemIndex];
}
- (void)drawRect:(NSRect)dirtyRect
{

    if(self.startColor && self.endColor)
    {
        NSGradient* aGradient = [[NSGradient alloc]
                                 initWithStartingColor:self.startColor
                                 endingColor:self.endColor];
        NSBezierPath *bezierPath = [NSBezierPath bezierPathWithRoundedRect: self.bounds xRadius:0.0 yRadius:0.0];
        [aGradient drawInBezierPath:bezierPath angle:270];
    }
    else
    {
        if(self.startColor)
        {
            [self.startColor setFill];
            NSRectFill(dirtyRect);
        }
        [super drawRect:dirtyRect];
    }
}

@end
@implementation HRToolbarButton
@synthesize groupIndex = _groupIndex;
@synthesize itemIndex = _itemIndex;
@end


text:
class RelationManager:
	'''instance per relation'''

	def __init__(self, from_entity_type, from_entity_id, to_entity_type, to_entity_id):

		self.from_entity_type = from_entity_type
		self.from_entity_id = from_entity_id
		self.to_entity_type = to_entity_type
		self.to_entity_id = to_entity_id

		entitier = IN.entitier

		self.from_entity = entitier.load_single(from_entity_type, from_entity_id)
		if not self.from_entity:
			raise In.entity.InvalidEntityException()

		self.to_entity  = entitier.load_single(to_entity_type, to_entity_id)
		if not self.to_entity:
			raise In.entity.InvalidEntityException()

		self.existing_relations = {}

		self.no_permission_message = s('Sorry! But you have no permission to do this action!')
		self.no_relation_message = s('Sorry! There is no relation exists!')
		self.relation_exists_message = s('Relation already exists!')
		self.request_already_sent_message = s('Request already sent!')

	def get_existing_relation(self, relation_type):
		if relation_type in self.existing_relations:
			return self.existing_relations[relation_type]

		relation_type_entity = relation_type

		existing_relation = None

		#if relation_type_entity.is_one_way():
			#where = [
				#['OR', [
					#['AND', [
						#['from_entity_type', self.from_entity_type],
						#['from_entity_id', self.from_entity_id],
						#['to_entity_type', self.to_entity_type],
						#['to_entity_id', self.to_entity_id],
					#]],
					#['AND', [
						#['from_entity_type', self.to_entity_type],
						#['from_entity_id', self.to_entity_id],
						#['to_entity_type', self.from_entity_type],
						#['to_entity_id', self.from_entity_id],
					#]],
				#],
				#['type', relation_type]
			#]
		#else:
		where = [
			['from_entity_type', self.from_entity_type],
			['from_entity_id', self.from_entity_id],
			['to_entity_type', self.to_entity_type],
			['to_entity_id', self.to_entity_id],
			['relation.type', relation_type]
		]

		cursor = IN.db.select({
			'table' : 'relation.relation_member',
			'join' : [
				['join', 'relation.relation', 'relation', [['relation_member.relation_id = relation.id']]],
			],
			'columns' : ['relation.id'],
			'where' : where,
		}).execute()

		if cursor.rowcount > 0:
			relation_id = cursor.fetchone()['id']

			existing_relation = IN.entitier.load_single('Relation', relation_id)

		self.existing_relations[relation_type] = existing_relation

		if existing_relation:
			return existing_relation

	def banned(self):
		# TODO: ban entity
		return False


text:
	<title>Robin Lustig's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Robin Lustig's panel show appearances

Robin Lustig (born 1948-08-30[ref]) has appeared in 2 episodes between 1996-1999.  Robin Lustig on Wikipedia.

1996

1997

1998

1999

1999-03-19 / The News Quiz

1996-09-06 / Call My Bluff


text:
Cromwell supports workflows referencing objects stored in [Google Cloud Storage](https://cloud.google.com/storage/).
The Cromwell configuration for GCS is as follow:

```hocon
filesystems {
  gcs {
    # A reference to a potentially different auth for manipulating files via engine functions.
    auth = "application-default"

    # Google project which will be billed for requests on buckets with requester pays enabled
    project = "google-billing-project"

    caching {
      # When a cache hit is found, the following duplication strategy will be followed to use the cached outputs
      # Possible values: "copy", "reference". Defaults to "copy"
      # "copy": Copy the output files
      # "reference": DO NOT copy the output files but point to the original output files instead.
      #              Will still make sure than all the original output files exist and are accessible before
      #              going forward with the cache hit.
      duplication-strategy = "copy"
    }
  }
}
```

- The `auth` field refers to the authentication schema that should be used to authenticate requests. See [here](../backends/Google.md) for more info.
- The `project` field has to do with the Requester Pays feature (see below).
- The `caching.duplication-strategy` field determines how Cromwell should behave w.r.t output files when call is being cached. The default strategy `copy` is to copy the file to its new call location. As mentioned, `reference` will not copy the file and simply point the results to the existing location.
See the [Call Caching documentation](../cromwell_features/CallCaching.md) for more information.

## Requester Pays

GCS has a feature called Requester Pays (RP). This section describes how Cromwell supports it and the consequences on cost. Please first read the [official documentation](https://cloud.google.com/storage/docs/requester-pays) if you're not already familiar with it.

The billing project Cromwell uses to access a bucket with requester pays is determined as follows:

- If a `google_project` was set in the [workflow options](../wf_options/Google.md) when the workflow was submitted, this value is used
- Otherwise, the value of the `project` field in the `gcs` filesystem configuration is used
- Otherwise, if the machine Cromwell runs on is authenticated using gcloud and a default project is set, this value will be used

**Important Note #1**: In order for a project to be billable to access a bucket with requester pays, the credentials used need to have the `serviceusage.services.use` permission on this project.

**Important Note #2**: Pipelines API version 1 does **not** support buckets with requester pays, so while Cromwell itself might be able to access bucket with RP, jobs running on Pipelines API V1 with file inputs and / or outputs will **not** work.
For full requester pays support, use the [Pipelines API v2 Cromwell backend](https://github.com/broadinstitute/cromwell/blob/develop/CHANGELOG.md#pipelines-api-v2).

**Important Note #3**: Access to requester pays buckets from Cromwell is seamless, this also means that Cromwell will not report in the logs or metadata when it access a bucket with requester pays. It is the user's responsibility to be aware of the extra cost of running workflows access requester pays buckets.


text:
'''run_client.py - An example client using the python socket implementation of
the Google Protocol Buffers.

This module is an executable script demonstrating the usage of the python socket
implementation of the Google Protocol Buffers. To work correctly, the script
requires a server to be running first (i.e. run_server.py).

Authors: Martin Norbury (mnorbury@lcogt.net)
         Eric Saunders (esaunders@lcogt.net)
         Zach Walker (zwalker@lcogt.net)
May 2009
'''

# Add main protobuf module to classpath
import sys
sys.path.append('../../main')

import time_pb2 as proto
import protobuf

import logging
log = logging.getLogger(__name__)
hostname = 'localhost'
port = 8090

if __name__=='__main__':

    logging.basicConfig(level=logging.DEBUG)
    log.debug("test")

    # Create request message
    request = proto.TimeRequest()

    service = protobuf.RpcService(proto.TimeService_Stub, port, hostname)
    try:
        response = service.getTime(request, timeout=1000)
        log.info(response)
    except Exception, ex:
        log.exception(ex)


text:
using System;
using System.Linq.Expressions;
using JetBrains.Annotations;
using Sitko.ModelSelector.Base;

namespace Sitko.ModelSelector.Predicates
{
    public class NotIsNullPredicate<TModel, TProperty> : Predicate<TModel, TProperty>
    {
        public NotIsNullPredicate(Expression<Func<TModel, TProperty>> property) : base(property)
        {
        }

        [UsedImplicitly]
        public NotIsNullPredicate(string propertyName, TProperty value) : base(propertyName)
        {
        }

        public override bool IsMultiple { get; } = true;

        public override PredicateType Type { get; } = PredicateType.NotNull;

        public override string ToDynamicLinqString(int index)
        {
            return $"{PropertyName} != null";
        }

        public override object GetAttribute()
        {
            return null;
        }
    }
}


text:
export interface Pairing {
    devicePairingId: Buffer;
    deviceLongTimePublicKey: Buffer;
}


text:
package abi44_0_0.expo.modules.location.exceptions;

import abi44_0_0.expo.modules.core.interfaces.CodedThrowable;
import abi44_0_0.expo.modules.core.errors.CodedException;

public class LocationRequestRejectedException extends CodedException implements CodedThrowable {
  public LocationRequestRejectedException(Exception cause) {
    super("Location request has been rejected: " + cause.getMessage());
  }

  @Override
  public String getCode() {
    return "E_LOCATION_REQUEST_REJECTED";
  }
}


text:
'use strict';

import moment from 'moment';

const format = 'MMM D YYYY';

export default wrapper => {
  describe('## Calendar', () => {
    const getDate = () => {
      return wrapper.find('UseCalendar').find('Calendar').childAt(0).childAt(0).text();
    };
    const choose = (type, index) => {
      wrapper.find('UseCalendar').find('Calendar').find('#is-chosen')
        .at(type).parents().first()
        .childAt(index).simulate('click');
    };

    it('### choose a date', () => {
      expect(getDate()).toBe(moment().format(format));

      choose(1, 0);
      choose(2, 30);

      expect(getDate()).toBe(moment({
        month: 0,
        date: 31
      }).format(format));
    });

    it('### choose April', () => {
      choose(1, 3);

      expect(getDate()).toBe(moment({
        month: 3,
        date: 30
      }).format(format));
    });
  });
};


text:
<?php

namespace Google\Service\Directory;

class Groups extends \Google\Collection
{
  protected $collection_key = 'groups';
  /**
   * @var string
   */
  public $etag;
  protected $groupsType = Group::class;
  protected $groupsDataType = 'array';
  /**
   * @var string
   */
  public $kind;
  /**
   * @var string
   */
  public $nextPageToken;

  /**
   * @param string
   */
  public function setEtag($etag)
  {
    $this->etag = $etag;
  }
  /**
   * @return string
   */
  public function getEtag()
  {
    return $this->etag;
  }
  /**
   * @param Group[]
   */
  public function setGroups($groups)
  {
    $this->groups = $groups;
  }
  /**
   * @return Group[]
   */
  public function getGroups()
  {
    return $this->groups;
  }
  /**
   * @param string
   */
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  /**
   * @return string
   */
  public function getKind()
  {
    return $this->kind;
  }
  /**
   * @param string
   */
  public function setNextPageToken($nextPageToken)
  {
    $this->nextPageToken = $nextPageToken;
  }
  /**
   * @return string
   */
  public function getNextPageToken()
  {
    return $this->nextPageToken;
  }
}

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


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>br.edu.ufcg</groupId>
	<artifactId>ProjetoDaca</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>ProjetoDaca</name>
	<description>Projeto da disciplina "Desenvolvimento de Aplicações Corporativas Avançadas"</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.6.RELEASE</version>
		<relativePath/>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.5.0</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.5.0</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>io.rest-assured</groupId>
			<artifactId>rest-assured</artifactId>
			<version>3.0.0</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.7</version>
		</dependency>

		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-ldap</artifactId>
        </dependency>

		<dependency>
			<groupId>org.springframework.hateoas</groupId>
			<artifactId>spring-hateoas</artifactId>
			<version>0.20.0.RELEASE</version>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.0.0</version>
				<configuration>
					<webappDirectory>/target/projeto-daca</webappDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
module ValueGraphTransformation

  # Represents a value, which can be identified with a fixed number or a
  # variable identifier.
  class Value < Graph::Vertex

    # @return [Array<Object>] the identifiers of this value.
    attr_reader :identifiers

    def initialize(identifier=nil)
      super()
      @identifiers = []
      @identifiers << identifier unless identifier.nil?
    end

  end
end


text:
<?xml version="1.0"?>
<!DOCTYPE project>

<project name="fb-j2eecn-portlet" basedir="." default="deploy">
	<import file="../build-common-portlet.xml" />
</project>


text:
package com.esri.ges.manager.routes;

import java.util.Date;

import com.esri.ges.spatial.Geometry;
import com.esri.ges.spatial.Point;

public class DefaultRoute implements Route
{

  private String driverName;
  private Date lastUpdated;
  private String passengerName;
  private Date routeEnd;
  private String routeName;
  private Date routeStart;
  private Geometry shape;
  private String vehicleName;
  private Point routeStartPoint;
  private Point routeEndPoint;
  private String dispatchAck;

  public DefaultRoute()
  {

  }

  public DefaultRoute( Route seed )
  {
    if( seed != null )
    {
      setDriverName( seed.getDriverName() );
      setLastUpdated( seed.getLastUpdated() );
      setPassengerName( seed.getPassengerName() );
      setRouteEnd( seed.getRouteEnd() );
      setRouteName( seed.getRouteName() );
      setRouteStart( seed.getRouteStart() );
      setShape( seed.getShape() );
      setVehicleName( seed.getVehicleName() );
      setRouteStartPoint( seed.getRouteStartPoint() );
      setRouteEndPoint( seed.getRouteEndPoint() );
      setDispatchAck( seed.getDispatchAck() );
    }
  }

  @Override
  public String getDriverName()
  {
    return driverName;
  }

  @Override
  public Date getLastUpdated()
  {
    return lastUpdated;
  }

  @Override
  public String getPassengerName()
  {
    return passengerName;
  }

  @Override
  public Date getRouteEnd()
  {
    return routeEnd;
  }

  @Override
  public String getRouteName()
  {
    return routeName;
  }

  @Override
  public Date getRouteStart()
  {
    return routeStart;
  }

  @Override
  public Geometry getShape()
  {
    return shape;
  }

  @Override
  public String getVehicleName()
  {
    return vehicleName;
  }

  @Override
  public Point getRouteEndPoint()
  {
    return routeEndPoint;
  }

  @Override
  public Point getRouteStartPoint()
  {
    return routeStartPoint;
  }

  public void setDriverName(String driverName)
  {
    this.driverName = driverName;
  }

  public void setLastUpdated(Date lastUpdated)
  {
    this.lastUpdated = lastUpdated;
  }

  public void setPassengerName(String passengerName)
  {
    this.passengerName = passengerName;
  }

  public void setRouteEnd(Date routeEnd)
  {
    this.routeEnd = routeEnd;
  }

  public void setRouteName(String routeName)
  {
    this.routeName = routeName;
  }

  public void setRouteStart(Date routeStart)
  {
    this.routeStart = routeStart;
  }

  public void setShape(Geometry shape)
  {
    this.shape = shape;
  }

  public void setVehicleName(String vehicleName)
  {
    this.vehicleName = vehicleName;
  }

  public void setRouteEndPoint( Point routeEndPoint )
  {
    this.routeEndPoint = routeEndPoint;
  }

  public void setRouteStartPoint( Point routeStartPoint )
  {
    this.routeStartPoint = routeStartPoint;
  }

  @Override
  public String getDispatchAck()
  {
    return dispatchAck;
  }

  public void setDispatchAck(String dispatchAck)
  {
    this.dispatchAck = dispatchAck;
  }
}


text:
class AddForeignKeyToCiPipelinesMergeRequests < ActiveRecord::Migration[4.2]
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  disable_ddl_transaction!

  def up
    add_concurrent_index :ci_pipelines, :merge_request_id, where: 'merge_request_id IS NOT NULL'
    add_concurrent_foreign_key :ci_pipelines, :merge_requests, column: :merge_request_id, on_delete: :cascade
  end

  def down
    if foreign_key_exists?(:ci_pipelines, :merge_requests, column: :merge_request_id)
      remove_foreign_key :ci_pipelines, :merge_requests
    end

    remove_concurrent_index :ci_pipelines, :merge_request_id, where: 'merge_request_id IS NOT NULL'
  end
end


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="video_height">240dp</dimen>
    <dimen name="default_margin">12dp</dimen>
    <dimen name="default_padding">4dp</dimen>
    <dimen name="title_text_size">16sp</dimen>
</resources>


text:
<?php

namespace TwigYard\Component;

use Relay\RelayBuilder;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use TwigYard\Middleware\Config\ConfigMiddleware;
use TwigYard\Middleware\Data\DataMiddleware;
use TwigYard\Middleware\Error\ErrorMiddleware;
use TwigYard\Middleware\Form\FormHandlerFactory;
use TwigYard\Middleware\Form\FormMiddleware;
use TwigYard\Middleware\Form\FormValidator;
use TwigYard\Middleware\Header\HeaderMiddleware;
use TwigYard\Middleware\Httpauth\HttpauthMiddleware;
use TwigYard\Middleware\Locale\LocaleMiddleware;
use TwigYard\Middleware\Redirect\RedirectMiddleware;
use TwigYard\Middleware\Renderer\RendererMiddleware;
use TwigYard\Middleware\Router\RouterMiddleware;
use TwigYard\Middleware\Tracking\TrackingMiddleware;
use TwigYard\Middleware\Url\UrlMiddleware;
use Zend\Diactoros\Response;
use Zend\Diactoros\Server;
use Zend\Diactoros\ServerRequestFactory;

class Application
{
    // Sites can not implement any other locales
    const VALID_LOCALES = ['cs_CZ', 'en_US', 'de_DE'];

    /**
     * @var ApplicationConfig
     */
    private $config;

    /**
     * @var string
     */
    private $appRoot;

    /**
     * @var ContainerBuilder
     */
    private $container;

    public function __construct(string $appRoot, ApplicationConfig $config)
    {
        $this->appRoot = $appRoot;
        $this->config = $config;

        $containerFactory = new ContainerFactory($appRoot, $config);
        $this->container = $containerFactory->createContainer();
    }

    /**
     * @throws \Exception
     */
    public function run(): void
    {
        $server = new Server(
            (new RelayBuilder())->newInstance($this->getQueue()),
            ServerRequestFactory::fromGlobals($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES),
            new Response()
        );
        $server->listen();
    }

    /**
     * @throws \Exception
     */
    private function getQueue(): array
    {
        $appState = new AppState($this->appRoot . '/' . $this->config->getSitesDir());

        $globalParameters = $this->container->getParameter('app.parameters');

        $validatorBuilderFactory = $this->container->get(ValidatorBuilderFactory::class);
        $mailerFactory = $this->container->get(MailerFactory::class);
        $twigTemplatingFactory = $this->container->get(TwigTemplatingFactory::class);
        $siteLoggerFactory = $this->container->get(SiteLoggerFactory::class);
        $loggerFactory = $this->container->get(LoggerFactory::class);
        $configCache = $this->container->get(ConfigCache::class);
        $curlDownloader = $this->container->get(CurlDownloader::class);
        $csrfTokenGenerator = $this->container->get(CsrfTokenGenerator::class);
        $httpRequestSender = $this->container->get(HttpRequestSender::class);
        $translatorFactory = $this->container->get(TranslatorFactory::class);
        $siteTranslatorFactory = $this->container->get(SiteTranslatorFactory::class);

        if (
            !$validatorBuilderFactory instanceof ValidatorBuilderFactory
            || !$mailerFactory instanceof MailerFactory
            || !$twigTemplatingFactory instanceof TwigTemplatingFactory
            || !$siteLoggerFactory instanceof SiteLoggerFactory
            || !$loggerFactory instanceof LoggerFactory
            || !$configCache instanceof ConfigCache
            || !$curlDownloader instanceof CurlDownloader
            || !$csrfTokenGenerator instanceof CsrfTokenGenerator
            || !$httpRequestSender instanceof HttpRequestSender
            || !$translatorFactory instanceof TranslatorFactory
            || !$siteTranslatorFactory instanceof SiteTranslatorFactory
        ) {
            throw new \Exception('Error while receiving instances from containers.');
        }

        $formValidator = new FormValidator($validatorBuilderFactory, $httpRequestSender);
        $formHandlerFactory = new FormHandlerFactory(
            $appState,
            $mailerFactory,
            $twigTemplatingFactory,
            $siteLoggerFactory,
            $httpRequestSender
        );

        $queue = [];
        $queue[] = new ErrorMiddleware(
            $appState,
            $globalParameters['show_errors'],
            $loggerFactory,
            $this->config->getTemplateDir(),
            $this->config->getError404PageName(),
            $this->config->getError500PageName()
        );
        $queue[] = new ConfigMiddleware(
            $appState,
            $configCache,
            $this->appRoot . '/' . $this->config->getSitesDir(),
            $globalParameters['site_config'],
            $globalParameters['parent_domain']
        );
        $queue[] = new UrlMiddleware(
            $appState,
            !empty($globalParameters['ssl_allowed']),
            $globalParameters['parent_domain']
        );
        $queue[] = new RedirectMiddleware($appState);
        $queue[] = new HttpauthMiddleware($appState);
        $queue[] = new LocaleMiddleware($appState, self::VALID_LOCALES);
        $queue[] = new DataMiddleware(
            $appState,
            $this->config->getDataDir(),
            $curlDownloader
        );
        $queue[] = new RouterMiddleware($appState);
        $queue[] = new FormMiddleware(
            $appState,
            $csrfTokenGenerator,
            $formValidator,
            $formHandlerFactory,
            $translatorFactory,
            $siteTranslatorFactory,
            $this->config->getLogDir()
        );
        $queue[] = new TrackingMiddleware($appState, $globalParameters['tracking_enabled']);
        $queue[] = new RendererMiddleware(
            $appState,
            $twigTemplatingFactory
        );
        $queue[] = new HeaderMiddleware($appState);

        return $queue;
    }
}


text:
module Authlogic
  module ActsAsAuthentic
    # This module is responsible for transitioning existing applications from the restful_authentication plugin.
    module RestfulAuthentication
      def self.included(klass)
        klass.class_eval do
          extend Config
          include InstanceMethods
        end
      end

      module Config
        # Switching an existing app to Authlogic from restful_authentication? No problem, just set this true and your users won't know
        # anything changed. From your database perspective nothing will change at all. Authlogic will continue to encrypt passwords
        # just like restful_authentication, so your app won't skip a beat. Although, might consider transitioning your users to a newer
        # and stronger algorithm. Checkout the transition_from_restful_authentication option.
        #
        # * <tt>Default:</tt> false
        # * <tt>Accepts:</tt> Boolean
        def act_like_restful_authentication(value = nil)
          r = config(:act_like_restful_authentication, value, false)
          set_restful_authentication_config if value
          r
        end
        alias_method :act_like_restful_authentication=, :act_like_restful_authentication

        # This works just like act_like_restful_authentication except that it will start transitioning your users to the algorithm you
        # specify with the crypto provider option. The next time they log in it will resave their password with the new algorithm
        # and any new record will use the new algorithm as well.
        def transition_from_restful_authentication(value = nil)
          r = config(:transition_from_restful_authentication, value, false)
          set_restful_authentication_config if value
          r
        end
        alias_method :transition_from_restful_authentication=, :transition_from_restful_authentication

        private
          def set_restful_authentication_config
            crypto_provider_key = act_like_restful_authentication ? :crypto_provider : :transition_from_crypto_providers
            self.send("#{crypto_provider_key}=", CryptoProviders::Sha1)
            if !defined?(::REST_AUTH_SITE_KEY) || ::REST_AUTH_SITE_KEY.nil?
              class_eval("::REST_AUTH_SITE_KEY = ''") if !defined?(::REST_AUTH_SITE_KEY)
              CryptoProviders::Sha1.stretches = 1
            end
          end
      end

      module InstanceMethods
        private
          def act_like_restful_authentication?
            self.class.act_like_restful_authentication == true
          end

          def transition_from_restful_authentication?
            self.class.transition_from_restful_authentication == true
          end
      end
    end
  end
end


text:
.class public Landroid/speech/tts/EventLogTags;
.super Ljava/lang/Object;
.source "EventLogTags.java"

# static fields
.field public static final TTS_SPEAK_FAILURE:I = 0x128e2

.field public static final TTS_SPEAK_SUCCESS:I = 0x128e1

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 11
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static writeTtsSpeakFailure(Ljava/lang/String;IIILjava/lang/String;II)V
    .locals 4
    .parameter "engine"
    .parameter "callerUid"
    .parameter "callerPid"
    .parameter "length"
    .parameter "locale"
    .parameter "rate"
    .parameter "pitch"

    .prologue
    .line 24
    const v0, 0x128e2

    const/4 v1, 0x7

    new-array v1, v1, [Ljava/lang/Object;

    const/4 v2, 0x0

    aput-object p0, v1, v2

    const/4 v2, 0x1

    invoke-static {p1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    aput-object v3, v1, v2

    const/4 v2, 0x2

    invoke-static {p2}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    aput-object v3, v1, v2

    const/4 v2, 0x3

    invoke-static {p3}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    aput-object v3, v1, v2

    const/4 v2, 0x4

    aput-object p4, v1, v2

    const/4 v2, 0x5

    invoke-static {p5}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    aput-object v3, v1, v2

    const/4 v2, 0x6

    invoke-static {p6}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    aput-object v3, v1, v2

    invoke-static {v0, v1}, Landroid/util/EventLog;->writeEvent(I[Ljava/lang/Object;)I

    .line 25
    return-void
.end method

.method public static writeTtsSpeakSuccess(Ljava/lang/String;IIILjava/lang/String;IIJJJ)V
    .locals 4
    .parameter "engine"
    .parameter "callerUid"
    .parameter "callerPid"
    .parameter "length"
    .parameter "locale"
    .parameter "rate"
    .parameter "pitch"
    .parameter "engineLatency"
    .parameter "engineTotal"
    .parameter "audioLatency"

    .prologue
    .line 20
    const v0, 0x128e1

    const/16 v1, 0xa

    new-array v1, v1, [Ljava/lang/Object;

    const/4 v2, 0x0

    aput-object p0, v1, v2

    const/4 v2, 0x1

    invoke-static {p1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    aput-object v3, v1, v2

    const/4 v2, 0x2

    invoke-static {p2}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    aput-object v3, v1, v2

    const/4 v2, 0x3

    invoke-static {p3}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    aput-object v3, v1, v2

    const/4 v2, 0x4

    aput-object p4, v1, v2

    const/4 v2, 0x5

    invoke-static {p5}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    aput-object v3, v1, v2

    const/4 v2, 0x6

    invoke-static {p6}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    aput-object v3, v1, v2

    const/4 v2, 0x7

    invoke-static {p7, p8}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v3

    aput-object v3, v1, v2

    const/16 v2, 0x8

    invoke-static {p9, p10}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v3

    aput-object v3, v1, v2

    const/16 v2, 0x9

    invoke-static/range {p11 .. p12}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v3

    aput-object v3, v1, v2

    invoke-static {v0, v1}, Landroid/util/EventLog;->writeEvent(I[Ljava/lang/Object;)I

    .line 21
    return-void
.end method


text:
class Post < ActiveRecord::Base
  include Legacy
end


text:
"""
Script to train a neural networks for NLP tagging tasks.

Author: Erick Rocha Fonseca
"""

import logging
import numpy as np

import nlpnet.config as config
import nlpnet.utils as utils
import nlpnet.taggers as taggers
import nlpnet.metadata as metadata
import nlpnet.srl as srl
import nlpnet.pos as pos
import nlpnet.parse as parse
import nlpnet.arguments as arguments
import nlpnet.reader as reader
import nlpnet.attributes as attributes
from nlpnet.network import Network, ConvolutionalNetwork, ConvolutionalDependencyNetwork

############################
### FUNCTION DEFINITIONS ###
############################

def create_reader(args, md, validation=False):
    """
    Creates and returns a TextReader object according to the task at hand.

    :param args: the object containing the program arguments
    :param md: metadata for the task
    :param validation: whether the reader should read the validation data
        from `args`
    """
    if validation:
        msg = "validation"
        filename = args.dev
    else:
        msg = "training"
        filename = args.gold

    logger.info("Reading %s data..." % msg)
    if args.task == 'pos':
        text_reader = pos.POSReader(md, filename=filename)
        if args.suffix:
            text_reader.create_affix_list('suffix', args.suffix_size, 5)
        if args.prefix:
            text_reader.create_affix_list('prefix', args.prefix_size, 5)

    elif args.task.startswith('srl'):
        text_reader = srl.SRLReader(md, filename=filename, only_boundaries=args.identify,
                                    only_classify=args.classify,
                                    only_predicates=args.predicates)
        if args.identify:
            # only identify arguments
            text_reader.convert_tags('iobes', only_boundaries=True)

        elif not args.classify and not args.predicates:
            # this is SRL as one step, we use IOB
            text_reader.convert_tags('iob', update_tag_dict=False)

    elif 'dependency' in args.task:
        text_reader = parse.DependencyReader(md, filename)

    else:
        raise ValueError("Unknown task: %s" % args.task)

    text_reader.codify_sentences()
    return text_reader

def create_network(args, text_reader, feature_tables, md):
    """Creates and returns the neural network according to the task at hand."""
    logger = logging.getLogger("Logger")

    is_dependency = 'dependency' in args.task
    is_convolution_srl =  args.task.startswith('srl') and args.task != 'srl_predicates'
    is_convolution = is_convolution_srl or is_dependency

    if is_convolution:
        # get some data structures used both by dep parsing and SRL
        distance_tables = utils.set_distance_features(args.max_dist, args.target_features,
                                                      args.pred_features)
        padding_left = text_reader.converter.get_padding_left(False)
        padding_right = text_reader.converter.get_padding_right(False)

        if is_dependency:
            output_size = 1 if not args.labeled else len(text_reader.tag_dict)
            nn = ConvolutionalDependencyNetwork.create_new(feature_tables, distance_tables[0],
                                                           distance_tables[1], args.window,
                                                           args.convolution, args.hidden, output_size)

        else:
            # not dependency (SRL)
            num_tags = len(text_reader.tag_dict)
            nn = ConvolutionalNetwork.create_new(feature_tables, distance_tables[0],
                                                 distance_tables[1], args.window,
                                                 args.convolution, args.hidden, num_tags)

            if args.identify:
                logger.info("Loading initial transition scores table for argument identification")
                transitions = srl.init_transitions_simplified(text_reader.tag_dict)
                nn.transitions = transitions
                nn.learning_rate_trans = args.learning_rate_transitions

            elif not args.classify:
                logger.info("Loading initial IOB transition scores table")
                transitions = srl.init_transitions(text_reader.tag_dict, 'iob')
                nn.transitions = transitions
                nn.learning_rate_trans = args.learning_rate_transitions

    else:
        # not convolution
        num_tags = len(text_reader.tag_dict)
        nn = Network.create_new(feature_tables, args.window, args.hidden, num_tags)
        if args.learning_rate_transitions > 0:
            transitions = np.zeros((num_tags + 1, num_tags), np.float)
            nn.transitions = transitions
            nn.learning_rate_trans = args.learning_rate_transitions

        padding_left = text_reader.converter.get_padding_left(args.task == 'pos')
        padding_right = text_reader.converter.get_padding_right(args.task == 'pos')

    nn.padding_left = np.array(padding_left)
    nn.padding_right = np.array(padding_right)
    nn.learning_rate = args.learning_rate
    nn.learning_rate_features = args.learning_rate_features

    if 'convolution' in args and args.convolution > 0 and args.hidden > 0:
        layer_sizes = (nn.input_size, nn.hidden_size, nn.hidden2_size, nn.output_size)
    else:
        layer_sizes = (nn.input_size, nn.hidden_size, nn.output_size)

    logger.info("Created new network with the following layer sizes: %s"
                % ', '.join(str(x) for x in layer_sizes))

    nn.network_filename = config.FILES[md.network]
    return nn

def load_network_train(args, md):
    """Loads and returns a neural network with all the necessary data."""
    nn = taggers.load_network(md)

    logger.info("Loaded network with following parameters:")
    logger.info(nn.description())

    nn.learning_rate = args.learning_rate
    nn.learning_rate_features = args.learning_rate_features
    if md.task.startswith('srl') or md.task == 'pos':
        nn.learning_rate_trans = args.learning_rate_transitions

    return nn

def create_metadata(args):
    """Creates a Metadata object from the given arguments."""
    # using getattr because the SRL args object doesn't have a "suffix" attribute
    use_caps = getattr(args, 'caps', False)
    use_suffix = getattr(args, 'suffix', False)
    use_prefix = getattr(args, 'prefix', False)
    use_pos = getattr(args, 'pos', False)
    use_chunk = getattr(args, 'chunk', False)

    return metadata.Metadata(args.task, None, use_caps, use_suffix, use_prefix,
                               use_pos, use_chunk)

def set_validation_data(nn, task, reader):
    """Sets the neural network validation data."""
    if task == 'pos' or task == 'srl_predicates':
        nn.set_validation_data(reader.sentences, reader.tags)

    elif task.startswith('srl') and task != 'srl_predicates':
        arg_limits = None if task != 'srl_classify' else reader.arg_limits
        nn.set_validation_data(reader.sentences, reader.predicates,
                               reader.tags, arg_limits)

    elif task.endswith('dependency'):
        if task.startswith('unlabeled'):
            nn.set_validation_data(reader.sentences, reader.heads)
        else:
            nn.set_validation_data(reader.sentences, reader.heads, reader.labels)

    else:
        raise ValueError('Unknown task: %s' % task)

def load_or_create_metadata(args):
    """
    Loads or creates a metadata object, depending on command line arguments.
    """
    if not args.load_network:
        # if we are about to create a new network, create the metadata too
        md = create_metadata(args)
        md.save_to_file()
    else:
        md = metadata.Metadata.load_from_file(args.task)

    return md

def train(nn, reader, args):
    """Trains a neural network for the selected task."""
    num_sents = len(reader.sentences)
    logger.info("Starting training with %d sentences" % num_sents)

    avg_len = sum(len(x) for x in text_reader.sentences) / float(num_sents)
    logger.debug("Average sentence length is %f tokens" % avg_len)

    logger.debug("Network connection learning rate: %f" % nn.learning_rate)
    logger.debug("Feature vectors learning rate: %f" % nn.learning_rate_features)
    logger.debug("Tag transition matrix learning rate: %f\n" % nn.learning_rate_trans)

    intervals = max(args.iterations / 200, 1)
    np.seterr(over='raise')

    if args.decay:
        nn.set_learning_rate_decay(args.decay)

    if args.task.startswith('srl') and args.task != 'srl_predicates':
        arg_limits = None if args.task != 'srl_classify' else text_reader.arg_limits

        nn.train(reader.sentences, reader.predicates, reader.tags,
                 args.iterations, intervals, args.accuracy, arg_limits)

    elif args.task.endswith('dependency'):
        if args.labeled:
            nn.train(reader.sentences, reader.heads, args.iterations,
                     intervals, args.accuracy, text_reader.labels)
        else:
            nn.train(reader.sentences, reader.heads, args.iterations,
                     intervals, args.accuracy)

    else:
        nn.train(reader.sentences, reader.tags,
                 args.iterations, intervals, args.accuracy)

if __name__ == '__main__':
    args = arguments.get_args()

    logging_level = logging.DEBUG if args.verbose else logging.INFO
    utils.set_logger(logging_level)
    logger = logging.getLogger("Logger")

    config.set_data_dir(args.data)

    md = load_or_create_metadata(args)
    text_reader = create_reader(args, md)

    if args.load_network:
        logger.info("Loading provided network...")
        nn = load_network_train(args, md)
    else:
        logger.info('Creating new network...')
        feature_tables = utils.create_feature_tables(args, md, text_reader)
        nn = create_network(args, text_reader, feature_tables, md)

    if args.dev is not None:
        validation_reader = create_reader(args, md, True)
        set_validation_data(nn, args.task, validation_reader)

    train(nn, text_reader, args)
    logger.info("Finished training")


text:
'use strict';

var expect = require('chai').expect,
    kasane = require('../lib/kasane');

describe('kasane', function () {

    describe('.use', function () {

        it('should throw errors if `path` argument is not a string', function () {
            try {
                kasane().use(1, function () {});
            } catch (err) {
                expect(err).to.be.instanceOf(Error);
            }
        });

        it('should throw errors if `dispatcher` argument is not a function', function () {
            try {
                kasane().use('/', 1);
            } catch (err) {
                expect(err).to.be.instanceOf(Error);
            }
        });

        it('should add middleware successfully', function () {
            kasane().use(function () {});
            kasane().use('/test', function () {});
        });

    });

});


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE

using OpenTK;

namespace osu.Framework.Graphics.Sprites
{
    /// <summary>
    /// A triangle which has all side lengths and angles equal.
    /// </summary>
    public class EquilateralTriangle : Triangle
    {
        /// <summary>
        /// For equilateral triangles, height = cos(30) * sidelength = ~0.866 * sidelength.
        /// This is applied to the side length of the triangle to determine the height.
        /// </summary>
        private const float sidelength_to_height_factor = 0.866f;

        /// <summary>
        /// The size of this triangle.
        /// <para>
        /// When setting the size, the Y-value is ignored (use <see cref="Height"/> if you desire a specific height instead).
        /// </para>
        /// </summary>
        public override Vector2 Size => new Vector2(base.Size.X, base.Size.X * sidelength_to_height_factor);

        /// <summary>
        /// Sets the height of the triangle, adjusting the width as appropriate.
        /// </summary>
        public override float Height
        {
            get { return Width * sidelength_to_height_factor; }
            set { Size = new Vector2(value / sidelength_to_height_factor); }
        }
    }
}


text:
    static int GetType_static() \
    { \
        static int const typ = platform::AutoId( #ComponentType ); \
        return typ; \
    } \
    virtual int GetType() const \
    { \
        return ComponentType::GetType_static(); \
    } \

extern const double PRECISION;

class Actor;

class Component
{
public:
    DEFINE_COMPONENT_BASE( Component )
    virtual ~Component();
    virtual void SetActorGUID( int32_t actorGUID );
    void SetId( int32_t id );
    int32_t GetId() const;
    virtual void Save( Json::Value& component );

    friend class ::boost::serialization::access;
    template<class Archive>
    void serialize( Archive& ar, const unsigned int version );
    Component();
protected:
    int32_t mActorGUID;
    int32_t mId;
};

template<class Archive>
void Component::serialize( Archive& ar, const unsigned int version )
{
    ar& mActorGUID;
    ar& mId;
}

class ComponentFactory;

class ComponentHolder
{
protected:
    typedef boost::ptr_map<int32_t, Component> ComponentList_t;
    ComponentFactory& mComponentFactory;
    ComponentList_t mComponents;

public:
    ComponentHolder();
    virtual void AddComponent( std::auto_ptr<Component> Comp  );
    void DropComponent( int32_t id );

    template<typename Component_t>
    Opt<Component_t> Get() const;
    template<typename Component_t>
    Opt<Component_t> Get();
    virtual ~ComponentHolder();
    friend class ::boost::serialization::access;
    template<class Archive>
    void serialize( Archive& ar, const unsigned int version );
};

template<class Archive>
void ComponentHolder::serialize( Archive& ar, const unsigned int version )
{
    ar& mComponents;
}

template<typename Component_t>
Opt<Component_t> ComponentHolder::Get() const
{
    ComponentList_t::const_iterator i = mComponents.find( Component_t::GetType_static() );
    return Opt<Component_t>( dynamic_cast<Component_t*>( const_cast<Component*>(
                                 i == mComponents.end() ? NULL : i->second ) ) );
}

template<typename Component_t>
Opt<Component_t> ComponentHolder::Get()
{
    return ( ( const ComponentHolder* )this )->Get<Component_t>();
}

class DefaultComponent : public Component
{
public:
    DEFINE_COMPONENT_BASE( DefaultComponent )
    DefaultComponent();
    friend class ::boost::serialization::access;
    template<class Archive>
    void serialize( Archive& ar, const unsigned int version );
};

template<class Archive>
void DefaultComponent::serialize( Archive& ar, const unsigned int version )
{
    //NOTE: generated archive for this class
    ar& boost::serialization::base_object<Component>( *this );
}

template<typename COMPONENT>
class ComponentLoader: public PropertyLoader<COMPONENT, Component>
{
public:
    virtual void FillProperties( ComponentHolder& actor )const;
};

template<typename COMPONENT>
void ComponentLoader<COMPONENT>::FillProperties( ComponentHolder& actor ) const
{
    if ( this->mBase.get() )
    {
        static_cast<const ComponentLoader<Component> *>( this->mBase.get() )->FillProperties( actor );
    }
    if ( this->mSetterFuncList.empty() )
    {
        return;
    }
    Opt<COMPONENT> castedTarget = actor.Get<COMPONENT>();
    if ( !castedTarget.IsValid() )
    {
        return;
    }
    for( auto const& fun : this->mSetterFuncList )
    {
        fun( castedTarget.Get() );
    }
}

REAPING2_CLASS_EXPORT_KEY2( DefaultComponent, DefaultComponent, "default_component" );
#endif//INCLUDED_CORE_COMPONENT_H


text:
using Gallio.UI.Events;

namespace Gallio.Icarus.Models
{
    public class SortTreeEvent : Event
    {
        public SortOrder SortOrder { get; private set; }

        public SortTreeEvent(SortOrder sortOrder)
        {
            SortOrder = sortOrder;
        }
    }
}


text:
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_XLA_DEBUG_INFO_MANAGER_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_XLA_DEBUG_INFO_MANAGER_H_

#include <string>
#include <utility>

#include "absl/container/flat_hash_map.h"
#include "tensorflow/compiler/xla/service/hlo.pb.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/tsl/platform/status.h"

namespace xla {

using ModuleIdentifier = int;

// XlaDebugInfoManager tracks all XLA programs (Executables) throughout their
// lifetime. Because the tracing period can start during an Executable's
// execution, we need to track Executables even when tracing is off.
// This class is thread-safe.
class XlaDebugInfoManager {
 public:
  static XlaDebugInfoManager* Get() {
    static XlaDebugInfoManager* singleton = new XlaDebugInfoManager();
    return singleton;
  }

  // Registers an active module to XlaDebugInfoManager.
  // The module_id is expected to be unique per process.
  void RegisterModule(
      ModuleIdentifier module_id, std::shared_ptr<const HloModule> hlo_module,
      std::shared_ptr<const BufferAssignmentProto> buffer_assignment);

  // Unregisters an active module.
  void UnregisterModule(ModuleIdentifier module_id);

  // Start tracing, began to collecting debug information for all the running
  // modules during the tracing period.
  void StartTracing();

  // Stops tracing.
  // If module_debug_info is not null, returns debug information for all the
  // modules that were alive since StartTracing().
  void StopTracing(
      std::vector<std::unique_ptr<HloProto>>* module_debug_info = nullptr);

  friend class XlaDebugInfoManagerTestPeer;

 private:
  XlaDebugInfoManager() = default;

  struct XlaModuleEntry {
    std::shared_ptr<const HloModule> hlo_module;
    std::shared_ptr<const BufferAssignmentProto> buffer_assignment;
    bool active = false;
  };

  mutable absl::Mutex mutex_;
  bool tracing_active_ ABSL_GUARDED_BY(mutex_) = false;
  // Active modules are those still tracked by us. There could be much more
  // active modules than running modules, we will try to reduce the trace size
  // by only transfer those modules that were running during tracing period.
  absl::flat_hash_map<ModuleIdentifier, XlaModuleEntry> modules_
      ABSL_GUARDED_BY(mutex_);
};

}  // namespace xla

#endif  // TENSORFLOW_COMPILER_XLA_SERVICE_XLA_DEBUG_INFO_MANAGER_H_


text:
<!DOCTYPE html>

	<title>Microsoft Office SharePoint Server</title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="description" content="" />
	<meta name="keywords" content="" />
	<meta name="generator" content="Zeta Producer 11 11.1.0.0 ZP11M, Build 11.1.0.0, 30.11.2012 05:55:48 (RELEASE)" />
	<meta name="robots" content="index, follow" />
	<meta name="verify-v1" content="H96koBOJb+X5QhfuicT5QHCSU5ds5uvlH07WpdD1JHM=" />
<meta name="google-site-verification" content="cZ1PyyoGOpsaQuVCYz6_vEvcsdC39hPh1gAnNl0pJQk" />

	<link rel="shortcut icon" type="image/x-icon" href="_media/stock-files/favicon.ico?v=1" />
	<link rel="stylesheet" type="text/css" href="_media/bootstrap/bootstrap.css" />
	<link rel="stylesheet" type="text/css" href="_media/flexslider.css" media="screen" />
	<link rel="stylesheet" type="text/css" href="_media/styles.css" media="screen" />
	<link rel="stylesheet" type="text/css" href="_media/print.css" media="print" />

	<link rel="stylesheet" type="text/css" href="/_inline-editing/inline-editing.css" media="screen" />

Bewegen Sie die Maus über den Text, den Sie bearbeiten wollen.

OK

				<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">

				</button>

					<form id="searchform" name="searchengine1" onsubmit="return search1()" action="action" class="pull-right"><input id="searchfield" class="search-query pull-right" type="text" name="keyword1" value="" onfocus="if(this.value==''){this.value=''}" onblur="if(this.value==''){this.value=''}" /><input id="searchbutton" type="image" name="submit" src="_media/stock-images/magnifier.png" alt="searchbutton" /></form>

				Bearbeiten

Lösungen

Softwarelösungen

Content Management

Microsoft SharePoint

Suchmaschinenoptimierung (SEO)

Intranet-Konzepte

App-Entwicklung

Referenzen

Bock Kältemaschinen

Bodycote Wärmebehandlung

LBBW AM GmbH

NOE Schaltechnik

Leicht Küchen AG

Allgaier Werke GmbH

BKH Landshut

Wolverine Advanced Materials

Novaplus GmbH

Stadt Hof

Kunden

Kontakt

Karriere

Junior-Softwareentwickler (m/w)

Praktikant Online-Marketing (m/w)

Mitteilung

Mitgliedschaften

				Bearbeiten

Softwarelösungen für Unternehmen

				Bearbeiten

Wir erstellen für Sie Pflichtenhefte, Grob- und
Feinkonzepte und überwachen den Projektablauf.

Außerdem sorgen wir dafür, dass das Endergebnis so ausfällt, wie
Sie es sich vorgestellt haben.

			Artikel einfügen

			Artikel einfügen

					Bearbeiten

Microsoft Office SharePoint Server

					Bearbeiten
					Neu
					Erweitert

Eine beeindruckende Liste von Funktionen und Vorteilen erwartet
Sie:

Verwalten von Inhalten und Prozessen

Optimieren Sie tägliche Geschäftsaktivitäten. Erweitern Sie
Geschäftsprozesse auf das gesamte Unternehmen. Vereinfachen Sie die
Verwaltung von Webinhalten. Zentralisieren Sie Speicherung,
Verwaltung und Abruf von Dokumenten unternehmensweit. Steuern Sie
Dokumente über eine detaillierte, erweiterbare
Richtlinienverwaltung.

Wollen Sie Ihre Verwaltung
effizienter gestalten?

Gewinnen von besserem Verständnis für geschäftliche
Faktoren

Machen Sie Unternehmensdaten nutzbar. Nutzen Sie Ihre
unstrukturierten geschäftlichen Netzwerke als Grundlage für bessere
Entscheidungen. Geben Sie Unternehmensdaten für viele Benutzer
frei, und schützen Sie zugleich sensible Informationen. Ermöglichen
Sie Benutzern schnellen Zugang zu Informationen.

Stellen Sie unverzichtbare Informationen an einem einzigen,
zentralen Ort bereit.

Wollen Sie Ihre
Entscheidungen so fundiert wie möglich treffen?

Vereinfachen der internen und externen
Zusammenarbeit

Personalisieren Sie Benutzeroberflächen, um Inhalte,
Informationen und Anwendungen gezielt zu steuern. Stellen Sie
Verbindungen her, und geben Sie Wissen für andere Personen frei.
Arbeiten Sie, wann und wo Sie möchten. Überall zugreifbare
unternehmensweite Suche. Verbessern Sie die Beziehungen zu Kunden
und Partnern.

Wollen Sie Ihre interne oder
externe Kommunikation vereinfachen?

Möglichkeiten zur Mitwirkung an Strategien für die
IT-Abteilung

Versetzen Sie die IT-Abteilung in die Lage, sich stärker auf
strategische Aufgaben zu konzentrieren. Vereinfachen Sie die
Bereitstellung, Verwaltung und Systemadministration. Robuste Tools
zur Systemüberwachung und Verwendungsnachverfolgung.

Soll Ihre IT-Abteilung besser
in Unternehmensanforderungen eingebunden sein?

Kontaktieren Sie
uns

			Artikel einfügen

Lösungen

Softwarelösungen

Content Management

Microsoft SharePoint

Suchmaschinenoptimierung (SEO)

Intranet-Konzepte

App-Entwicklung

Referenzen

Bock Kältemaschinen

Bodycote Wärmebehandlung

LBBW AM GmbH

NOE Schaltechnik

Leicht Küchen AG

Allgaier Werke GmbH

BKH Landshut

Wolverine Advanced Materials

Novaplus GmbH

Stadt Hof

Kunden

Kontakt

Karriere

Mitteilung

Mitgliedschaften

Zeta Software GmbH

Manfred Wörner Straße 115

73037 Göppingen

www.zeta-software.de

info@zeta-software.de

07161 / 98897-0

Kontakt zu uns

ImpressumBlog


text:
using System.Text.Json;
using Azure.Core;
using Azure.ResourceManager.Resources.Models;

namespace Azure.ResourceManager.Cdn.Models
{
    public partial class UriSigningKeyProperties : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("keyId");
            writer.WriteStringValue(KeyId);
            writer.WritePropertyName("secretSource");
            JsonSerializer.Serialize(writer, SecretSource); if (Optional.IsDefined(SecretVersion))
            {
                writer.WritePropertyName("secretVersion");
                writer.WriteStringValue(SecretVersion);
            }
            writer.WritePropertyName("type");
            writer.WriteStringValue(SecretType.ToString());
            writer.WriteEndObject();
        }

        internal static UriSigningKeyProperties DeserializeUriSigningKeyProperties(JsonElement element)
        {
            string keyId = default;
            WritableSubResource secretSource = default;
            Optional<string> secretVersion = default;
            SecretType type = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("keyId"))
                {
                    keyId = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("secretSource"))
                {
                    secretSource = JsonSerializer.Deserialize<WritableSubResource>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("secretVersion"))
                {
                    secretVersion = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new SecretType(property.Value.GetString());
                    continue;
                }
            }
            return new UriSigningKeyProperties(type, keyId, secretSource, secretVersion.Value);
        }
    }
}


text:
define([
        'doh/main',
        'Sds/Validator/IdentifierArray'
    ],
    function(
        doh,
        IdentifierArray
    ){
        doh.register("Sds/Test/Validator/TestIdentifierArray", [

            function ValidatorTest(doh){
                var validator = new IdentifierArray;

                var testArray = [
                    [true, ['username', 'username1', '1username']],
                    [false, ['username1', 'u']]
                ];

                var index;
                for (index in testArray){
                    if (testArray[index][0]){
                        doh.assertTrue(validator.isValid(testArray[index][1]).result);
                    } else {
                        doh.assertFalse(validator.isValid(testArray[index][1]).result);
                    }
                }
            },

        ]);
    }
);


text:
RAILS_ENV=production bundle exec rake assets:clobber
RAILS_ENV=production bundle exec rake tmp:clear
RAILS_ENV=production bundle exec rake assets:precompile
touch tmp/restart.txt


text:
/*global module:false*/
module.exports = function (grunt) {
    var fs = require('fs-sync'),
        baseUrl = "src",
        paths = {
            "jquery": "../bower_components/jquery/dist/jquery"
        };
    // Project configuration.
    grunt.initConfig({
        // Metadata.
        pkg: grunt.file.readJSON('bower.json'),
        banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' +
            '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
            '<%= pkg.homepage ? "* see: " + pkg.homepage + "\\n" : "" %>' +
            '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.authors.join(", ") %>\n' +
            '* Licensed: <%= pkg.license.type %> */\n',
        // Task configuration.
        concat: {
            options: {
                banner: '<%= banner %>',
                stripBanners: true
            },
            dist: {
                src: ['dist/<%= pkg.name %>.js'],
                dest: 'dist/<%= pkg.name %>.js'
            }
        },
        requirejs: {
            compile: {
                options: {
                    baseUrl: baseUrl,
                    paths: paths,
                    // build file destination, relative to the build file itself
                    out: function (text, sourceMapText) {
                        var configFile = grunt.file.readJSON('bower.json'),
                            version = configFile.version,
                            newDirectory = "dist/" + version,
                            appendVersion = false;

                        if (!fs.exists(newDirectory)) {
                            fs.mkdir(newDirectory);
                            appendVersion = true;
                        }

                        fs.write("dist/opening-hours.js", text);
                        fs.copy("dist/opening-hours.js", newDirectory + "/opening-hours.js", {force: true});

                        fs.copy("src/styles/opening-hours.css", newDirectory + "/opening-hours.css", {force: true});
                        fs.copy("src/styles/opening-hours.css", "dist/opening-hours.css", {force: true});

                        if (appendVersion) {
                            var file = fs.read('dist/versions.txt'),
                                versions = file.split('\n'),
                                output = "",
                                alreadyinList = false,
                                i;

                            versions.splice(versions.length - 1, 1);

                            for (i = 0; i < versions.length; i++) {
                                if (versions[i] === version) {
                                    alreadyinList = true;
                                    break;
                                }
                            }
                            if (!alreadyinList) {
                                versions.push(version);
                            }

                            for (i = 0; i < versions.length; i++) {
                                output += versions[i] + '\n';
                            }

                            fs.write('dist/versions.txt', output);
                        }
                    },
                    // specify custom module name paths
                    // target amd loader shim as the main module, path is relative to baseUrl.
                    name: "../tools/almond",

                    optimize: "none",

                    // files to include along with almond. only main file is defined, as
                    // it pulls in the rest of the dependencies automatically.
                    include: ["js/OpeningHours"],
                    exclude: ["jquery"],

                    // code to wrap around the start / end of the resulting build file
                    // the global variable used to expose the API is defined here
                    wrap: {
                        startFile: "startLib.js",
                        endFile: "endLib.js"
                    }
                }

            }
        },
        sass: {
            options: {
                sourceMap: false,
                outputStyle: "compressed" // nested | compressed
            },
            dist: {
                files: {
                    'src/styles/opening-hours.css': 'src/styles/sass/opening-hours.scss'
                }
            }
        },
        watch: {
            scss: {
                files: ['src/styles/sass/*.scss'],
                tasks: ['sass']
            }
        },
        jasmine: {
            coverage: {
                src: "src/js/**/*.js",
                options: {
                    specs: 'test/unit/**/*Test.js',
                    template: require('grunt-template-jasmine-istanbul'),
                    templateOptions: {
                        coverage: 'test/code-coverage/coverage.json',
                        report: [
                            {
                                type: 'html',
                                options: {
                                    dir: 'test/code-coverage/html'
                                }
                            },
                            {
                                type: 'text',
                                options: {
                                    file: 'test/code-coverage/summary/summary.txt'
                                }
                            },
                            {
                                type: 'text'
                            }
                        ],
                        template: require('grunt-template-jasmine-requirejs'),
                        templateOptions: {
                            requireConfig: {
                                baseUrl: ".grunt/grunt-contrib-jasmine/" + baseUrl,
                                paths: {
                                    "jquery": "../../../bower_components/jquery/dist/jquery"
                                }
                            }
                        }
                    }
                }
            }
        },
        uglify: {
            options: {
                banner: '<%= banner %>'
            },
            dist: {
                src: 'dist/<%= pkg.name %>.js',
                dest: 'dist/<%= pkg.name %>.min.js'
            }
        },
        jsdoc: {
            dist: {
                src: ['src/**/*.js', 'README.md'],
                options: {
//                    tutorials: "tutorials/",
                    private: false,
                    destination: 'doc',
                    template: "node_modules/ink-docstrap/template",
                    config: "jsdoc.conf.json"
                }
            }
        }
    });

    // These plugins provide necessary tasks.
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-jsdoc');
    grunt.loadNpmTasks('grunt-contrib-requirejs');
    grunt.loadNpmTasks('grunt-sass');
    grunt.loadNpmTasks('grunt-contrib-jasmine');
    grunt.loadNpmTasks('grunt-contrib-watch');

    // Default task.
    grunt.registerTask('default', ['sass', 'jasmine:coverage', 'requirejs', 'concat', 'uglify']);

    grunt.registerTask('doc', ['jsdoc']);
    grunt.registerTask('test', ['jasmine:coverage']);
};


text:
import { UPDATE_PET_TOGGLE, UPDATE_PET_REQUEST, UPDATE_PET_SUCCESS, UPDATE_PET_ERROR } from '../constants/petConstants';
import { API_URI } from '../constants/apiConstants';
import fetch from 'isomorphic-fetch';

export const updatePetToggle = (_id, updating) => {
  return {
    type: UPDATE_PET_TOGGLE,
    _id,
    updating
  };
};

export const updatePetSuccess = (pet) => {
  return {
    type: UPDATE_PET_SUCCESS,
    pet
  };
};

export const updatePetError = (error) => {
  return {
    type: UPDATE_PET_ERROR,
    error
  };
};

export const updatePetRequest = () => {
  return {
    type: UPDATE_PET_REQUEST
  };
};

export const updatePet = (pet) => {
  return dispatch => {
    dispatch(updatePetRequest());
    return fetch(`${API_URI}`, {
      method: 'PUT',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        name: pet.name,
        _id: pet._id
      })
    })
    .then(response => response.json())
    .then(updatedPet => dispatch(updatePetSuccess(updatedPet)))
    .catch(error => dispatch(updatePetError(error)));
  };
};