text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import numpy as np
import tensorflow.compat.v2 as tf

from typing import Any, Callable, List, Optional, Text, Tuple, Union

from dice_rl.data.dataset import EnvStep, OffpolicyDataset, StepType
from dice_rl.data.tf_offpolicy_dataset import TFOffpolicyDataset

EpisodeInfo = collections.namedtuple(
    'EpisodeInfo', ['episode_start_id', 'episode_end_id',
                    'episode_start_type', 'episode_end_type'])

class PerturbedDataset(OffpolicyDataset):
  """An off-policy dataset with perturbed rewards."""

  def __init__(self,
               dataset: TFOffpolicyDataset,
               num_perturbations: Optional[int] = None,
               perturbation_scale: float = 1.):
    """Creates a PerturbedDataset.

    Args:
      dataset: The off-policy dataset to perturb.
      num_perturbations: How many perturbations to apply. Defaults to None
        (a single perturbation).
      perturbation_scale: Scale of random perturbations.
    """
    self._dataset = dataset
    if num_perturbations is not None and num_perturbations >= 64:
      raise ValueError('Number of permutations %d is too high.' % num_perturbations)
    self._num_perturbations = num_perturbations
    self._perturbation_scale = perturbation_scale

    with tf.device(self._dataset.device):
      self._random_numbers = tf.random.uniform([self._dataset.capacity])

  @property
  def spec(self):
    return self._dataset.spec

  @property
  def num_steps(self) -> Union[int, tf.Tensor]:
    return self._dataset.num_steps

  @property
  def num_total_steps(self) -> Union[int, tf.Tensor]:
    return self._dataset.num_total_steps

  @property
  def num_episodes(self) -> Union[int, tf.Tensor]:
    return self._dataset.num_episodes

  @property
  def num_total_episodes(self) -> Union[int, tf.Tensor]:
    return self._dataset.num_total_episodes

  @property
  def constructor_args_and_kwargs(self):
    args = [self._dataset]
    kwargs = {'num_perturbations': self._num_perturbation,  # pytype: disable=attribute-error  # bind-properties
              'perturbation_scale': self._perturbation_scale}
    return args, kwargs

  def add_step(self, env_step: EnvStep):
    self._dataset.add_step(env_step)

  def _add_perturbations(self, env_step: EnvStep, last_rows_read: tf.Tensor):
    """Add history perturbations to rewards."""
    randoms = tf.gather(self._random_numbers, last_rows_read)
    num_perturbations = self._num_perturbations or 1
    perturbations = tf.cast(
        randoms[..., None] *
        tf.pow(2., 1 + tf.range(num_perturbations, dtype=tf.float32)),
        tf.int64)
    perturbations = tf.cast(tf.math.mod(perturbations, 2),
                            env_step.reward.dtype) - 0.5

    new_reward = (env_step.reward[..., None] +
                  self._perturbation_scale * perturbations)
    if self._num_perturbations is None:
      new_reward = tf.squeeze(new_reward, -1)
      new_discount = env_step.discount
    else:
      new_discount = env_step.discount[..., None]
    return env_step.write(reward=new_reward, discount=new_discount)

  def get_step(self, batch_size: Optional[int] = None,
               num_steps: Optional[int] = None) -> EnvStep:
    env_steps = self._dataset.get_step(batch_size, num_steps)
    return self._add_perturbations(env_steps, self._dataset.last_rows_read)

  def get_episode(self, batch_size: Optional[int] = None,
                  truncate_episode_at: Optional[int] = None) -> Tuple[
                      EnvStep, Union[np.ndarray, tf.Tensor]]:
    env_steps, valid_steps = self._dataset.get_episode(
        batch_size, truncate_episode_at)
    perturbed_steps = self._add_perturbations(
        env_steps, self._dataset.last_rows_read)
    return perturbed_steps, valid_steps

  def get_all_steps(self, num_steps: Optional[int] = None,
                    limit: Optional[int] = None) -> EnvStep:
    env_steps = self._dataset.get_all_steps(num_steps, limit)
    perturbed_steps = self._add_perturbations(
        env_steps, self._dataset.last_rows_read)
    return perturbed_steps

  def get_all_episodes(self, truncate_episode_at: Optional[int] = None,
                       limit: Optional[int] = None) -> Tuple[
                           EnvStep, Union[np.ndarray, tf.Tensor]]:
    env_steps, valid_steps = self._dataset.get_all_episodes(
        truncate_episode_at, limit)
    perturbed_steps = self._add_perturbations(
        env_steps, self._dataset.last_rows_read)
    return perturbed_steps, valid_steps


text:
package com.ja.smarkdown.processing;

import javax.enterprise.context.Dependent;

import lombok.Getter;

@Dependent
public abstract class AbstractContentDataProcessor implements
		ContentDataProcessor {
	@Getter
	private MetaData metaData;

	@Override
	public void start(MetaData metaData, StringBuilder out) {
		this.metaData = metaData;
	}

	@Override
	public void processLine(final String line, final LineContext ctx) {

	}

	@Override
	public void end(MetaData metaData, StringBuilder out) {

	}

}

redpajama_set_name: RedPajamaGithub


text:
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2012 Live Networks, Inc.  All rights reserved.
// H.261 Video RTP Sources
// Implementation

#include "H261VideoRTPSource.hh"

H261VideoRTPSource*
H261VideoRTPSource::createNew(UsageEnvironment& env, Groupsock* RTPgs,
				  unsigned char rtpPayloadFormat,
				  unsigned rtpTimestampFrequency) {
  return new H261VideoRTPSource(env, RTPgs, rtpPayloadFormat,
				    rtpTimestampFrequency);
}

H261VideoRTPSource
::H261VideoRTPSource(UsageEnvironment& env, Groupsock* RTPgs,
			 unsigned char rtpPayloadFormat,
			 unsigned rtpTimestampFrequency)
  : MultiFramedRTPSource(env, RTPgs,
			 rtpPayloadFormat, rtpTimestampFrequency),
  fLastSpecialHeader(0) {
}

H261VideoRTPSource::~H261VideoRTPSource() {
}

Boolean H261VideoRTPSource
::processSpecialHeader(BufferedPacket* packet,
                       unsigned& resultSpecialHeaderSize) {
  // There's a 4-byte video-specific header
  if (packet->dataSize() < 4) return False;

  unsigned char* headerStart = packet->data();
  fLastSpecialHeader
    = (headerStart[0]<<24)|(headerStart[1]<<16)|(headerStart[2]<<8)|headerStart[3];

#ifdef DELIVER_COMPLETE_FRAMES
  fCurrentPacketBeginsFrame = fCurrentPacketCompletesFrame;
  // whether the *previous* packet ended a frame

  // The RTP "M" (marker) bit indicates the last fragment of a frame:
  fCurrentPacketCompletesFrame = packet->rtpMarkerBit();
#endif

  resultSpecialHeaderSize = 4;
  return True;
}

char const* H261VideoRTPSource::MIMEtype() const {
  return "video/H261";
}


text:
package integration;

import com.jwm.ir.persistence.Domain;
import com.jwm.ir.persistence.Page;
import com.jwm.ir.persistence.dao.*;
import org.hibernate.Session;
import org.junit.Test;

/**
 * Created by Jeff on 2016-08-08.
 */
public class PageTermDaoImpl_create_IntegrationTest extends DbTestBase {

    @Test
    public void test_create() {

        Domain domain = Domain.createFromUrl("google.com");
        Page page = Page.create(domain, "google.com/a");
        saveOrUpdate(domain);
        saveOrUpdate(page);
        Session session = sessionFactory.openSession();
        TermDao termDao = new TermDaoImpl(session);
        PageDao pageDao = new PageDaoImpl(session);
        Page p = pageDao.getPage("google.com/a");
        PageTermDao sut = new PageTermDaoImpl(termDao, pageDao, session);
        sut.create(p.getId(), "hello", 1);
    }

}


text:
| Text object | Change | Delete | Copy |
| :---        | :---   | :---   | :--- |
| One word | `cw` | `dw` | `yw` |
| Given number of words, without punctuation | `2cW` | `2dW` | `2yW` |
| Given number of words back | `3cb` | `3db` | `3yb` |
| One line | `cc` | `dd` | `yy`, `Y` |
| To end of line | `c$`, `C` | `d$`, `D` | `y$` |
| To beginning of line | `c0` | `d0` | `y0` |
| Single character | `r` | `x`, `X` | `yl`, `yh` |
| Given number of characters | `5s` | `5x` | `5yl` |

#### Editing commands
| Editing action | Command |
| :---           | :---    |
| Swap two characters | `xp` |
| Change whole word under cursor | `ciw` |
| Change text inside brackets | `ci(`, `ci[` |

#### Movement
| Movement | Command |
| :---     | :---    |
| To first line | `gg` |
| To last line | `G` |
| To given line number | `13G`, `24gg`, `:56` |
| To first character of next line | `+` |
| To first character of previous line | `-` |
| To end of word | `e`, `2e` |
| Forward by word | `w`, `3w` |
| Backward by word | `b`, `4b` |
| To end of line | `$` |
| To beginning of line | `^`, `0` |
| Next line | `j`, `5j` |
| Previous line | `k`, `6k` |
| Forward by character | `l`, `4l` |
| Backward by character | `h`, `3h` |
| Next paragraphs | `}`, `2}` |
| Previous paragraph | `{`, `3{` |
| Next function | `]]` |
| Previous function | `[[` |
| To first given character in line | `fx`, `f)` |

#### Text creation and manipulation commands
| Editing action | Command |
| :---           | :---    |
| Insert text at current position | `i` |
| Insert text at beginning of line | `I` |
| Append text at current position | `a` |
| Append text at end of line | `A` |
| Open new line below cursor for new text | `o` |
| Open new line above cursor for new text | `O` |
| Delete line and substitute text | `S` |
| Over strike existing characters with new text | `R` |
| Toggle case | `~` |
| Repeat last action | `.` |
| Undo last change | `u` |
| Restore line to original state | `U` |
| Indent whole file | `gg=G` |
| Add indention level in Insert Mode | `^T` |
| Remove indention leve in Insert Mode | `^D` |
| Add indention level in Normal/Visual Mode | `>>` |
| Remove indention leve in Normal/Visual Mode | `<<` |

#### Changing case commands
| Change case action | Command |
| :---               | :---    |
| Current character | `~` |
| Current line from upper to lower | `guu` |
| Current line from lower to upper | `gUU` |
| To end of current word from upper to lower | `guw` |
| To end of current word from lower to upper | `gUw` |
| All of current word to lower | `guaw` |
| All of current word to upper | `gUaw` |
| Invert case to entire line | `g~~` |

#### Text spelling
| Spelling action | Command |
| :---            | :---    |
| Enable spell check for current file | `:setlocal spell spelllang=en,ru` |
| Disable spell check for current file | `:setlocal nospell`
| Go to next misspelled word | `]s` |
| Go to previous misspelled word | `[s` |
| Show suggestions for word under cursor | `z=` |

#### Moving over file
| Move action | Command |
| :---        | :---    |
| Back one full screen | `<C-b>` |
| Forward one full screen | `<C-f>` |
| Down 1/2 screen | `<C-d>` |
| Up 1/2 screen | `<C-u>` |

#### Positioning on screen
| Position action | Command |
| :---            | :---    |
| Current line to middle | `z.` |
| Current line to top | `zt` |
| Current lint to bottom | `zb` |

#### Visual mode
| Visual selection actions | Command |
| :---                     | :---    |
| Select word | `iw`, `iW` |
| Select paragraph | `ip`, `ap` |
| Select block between pair symbols | `i{`, `i(`, `i<` |
| Enter column insert mode | `Shift+i` |
| Filter selected text | `!sort` will sort and replace selected text |

#### Search
| Search actions | Command |
| :---           | :---    |
| Go to next word under cursor | `*` |
| Go to previous word under cursor | `#` |
| Go to next subword under cursor | `g*` |
| Go to previous subword under cursor | `g#` |
| Go to local declaration | `gd` |
| Go to global declaration | `gD` |
| Show all lines with word under cursor | `[I`, `]I` |
| To search for pattern | `/pattern` |
| Go to next search results | `n` |
| Go to previous search results | `N` |
| To list lines with results last pattern | `:g//` |
| List lines with search results for pattern | `:g/pattern/` |
| Search in all Markdown files in current directory | `:vimgrep /pattern/ *.md` |
| Count number of matches in file | `:%s/patter//gn` |

#### Replace
| Replace actions | Command |
| :---            | :---    |
| Replace `aaa` to `bbb` in whole file | `:%s/aaa/bbb/g` |
| Replace only in lines that contains `string` | `:g/string/s/aaa/bbb/g` |
| Convert tabs to expandtab settings | `:%retab` |
| Delete lines that contains `pattern` | `:g/pattern/d` |
| Delete blank lines | `:g/^$/d` |

#### Moving over windows
| Move actions | Command |
| :---         | :---    |
| `:new` horizontal split (editing a new empty buffer) | `<C-w>n` |
| `:split` window horizontally (editing current buffer) | `<C-w>s` |
| `:vsplit` window vertically (editing current buffer) | `<C-w>v` |
| `:close` window | `<C-w>c` |
| close all windows, leaving :only the current window open | `<C-w>o` |
| go to next window | `<C-w>w` |
| go to previous window | `<C-w>p` |
| go to window above | `<C-w><Up>` |
| go to window below | `<C-w><Down>` |
| go to window on left | `<C-w><Left>` |
| go to window on right | `<C-w><Right>` |

#### Filtering text
| Filter action | Command |
| :---          | :---    |
| Sort lines from 12 to 42 and replace those lines | `12,42!sort` |

### Add-ons

#### Editing file with (m)vim
* `vim -p file1 file2` open in tabs
* `mvim --remote-tab file3` open file in existing editor as tab

#### Find text in files and display in QuickFix
* `:vimgrep /pattern/ *.ext`

Recursively:
* `:vimgrep /pattern/ **/*.ext`

#### Add new file type detection
```sh
$ mkdir ~/.vim/ftdetect
$ echo "au BufRead,BufNewFile *.ex,*.exs set filetype=elixir" > ~/.vim/ftdetect/elixir.vim
```

#### Reload `~/.vimrc` file without restarting vim
```sh
:so ~/.vimrc
```

#### Install new color theme
```sh
$ mkdir ~/.vim/colors/
$ mv mustang.vim ~/.vim/colors/
```

#### Show recently used files
* `:oldfiles` or `:browse oldfiles`


text:
<?php

namespace LoopAnime\AdminBundle\Command;

use LoopAnime\ShowsAPIBundle\Entity\AnimesAPI;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class UpdateAnimeCommand extends ContainerAwareCommand {

    /** @var OutputInterface */
    protected $output;

    protected function configure()
    {
        $this
            ->setName('loopanime:admin:import:update-animes')
            ->setDescription('Updates Animes on the database')
            ->addOption('all', 'a', InputOption::VALUE_NONE, 'Updates all Animes , including the ones that have already finish')
            ->addOption('anime', 'i', InputOption::VALUE_REQUIRED, 'Updates a specific Anime - Provide the ID of the database');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $isAll = $input->getOption('all');
        $anime = $input->getOption('anime');
        $this->output = $output;

        if ($isAll) {
            $this->output->writeln('<question>Updating All Animes!</question>');
        }
        if ($anime) {
            $this->output->writeln('<question>Updating only the anime with the ID: ' . $anime . '</question>');
        }

        $doctrine = $this->getContainer()->get('doctrine');
        /** @var AnimesAPI[] $animes */
        $animes = $doctrine->getRepository('LoopAnimeShowsAPIBundle:AnimesAPI')->getAnimesToUpdate($isAll, $anime);

        foreach ($animes as $anime) {
            $this->output->writeln('<error>Failed to update the anime ' . $anime->getApiAnimeKey() . '</error>');
            $command = $this->getApplication()->find('loopanime:admin:import:add-anime');
            $arguments = ['--tvdbId' => $anime->getApiAnimeKey()];
            $input = new ArrayInput($arguments);
            $returnCode = $command->run($input, $output);
            if ($returnCode !== 0) {
                $this->output->writeln('<error>Failed to update the anime ' . $anime->getApiAnimeKey() . '</error>');
            }
        }
        $this->output->writeln('<info>All Animes were Updated!</info>');
    }

}


text:
using System;
using System.Collections;

namespace Glimpse.Core.Extensibility
{
    /// <summary>
    /// An adapter between an <see cref="IDictionary"/> and <see cref="IDataStore"/>.
    /// </summary>
    public class DictionaryDataStoreAdapter : IDataStore
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="DictionaryDataStoreAdapter" /> class.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        /// <exception cref="System.ArgumentException">Throws an exception if a generic dictionary does not have a value of type <see cref="object"/> and a key of either <see cref="string"/> or <see cref="object"/>.</exception>
        public DictionaryDataStoreAdapter(IDictionary dictionary)
        {
            if (!IsValidDictionaryType(dictionary))
            {
                throw new ArgumentException("dictionary");
            }

            Dictionary = dictionary;
        }

        /// <summary>
        /// Gets or sets the dictionary.
        /// </summary>
        /// <value>
        /// The dictionary.
        /// </value>
        internal IDictionary Dictionary { get; set; }

        /// <summary>
        /// Gets the item with the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>
        /// The value stored at given key.
        /// </returns>
        public object Get(string key)
        {
            return Dictionary[key];
        }

        /// <summary>
        /// Sets the item with the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public void Set(string key, object value)
        {
            Dictionary[key] = value;
        }

        /// <summary>
        /// Determines whether the data store contains a definition for the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>
        ///   <c>true</c> if it contains the specified key; otherwise, <c>false</c>.
        /// </returns>
        public bool Contains(string key)
        {
            return Dictionary.Contains(key);
        }

        private static bool IsValidDictionaryType(IDictionary dictionary)
        {
            if (dictionary == null)
            {
                return false;
            }

            Type[] genericParameters = dictionary.GetType().GetGenericArguments();

            // Support non-generics IDictionary
            if (genericParameters.Length == 0)
            {
                return true;
            }

            // Only support IDictionary<string|object, object>
            if (genericParameters[0] != typeof(string) && genericParameters[0] != typeof(object))
            {
                return false;
            }

            if (genericParameters[1] != typeof(object))
            {
                return false;
            }

            return true;
        }
    }
}


text:
package cn.mutils.app.data;

import cn.mutils.app.queue.IQueueListener;

public interface IAsyncDataQueueListener extends IQueueListener {

}


text:
import test from 'tape'
import {commentViewState, feedViewState, posts, postsViewState, users} from 'src/redux/reducers'
import {unauthenticated} from 'src/redux/action-creators'

test('unauthenticated action clears reducer state', t => {

  const ordinaryReducers = [commentViewState, posts, postsViewState, users]

  const ordinaryReducersReduced = ordinaryReducers.map(reducer => reducer({'1':{},'2':{}}, unauthenticated()))

  ordinaryReducersReduced.forEach(reducedResult => t.equal(Object.keys(reducedResult).length, 0))

  const feedViewStateReduced = feedViewState({visibleEntries: ['1','2'], hiddenEntries:['3','4'], isHiddenRevealed: true}, unauthenticated())
  t.equal(feedViewStateReduced.visibleEntries.length, 0)
  t.equal(feedViewStateReduced.hiddenEntries.length, 0)
  t.notOk(feedViewStateReduced.isHiddenRevealed)

  t.end()
})


text:
package com.evolveum.midpoint.repo.sql;

import com.evolveum.midpoint.audit.api.AuditEventRecord;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.repo.sql.data.audit.RAuditEventRecord;
import com.evolveum.midpoint.repo.sql.util.SimpleTaskAdapter;
import com.evolveum.midpoint.schema.ObjectDeltaOperation;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CleanupPolicyType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;

import java.util.List;

/**
 * @author lazyman
 * @author mederly
 */
@ContextConfiguration(locations = {"../../../../../ctx-test.xml"})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class AuditCleanupPerformanceTest extends BaseSQLRepoTest {

    private static final Trace LOGGER = TraceManager.getTrace(AuditCleanupPerformanceTest.class);

    private static final int RECORDS = 50000;

    private static final boolean DO_CREATE = true;
    private static final boolean DO_CLEANUP = true;

    @Test
    public void testAuditCleanup() throws Exception {
        //GIVEN
        if (DO_CREATE) {
            prepareAuditEventRecords();
        }

        if (DO_CLEANUP) {
            //WHEN
            CleanupPolicyType policy = new CleanupPolicyType().maxRecords(1);

            OperationResult result = new OperationResult("Cleanup audit");
            long cleanupStart = System.currentTimeMillis();
            auditService.cleanupAudit(policy, result);
            long cleanupDuration = System.currentTimeMillis() - cleanupStart;
            System.out.println("Cleanup done in " + cleanupDuration + " ms (" + cleanupDuration / (RECORDS - 1) + " ms per record)");
            result.recomputeStatus();

            //THEN
            assertAuditEventRecord(result);
        }
    }

    private void assertAuditEventRecord(OperationResult result) {
        AssertJUnit.assertTrue(result.isSuccess());
        try (Session session = getFactory().openSession()) {
            session.beginTransaction();
            Query query = session.createQuery("from " + RAuditEventRecord.class.getSimpleName());
            List<RAuditEventRecord> records = query.list();
            AssertJUnit.assertEquals(1, records.size());
            session.getTransaction().commit();
        }
    }

    private void prepareAuditEventRecords() throws Exception {
        long start = System.currentTimeMillis();
        for (int i = 0; i < RECORDS;) {
            AuditEventRecord record = new AuditEventRecord();
            record.addDelta(createObjectDeltaOperation(i));
            record.setTimestamp(System.currentTimeMillis());
            record.addPropertyValue("prop1", "val1");
            record.addReferenceValue("ref1", ObjectTypeUtil.createObjectRef("oid1", ObjectTypes.USER).asReferenceValue());
            auditService.audit(record, new SimpleTaskAdapter());
            i++;
            if (i%1000 == 0 || i == RECORDS) {
                long duration = System.currentTimeMillis() - start;
                System.out.println(i + " records created in " + duration + " ms (" + duration / i + " ms per record)");
            }
        }
        try (Session session = getFactory().openSession()) {
            session.beginTransaction();
            Query query = session.createQuery("select count(*) from " + RAuditEventRecord.class.getSimpleName());
            Long count = (Long) query.uniqueResult();
            AssertJUnit.assertEquals(RECORDS, (long) count);
            session.getTransaction().commit();
        }
    }

    private ObjectDeltaOperation<UserType> createObjectDeltaOperation(int i) throws Exception {
        ObjectDelta<UserType> delta = prismContext.deltaFor(UserType.class)
                .item(UserType.F_DESCRIPTION).replace("d" + i)
                .asObjectDeltaCast("oid-" + i);
        ObjectDeltaOperation<UserType> odo = new ObjectDeltaOperation<>();
        odo.setObjectDelta(delta);
        odo.setExecutionResult(new OperationResult("asdf"));
        return odo;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/Users/cherish/Documents/yibairun/yibairun/build/intermediates/exploded-aar/yibairun/RefreshLibrary/unspecified/res/values-iw/values.xml -->
    <eat-comment/>
    <string name="pull_to_refresh_pull_label">משוך לרענון…</string>
    <string name="pull_to_refresh_refreshing_label">טוען…</string>
    <string name="pull_to_refresh_release_label">שחרר לרענון…</string>
</resources>


text:
const consoleOutput = require('./providers/console');
const tts = require('./providers/tts');

const provider = process.env.OUTPUT || 'consoleOutput';

const providers = {
  consoleOutput,
  tts,
};

module.exports = {
  instance: providers[provider],
};


text:
namespace clover {
namespace util {

SlicedTask::SlicedTask(TaskFunc f)
		: taskFunc(f)
		, initialPauseLock(mutex){
	launchFuture();
}

void SlicedTask::runFor(real64 seconds){
	ensure(seconds >= 0.0 || seconds == eternity);
	ensure(!finished);

	if (!blocking){
		if (seconds >= 0.0){
			auto time= util::asMicroseconds(seconds);

			{ InverseLock g(mutex); // Unleash the task thread
				if (future.wait_for(time) == std::future_status::ready){
					finished= true;
					if (future.valid())
						future.get(); // Possible exception
				}
			}
		}
		else if (seconds == eternity) {
			skipYield= true;
			{ InverseLock g(mutex);
				finished= true;
				future.get();
			}
			skipYield= false;
		}
	}
	else {
		// Single threaded
		taskFunc(nullYield());
		finished= true;
	}
}

bool SlicedTask::isFinished() const {
	return finished;
}

void SlicedTask::relaunch(){
	ensure(isFinished());
	finished= false;
	skipYield= false;
	blocking= false;
	launchFuture();
}

void SlicedTask::launchFuture(){
	std::thread::id super_id= std::this_thread::get_id();
	try {
		future= std::async(std::launch::async, [this, super_id] (){
			PROFILER_SUPER_THREAD(super_id);
			callTask();
		});
	}
	catch (std::system_error& e){
		print(debug::Ch::General, debug::Vb::Critical, "SlicedTask::launchFuture(): Launching async task failed: %s", e.what());
		print(debug::Ch::General, debug::Vb::Moderate, "SlicedTask::launchFuture(): Blocking mode enabled");
		blocking= true;
	}
}

void SlicedTask::callTask(){
	Yield yielder= [this] () {
		if (skipYield)
			return;

		/// @todo Measure time and filter unnecessary yields away

		PROFILER_STACK_DETACH();
		InverseLock g(mutex); // Unleash the main thread
		// This is needed on Linux, otherwise main thread won't get the
		// mutex and task will be completed at once. Seems like scheduling issue
		std::this_thread::sleep_for(std::chrono::nanoseconds(0));
	};

	{ Lock g(mutex); // Wait for running the task
		PROFILER_STACK_JOIN();
		taskFunc(yielder);
	}
}

} // util
} // clover


text:
<?php

namespace alexeevdv\sms\ru;

class Sms extends \yii\base\Model {

    /**
     * Sms identificator
     * @var string
     */
    public $id;

    /**
     * Sms sending result
     * @var integer
     */
    public $code = -1;

    public $from;

    public $to;

    public $text;

    public $test;

    public $translit = false;

    public function init() {

        parent::init();

        if (empty($this->to)) {
            throw new \yii\base\InvalidConfigException('`to` param is required');
        }

        if (empty($this->text)) {
            throw new \yii\base\InvalidConfigException('`text` param is required');
        }
    }
}


text:
package zeroconf

import "strings"

// trimDot is used to trim the dots from the start or end of a string
func trimDot(s string) string {
	return strings.Trim(s, ".")
}


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_Object2689449295.h"

// UnityEngine.ILogger
struct ILogger_t1425954571;

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// UnityEngine.Debug
struct  Debug_t1368543263  : public Il2CppObject
{
public:

public:
};

struct Debug_t1368543263_StaticFields
{
public:
	// UnityEngine.ILogger UnityEngine.Debug::s_Logger
	Il2CppObject * ___s_Logger_0;

public:
	inline static int32_t get_offset_of_s_Logger_0() { return static_cast<int32_t>(offsetof(Debug_t1368543263_StaticFields, ___s_Logger_0)); }
	inline Il2CppObject * get_s_Logger_0() const { return ___s_Logger_0; }
	inline Il2CppObject ** get_address_of_s_Logger_0() { return &___s_Logger_0; }
	inline void set_s_Logger_0(Il2CppObject * value)
	{
		___s_Logger_0 = value;
		Il2CppCodeGenWriteBarrier(&___s_Logger_0, value);
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
require File.expand_path('watir_helper/common_helpers', File.dirname(__FILE__))
require File.expand_path('watir_helper/include_other_helpers', File.dirname(__FILE__))


text:
/**
 * The interface for a block dragger.
 *
 * @namespace Blockly.IBlockDragger
 */
import * as goog from '../../closure/goog/goog.js';
import type {Coordinate} from '../utils/coordinate.js';
import type {BlockSvg} from '../block_svg.js';
goog.declareModuleId('Blockly.IBlockDragger');

/**
 * A block dragger interface.
 *
 * @alias Blockly.IBlockDragger
 */
export interface IBlockDragger {
  /**
   * Start dragging a block.  This includes moving it to the drag surface.
   *
   * @param currentDragDeltaXY How far the pointer has moved from the position
   *     at mouse down, in pixel units.
   * @param healStack Whether or not to heal the stack after disconnecting.
   */
  startDrag(currentDragDeltaXY: Coordinate, healStack: boolean): void;

  /**
   * Execute a step of block dragging, based on the given event.  Update the
   * display accordingly.
   *
   * @param e The most recent move event.
   * @param currentDragDeltaXY How far the pointer has moved from the position
   *     at the start of the drag, in pixel units.
   */
  drag(e: Event, currentDragDeltaXY: Coordinate): void;

  /**
   * Finish a block drag and put the block back on the workspace.
   *
   * @param e The mouseup/touchend event.
   * @param currentDragDeltaXY How far the pointer has moved from the position
   *     at the start of the drag, in pixel units.
   */
  endDrag(e: Event, currentDragDeltaXY: Coordinate): void;

  /**
   * Get a list of the insertion markers that currently exist.  Drags have 0, 1,
   * or 2 insertion markers.
   *
   * @returns A possibly empty list of insertion marker blocks.
   */
  getInsertionMarkers(): BlockSvg[];

  /** Sever all links from this object and do any necessary cleanup. */
  dispose(): void;
}


text:
require('ember-model/computed');
var get = Ember.get,
    set = Ember.set;

function storeFor(record) {
  var owner = Ember.getOwner(record);
  if (owner) {
    return owner.lookup('service:store');
  }

  return null;
}

function getType(record) {
  var type = this.type;

  if (typeof this.type === "string" && this.type) {
    type = Ember.get(Ember.lookup, this.type);

    if (!type) {
      var store = storeFor(record);
      type = store.modelFor(this.type);
      type.reopenClass({ adapter: store.adapterFor(this.type) });
    }
  }

  return type;
}

Ember.belongsTo = function(type, options) {
  options = options || {};

  var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo', getType: getType};

  return Ember.Model.computed("_data", {
    get: function(propertyKey){
      type = meta.getType(this);
      Ember.assert("Type cannot be empty.", !Ember.isEmpty(type));

      var key = options.key || propertyKey,
          self = this;

      var dirtyChanged = function(sender) {
        if (sender.get('isDirty')) {
          self._relationshipBecameDirty(propertyKey);
        } else {
          self._relationshipBecameClean(propertyKey);
        }
      };

      var store = storeFor(this),
          value = this.getBelongsTo(key, type, meta, store);
      this._registerBelongsTo(meta);
      if (value !== null && meta.options.embedded) {
        value.get('isDirty'); // getter must be called before adding observer
        value.addObserver('isDirty', dirtyChanged);
      }
      return value;
    },

    set: function(propertyKey, value, oldValue){
      type = meta.getType(this);
      Ember.assert("Type cannot be empty.", !Ember.isEmpty(type));

      var dirtyAttributes = get(this, '_dirtyAttributes'),
          createdDirtyAttributes = false,
          self = this;

      var dirtyChanged = function(sender) {
        if (sender.get('isDirty')) {
          self._relationshipBecameDirty(propertyKey);
        } else {
          self._relationshipBecameClean(propertyKey);
        }
      };

      if (!dirtyAttributes) {
        dirtyAttributes = [];
        createdDirtyAttributes = true;
      }

      if (value) {
        Ember.assert(Ember.String.fmt('Attempted to set property of type: %@ with a value of type: %@',
                    [value.constructor, type]),
                    value instanceof type);
      }

      if (oldValue !== value) {
        dirtyAttributes.pushObject(propertyKey);
      } else {
        dirtyAttributes.removeObject(propertyKey);
      }

      if (createdDirtyAttributes) {
        set(this, '_dirtyAttributes', dirtyAttributes);
      }

      if (meta.options.embedded) {
        if (oldValue) {
          oldValue.removeObserver('isDirty', dirtyChanged);
        }
        if (value) {
          value.addObserver('isDirty', dirtyChanged);
        }
      }

      return value === undefined ? null : value;
    }
  }).meta(meta);
};

Ember.Model.reopen({
  getBelongsTo: function(key, type, meta, store) {
    var idOrAttrs = get(this, '_data.' + key),
        record;

    if (Ember.isNone(idOrAttrs)) {
      return null;
    }

    if (meta.options.embedded) {
      var primaryKey = get(type, 'primaryKey'),
        id = idOrAttrs[primaryKey];
      var owner = Ember.getOwner(this);
      record = type.create({ isLoaded: false, id: id });
      Ember.setOwner(record, owner);

      record.load(id, idOrAttrs);
    } else {
      if (store) {
        record = store._findSync(meta.type, idOrAttrs);
      } else {
        record = type.find(idOrAttrs);
      }
    }

    return record;
  }
});


text:
@interface ComGoodowRealtimeStoreTextInsertedEvent : NSObject
@end

@implementation ComGoodowRealtimeStoreTextInsertedEvent

+ (const J2ObjcClassInfo *)__metadata {
  static const J2ObjcMethodInfo methods[] = {
    { "index", NULL, "I", 0x401, NULL },
    { "text", NULL, "Ljava.lang.String;", 0x401, NULL },
  };
  static const J2ObjcClassInfo _ComGoodowRealtimeStoreTextInsertedEvent = { 1, "TextInsertedEvent", "com.goodow.realtime.store", NULL, 0x201, 2, methods, 0, NULL, 0, NULL};
  return &_ComGoodowRealtimeStoreTextInsertedEvent;
}

@end

J2OBJC_INTERFACE_TYPE_LITERAL_SOURCE(ComGoodowRealtimeStoreTextInsertedEvent)


text:
#include "test_rearrange.hpp"

#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <algorithm>
#include <iterator>
#include "pre_multi_index.hpp"
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/next_prior.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/ref.hpp>
#include <boost/test/test_tools.hpp>
#include <vector>

using namespace boost::multi_index;

#undef CHECK_EQUAL
#define CHECK_EQUAL(p,check_seq) \
{\
  int v[]={BOOST_PP_SEQ_ENUM(check_seq)};\
  std::size_t size_v=sizeof(v)/sizeof(int);\
  BOOST_CHECK(std::size_t(std::distance((p).begin(),(p).end()))==size_v);\
  BOOST_CHECK(std::equal((p).begin(),(p).end(),&v[0]));\
}

#undef CHECK_VOID_RANGE
#define CHECK_VOID_RANGE(p) BOOST_CHECK((p).first==(p).second)

#if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
/* The "ISO C++ Template Parser" option makes CW8.3 incorrectly fail at
 * expressions of the form sizeof(x) where x is an array local to a
 * template function.
 */

#pragma parse_func_templ off
#endif

template<typename Sequence>
static void local_test_rearrange(BOOST_EXPLICIT_TEMPLATE_TYPE(Sequence))
{
  typedef typename Sequence::iterator   iterator;
  typedef typename Sequence::value_type value_type;

  Sequence sc;
  sc.push_back(0);
  sc.push_back(1);
  sc.push_back(2);
  sc.push_back(3);
  sc.push_back(4);
  sc.push_back(5);

  iterator it;

  it=sc.begin();
  std::advance(it,3);
  sc.relocate(sc.begin(),it);
  CHECK_EQUAL(sc,(3)(0)(1)(2)(4)(5));
  BOOST_CHECK(it==sc.begin());

  sc.relocate(it,it);
  CHECK_EQUAL(sc,(3)(0)(1)(2)(4)(5));

  std::advance(it,3);
  sc.relocate(sc.end(),it,sc.end());
  CHECK_EQUAL(sc,(3)(0)(1)(2)(4)(5));

  sc.relocate(sc.begin(),it,it);
  CHECK_EQUAL(sc,(3)(0)(1)(2)(4)(5));

  iterator it2;

  it2=sc.begin();
  ++it2;
  sc.relocate(it2,it,sc.end());
  CHECK_EQUAL(sc,(3)(2)(4)(5)(0)(1));
  BOOST_CHECK(std::distance(it,it2)==3);

  sc.relocate(boost::prior(sc.end()),it,it2);
  CHECK_EQUAL(sc,(3)(0)(2)(4)(5)(1));

  std::vector<boost::reference_wrapper<const value_type> > v;
  for(iterator it3=sc.begin();it3!=sc.end();++it3){
    v.push_back(boost::cref(*it3));
  }

  sc.rearrange(v.begin());
  BOOST_CHECK(std::equal(sc.begin(),sc.end(),v.begin()));

  std::reverse(v.begin(),v.end());
  sc.rearrange(v.begin());
  BOOST_CHECK(std::equal(sc.begin(),sc.end(),v.begin()));

  std::sort(v.begin(),v.end());
  sc.rearrange(v.begin());
  BOOST_CHECK(std::equal(sc.begin(),sc.end(),v.begin()));

  std::reverse(v.begin(),v.begin()+v.size()/2);
  sc.rearrange(v.begin());
  BOOST_CHECK(std::equal(sc.begin(),sc.end(),v.begin()));
}

#if BOOST_WORKAROUND(__MWERKS__,<=0x3003)
#pragma parse_func_templ reset
#endif

void test_rearrange()
{
  typedef multi_index_container<
    int,
    indexed_by<sequenced<> >
  > int_list;

  /* MSVC++ 6.0 chokes on local_test_rearrange without this
   * explicit instantiation
   */
  int_list il;
  local_test_rearrange<int_list>();

  typedef multi_index_container<
    int,
    indexed_by<random_access<> >
  > int_vector;

  int_vector iv;
  local_test_rearrange<int_vector>();
}


text:
Scour is a Python module that takes an input SVG and outputs a cleaner,
more concise SVG file.  The goal is that authors will use this script after
editing the file in a GUI editor such as Inkscape or Adobe Illustrator.

Scour was started as a vehicle for me to learn Python.  In addition, the goal
is to reduce the amount of time I spend in cleaning up files I find on sites
such as openclipart.org

Ideas are pulled from three places:

  * my head
  * Sam Ruby's SVG Tidy script: http://intertwingly.net/code/svgtidy/svgtidy.rb
  * Inkscape's proposal for a 'cleaned SVG': http://wiki.inkscape.org/wiki/index.php/Save_Cleaned_SVG

Regards,

Jeff Schiller, 2009-04-06

codedread@gmail.com

http://blog.codedread.com/

http://www.codedread.com/scour/

## Usage

Standard:

	scour -i mysvg.svg -o mysvg_opt.svg

Better (this works in IE which needs Viewbox):

	scour -i mysvg.svg -o mysvg_opt.svg --enable-viewboxing

Maximum:

	scour -i mysvg.svg -o mysvg_opt.svg --enable-viewboxing --enable-id-stripping \
          --enable-comment-stripping --shorten-ids --indent=none

Maximum + Compress:

	scour -i mysvg.svg -o mysvg_opt.svgz --enable-viewboxing --enable-id-stripping \
          --enable-comment-stripping --shorten-ids --indent=none

## Notes

Packaging from [sources](http://www.codedread.com/scour/) retrieved on 2013/20/22:

  * done by Tavendo GmbH, Tobias Oberstein
  * license same as upstream (Apache 2.0)


text:
using System;
using System.Windows;
using System.Windows.Controls;

namespace Wallace.IDE.Framework.UI
{
    /// <summary>
    /// Implements IFunctionManager using a ToolBar.
    /// </summary>
    internal class ToolBarFunctionManager : HostBase<ToolBar>, IFunctionManager
    {
        #region Fields

        /// <summary>
        /// Handler for button clicks.
        /// </summary>
        private RoutedEventHandler _buttonClickHandler;

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor.
        /// </summary>
        public ToolBarFunctionManager()
        {
            _buttonClickHandler = new RoutedEventHandler(Button_Click);
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="host">Host.</param>
        public ToolBarFunctionManager(ToolBar host)
            : this()
        {
            Host = host;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Remove event handlers.
        /// </summary>
        protected override void BeforeHostSet()
        {
            base.BeforeHostSet();

            if (Host != null)
                Host.RemoveHandler(Button.ClickEvent, _buttonClickHandler);
        }

        /// <summary>
        /// Setup event handlers.
        /// </summary>
        protected override void AfterHostSet()
        {
            base.AfterHostSet();

            if (Host != null)
                Host.AddHandler(Button.ClickEvent, _buttonClickHandler);
        }

        /// <summary>
        /// Gets the display element for the given function.
        /// </summary>
        /// <param name="function">The function to get the display element for.</param>
        /// <returns>The display element for the given function or null if it isn't found.</returns>
        private FrameworkElement GetElement(IFunction function)
        {
            EnsureHost();
            if (function == null)
                throw new ArgumentNullException("function");

            foreach (object item in Host.Items)
            {
                if (item is FrameworkElement)
                {
                    FrameworkElement element = item as FrameworkElement;
                    if (element.Tag is IFunction && (element.Tag as IFunction).Id == function.Id)
                        return element;
                }
            }

            return null;
        }

        /// <summary>
        /// Create and configure a display element to display for the given function.
        /// </summary>
        /// <param name="function">The function to build up a display element for.</param>
        /// <returns>The newly built display element.</returns>
        private FrameworkElement BuildUpElement(IFunction function)
        {
            FrameworkElement element = null;

            if (function is FunctionSeparator)
            {
                Separator separator = new Separator();
                separator.Tag = function;
                separator.Visibility = function.IsVisible ? Visibility.Visible : Visibility.Collapsed;
                separator.IsEnabled = function.IsEnabled;

                element = separator;
            }
            else
            {
                Button button = new Button();
                button.Tag = function;
                ButtonFunctionPresenter presenter = new ButtonFunctionPresenter(button, this);
                function.Init(FunctionHost.Toolbar, presenter);
                function.Update(FunctionHost.Toolbar, presenter);
                presenter.IsVisible = function.IsVisible;
                presenter.IsEnabled = function.IsEnabled;

                element = button;
            }

            function.IsEnabledChanged += function_IsEnabledChanged;
            function.IsVisibleChanged += function_IsVisibleChanged;

            return element;
        }

        /// <summary>
        /// Tear down a function that was previously built up.
        /// </summary>
        /// <param name="function">The function to tear down.</param>
        private void TearDownElement(IFunction function)
        {
            function.IsEnabledChanged -= function_IsEnabledChanged;
            function.IsVisibleChanged -= function_IsVisibleChanged;
        }

        #endregion

        #region IFunctionManager Members

        /// <summary>
        /// Add the given function to the root of the control.
        /// </summary>
        /// <param name="function">The function to add.</param>
        public void AddFunction(IFunction function)
        {
            AddFunction(function, int.MaxValue);
        }

        /// <summary>
        /// Add the given function to the root of the control.
        /// </summary>
        /// <param name="function">The function to add.</param>
        /// <param name="position">The position where the function will be inserted.</param>
        public void AddFunction(IFunction function, int position)
        {
            EnsureHost();

            if (function == null)
                throw new ArgumentException("function");

            if (GetElement(function) != null)
                return;

            if (position < 0)
                position = 0;
            if (position > Host.Items.Count)
                Host.Items.Add(BuildUpElement(function));
            else
                Host.Items.Insert(position, BuildUpElement(function));
        }

        /// <summary>
        /// Add the given function to the sub items of the function with the given id.
        /// </summary>
        /// <param name="function">The function to add.</param>
        /// <param name="parentId">The id of the parent to add the function to.</param>
        public void AddFunction(IFunction function, string parentId)
        {
            AddFunction(function, parentId, int.MaxValue);
        }

        /// <summary>
        /// This method is not supported.
        /// </summary>
        /// <param name="function">The function to add.</param>
        /// <param name="parentId">The id of the parent to add the function to.</param>
        /// <param name="position">The position where the function will be inserted.</param>
        public void AddFunction(IFunction function, string parentId, int position)
        {
            throw new NotSupportedException();
        }

        /// <summary>
        /// Remove the function from the control.
        /// </summary>
        /// <param name="function">The function to remove.</param>
        public void RemoveFunction(IFunction function)
        {
            EnsureHost();

            FrameworkElement element = GetElement(function);
            if (element != null)
            {
                RemoveFunctionChildren(function);

                ItemsControl parent = element.Parent as ItemsControl;
                if (parent != null)
                    parent.Items.Remove(element);

                TearDownElement(function);
            }
        }

        /// <summary>
        /// Remove all of the functions children.
        /// </summary>
        /// <param name="function">The function whose children will be removed.</param>
        public void RemoveFunctionChildren(IFunction function)
        {
            EnsureHost();

            ItemsControl parent = GetElement(function) as ItemsControl;
            if (parent != null)
            {
                foreach (object item in parent.Items)
                {
                    FrameworkElement element = item as FrameworkElement;
                    if (element != null && element.Tag is IFunction)
                    {
                        IFunction child = element.Tag as IFunction;
                        TearDownElement(child);
                        RemoveFunctionChildren(element.Tag as IFunction);
                    }
                }

                parent.Items.Clear();
            }
        }

        /// <summary>
        /// Update all functions.
        /// </summary>
        public void UpdateFunctions()
        {
            EnsureHost();

            foreach (FrameworkElement item in Host.Items)
            {
                if (item.Tag is IFunction && item is Button)
                    (item.Tag as IFunction).Update(FunctionHost.Toolbar, new ButtonFunctionPresenter(item as Button, this));
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Execute function that was clicked.
        /// </summary>
        /// <param name="sender">Object that raised the event.</param>
        /// <param name="e">Event arguments.</param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button button = VisualHelper.GetAncestor<Button>(e.OriginalSource as DependencyObject);
                if (button != null && button.Tag is IFunction)
                    (button.Tag as IFunction).Execute();
            }
            catch (Exception err)
            {
                IDE.HandleException(err);
            }
        }

        /// <summary>
        /// Update the visiblity of the function.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">The event arguments.</param>
        private void function_IsVisibleChanged(object sender, EventArgs e)
        {
            try
            {
                IFunction function = sender as IFunction;
                FrameworkElement element = GetElement(function);
                if (element != null)
                    element.Visibility = function.IsVisible ? Visibility.Visible : Visibility.Collapsed;
            }
            catch (Exception err)
            {
                IDE.HandleException(err);
            }
        }

        /// <summary>
        /// Update the enabled state of the function.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">The event arguments.</param>
        private void function_IsEnabledChanged(object sender, EventArgs e)
        {
            try
            {
                IFunction function = sender as IFunction;
                Button button = GetElement(function) as Button;
                if (button != null)
                    new ButtonFunctionPresenter(button, this).IsEnabled = function.IsEnabled;
            }
            catch (Exception err)
            {
                IDE.HandleException(err);
            }
        }

        #endregion
    }
}


text:
module Network.Hubbub
  ( Callback(Callback)
  , From(From)
  , HttpResource(HttpResource)
  , HubbubConfig(HubbubConfig)
  , HubbubAcidConfig(HubbubAcidConfig)
  , HubbubSqLiteConfig(HubbubSqLiteConfig)
  , HubbubEnv
  , LeaseSeconds(LeaseSeconds)
  , Secret(Secret)
  , ServerUrl(ServerUrl)
  , Subscription(Subscription)
  , Topic(Topic)
  , initializeHubbubAcid
  , initializeHubbubSqLite
  , httpResourceFromText
  , httpResourceToText
  , listSubscriptions
  , publish
  , shutdownHubbub
  , subscribe
  , unsubscribe
  ) where

import Network.Hubbub.Internal
  ( doDistributionEvent
  , doSubscriptionEvent
  , doPublicationEvent )
import Network.Hubbub.Http (ServerUrl(ServerUrl))
import Network.Hubbub.Queue
  ( AttemptCount(AttemptCount)
  , DistributionEvent
  , LeaseSeconds(LeaseSeconds)
  , PublicationEvent(PublicationEvent)
  , RetryDelay
  , SubscriptionEvent(Subscribe,Unsubscribe)
  , emptyDistributionQueue
  , emptyPublicationQueue
  , emptySubscriptionQueue
  , distributionLoop
  , publicationLoop
  , retryDelaySeconds
  , subscriptionLoop )

import qualified Network.Hubbub.Queue as Q
import Network.Hubbub.SubscriptionDb
  ( Callback(Callback)
  , From(From)
  , HttpResource(HttpResource)
  , Secret(Secret)
  , SubscriptionDbApi
  , Subscription(Subscription)
  , Topic(Topic)
  , expireSubscriptions
  , getAllSubscriptions
  , httpResourceFromText
  , httpResourceToText
  , shutdownDb )

import Network.Hubbub.SubscriptionDb.Acid (acidDbApi)
import Network.Hubbub.SubscriptionDb.SqLite (sqLiteDbApi)

import Prelude (Int,(*),div,fromIntegral)
import Control.Concurrent (ThreadId,forkIO,threadDelay)
import Control.Concurrent.STM(TQueue,atomically)
import Control.Exception.Base (SomeException)
import Control.Error (EitherT,eitherT)
import Control.Monad (replicateM,return,mapM_,(>>=),forever)
import Control.Monad.IO.Class (liftIO)
import Data.Function (($),(.))
import Data.List (concat,(++))
import Data.Maybe (Maybe,maybe,fromMaybe)
import Data.Time (getCurrentTime)
import System.IO (IO,FilePath,putStrLn)
import System.Random (StdGen,getStdGen)
import Text.Printf (printf)
import Text.Show (Show,show)

--------------------------------------------------------------------------------
-- Define configuration data types
--------------------------------------------------------------------------------

data HubbubConfig = HubbubConfig {
  subscriptionThreads::Int
  , publicationThreads::Int
  , distributionThreads::Int
  , serverUrl::ServerUrl
  , defaultLeaseTimeout::LeaseSeconds
  }

data HubbubAcidConfig = HubbubAcidConfig {
  acidFilePath :: Maybe FilePath
  }

data HubbubSqLiteConfig = HubbubSqLiteConfig {
  sqLiteFilePath :: Maybe FilePath
  }

-- Plus all the state our code needs to run

data HubbubEnv = HubbubEnv {
  _subscriptionThreadIds::[ThreadId]
  , _publicationThreadIds::[ThreadId]
  , _distributionThreadIds::[ThreadId]
  , _expirationThreadId::ThreadId
  , subscriptionQueue::TQueue SubscriptionEvent
  , publicationQueue::TQueue PublicationEvent
  , _distributionQueue::TQueue DistributionEvent
  , subscriptionDbApi::SubscriptionDbApi
  , envDefaultLeaseTimeout::LeaseSeconds
  }

--------------------------------------------------------------------------------
-- Client callable function to initialise either acidstate or sqlite
--------------------------------------------------------------------------------

initializeHubbubAcid :: HubbubConfig -> HubbubAcidConfig -> IO HubbubEnv
initializeHubbubAcid conf acidConf =
  acidDbApi (acidFilePath acidConf) >>= initializeHubbub conf

initializeHubbubSqLite :: HubbubConfig -> HubbubSqLiteConfig -> IO HubbubEnv
initializeHubbubSqLite conf sqLiteConf =
  sqLiteDbApi (sqLiteFilePath sqLiteConf) >>= initializeHubbub conf

--------------------------------------------------------------------------------
-- And the functions that the client calls (shutdown,publish,subscribe,list)
--------------------------------------------------------------------------------

shutdownHubbub :: HubbubEnv -> IO ()
shutdownHubbub = shutdownDb . subscriptionDbApi

subscribe ::
  HubbubEnv ->
  Topic ->
  Callback ->
  Maybe LeaseSeconds ->
  Maybe Secret ->
  Maybe From ->
  IO ()
subscribe env t cb lsm s f = atomically $ Q.subscribe (subscriptionQueue env) ev
  where
    ev = Subscribe t cb ls firstAttempt s f
    ls = fromMaybe (envDefaultLeaseTimeout env) lsm

unsubscribe :: HubbubEnv -> Topic -> Callback -> IO ()
unsubscribe env t cb = atomically $ Q.subscribe (subscriptionQueue env) ev
  where ev = Unsubscribe t cb firstAttempt

publish :: HubbubEnv -> Topic -> IO ()
publish env t =
  atomically . Q.publish (publicationQueue env) $ PublicationEvent t firstAttempt

listSubscriptions ::
  HubbubEnv ->
  EitherT SomeException IO [(Topic,Callback,Subscription)]
listSubscriptions = getAllSubscriptions . subscriptionDbApi

--------------------------------------------------------------------------------
--- Private Stuff Below
--------------------------------------------------------------------------------

initializeHubbub :: HubbubConfig -> SubscriptionDbApi -> IO HubbubEnv
initializeHubbub c dbApi = do
  rng <- getStdGen
  sQ  <- atomically emptySubscriptionQueue
  pQ  <- atomically emptyPublicationQueue
  dQ  <- atomically emptyDistributionQueue
  sTs <- startNThreads (subscriptionThreads c) (subscriptionThread rng dbApi sQ)
  pTs <- startNThreads (publicationThreads c)  (publicationThread dbApi dQ pQ)
  dTs <- startNThreads (distributionThreads c) (distributionThread sUrl dQ)
  eT  <- expirationThread dbApi lto
  return $ HubbubEnv sTs pTs dTs eT sQ pQ dQ dbApi lto
  where
    sUrl = serverUrl c
    lto  = defaultLeaseTimeout c

startNThreads :: Int -> IO () -> IO [ThreadId]
startNThreads n = replicateM n . forkIO

subscriptionThread ::
  StdGen ->
  SubscriptionDbApi ->
  TQueue SubscriptionEvent ->
  IO ()
subscriptionThread rng api = subscriptionLoop handleEvent logError
  where
    handleEvent = doSubscriptionEvent rng api

publicationThread ::
  SubscriptionDbApi ->
  TQueue DistributionEvent ->
  TQueue PublicationEvent ->
  IO ()
publicationThread api distQ = publicationLoop handleEvent logError
  where
    handleEvent ev = do
      distEvs <- doPublicationEvent api ev
      liftIO $ atomically $ mapM_ (Q.distribute distQ) distEvs

distributionThread :: ServerUrl -> TQueue DistributionEvent -> IO ()
distributionThread surl = distributionLoop handleEvent logError
  where
    handleEvent = doDistributionEvent surl

expirationThread :: SubscriptionDbApi -> LeaseSeconds -> IO ThreadId
expirationThread dbApi (LeaseSeconds s) = forkIO . forever $ do
  threadDelay ((fromIntegral s * 1000 * 1000) `div` 2)
  time <- getCurrentTime
  eitherT
    (putStrLn . ("error expiring subscriptions: " ++) . show)
    return
    (expireSubscriptions dbApi time)

logError :: (Show a,Show e) => a -> e -> Maybe RetryDelay -> IO ()
logError event err retryDelay = putStrLn $ concat
           [ "Got an error processing event '"
           , show event
           , "'. Error was '"
           , show err
           , "'. "
           , retryMessage
           ]
  where
    retryMessage = maybe retryDiscarded retryScheduled retryDelay
    retryScheduled rt = concat [
      " It will be retried in "
      , printf "%.3f" . retryDelaySeconds $ rt
      , " seconds"
      ]
    retryDiscarded = " It has failed too many times and has been discarded."

firstAttempt :: AttemptCount
firstAttempt = AttemptCount 0

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


text:
package org.apache.skywalking.oap.server.receiver.zipkin.analysis.transform;

import com.google.common.base.Strings;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;
import org.apache.skywalking.apm.network.language.agent.v3.Log;
import org.apache.skywalking.apm.network.language.agent.v3.RefType;
import org.apache.skywalking.apm.network.language.agent.v3.SegmentObject;
import org.apache.skywalking.apm.network.language.agent.v3.SegmentReference;
import org.apache.skywalking.apm.network.language.agent.v3.SpanObject;
import org.apache.skywalking.apm.network.language.agent.v3.SpanType;
import org.apache.skywalking.apm.util.StringUtil;
import org.apache.skywalking.oap.server.receiver.zipkin.analysis.data.SkyWalkingTrace;
import zipkin2.Endpoint;
import zipkin2.Span;

public class SegmentBuilder {
    private Context context;
    private LinkedList<Segment> segments;
    private Map<String, ClientSideSpan> clientPartSpan;

    private SegmentBuilder() {
        segments = new LinkedList<>();
        context = new Context();
        clientPartSpan = new HashMap<>();
    }

    public static SkyWalkingTrace build(List<Span> traceSpans) throws Exception {
        SegmentBuilder builder = new SegmentBuilder();
        // This map groups the spans by their parent id, in order to assist to build tree.
        // key: parentId
        // value: span
        Map<String, List<Span>> childSpanMap = new HashMap<>();
        AtomicReference<Span> root = new AtomicReference<>();
        traceSpans.forEach(span -> {
            if (span.parentId() == null) {
                root.set(span);
            }
            List<Span> spanList = childSpanMap.get(span.parentId());
            if (spanList == null) {
                spanList = new LinkedList<>();
                spanList.add(span);
                childSpanMap.put(span.parentId(), spanList);
            } else {
                spanList.add(span);
            }
        });

        Span rootSpan = root.get();
        long timestamp = 0;
        if (rootSpan != null) {
            String applicationCode = rootSpan.localServiceName();
            // If root span doesn't include applicationCode, a.k.a local service name,
            // Segment can't be built
            // Ignore the whole trace.
            // :P Hope anyone could provide better solution.
            // Wu Sheng.
            if (!Strings.isNullOrEmpty(applicationCode)) {
                timestamp = rootSpan.timestampAsLong();
                builder.context.addService(applicationCode);

                SpanObject.Builder rootSpanBuilder = builder.initSpan(null, null, rootSpan, true);
                builder.context.currentSegment().addSpan(rootSpanBuilder);
                builder.scanSpansFromRoot(rootSpanBuilder, rootSpan, childSpanMap);

                builder.segments.add(builder.context.removeApp());
            }
        }

        List<SegmentObject.Builder> segmentBuilders = new LinkedList<>();
        // microseconds -> million seconds
        long finalTimestamp = timestamp / 1000;
        builder.segments.forEach(segment -> {
            SegmentObject.Builder traceSegmentBuilder = segment.freeze();
            segmentBuilders.add(traceSegmentBuilder);
        });
        return new SkyWalkingTrace(segmentBuilders);
    }

    private void scanSpansFromRoot(SpanObject.Builder parentSegmentSpan, Span parent,
                                   Map<String, List<Span>> childSpanMap) throws Exception {
        String parentId = parent.id();
        // get child spans by parent span id
        List<Span> spanList = childSpanMap.get(parentId);
        if (spanList == null) {
            return;
        }
        for (Span childSpan : spanList) {
            String localServiceName = childSpan.localServiceName();
            boolean isNewApp = false;
            if (StringUtil.isNotEmpty(localServiceName)) {
                if (context.isServiceChanged(localServiceName)) {
                    isNewApp = true;
                }
            }

            try {
                if (isNewApp) {
                    context.addService(localServiceName);
                }
                SpanObject.Builder childSpanBuilder = initSpan(parentSegmentSpan, parent, childSpan, isNewApp);

                context.currentSegment().addSpan(childSpanBuilder);
                scanSpansFromRoot(childSpanBuilder, childSpan, childSpanMap);

            } finally {
                if (isNewApp) {
                    segments.add(context.removeApp());
                }
            }
        }
    }

    private SpanObject.Builder initSpan(SpanObject.Builder parentSegmentSpan, Span parentSpan, Span span,
                                        boolean isSegmentRoot) {
        SpanObject.Builder spanBuilder = SpanObject.newBuilder();
        spanBuilder.setSpanId(context.currentIDs().nextSpanId());
        if (isSegmentRoot) {
            // spanId = -1, means no parent span
            // spanId is considered unique, and from a positive sequence in each segment.
            spanBuilder.setParentSpanId(-1);
        }
        if (!isSegmentRoot && parentSegmentSpan != null) {
            spanBuilder.setParentSpanId(parentSegmentSpan.getSpanId());
        }
        Span.Kind kind = span.kind();
        String opName = Strings.isNullOrEmpty(span.name()) ? "-" : span.name();
        spanBuilder.setOperationName(opName);
        ClientSideSpan clientSideSpan;
        switch (kind) {
            case CLIENT:
                spanBuilder.setSpanType(SpanType.Exit);
                String peer = getPeer(parentSpan, span);
                if (peer != null) {
                    spanBuilder.setPeer(peer);
                }
                clientSideSpan = new ClientSideSpan(span, spanBuilder);
                clientPartSpan.put(span.id(), clientSideSpan);
                break;
            case SERVER:
                spanBuilder.setSpanType(SpanType.Entry);
                this.buildRef(spanBuilder, span, parentSegmentSpan, parentSpan);
                break;
            case CONSUMER:
                spanBuilder.setSpanType(SpanType.Entry);
                this.buildRef(spanBuilder, span, parentSegmentSpan, parentSpan);
                break;
            case PRODUCER:
                spanBuilder.setSpanType(SpanType.Exit);
                peer = getPeer(parentSpan, span);
                if (peer != null) {
                    spanBuilder.setPeer(peer);
                }
                clientSideSpan = new ClientSideSpan(span, spanBuilder);
                clientPartSpan.put(span.id(), clientSideSpan);
                break;
            default:
                spanBuilder.setSpanType(SpanType.Local);
        }
        // microseconds in Zipkin -> milliseconds in SkyWalking
        long startTime = span.timestamp() / 1000;
        // Some implement of zipkin client not include duration field in its report
        // package when duration's value be 0ms, Causing a null pointer exception here.
        Long durationObj = span.duration();
        long duration = (durationObj == null) ? 0 : durationObj.longValue() / 1000;
        spanBuilder.setStartTime(startTime);
        spanBuilder.setEndTime(startTime + duration);

        span.tags()
            .forEach((tagKey, tagValue) -> spanBuilder.addTags(KeyStringValuePair.newBuilder()
                                                                                .setKey(tagKey)
                                                                                .setValue(tagValue)
                                                                                .build()));

        span.annotations()
            .forEach(annotation -> spanBuilder.addLogs(Log.newBuilder()
                                                          .setTime(annotation.timestamp() / 1000)
                                                          .addData(KeyStringValuePair.newBuilder()
                                                                                .setKey("zipkin.annotation")
                                                                                .setValue(annotation.value())
                                                                                .build())));

        return spanBuilder;
    }

    private void buildRef(SpanObject.Builder spanBuilder, Span span, SpanObject.Builder parentSegmentSpan,
                          Span parentSpan) {
        Segment parentSegment = context.parentSegment();
        if (parentSegment == null) {
            return;
        }
        Segment rootSegment = context.rootSegment();
        if (rootSegment == null) {
            return;
        }

        if (span.shared() != null && span.shared()) {
            // using same span id in client and server for RPC
            // SkyWalking will build both sides of span
            ClientSideSpan clientSideSpan = clientPartSpan.get(span.id());
            if (clientSideSpan != null) {
                // For the root span, there may be no ref, because of no parent.
                parentSegmentSpan = clientSideSpan.getBuilder();
                parentSpan = clientSideSpan.getSpan();
            }
        }

        String peer = getPeer(parentSpan, span);
        if (StringUtil.isEmpty(peer)) {
            //The IP is the most important for building the ref at both sides.
            return;
        }

        SegmentReference.Builder refBuilder = SegmentReference.newBuilder();

        // parent ref info
        refBuilder.setNetworkAddressUsedAtPeer(peer);
        parentSegmentSpan.setPeer(refBuilder.getNetworkAddressUsedAtPeer());
        refBuilder.setParentServiceInstance(parentSegment.builder().getServiceInstance());
        refBuilder.setParentSpanId(parentSegmentSpan.getSpanId());
        refBuilder.setParentTraceSegmentId(parentSegment.builder().getTraceSegmentId());
        refBuilder.setParentEndpoint(parentSegment.getEntryEndpointName());
        refBuilder.setRefType(RefType.CrossProcess);

        spanBuilder.addRefs(refBuilder);
    }

    private String getPeer(Span parentSpan, Span childSpan) {
        String peer;

        Endpoint serverEndpoint = childSpan == null ? null : childSpan.localEndpoint();
        peer = endpoint2Peer(serverEndpoint);

        if (peer == null) {
            Endpoint clientEndpoint = parentSpan == null ? null : parentSpan.remoteEndpoint();
            peer = endpoint2Peer(clientEndpoint);
        }

        return peer;
    }

    private String endpoint2Peer(Endpoint endpoint) {
        String ip = null;
        Integer port = 0;

        if (endpoint != null) {
            if (!Strings.isNullOrEmpty(endpoint.ipv4())) {
                ip = endpoint.ipv4();
                port = endpoint.port();
            } else if (!Strings.isNullOrEmpty(endpoint.ipv6())) {
                ip = endpoint.ipv6();
                port = endpoint.port();
            }
        }
        if (ip == null) {
            return null;
        } else {
            return port == null || port == 0 ? ip : ip + ":" + port;
        }
    }

    /**
     * Context holds the values in build process.
     */
    private class Context {
        private LinkedList<Segment> segmentsStack = new LinkedList<>();

        private boolean isServiceChanged(String service) {
            return !Strings.isNullOrEmpty(service) && !service.equals(currentIDs().service);
        }

        private Segment addService(String serviceCode) throws Exception {
            Segment segment = new Segment(serviceCode, serviceCode);
            segmentsStack.add(segment);
            return segment;
        }

        private IDCollection currentIDs() {
            return segmentsStack.getLast().ids;
        }

        private Segment currentSegment() {
            return segmentsStack.getLast();
        }

        private Segment parentSegment() {
            if (segmentsStack.size() < 2) {
                return null;
            } else {
                return segmentsStack.get(segmentsStack.size() - 2);
            }

        }

        private Segment rootSegment() {
            if (segmentsStack.size() < 2) {
                return null;
            } else {
                return segmentsStack.getFirst();
            }
        }

        private Segment removeApp() {
            return segmentsStack.removeLast();
        }

        private int waitForExchange(Callable<Integer> callable, int retry) throws Exception {
            for (int i = 0; i < retry; i++) {
                Integer id = callable.call();
                if (id == 0) {
                    Thread.sleep(1000L);
                } else {
                    return id;
                }
            }
            throw new TimeoutException("ID exchange costs more than expected.");
        }
    }

    private class Segment {
        private SegmentObject.Builder segmentBuilder;
        private IDCollection ids;
        private String entryEndpointName = null;
        private List<SpanObject.Builder> spans;
        private long endTime = 0;

        private Segment(String service, String serviceInstance) {
            ids = new IDCollection(service, serviceInstance);
            spans = new LinkedList<>();
            segmentBuilder = SegmentObject.newBuilder();
            segmentBuilder.setService(service);
            segmentBuilder.setServiceInstance(serviceInstance);
            segmentBuilder.setTraceSegmentId(UUID.randomUUID().toString().replaceAll("-", ""));
        }

        private SegmentObject.Builder builder() {
            return segmentBuilder;
        }

        private void addSpan(SpanObject.Builder spanBuilder) {
            String operationName = spanBuilder.getOperationName();
            if (StringUtil.isEmpty(entryEndpointName) && !Strings.isNullOrEmpty(operationName)) {
                if (SpanType.Entry.equals(spanBuilder.getSpanType())) {
                    if (!Strings.isNullOrEmpty(operationName)) {
                        entryEndpointName = operationName;
                    }
                }
            }

            // init by root span
            if (spanBuilder.getSpanId() == 1 && StringUtil.isEmpty(entryEndpointName)) {
                if (!Strings.isNullOrEmpty(operationName)) {
                    entryEndpointName = operationName;
                }
            }

            spans.add(spanBuilder);
            if (spanBuilder.getEndTime() > endTime) {
                endTime = spanBuilder.getEndTime();
            }
        }

        public String getEntryEndpointName() {
            return entryEndpointName;
        }

        private IDCollection ids() {
            return ids;
        }

        public SegmentObject.Builder freeze() {
            for (SpanObject.Builder span : spans) {
                segmentBuilder.addSpans(span);
            }
            return segmentBuilder;
        }
    }

    private class IDCollection {
        private String service;
        private String instanceName;
        private int spanIdSeq;

        private IDCollection(String service, String instanceName) {
            this.service = service;
            this.instanceName = instanceName;
            this.spanIdSeq = 0;
        }

        private int nextSpanId() {
            return spanIdSeq++;
        }
    }

    private class ClientSideSpan {
        private Span span;
        private SpanObject.Builder builder;

        public ClientSideSpan(Span span, SpanObject.Builder builder) {
            this.span = span;
            this.builder = builder;
        }

        public Span getSpan() {
            return span;
        }

        public SpanObject.Builder getBuilder() {
            return builder;
        }
    }
}


text:
'use strict';

module.exports = {
  // NODE_ENV is set to test by jest and by smokehouse CLI runner
  // CI as a catchall for everything we do in GitHub Actions
  isUnderTest: !!process.env.CI || process.env.NODE_ENV === 'test',
};


text:
var _self,
    db = ripple('db'),
    utils = ripple('utils'),
    platform = ripple('platform'),
    event = ripple('event'),
    _devices = {};

event.on("HardwareKeyDefault", function (key) {
    if (key === 0 || key === "0") { //back button key
        ripple('emulatorBridge').window().history.back();
    }
});

function _getRequestedDevice() {
    //format is platform-version-device
    return (utils.queryString().enableripple || "").split('-')[2];
}

_self = module.exports = {
    initialize: function () {
        _devices = [
            "AcerA500",
            "Bold9700",
            "Bold9900",
            "Q10",
            "Z10",
            "Curve9300",
            "Curve9350-9360-9370",
            "FWVGA",
            "G1",
            "HPPre3",
            "HPVeer",
            "HVGA",
            "iPad",
            "iPad3",
            "iPhone3",
            "iPhone4",
            "iPhone5",
            "Legend",
            "Nexus",
            "NexusS",
            "NexusGalaxy",
            "Nexus7",
            "Nexus4",
            "NokiaN8",
            "NokiaN97",
            "PalmPre",
            "PalmPre2",
            "Pearl9100",
            "Playbook",
            "QVGA",
            "Style9670",
            "Tattoo",
            "Torch9800",
            "Torch9810",
            "Torch9860-9850",
            "Wave",
            "WQVGA",
            "WVGA"
        ].reduce(function (hash, deviceID) {
            hash[deviceID.toLowerCase()] = ripple('devices/' + deviceID);
            return hash;
        }, {});

        var current = this.getCurrentDevice();
        ripple('bus').send('userAgent', current.userAgent);
    },

    getCurrentDevice: function () {
        var deviceId = _getRequestedDevice() || db.retrieve("device-key"),
            device = this.getDevice(deviceId),
            platformId = platform.current().id,
            does = function (device) {
                return {
                    include: function (platformId) {
                        return device.platforms.some(function (id) {
                            return platformId === id;
                        });
                    }
                };
            };

        if (!device || !does(device).include(platformId)) {
            deviceId = utils.reduce(_devices, function (current, device, id) {
                return does(device).include(platformId) ? id : current;
            });

            device = this.getDevice(deviceId);
        }

        return device;
    },

    getDevice: function (deviceId) {
        return utils.copy(_devices[(deviceId || "").toLowerCase()]);
    },

    getDevicesForPlatform: function (platformId) {
        return utils.filter(_devices, function (device) {
            return device.platforms.indexOf(platformId) > -1;
        });
    }
};


text:
import React from 'react';
import { mount, shallow } from 'enzyme';
import {expect} from 'chai';

import Avatar from '../src/avatar';

Feature('Avatar','should show a picture and an email', ()=>{
  Scenario('user visits page for the first time',()=>{

      const wrapper = mount(<Avatar/>);

      Given('should have a temporary picture',()=>{
      	expect(wrapper.find('img')).to.exist
      })
      And('should have email and foto properties',()=>{

        wrapper.setProps({ email:''})
      	expect(wrapper.props().email).to.exist
        wrapper.setProps({ src:''})
      	expect(wrapper.props().src).to.exist
      })
  })
})


text:
namespace Orchard.Themes.Preview {
    public interface IPreviewTheme : IDependency {
        string GetPreviewTheme();
        void SetPreviewTheme(string themeName);
    }
}


text:
package fi.csc.microarray.messaging.message;

import java.awt.Color;
import java.util.LinkedList;
import java.util.List;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import fi.csc.microarray.util.XmlUtil;

/**
 * Message for sending module information and tool
 * descriptions.
 *
 * @author naktinis
 *
 */
public class ModuleDescriptionMessage extends ChipsterMessage {

    private final static String KEY_MODULE = "module";
    private final static String KEY_MODULE_NAME = "module-name";

    public Document moduleXml;
    private String moduleName;
    private List<Category> categories = new LinkedList<Category>();

    /**
     * Empty constructor (needed for MessageListenerWrap.onMessage)
     */
    public ModuleDescriptionMessage() { }

    public ModuleDescriptionMessage(String moduleName) {
    	try {
    		// Start constructing the XML
    		moduleXml = XmlUtil.newDocument();
    		moduleXml.appendChild(moduleXml.createElement("module"));

    		// Set module's name
    		setModuleName(moduleName);
    		getFirstModule().setAttribute("name", moduleName);

    	} catch (ParserConfigurationException e) {
    		throw new RuntimeException(e); // should never happen
    	}
    }

    private void setModuleName(String moduleName) {
        this.moduleName = moduleName;
    }

    public String getModuleName() {
        return this.moduleName;
    }

    public void addConfString(String configuration) {
        // TODO ADD to XML
    }

    private Element getFirstModule() {
        return (Element)moduleXml.getElementsByTagName("module").item(0);
    }

    /**
     * Store a Category object in the inner XML.
     *
     * @param category
     */
    public void addCategory(Category category) {
        Element categoryElement = moduleXml.createElement("category");
        categoryElement.setAttribute("name", category.getName());
        String colorString = Integer.toHexString(category.getColor().getRGB());
        colorString = "#" + colorString.substring(2, colorString.length());
        categoryElement.setAttribute("color", colorString);
        categoryElement.setAttribute("hidden", category.isHidden().toString());

        for (Tool tool : category.getTools()) {
            Element toolElement = moduleXml.createElement("tool");
            toolElement.setAttribute("helpURL", tool.getHelpURL());
            toolElement.setTextContent(tool.getDescription());
            categoryElement.appendChild(toolElement);
        }

        getFirstModule().appendChild(categoryElement);
    }

    /**
     * @return all categories contained in the inner XML.
     */
    public List<Category> getCategories() {
        NodeList categoryList = getFirstModule().getElementsByTagName("category");
        for (int i=0; i<categoryList.getLength(); i++) {
            Element categoryElement = (Element) categoryList.item(i);
            Category category = new Category(categoryElement.getAttribute("name"),
                    categoryElement.getAttribute("color"),
                    Boolean.valueOf(categoryElement.getAttribute("hidden")));
            NodeList toolList = categoryElement.getElementsByTagName("tool");
            for (int j=0; j<toolList.getLength(); j++) {
                Element toolElement = (Element) toolList.item(j);
                category.addTool(toolElement.getTextContent(),
                        toolElement.getAttribute("helpURL"));
            }
            categories.add(category);
        }
        return categories;
    }

    @Override
    public void unmarshal(MapMessage from) throws JMSException {
        super.unmarshal(from);
        this.setModuleName(from.getStringProperty(KEY_MODULE_NAME));
        this.moduleXml = XmlUtil.stringToXML(from.getString(KEY_MODULE));
    }

    @Override
    public void marshal(MapMessage to) throws JMSException {
        super.marshal(to);
        to.setStringProperty(KEY_MODULE_NAME, this.getModuleName());
        to.setString(KEY_MODULE, XmlUtil.xmlToString(moduleXml));
    }

    /**
     * Tool category. Contains several related tools.
     */
    public static class Category {
        private String name;
        private List<Tool> tools = new LinkedList<Tool>();
        private Color color;
        private Boolean hidden;

        /**
         * @param name - name for this category.
         * @param color - String representing hexidecimal RGB value (e.g. "FF1122")
         */
        public Category(String name, String color, Boolean hidden) {
            this.name = name;
            this.color = Color.decode(color);
            this.hidden = hidden;
        }

        public String getName() {
            return name;
        }

        public Color getColor() {
            return color;
        }

        public Boolean isHidden() {
            return hidden;
        }

        public void addTool(String description, String helpURL) {
            tools.add(new Tool(description, helpURL));
        }

        public List<Tool> getTools() {
            return tools;
        }
    }

    /**
     * Single analysis tool.
     */
    public static class Tool {
        private String description;
        private String helpURL;

        public Tool(String description, String helpURL) {
            this.description = description;
            this.helpURL = helpURL;
        }

        public String getHelpURL() {
            return helpURL;
        }

        public String getDescription() {
            return description;
        }
    }
}


text:
package hr.fer.zemris.jcms.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import hr.fer.zemris.jcms.JCMSSettings;
import hr.fer.zemris.jcms.dao.DAOHelper;
import hr.fer.zemris.jcms.dao.DAOHelperFactory;
import hr.fer.zemris.jcms.dao.DatabaseOperation;
import hr.fer.zemris.jcms.dao.PersistenceUtil;
import hr.fer.zemris.jcms.model.RepositoryCategory;
import hr.fer.zemris.jcms.model.RepositoryCourse;
import hr.fer.zemris.jcms.model.RepositoryFile;
import hr.fer.zemris.jcms.model.RepositoryFilePage;
import hr.fer.zemris.jcms.model.RepositoryFilePageComment;
import hr.fer.zemris.jcms.security.JCMSSecurityManagerFactory;
import hr.fer.zemris.jcms.web.actions.data.RepositoryData;
import hr.fer.zemris.jcms.web.actions.data.RepositoryFilePageData;
import hr.fer.zemris.jcms.web.actions.data.support.AbstractActionData;
import hr.fer.zemris.jcms.web.actions.data.support.IMessageLogger;

import javax.persistence.EntityManager;

	public class RepositoryFilePageService {

		public static void showFilePage(final RepositoryFilePageData data, final Long userID,
				final String courseInstanceID, final Long fileID, final Long pageNumber) {
			PersistenceUtil.executeSingleDatabaseOperation(new DatabaseOperation<Void>() {
				@Override
				public Void executeOperation(EntityManager em) {
					if(!BasicBrowsing.fillCurrentUser(em, data, userID, "Error.noPermission", AbstractActionData.RESULT_FATAL)) return null;
					if(!BasicBrowsing.fillCourseInstance(em, data, courseInstanceID, "Error.invalidParameters", AbstractActionData.RESULT_FATAL)) return null;
					JCMSSecurityManagerFactory.getManager().init(data.getCurrentUser(), em);
					if(!JCMSSecurityManagerFactory.getManager().canUserAccessCourse(data.getCourseInstance())) {
						data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission"));
						data.setResult(AbstractActionData.RESULT_FATAL);
						return null;
					}

					//da li je to administrator
					data.setAdmin(JCMSSecurityManagerFactory.getManager().canPerformCourseAdministration(data.getCourseInstance()));

					//da li je to nastavno osoblje
					DAOHelper dh = DAOHelperFactory.getDAOHelper();
					data.setStaffMember(dh.getCourseInstanceDAO().isCourseStaffMember(em, data.getCourseInstance(), data.getCurrentUser()));

					RepositoryFile repFile = dh.getRepositoryFileDAO().getFile(em, fileID);

					if(repFile == null){

						data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.invalidParameters"));
						data.setResult(AbstractActionData.RESULT_FATAL);
						return null;
					}

					//provjeravamo da li postoje već izgenerirane sličice, ako ne, generiraj ih.
					//Ako se dogodi pogreška u generiranju slika, prikaži stranicu ali bez slike

					if(!imagesExist(repFile)){
						if(!imagesCreate(repFile, dh, em)){
							data.setResult(AbstractActionData.RESULT_NONFATAL_ERROR);
							return null;
						}
					}

					data.setFileID(repFile.getId());

					Long filePageID = null;

					for (RepositoryFilePage repositoryFilePage : repFile.getFilePages()) {
						if(repositoryFilePage.getPage() == pageNumber){
							filePageID = repositoryFilePage.getId();
							break;
						}
					}

					RepositoryFilePage filePage = dh.getRepositoryFilePageDAO().getFilePage(em, filePageID);
					//komentari na pripadajućoj stranici
					List<RepositoryFilePageComment> comments = new ArrayList<RepositoryFilePageComment>();

					data.setComments(comments);

					for (RepositoryFilePageComment pageComments : filePage.getComments()) {
						comments.add(pageComments);
					}

					data.setResult(AbstractActionData.RESULT_SUCCESS);
					return null;
				}

			});

		}

		private static boolean imagesExist(RepositoryFile repFile) {

			if(repFile.getFilePages().isEmpty()){
				return false;
			}
			return true;
		}

		protected static boolean imagesCreate(RepositoryFile repFile, DAOHelper dh, EntityManager em) {

			//RepositoryFilePage filePage = new RepositoryFilePage();
			//filePage.setRepositoryFile(repFile);

			RepositoryFilePage filePageAdd = new RepositoryFilePage();
			filePageAdd.setPage(0);
			filePageAdd.setRepositoryFile(repFile);

			repFile.getFilePages().add(filePageAdd);

			dh.getRepositoryFilePageDAO().save(em, filePageAdd);

			return true;
		}

		public static void setRepositoryFilePageNewComment(
				final RepositoryFilePageData data, final Long userID,
				 final String courseInstanceID, final String comment,
				  final Long pageNumber, final Long fileID,
				  	final int commentType ){

			PersistenceUtil.executeSingleDatabaseOperation(new DatabaseOperation<Void>() {
				public Void executeOperation(EntityManager em) {

					if(!BasicBrowsing.fillCurrentUser(em, data, userID, "Error.noPermission", AbstractActionData.RESULT_FATAL)) return null;
					if(!BasicBrowsing.fillCourseInstance(em, data, courseInstanceID, "Error.invalidParameters", AbstractActionData.RESULT_FATAL)) return null;
					JCMSSecurityManagerFactory.getManager().init(data.getCurrentUser(), em);
					if(!JCMSSecurityManagerFactory.getManager().canUserAccessCourse(data.getCourseInstance())|| (!JCMSSecurityManagerFactory.getManager().canUserManageRepository(data.getCourseInstance()))) {
						data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission"));
						data.setResult(AbstractActionData.RESULT_FATAL);
						return null;
					}

					DAOHelper dh = DAOHelperFactory.getDAOHelper();

					RepositoryFile repFile = dh.getRepositoryFileDAO().getFile(em, fileID);
					List<RepositoryFilePage> filePages = repFile.getFilePages();

					//String h = Long.toString(pageNumber);
					//int a = Integer.getInteger(h);

					//RepositoryFilePage filePage = dh.getRepositoryFilePageDAO().getFilePage(em, fileID);

					RepositoryFilePage filePage = null;

					for (RepositoryFilePage repositoryFilePage : filePages) {
						if(repositoryFilePage.getPage() == pageNumber){
							filePage = repositoryFilePage;
							break;
						}
					}

					if(filePage == null){
						data.getMessageLogger().addErrorMessage(data.getMessageLogger().getText("Error.noPermission"));
						data.setResult(AbstractActionData.RESULT_FATAL);
						return null;
					}

					RepositoryFilePageComment pageComment = new RepositoryFilePageComment();
					pageComment.setComment(comment);
					pageComment.setCommentType(commentType);
					pageComment.setDate(new Date());
					pageComment.setRepositoryFilePage(filePage);
					pageComment.setUser(data.getCurrentUser());

					filePage.getComments().add(pageComment);

					dh.getRepositoryFilePageDAO().save(em, pageComment);

					data.setResult(AbstractActionData.RESULT_SUCCESS);
					return null;
				}//kraj executeOperation
			});
		} //kraj metode

}//kraj razreda


text:
void showUsage();

int parseInputArgs(int argc, char *argv[]);

void processConfig()   {P_CnfgFile.processFile(P_LogData);}

void processInitfile() {P_InitFile.processFile(P_LogData);}

void processSpydef()   {P_SpydFile.processFile(P_LogData);}

void processScandef()  {P_ScndFile.processFile(P_LogData);}

#endif  // IFSCRUBBER_H


text:
using System;
using AutoSharp.Utils;
using LeagueSharp;
using LeagueSharp.Common;

namespace AutoSharp.Plugins
{
    public class Fiora : PluginBase
    {
        public Fiora()
        {
            Q = new Spell(SpellSlot.Q, 600f);
            W = new Spell(SpellSlot.W);
            E = new Spell(SpellSlot.E);
            R = new Spell(SpellSlot.R, 350f);
        }

        public override void OnUpdate(EventArgs args)
        {
            if (ComboMode)
            {
                if (Q.CastCheck(Target, "ComboQ"))
                {
                    Q.Cast(Target);
                    W.Cast();
                    E.Cast();
                }
                if (R.IsReady() && R.GetDamage(Target) > Target.Health)
                {
                    R.Cast(Target);
                }
            }
        }

        public override void ComboMenu(Menu config)
        {
            config.AddBool("ComboQ", "Use Q", true);
            config.AddBool("ComboW", "Use W", true);
            config.AddBool("ComboE", "Use E", true);
            config.AddBool("ComboR", "Use R", true);
        }
    }
}


text:
Backends
--------

rmoq supports custom storage backends by passing an instance into the backend parameter of
:func:`rmoq.activate` method. A storage backend must inherit from :class:`rmoq.RmoqStorageBackend`
and implement the :func:`.get` and :func:`.put` methods.

.. autoclass:: rmoq.RmoqStorageBackend
    :members:

.. autoclass:: rmoq.FileStorageBackend
    :members:
    :undoc-members:
    :show-inheritance:

.. autoclass:: rmoq.MemcachedStorageBackend
    :members:
    :undoc-members:
    :show-inheritance:


text:
var __extends = this.__extends || function (d, b) {
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Foo;
(function (Foo) {
    var Object = (function () {
        function Object() { }
        return Object;
    })();
    Foo.Object = Object;
})(Foo || (Foo = {}));
var Bar = (function (_super) {
    __extends(Bar, _super);
    function Bar() {
        _super.call(this);
    }
    return Bar;
})(Foo.Object);
var Baz = (function (_super) {
    __extends(Baz, _super);
    function Baz() {
        _super.call(this);
    }
    return Baz;
})(Object);


text:
using System;
using Microsoft.Extensions.Logging;
using WorkflowCore.Interface;
using WorkflowCore.Providers.Redis.Services;
using WorkflowCore.UnitTests;
using Xunit;

namespace WorkflowCore.Tests.Redis
{
    [Collection("Redis collection")]
    public class RedisPersistenceProviderFixture : BasePersistenceFixture
    {
        RedisDockerSetup _dockerSetup;
        private IPersistenceProvider _subject;

        public RedisPersistenceProviderFixture(RedisDockerSetup dockerSetup)
        {
            _dockerSetup = dockerSetup;
        }

        protected override IPersistenceProvider Subject
        {
            get
            {
                if (_subject == null)
                {
                    var client = new RedisPersistenceProvider(RedisDockerSetup.ConnectionString, "test", false, new LoggerFactory());
                    client.EnsureStoreExists();
                    _subject = client;
                }
                return _subject;
            }
        }
    }
}