text:
#include <numeric>
#include <boost/lexical_cast.hpp>
#include "cj/representation/term.hh"
#include "cj/utils/string.hh"

namespace cj {

// Private visitors:

struct term_expr_complexity_vstr {
  auto operator()(value_ptr<function> const& f) const -> pair<uint32_t, uint32_t> {
    auto res = pair<uint32_t, uint32_t>{1, 0};
    for (auto const& t : *f) {
      auto const c = std::visit(term_expr_complexity_vstr{}, t);
      res.first = res.first + c.first;
      res.second = res.second + c.second;
    };
    res.second += res.first;
    return res;
  }

  template<typename T>
  auto operator()(T const&) const -> pair<uint32_t, uint32_t> {
    return pair<uint32_t, uint32_t>{1, 1};
  }
};

struct term_json_fmt_vstr {
  auto operator()(int64_t i) const -> string {
    return string{"{\"term_node\":\"integer\",\"value\":"} + std::to_string(i) + "}";
  }

  auto operator()(variable const& v) const -> string {
    return string{"{\"term_node\":\"variable\",\"value\":\""} + v.name() + "\"}";
  }

  auto operator()(double r) const -> string {
    return string{"{\"term_node\":\"real\",\"value\":"} + std::to_string(r) + "}";
  }

  auto operator()(std::complex<double> const& c) const -> string {
    return string{"{\"term_node\":\"complex\",\"value\":\""} + boost::lexical_cast<string>(c) + "i\"}";
  }

  auto operator()(string const& s) const -> string {
    return string{"{\"term_node\":\"text\",\"value\":\"" + s + "\"}"};
  }

  auto operator()(value_ptr<function> const& f) const -> string {
    std::ostringstream oss;
    oss << "{\"term_node\":\"function\",\"name\":\"" << f->name() << "\",\"terms\":[";
    if (f->arity()) {
      oss << std::visit(term_json_fmt_vstr{}, f->at(0));
      for (auto i = 1u; i < f->arity(); ++i) {
        oss << ", " << std::visit(term_json_fmt_vstr{}, f->at(i));
      }
    }
    oss << "]}";
    return oss.str();
  }
};

struct term_fmt_vstr {
  std::ostream& m_os;
  bool m_use_latex;
  size_t m_pr;

  term_fmt_vstr(std::ostream& os, bool use_latex = false, size_t pr = 0)
    : m_os(os), m_use_latex(use_latex), m_pr(pr) {
  }

  auto operator()(value_ptr<function> const& f) const -> std::ostream& {
    static const ordered_map<string, string> op_names = {
      {"exponentiation", "^"},
      {"multiplication", "*"},
      {"division", "/"},
      {"addition", "+"},
      {"substraction", "-"}
    };

    static const ordered_map<string, size_t> precedence = {
      {"exponentiation", 6},
      {"multiplication", 4},
      {"division", 4},
      {"addition", 2},
      {"substraction", 2}
    };

    if (f->name() == "minus") {
      m_os << '-';
      //if (m_pr > 8) {
      //  m_os << '(';
      //}
      std::visit(term_fmt_vstr{m_os, m_use_latex, 8}, f->at(0));
      //if (m_pr > 8) {
      //  m_os << ')';
      //}
      return m_os;
    }

    auto const& it = op_names.find(f->name());
    if (it != op_names.end()) {
      auto const pre = precedence.at(f->name());
      if (m_pr > pre) {
        m_os << '(';
      }
      string const space = it->second == "^"? string{""} : string{" "};
      std::visit(term_fmt_vstr{m_os, m_use_latex, pre + 1}, f->at(0));
      m_os << space;
      if (m_use_latex && it->second == "*") {
        m_os << "\\times";
      } else {
        m_os << it->second;
      }
      m_os << space;
      if (m_use_latex && it->second == "^") {
        m_os << '{';
        std::visit(term_fmt_vstr{m_os, m_use_latex, 0}, f->at(1));
        m_os << '}';
      } else {
        std::visit(term_fmt_vstr{m_os, m_use_latex, pre}, f->at(1));
      }
      if (m_pr > pre) {
        m_os << ')';
      }
    } else {
      m_os << f->name();
      if (f->arity()) {
        m_os << "(" << intersperse(f->begin(), f->end()) << ")";
      }
    }
    return m_os;
  }

  template<typename T>
  auto operator()(T const& t) const -> std::ostream& {
    m_os << t;
    return m_os;
  }
};

struct is_variable_vstr {
  auto operator()(variable const&) const -> bool {
    return true;
  }

  template<typename T>
  auto operator()(T const&) const -> bool {
    return false;
  }
};

struct is_function_vstr {
  auto operator()(value_ptr<function> const&) const -> bool {
    return true;
  }

  template<typename T>
  auto operator()(T const&) const -> bool {
    return false;
  }
};

struct is_ground_term_vstr {
  auto operator()(value_ptr<function> const& f) const -> bool {
    return
      std::all_of(f->begin(), f->end(), [](term const& t) {
        return std::visit(is_ground_term_vstr{}, t);
      });
  }

  auto operator()(variable const&) const -> bool {
    return false;
  }

  template<typename T>
  auto operator()(T const&) const -> bool {
    return true;
  }
};

struct term_size_vstr {
  bool m_count_internal;

  term_size_vstr(bool count_internal = true)
    : m_count_internal(count_internal) {
  }

  auto operator()(value_ptr<function> const& f) const -> uint32_t {
    uint32_t count = m_count_internal;
    for (auto const& t : *f) {
      count += std::visit(term_size_vstr{m_count_internal}, t);
    }
    return count;
  }

  template<typename T>
  auto operator()(T const&) const -> uint32_t {
    return 1;
  }
};

struct has_variables_vstr {
  auto operator()(variable const&) const -> bool {
    return true;
  }

  auto operator()(value_ptr<function> const& f) const -> bool {
    return
      std::any_of(f->begin(), f->end(), [](term const& t) {
        return std::visit(has_variables_vstr{}, t);
      });
  }

  template<typename T>
  auto operator()(T const&) const -> bool {
    return false;
  }
};

struct get_variables_vstr {
  auto operator()(variable const& v) const -> unordered_set<variable> {
    return unordered_set<variable>{v};
  }

  auto operator()(value_ptr<function> const& f) const -> unordered_set<variable> {
    auto vars = unordered_set<variable>{};
    for (auto const& t : *f) {
      auto const vars_t = std::visit(get_variables_vstr{}, t);
      vars.insert(vars_t.begin(), vars_t.end());
    }
    return vars;
  }

  template<typename T>
  auto operator()(T const&) const -> unordered_set<variable> {
    return unordered_set<variable>{};
  }
};

struct get_constants_vstr {
  auto operator()(variable const& v) const -> unordered_set<term> {
    return unordered_set<term>{};
  }

  auto operator()(value_ptr<function> const& f) const -> unordered_set<term> {
    auto vars = unordered_set<term>{};
    for (auto const& t : *f) {
      auto const vars_t = std::visit(get_constants_vstr{}, t);
      vars.insert(vars_t.begin(), vars_t.end());
    }
    return vars;
  }

  template<typename T>
  auto operator()(T const& t) const -> unordered_set<term> {
    return unordered_set<term>{t};
  }
};

struct get_functions_vstr {
  auto operator()(value_ptr<function> const& f) const -> unordered_set<value_ptr<function>> {
    auto functions = unordered_set<value_ptr<function>>{f};
    for (auto const& t : *f) {
      auto const functions_t = std::visit(get_functions_vstr{}, t);
      functions.insert(functions_t.begin(), functions_t.end());
    }
    return functions;
  }

  template<typename T>
  auto operator()(T const&) const -> unordered_set<value_ptr<function>> {
    return unordered_set<value_ptr<function>>{};
  }
};

struct get_function_names_vstr {
  auto operator()(value_ptr<function> const& f) const -> unordered_set<string> {
    auto functions = unordered_set<string>{f->name()};
    for (auto const& t : *f) {
      auto const functions_t = std::visit(get_function_names_vstr{}, t);
      functions.insert(functions_t.begin(), functions_t.end());
    }
    return functions;
  }

  template<typename T>
  auto operator()(T const&) const -> unordered_set<string> {
    return unordered_set<string>{};
  }
};

// Functions:

auto size(term const& t, bool count_internal) -> uint32_t {
  return std::visit(term_size_vstr{count_internal}, t);
}

auto expressional_complexity(term const& t) -> uint32_t {
  return std::visit(term_expr_complexity_vstr{}, t).second;
}

auto size_and_expr_complexity(term const& t) -> pair<uint32_t, uint32_t> {
  return std::visit(term_expr_complexity_vstr{}, t);
}

auto is_variable(term const& t) -> bool {
  return std::visit(is_variable_vstr{}, t);
}

auto is_function(term const& t) -> bool {
  return std::visit(is_function_vstr{}, t);
}

auto is_ground(term const& t) -> bool {
  return std::visit(is_ground_term_vstr{}, t);
}

auto has_variables(term const& t) -> bool {
  return std::visit(has_variables_vstr{}, t);
}

auto get_variables(term const& t) -> unordered_set<variable> {
  return std::visit(get_variables_vstr{}, t);
}

auto get_constants(term const& t) -> unordered_set<term> {
  return std::visit(get_constants_vstr{}, t);
}

auto get_functions(term const& t) -> unordered_set<value_ptr<function>> {
  return std::visit(get_functions_vstr{}, t);
}

auto get_function_names(term const& t) -> unordered_set<string> {
  return std::visit(get_function_names_vstr{}, t);
}

auto count_variables(term const& t) -> size_t {
  return std::visit(get_variables_vstr{}, t).size();
}

auto count_constants(term const& t) -> size_t {
  return std::visit(get_constants_vstr{}, t).size();
}

auto count_functions(term const& t) -> size_t {
  return std::visit(get_function_names_vstr{}, t).size();
}

auto count_function_names(term const& t) -> size_t {
  return std::visit(get_function_names_vstr{}, t).size();
}

auto to_json(term const& t) -> string {
  return std::visit(term_json_fmt_vstr{}, t);
}

auto fmt(std::ostream& os, term const& t, bool use_latex) -> std::ostream& {
  std::visit(term_fmt_vstr{os, use_latex}, t);
  return os;
}

auto to_string(term const& t, bool use_latex) -> string {
  std::ostringstream oss;
  std::visit(term_fmt_vstr{oss, use_latex}, t);
  return oss.str();
}

auto operator<<(std::ostream& os, term const& t) -> std::ostream& {
  std::visit(term_fmt_vstr{os}, t);
  return os;
}

auto operator<<(std::ostream& os, function const& f) -> std::ostream& {
  term const& t = term(f);
  std::visit(term_fmt_vstr{os}, t);
  return os;
}

auto operator<<(std::ostream& os, variable const& v) -> std::ostream& {
  os << v.name();
  return os;
}

auto operator<<(std::ostream& os, std::complex<double> const& c) -> std::ostream& {
  os << c.real() << " + " << c.imag() << 'i';
  return os;
}

auto operator+(term const& lhs, term const& rhs) -> term {
  return function{"addition", {lhs, rhs}};
}

auto operator-(term const& lhs, term const& rhs) -> term {
  return function{"substraction", {lhs, rhs}};
}

auto operator-(term const& t) -> term {
  return function{"minus", {t}};
}

auto operator*(term const& lhs, term const& rhs) -> term {
  return function{"multiplication", {lhs, rhs}};
}

auto operator/(term const& lhs, term const& rhs) -> term {
  return function{"division", {lhs, rhs}};
}

auto operator^(term const& lhs, term const& rhs) -> term {
  return function{"exponentiation", {lhs, rhs}};
}

} /* end namespace cj */


text:
layout: post
title: "A few days in Holland"
date: 2016-10-24 07:00:00 +01:00
author: Coloma Farré
backgrounds:
    - /img/amsterdam/IMG_5914.jpg
thumb: /img/amsterdam/IMG_5914.jpg
categories: Parenting Family Tavelling
comments: true
---

At the end of September we went for 5 days to Amsterdam. My husband had a work conference there and we took advantage of it to enjoy it as a family. I lived in Holland before, in 2009 during my Erasmus semester, in Utrecht, 20 minutes train ride from Amsterdam, and I loved it! I love the people there and the fact that everybody rides bikes everywhere!! It's like a dream!

This time we stayed in an AirBnB in the Pijp neighborhood in Amsterdam. Such a cool place, we were very close to a big and beautiful park (Sarphatipark) with a really nice playground and lake with ducks. There were a lot of hip restaurants and stores and the Albert Cuypmarkt (the biggest and most popular outdoor market in the Netherlands) very close by too.

We did go to Utrecht for one afternoon to visit some friends that live there! It's such a nice city, much more relaxed and calm than Amsterdam! We can't decide which one we like better.

We loved the time there. It was great the fact that almost every restaurant or cafe was family friendly, with a little corner with wooden toys or books for the kids to play with! It was so fun to rent bikes and ride around the center with Ramona! She liked riding in front of the bike (in Barcelona her bike seat is behind Joe's and I think she can't see as much). It was funny buying baby food there and realizing how different they are, with ingredients that you'll never find in Spanish baby food, like: beef+apples+beans, or fish+pasta+spinach.

Here are some of my favorite pictures of those days!

  We ate so many croissants!!

  Blueberries!!!

  Sarphatipark's playground.

  She looooves the bubbles!!

It was a great week! And we are even more excited because next year we will get to live for a while in Holland. Help us decide, should we choose, Utrecht or Amsterdam???

redpajama_set_name: RedPajamaGithub


text:
"""Implementation of Basic KNX DPT_1_Ucount Values."""
from __future__ import annotations

from xknx.exceptions import ConversionError

from .dpt import DPTNumeric

class DPTValue1ByteUnsigned(DPTNumeric):
    """
    Abstraction for KNX 1 Octet.

    DPT 5.***
    """

    dpt_main_number = 5
    dpt_sub_number: int | None = None
    value_type = "1byte_unsigned"
    unit = ""
    payload_length = 1

    value_min = 0
    value_max = 255
    resolution = 1

    @classmethod
    def from_knx(cls, raw: tuple[int, ...]) -> int:
        """Parse/deserialize from KNX/IP raw data."""
        cls.test_bytesarray(raw)

        value = raw[0]

        if not cls._test_boundaries(value):
            raise ConversionError(
                f"Could not parse {cls.__name__}", value=value, raw=raw
            )

        return value

    @classmethod
    def to_knx(cls, value: int | float) -> tuple[int]:
        """Serialize to KNX/IP raw data."""
        try:
            knx_value = int(value)
            if not cls._test_boundaries(knx_value):
                raise ValueError
            return (knx_value,)
        except ValueError:
            raise ConversionError(f"Could not serialize {cls.__name__}", value=value)

    @classmethod
    def _test_boundaries(cls, value: int) -> bool:
        """Test if value is within defined range for this object."""
        return cls.value_min <= value <= cls.value_max

class DPTPercentU8(DPTValue1ByteUnsigned):
    """
    Abstraction for KNX 1 Octet Percent.

    DPT 5.004
    """

    dpt_main_number = 5
    dpt_sub_number = 4
    value_type = "percentU8"
    unit = "%"

class DPTDecimalFactor(DPTValue1ByteUnsigned):
    """
    Abstraction for KNX 1 Octet Percent.

    DPT 5.005
    """

    dpt_main_number = 5
    dpt_sub_number = 5
    value_type = "decimal_factor"

class DPTTariff(DPTValue1ByteUnsigned):
    """
    Abstraction for KNX 1 Octet tariff information.

    DPT 5.006
    """

    dpt_main_number = 5
    dpt_sub_number = 6
    value_type = "tariff"
    value_max = 254

class DPTValue1Ucount(DPTValue1ByteUnsigned):
    """
    Abstraction for KNX 1 Octet counter pulses.

    DPT 5.010
    """

    dpt_main_number = 5
    dpt_sub_number = 10
    value_type = "pulse"
    unit = "counter pulses"

class DPTSceneNumber(DPTValue1ByteUnsigned):
    """
    Abstraction for KNX 1 Octet Scene Number.

    DPT 17.001
    """

    dpt_main_number = 17
    dpt_sub_number = 1
    value_type = "scene_number"
    unit = ""

    value_min = 1
    value_max = 64

    @classmethod
    def from_knx(cls, raw: tuple[int, ...]) -> int:
        """Parse/deserialize from KNX/IP raw data."""
        cls.test_bytesarray(raw)

        value = raw[0] + 1

        if not cls._test_boundaries(value):
            raise ConversionError(
                f"Could not parse {cls.__name__}", value=value, raw=raw
            )

        return value

    @classmethod
    def to_knx(cls, value: int | float) -> tuple[int]:
        """Serialize to KNX/IP raw data."""
        try:
            knx_value = int(value) - 1
            if not cls._test_boundaries(knx_value + 1):
                raise ValueError
            return (knx_value,)
        except ValueError:
            raise ConversionError(f"Could not serialize {cls.__name__}", value=value)


text:
A book trading app/site for freeCodeCamp fullstack projects. See the page
(https://www.freecodecamp.com/challenges/manage-a-book-trading-club) for a full
description of the requirements.

The website is deployed to Heroku: (http://bookwyrms.herokuapp.com).

## Description

A user can signup for the book club. People can trade their (physical) copies of the
books via the website. The website shows a list of all books by all users, and
registered users can click and request a trade.

## Tools/technologies used

The website is a MERN full stack Javascript application. It uses the following
features:

  1. mongodb (via (http://www.mlab.com))
  2. express
  3. react
  4. node.js
  5. pug
  6. gulp
  7. passport.js for signup/logins
  + many more (ctags, eslint, sass-lint)

## Development

To have the application fully working, you need to get an API key from
(https://developers.google.com/books/).

First, clone the repository:

    git clone https://github.com/tpoikela/fcc-bookclub.git

Install required modules:

    npm install

This will build the application automatically. Rename `sample.env` to `.env`.

    mv sample.env .env

Set your mongodb and API key in .env. Then, you can start the server:

    node server

Now you can visit the pages in `localhost:8080`, or whatever port you set.


text:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CoreModule } from './core/core.module';
import { AppStoreModule } from './store/app-store.module';
import { MetaReducer, StoreModule } from '@ngrx/store';
import { environment } from '../environments/environment';
import { EffectsModule } from '@ngrx/effects';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';

export const metaReducers: MetaReducer<any>[] = environment.production ? [] : [];

@NgModule({
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    CoreModule,
    HttpClientModule,
    AppRoutingModule,
    AppStoreModule,
    StoreModule.forRoot({}, { metaReducers }),
    EffectsModule.forRoot([]),
    !environment.production ? StoreDevtoolsModule.instrument() : []
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}


text:
/**
 * @file
 * Styles for the system status report counters.
 */

.system-status-report-counters__item {
  margin: 10px 0;
  width: 100%;
}

@media screen and (min-width: 60em) {
  .system-status-report-counters__item {
    margin-bottom: 20px;
  }
  .system-status-report-counters {
    flex-wrap: wrap;
    display: flex;
    justify-content: space-between;
  }
  .system-status-report-counters__item--half-width {
    width: 49%;
  }
  .system-status-report-counters__item--third-width {
    width: 32%;
  }
}


text:
'use strict';

const path = require('path');
const test = require('tape');
const remote = require('../marklogic-remote')();
const parseTAP = require('../lib/tap-helpers').parseTAP;

test('mutiple tests', assert => {
  assert.plan(2);
  remote(
    'multiple-tests.test.sjs',
    path.resolve(__dirname, '../../marklogic/test')
  )
    .then(tap => parseTAP(tap))
    .then(tap => {
      assert.equal(tap.pass, 3, '3 tests pass');
      assert.equal(tap.fail, 1, '1 test fails');
    })
    .catch(assert.end);
});


text:
bool MethodInModule::operator <(const MethodInModule& other) const
{
    STANDARD_VM_CONTRACT;
    if (m_module == other.m_module)
    {
        return m_methodDef < other.m_methodDef;
    }
    else
    {
        // Since NGen images are supposed to be determenistic,
        // we need stable sort order that isn't changing between different runs
        // That's why we use names and GUIDs instead of just doing m_module < other.m_module

        // First we try to compare simple names (should be fast enough)
        LPCUTF8 simpleName = m_module ? m_module->GetSimpleName() : "";
        LPCUTF8 otherSimpleName = other.m_module ? other.m_module->GetSimpleName() : "";
        int nameCmpResult = strcmp(simpleName, otherSimpleName);

        if (nameCmpResult == 0)
        {
            // Names are equal but module addresses aren't, it's suspicious
            // falling back to module GUIDs
            GUID thisGuid, otherGuid;
            if (m_module == NULL)
            {
                memset(&thisGuid, 0, sizeof(GUID));
            }
            else
            {
                m_module->GetFile()->GetMVID(&thisGuid);
            }

            if (other.m_module == NULL)
            {
                memset(&otherGuid, 0, sizeof(GUID));
            }
            else
            {
                other.m_module->GetFile()->GetMVID(&otherGuid);
            }

            return memcmp(&thisGuid, &otherGuid, sizeof(GUID)) < 0;
        }
        else
        {
            return nameCmpResult < 0;
        }
    }
}

bool MethodInModule::operator ==(const MethodInModule& other) const
{
    LIMITED_METHOD_DAC_CONTRACT;
    return m_methodDef == other.m_methodDef &&
           m_module == other.m_module;
}

bool MethodInModule::operator !=(const MethodInModule& other) const
{
    LIMITED_METHOD_DAC_CONTRACT;
    return m_methodDef != other.m_methodDef ||
           m_module != other.m_module;
}

void InlineTrackingEntry::SortAndDeduplicate()
{
    STANDARD_VM_CONTRACT;

    //Sort
    MethodInModule *begin = &m_inliners[0];
    MethodInModule *end = begin + m_inliners.GetCount();
    util::sort(begin, end);

    //Deduplicate
    MethodInModule *left = begin;
    MethodInModule *right = left + 1;
    while (right < end)
    {
        auto rvalue = *right;
        if (*left != rvalue)
        {
            left++;
            if (left != right)
            {
                *left = rvalue;
            }
        }
        right++;
    }

    //Shrink
    int newCount = (int)(left - begin + 1);
    m_inliners.SetCount(newCount);
}

InlineTrackingEntry::InlineTrackingEntry(const InlineTrackingEntry& other)
    :m_inlinee(other.m_inlinee)
{
    STANDARD_VM_CONTRACT;
    m_inliners.Set(other.m_inliners);
}

InlineTrackingEntry & InlineTrackingEntry::operator = (const InlineTrackingEntry &other)
{
    STANDARD_VM_CONTRACT;
    m_inlinee = other.m_inlinee;
    m_inliners.Set(other.m_inliners);
    return *this;
}

void InlineTrackingEntry::Add(PTR_MethodDesc inliner)
{
    STANDARD_VM_CONTRACT;

    MethodInModule method(inliner->GetModule(), inliner->GetMemberDef());

    // Going through last 10 inliners to check if a given inliner has recently been registered.
    // It allows to filter out most duplicates without having to scan through hundreds of inliners
    // for methods like Object.ctor or Monitor.Enter.
    // We are OK to keep occasional duplicates in m_inliners, we'll get rid of them
    // in SortAndDeduplicate() anyway.
    int count = static_cast<int>(m_inliners.GetCount());
    int start = max(0, count - 10);
    for (int i = count - 1; i >= start; i--)
    {
        if (m_inliners[i] == method)
            return;
    }

    //look like we see this inliner for the first time, add it to the collection
    m_inliners.Append(method);
}

InlineTrackingMap::InlineTrackingMap()
    : m_mapCrst(CrstInlineTrackingMap)
{
    STANDARD_VM_CONTRACT;
}

void InlineTrackingMap::AddInlining(MethodDesc *inliner, MethodDesc *inlinee)
{
    STANDARD_VM_CONTRACT;
    _ASSERTE(inliner != NULL);
    _ASSERTE(inlinee != NULL);

    MethodInModule inlineeMnM(inlinee->GetModule(), inlinee->GetMemberDef());

    if (RidFromToken(inlineeMnM.m_methodDef) == 0 || RidFromToken(inliner->GetMemberDef()) == 0)
    {
        // Sometimes we do see methods that don't have valid tokens (stubs etc)
        // we just ignore them.
        return;
    }

    CrstHolder lock(&m_mapCrst);
    InlineTrackingEntry *existingEntry = const_cast<InlineTrackingEntry *>(LookupPtr(inlineeMnM));
    if (existingEntry)
    {
        // We saw this inlinee before, just add one more inliner
        existingEntry->Add(inliner);
    }
    else
    {
        // We haven't seen this inlinee before, create a new record in the hashtable
        // and add a first inliner to it.
        InlineTrackingEntry newEntry;
        newEntry.m_inlinee = inlineeMnM;
        newEntry.Add(inliner);
        Add(newEntry);
    }
}

#endif //!DACCESS_COMPILE

void ZapInlineeRecord::InitForNGen(RID rid, LPCUTF8 simpleName)
{
    LIMITED_METHOD_CONTRACT;
    //XOR of up to first 24 bytes in module name
    DWORD hash = 0;
    for (int i = 0; simpleName[i] && i < 24; i++)
        hash ^= (BYTE)simpleName[i];

    // This key contains 24 bits of RID and 8 bits from module name.
    // Since RID can't be longer than 24 bits, we can't have method RID collistions,
    // that's why PersistentInlineTrackingMap::GetInliners only deals with module collisions.
    m_key = (hash << 24) | rid;
}

COUNT_T PersistentInlineTrackingMapNGen::GetInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL *incompleteData)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE(inlineeOwnerMod);
    _ASSERTE(inliners);

    if (incompleteData)
    {
        *incompleteData = FALSE;
    }
    if (m_inlineeIndex == NULL || m_inlinersBuffer == NULL)
    {
        //No inlines saved in this image.
        return 0;
    }

    // Binary search to find all records matching (inlineeTkn/inlineeOwnerMod)
    ZapInlineeRecord probeRecord;
    probeRecord.InitForNGen(RidFromToken(inlineeTkn), inlineeOwnerMod->GetSimpleName());
    ZapInlineeRecord *begin = m_inlineeIndex;
    ZapInlineeRecord *end = m_inlineeIndex + m_inlineeIndexSize;
    ZapInlineeRecord *foundRecord = util::lower_bound(begin, end, probeRecord);
    DWORD result = 0;
    DWORD outputIndex = 0;

    // Go through all matching records
    for (; foundRecord < end && *foundRecord == probeRecord; foundRecord++)
    {
        DWORD offset = foundRecord->m_offset;
        NibbleReader stream(m_inlinersBuffer + offset, m_inlinersBufferSize - offset);

        DWORD inlineeModuleZapIndex = stream.ReadEncodedU32();
        Module *decodedInlineeModule = GetModuleByIndex(inlineeModuleZapIndex);

        // Check if this is just token/method name hash collision
        if (decodedInlineeModule == inlineeOwnerMod)
        {
            // We found the token and the module we were looking for!
            DWORD inlinerModuleZapIndex = stream.ReadEncodedU32(); //read inliner module, it is same for all inliners
            Module *inlinerModule = GetModuleByIndex(inlinerModuleZapIndex);

            if (inlinerModule != NULL)
            {
                DWORD inlinersCount = stream.ReadEncodedU32();
                _ASSERTE(inlinersCount > 0);

                RID inlinerRid = 0;
                // Reading inliner RIDs one by one, each RID is represented as an adjustment (diff) to the previous one.
                // Adding inliners module and coping to the output buffer
                for (DWORD i = 0; i < inlinersCount && outputIndex < inlinersSize; i++)
                {
                    inlinerRid += stream.ReadEncodedU32();
                    mdMethodDef inlinerTkn = TokenFromRid(inlinerRid, mdtMethodDef);
                    inliners[outputIndex++] = MethodInModule(inlinerModule, inlinerTkn);
                }
                result += inlinersCount;
            }
            else
            {
                // We can't find module for this inlineeModuleZapIndex, it means it hasn't been loaded yet
                // (maybe it never will be), we just report it to the profiler.
                // Profiler might want to try later when more modules are loaded.
                if (incompleteData)
                {
                    *incompleteData = TRUE;
                }
            }
        }
    }

    return result;
}

Module *PersistentInlineTrackingMapNGen::GetModuleByIndex(DWORD index)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // This "black magic spell" has in fact nothing to do with GenericInstantiationCompare per se, but just sets a thread flag
    // that later activates more thorough search inside Module::GetAssemblyIfLoaded, which is indirectly called from GetModuleFromIndexIfLoaded.
    // This is useful when ngen image was compiler against a different assembly version than the one loaded now.
    ClrFlsThreadTypeSwitch genericInstantionCompareHolder(ThreadType_GenericInstantiationCompare);

    return m_module->GetModuleFromIndexIfLoaded(index);
}

#ifndef DACCESS_COMPILE
#ifdef FEATURE_NATIVE_IMAGE_GENERATION

// This is a shared serialization routine used for both NGEN and R2R formats. If image != NULL the NGEN format is generated, otherwise the R2R format
void SerializeInlineTrackingEntry(DataImage* image, SBuffer *inlinersBuffer, SArray<ZapInlineeRecord> *inlineeIndex, InlineTrackingEntry *entry)
{
    STANDARD_VM_CONTRACT;
    // This call removes duplicates from inliners and makes sure they are sorted by module
    entry->SortAndDeduplicate();
    MethodInModule inlinee = entry->m_inlinee;
    DWORD inlineeModuleZapIndex = 0;
    if (image != NULL)
    {
        inlineeModuleZapIndex = image->GetModuleImportIndex(inlinee.m_module);
    }
    InlineSArray<MethodInModule, 3> &inliners = entry->m_inliners;
    COUNT_T totalInlinersCount = inliners.GetCount();
    _ASSERTE(totalInlinersCount > 0);

    COUNT_T sameModuleCount;
    // Going through all inliners and grouping them by their module, for each module we'll create
    // an ZapInlineeRecord and encode inliners as bytes in inlinersBuffer.
    for (COUNT_T thisModuleBegin = 0; thisModuleBegin < totalInlinersCount; thisModuleBegin += sameModuleCount)
    {
        Module *lastInlinerModule = inliners[thisModuleBegin].m_module;
        DWORD lastInlinerModuleZapIndex = 0;
        if (image != NULL)
        {
            lastInlinerModuleZapIndex = image->GetModuleImportIndex(lastInlinerModule);
        }

        // Counting how many inliners belong to this module
        sameModuleCount = 1;
        while (thisModuleBegin + sameModuleCount < totalInlinersCount &&
            inliners[thisModuleBegin + sameModuleCount].m_module == lastInlinerModule)
        {
            sameModuleCount++;
        }

        // Saving module indexes and number of inliners
        NibbleWriter inlinersStream;
        if (image != NULL)
        {
            inlinersStream.WriteEncodedU32(inlineeModuleZapIndex);
            inlinersStream.WriteEncodedU32(lastInlinerModuleZapIndex);
        }
        inlinersStream.WriteEncodedU32(sameModuleCount);

        // Saving inliners RIDs, each new RID is represented as an adjustment (diff) to the previous one
        RID prevMethodRid = 0;
        for (COUNT_T i = thisModuleBegin; i < thisModuleBegin + sameModuleCount; i++)
        {
            RID methodRid = RidFromToken(inliners[i].m_methodDef);
            _ASSERTE(methodRid >= prevMethodRid);
            inlinersStream.WriteEncodedU32(methodRid - prevMethodRid);
            prevMethodRid = methodRid;
        }
        inlinersStream.Flush();

        // Copy output of NibbleWriter into a big buffer (inlinersBuffer) for inliners from the same module
        // and create an InlineeRecord with correct offset
        DWORD inlinersStreamSize;
        const BYTE *inlinersStreamPtr = (const BYTE *)inlinersStream.GetBlob(&inlinersStreamSize);
        ZapInlineeRecord record;
        if (image != NULL)
        {
            record.InitForNGen(RidFromToken(inlinee.m_methodDef), inlinee.m_module->GetSimpleName());
        }
        else
        {
            record.InitForR2R(RidFromToken(inlinee.m_methodDef));
        }
        record.m_offset = inlinersBuffer->GetSize();
        inlinersBuffer->Insert(inlinersBuffer->End(), SBuffer(SBuffer::Immutable, inlinersStreamPtr, inlinersStreamSize));
        inlineeIndex->Append(record);
    }
}

bool compare_entry(const InlineTrackingEntry* first, const InlineTrackingEntry* second)
{
    return first->m_inlinee < second->m_inlinee;
}

// This is a shared serialization routine used for both NGEN and R2R formats. If image != NULL the NGEN format is generated, otherwise the R2R format
void SerializeTrackingMapBuffers(ZapHeap* heap, DataImage *image, SBuffer *inlinersBuffer, SArray<ZapInlineeRecord> *inlineeIndex, InlineTrackingMap* runtimeMap)
{
    STANDARD_VM_CONTRACT;
    _ASSERTE(runtimeMap != NULL);

    // Sort records from runtimeMap, because we need to make sure
    // we save everything in deterministic order. Hashtable iteration is not deterministic.
    COUNT_T runtimeMapCount = runtimeMap->GetCount();
    InlineTrackingEntry **inlinees = new (heap) InlineTrackingEntry *[runtimeMapCount];
    int index = 0;
    for (auto iter = runtimeMap->Begin(), end = runtimeMap->End(); iter != end; ++iter)
    {
        inlinees[index++] = const_cast<InlineTrackingEntry *>(&*iter);
    }
    util::sort(inlinees, inlinees + runtimeMapCount, compare_entry);

    // Iterate throught each inlinee record from the InlineTrackingMap
    // and write corresponding records into inlineeIndex and inlinersBuffer
    for (COUNT_T i = 0; i < runtimeMapCount; i++)
    {
        SerializeInlineTrackingEntry(image, inlinersBuffer, inlineeIndex, inlinees[i]);
    }
}

void PersistentInlineTrackingMapNGen::Save(DataImage *image, InlineTrackingMap* runtimeMap)
{
    STANDARD_VM_CONTRACT;
    _ASSERTE(image != NULL);
    _ASSERTE(runtimeMap != NULL);

    SArray<ZapInlineeRecord> inlineeIndex;
    SBuffer inlinersBuffer;

    SerializeTrackingMapBuffers(image->GetHeap(), image, &inlinersBuffer, &inlineeIndex, runtimeMap);

    m_inlineeIndexSize = inlineeIndex.GetCount();
    m_inlinersBufferSize = inlinersBuffer.GetSize();
    _ASSERTE((m_inlineeIndexSize == 0) == (m_inlinersBufferSize == 0));

    if (m_inlineeIndexSize != 0 && m_inlinersBufferSize != 0)
    {
        // Copy everything to the class fields, we didn't use the class fields for addition
        // because we want to make sure we don't waste memory for buffer's amortized growth
        m_inlineeIndex = new (image->GetHeap()) ZapInlineeRecord[m_inlineeIndexSize];
        inlineeIndex.Copy(m_inlineeIndex, inlineeIndex.Begin(), m_inlineeIndexSize);

        m_inlinersBuffer = new (image->GetHeap()) BYTE[m_inlinersBufferSize];
        inlinersBuffer.Copy(m_inlinersBuffer, inlinersBuffer.Begin(), m_inlinersBufferSize);

        //Sort m_inlineeIndex so we can later use binary search
        util::sort(m_inlineeIndex, m_inlineeIndex + m_inlineeIndexSize);

        //Making sure all this memory actually gets saved into NGEN image
        image->StoreStructure(m_inlineeIndex, m_inlineeIndexSize * sizeof(m_inlineeIndex[0]), DataImage::ITEM_INLINING_DATA);
        image->StoreStructure(m_inlinersBuffer, m_inlinersBufferSize, DataImage::ITEM_INLINING_DATA);
    }

    image->StoreStructure(this, sizeof(*this), DataImage::ITEM_INLINING_DATA);
    LOG((LF_ZAP, LL_INFO100000,
        "PersistentInlineTrackingMap saved. InlineeIndexSize: %d bytes, InlinersBufferSize: %d bytes\n",
        m_inlineeIndexSize * sizeof(m_inlineeIndex[0]), m_inlinersBufferSize));
}

void PersistentInlineTrackingMapNGen::Fixup(DataImage *image)
{
    STANDARD_VM_CONTRACT;
    image->FixupPointerField(this, offsetof(PersistentInlineTrackingMapNGen, m_module));
    image->FixupPointerField(this, offsetof(PersistentInlineTrackingMapNGen, m_inlineeIndex));
    image->FixupPointerField(this, offsetof(PersistentInlineTrackingMapNGen, m_inlinersBuffer));
}

#endif //FEATURE_NATIVE_IMAGE_GENERATION
#endif //!DACCESS_COMPILE

#ifdef FEATURE_READYTORUN

struct InliningHeader
{
    int SizeOfInlineeIndex;
};

#ifndef DACCESS_COMPILE
#ifdef FEATURE_NATIVE_IMAGE_GENERATION

void PersistentInlineTrackingMapR2R::Save(ZapHeap* pHeap, SBuffer* pSaveTarget, InlineTrackingMap* runtimeMap)
{
    STANDARD_VM_CONTRACT;
    _ASSERTE(pSaveTarget != NULL);
    _ASSERTE(runtimeMap != NULL);

    SArray<ZapInlineeRecord> inlineeIndex;
    SBuffer inlinersBuffer;

    SerializeTrackingMapBuffers(pHeap, NULL, &inlinersBuffer, &inlineeIndex, runtimeMap);

    InliningHeader header;
    header.SizeOfInlineeIndex = inlineeIndex.GetCount() * sizeof(ZapInlineeRecord);

    pSaveTarget->Insert(pSaveTarget->End(), SBuffer(SBuffer::Immutable, (const BYTE*) &header, sizeof(header)));
    DWORD unused = 0;
    pSaveTarget->Insert(pSaveTarget->End(), SBuffer(SBuffer::Immutable, (const BYTE*) inlineeIndex.GetElements(), header.SizeOfInlineeIndex));
    pSaveTarget->Insert(pSaveTarget->End(), SBuffer(SBuffer::Immutable, (const BYTE*) inlinersBuffer, inlinersBuffer.GetSize()));

    LOG((LF_ZAP, LL_INFO100000,
        "PersistentInlineTrackingMap saved. InlineeIndexSize: %d bytes, InlinersBufferSize: %d bytes\n",
        header.SizeOfInlineeIndex, inlinersBuffer.GetSize()));
}

#endif //FEATURE_NATIVE_IMAGE_GENERATION

BOOL PersistentInlineTrackingMapR2R::TryLoad(Module* pModule, const BYTE* pBuffer, DWORD cbBuffer,
	                                         AllocMemTracker *pamTracker, PersistentInlineTrackingMapR2R** ppLoadedMap)
{
    InliningHeader* pHeader = (InliningHeader*)pBuffer;
    if (pHeader->SizeOfInlineeIndex > (int)(cbBuffer - sizeof(InliningHeader)))
    {
		//invalid serialized data, the index can't be larger the entire block
		_ASSERTE(!"R2R image is invalid or there is a bug in the R2R parser");
        return FALSE;
    }

	//NOTE: Error checking on the format is very limited at this point.
	//We trust the image format is valid and this initial check is a cheap
	//verification that may help catch simple bugs. It does not secure against
	//a deliberately maliciously formed binary.

	LoaderHeap *pHeap = pModule->GetLoaderAllocator()->GetHighFrequencyHeap();
	void * pMemory = pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(PersistentInlineTrackingMapR2R)));
	PersistentInlineTrackingMapR2R* pMap = new (pMemory) PersistentInlineTrackingMapR2R();

    pMap->m_module = pModule;
	pMap->m_inlineeIndex = (PTR_ZapInlineeRecord)(pHeader + 1);
	pMap->m_inlineeIndexSize = pHeader->SizeOfInlineeIndex / sizeof(ZapInlineeRecord);
	pMap->m_inlinersBuffer = ((PTR_BYTE)(pHeader+1)) + pHeader->SizeOfInlineeIndex;
	pMap->m_inlinersBufferSize = cbBuffer - sizeof(InliningHeader) - pMap->m_inlineeIndexSize;
	*ppLoadedMap = pMap;
    return TRUE;
}

#endif //!DACCESS_COMPILE

COUNT_T PersistentInlineTrackingMapR2R::GetInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL *incompleteData)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE(inlineeOwnerMod);
    _ASSERTE(inliners);

    if (incompleteData)
    {
        *incompleteData = FALSE;
    }
    if (m_inlineeIndex == NULL || m_inlinersBuffer == NULL)
    {
        //No inlines saved in this image.
        return 0;
    }
    if(inlineeOwnerMod != m_module)
    {
        // no cross module inlining (yet?)
        return 0;
    }

    // Binary search to find all records matching (inlineeTkn)
    ZapInlineeRecord probeRecord;
    probeRecord.InitForR2R(RidFromToken(inlineeTkn));
    ZapInlineeRecord *begin = m_inlineeIndex;
    ZapInlineeRecord *end = m_inlineeIndex + m_inlineeIndexSize;
    ZapInlineeRecord *foundRecord = util::lower_bound(begin, end, probeRecord);
    DWORD result = 0;
    DWORD outputIndex = 0;

    // Go through all matching records
    for (; foundRecord < end && *foundRecord == probeRecord; foundRecord++)
    {
        DWORD offset = foundRecord->m_offset;
        NibbleReader stream(m_inlinersBuffer + offset, m_inlinersBufferSize - offset);
        Module *inlinerModule = m_module;

        DWORD inlinersCount = stream.ReadEncodedU32();
        _ASSERTE(inlinersCount > 0);

        RID inlinerRid = 0;
        // Reading inliner RIDs one by one, each RID is represented as an adjustment (diff) to the previous one.
        // Adding inliners module and coping to the output buffer
        for (DWORD i = 0; i < inlinersCount && outputIndex < inlinersSize; i++)
        {
            inlinerRid += stream.ReadEncodedU32();
            mdMethodDef inlinerTkn = TokenFromRid(inlinerRid, mdtMethodDef);
            inliners[outputIndex++] = MethodInModule(inlinerModule, inlinerTkn);
        }
        result += inlinersCount;
    }

    return result;
}

#endif //FEATURE_READYTORUN

#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
JITInlineTrackingMap::JITInlineTrackingMap(LoaderAllocator *pAssociatedLoaderAllocator) :
    m_mapCrst(CrstJitInlineTrackingMap),
    m_map()
{
    LIMITED_METHOD_CONTRACT;

    m_map.Init(pAssociatedLoaderAllocator);
}

BOOL JITInlineTrackingMap::InliningExistsDontTakeLock(MethodDesc *inliner, MethodDesc *inlinee)
{
    LIMITED_METHOD_CONTRACT;

    _ASSERTE(m_mapCrst.OwnedByCurrentThread());
    _ASSERTE(inliner != NULL);
    _ASSERTE(inlinee != NULL);

    BOOL found = FALSE;
    auto lambda = [&](OBJECTREF obj, MethodDesc *lambdaInlinee, MethodDesc *lambdaInliner)
    {
        _ASSERTE(inlinee == lambdaInlinee);

        if (lambdaInliner == inliner)
        {
            found = TRUE;
            return false;
        }

        return true;
    };

    m_map.VisitValuesOfKey(inlinee, lambda);

    return found;
}

void JITInlineTrackingMap::AddInlining(MethodDesc *inliner, MethodDesc *inlinee)
{
    LIMITED_METHOD_CONTRACT;

    inlinee = inlinee->LoadTypicalMethodDefinition();

    CrstHolder holder(&m_mapCrst);
    AddInliningDontTakeLock(inliner, inlinee);
}

void JITInlineTrackingMap::AddInliningDontTakeLock(MethodDesc *inliner, MethodDesc *inlinee)
{
    LIMITED_METHOD_CONTRACT;

    _ASSERTE(m_mapCrst.OwnedByCurrentThread());
    _ASSERTE(inliner != NULL);
    _ASSERTE(inlinee != NULL);

    GCX_COOP();

    if (!InliningExistsDontTakeLock(inliner, inlinee))
    {
        LoaderAllocator *loaderAllocatorOfInliner = inliner->GetLoaderAllocator();
        m_map.Add(inlinee, inliner, loaderAllocatorOfInliner);
    }
}

#endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)


text:
'use strict';

//Chats service used to communicate Chats REST endpoints
angular.module('chats').factory('Chats', ['$resource',
	function($resource) {
		return $resource('chats/:chatId', {
			articleId: '@_id'
		}, {
			update: {
				method: 'PUT'
			}
		});
	}
]);


text:
/**
 *
 */
package me.learn.personal.month7;

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

/**
 * Title 936 :
 *
 * Date : Mar 6, 2021
 *
 * @author bramanarayan
 *
 */

/*
 * The idea is the same as the most upvoted post. Think reversely!
Let's take an example to illustrate.
Stamp = "abc", Target = "ababcbc`

    Target = ab***bc
    Target = ab*****
    Target = *******

We will go through the whole Target string to find if there exists any substring equals to Stamp. And then replace the whole substring with *. You can see in the step 1, we replace substring abc with ***. Then we keep doing the same thing. In the step 2, you will find we replace substring *bc to ***. * can match to any character because * will be override by the next stamp. Finally we get the result and output the reversed result. When # of stars equals to target.length(), we will return the result. If during one scan, we are not able to replace even one substring with *, directly return empty array.

Comments for two helper functions:
canReplace(char[] T, int p, char[] S) is used to check if any substring from Target is existing to be replaced with *.
doReplace(char[] T, int p, int len, int count) is used to replace the substring with * and return the total number of * we have now.
 */
public class StampingTheSequence {

	public int[] movesToStamp(String stamp, String target) {

		char[] stampChars = stamp.toCharArray();
		char[] targetChars = target.toCharArray();

		List<Integer> res = new ArrayList<>();

		boolean[] visited = new boolean[targetChars.length];

		int stars = 0;

		while (stars < targetChars.length) {
			boolean doneReplace = false;

			for (int i = 0; i <= targetChars.length - stampChars.length; i++) {
				if (!visited[i] && canReplace(targetChars, i, stampChars)) {

					stars = doReplace(targetChars, i, stampChars.length, stars); // replace all characters in the stamp window if its substring

					doneReplace = true;
					visited[i] = true;
					res.add(i);
					if (stars == targetChars.length) {
						break;
					}
				}
			}

			if (!doneReplace) {
				return new int[0];
			}
		}

		// convert List to int[]
		int[] resArray = new int[res.size()];
		for (int i = 0; i < res.size(); i++) {
			resArray[i] = res.get(res.size() - i - 1);
		}
		return resArray;
	}

	//is used to check if any substring from Target is existing to be replaced with *.
	private boolean canReplace(char[] targetChars, int start, char[] stampChars) {
		for (int i = 0; i < stampChars.length; i++) {
			if (targetChars[i + start] != '*' && targetChars[i + start] != stampChars[i]) {
				return false;
			}
		}
		return true;
	}

	//is used to replace the substring with * and return the total number of * we have now.

	private int doReplace(char[] targetChars, int start, int stampLength, int count) {
		for (int i = 0; i < stampLength; i++) {
			if (targetChars[i + start] != '*') {
				targetChars[i + start] = '*';
				count++;
			}
		}
		return count;
	}

}


text:
using sandbox::SyscallSets;
using sandbox::bpf_dsl::Allow;
using sandbox::bpf_dsl::Error;
using sandbox::bpf_dsl::ResultExpr;

namespace content {

UtilityProcessPolicy::UtilityProcessPolicy() {
}
UtilityProcessPolicy::~UtilityProcessPolicy() {
}

ResultExpr UtilityProcessPolicy::EvaluateSyscall(int sysno) const {
  switch (sysno) {
    case __NR_ioctl:
      return sandbox::RestrictIoctl();
    // Allow the system calls below.
    case __NR_fdatasync:
    case __NR_fsync:
#if defined(__i386__) || defined(__x86_64__) || defined(__mips__) || \
    defined(__aarch64__)
    case __NR_getrlimit:
#endif
#if defined(__i386__) || defined(__arm__)
    case __NR_ugetrlimit:
#endif
    case __NR_mremap:  // https://crbug.com/546204
    case __NR_pread64:
    case __NR_pwrite64:
    case __NR_sysinfo:
    case __NR_times:
    case __NR_uname:
      return Allow();
    default:
      // Default on the content baseline policy.
      return SandboxBPFBasePolicy::EvaluateSyscall(sysno);
  }
}

}  // namespace content


text:
#import <Foundation/Foundation.h>

#ifndef DeviceAttestationCredentialsHolder_h
#define DeviceAttestationCredentialsHolder_h

@interface DeviceAttestationCredentialsHolder : NSObject

- (DeviceAttestationCredentialsHolder * _Nonnull)
      initWithCertificationDeclaration:(NSData * _Nonnull)certificationDeclaration
                   firmwareInformation:(NSData * _Nonnull)firmwareInformation
                 deviceAttestationCert:(NSData * _Nonnull)deviceAttestationCert
    productAttestationIntermediateCert:(NSData * _Nonnull)productAttestationIntermediateCert
       deviceAttestationCertPrivateKey:(NSData * _Nonnull)deviceAttestationCertPrivateKey
     deviceAttestationCertPublicKeyKey:(NSData * _Nonnull)deviceAttestationCertPublicKeyKey;

- (NSData * _Nonnull)getCertificationDeclaration;

- (NSData * _Nonnull)getFirmwareInformation;

- (NSData * _Nonnull)getDeviceAttestationCert;

- (NSData * _Nonnull)getProductAttestationIntermediateCert;

- (NSData * _Nonnull)getDeviceAttestationCertPrivateKey;

- (NSData * _Nonnull)getDeviceAttestationCertPublicKeyKey;

@end

#endif /* DeviceAttestationCredentialsHolder_h */


text:
This should let you build AppRTCDemo without much effort.
I built WebRTC distribution on 9/6/2014, extracted `trunk/talk/examples/android`,
and it is imported to Android Studio.

## Background

It is not straightforward to build WebRTC for Android on Mac OS X.

- WebRTC can be only built on Linux.
- You need to have 6G+ disk space to build.
- Git clone takes up an hour.
- It requries a lot of libraries/packages installed.

However, it turned out that at the end of the day, you just need a few files to
build it on Android.

## Prerequisite

While this requries almost no effort to build, you need:

- Android NDK installed on your machine.
- Point the NDK installation via `local.properties`


text:
package liquibase.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.text.ParseException;

/**
 * Miscellaneous utility methods for number conversion and parsing.
 * Mainly for internal use within the framework; consider Jakarta's
 * Commons Lang for a more comprehensive suite of string utilities.
 *
 * @author Juergen Hoeller
 * @author Rob Harrop
 * @since 1.1.2
 */
public abstract class NumberUtils {

    /**
     * Convert the given number into an instance of the given target class.
     *
     * @param number      the number to convert
     * @param targetClass the target class to convert to
     * @return the converted number
     * @throws IllegalArgumentException if the target class is not supported
     *                                  (i.e. not a standard Number subclass as included in the JDK)
     * @see java.lang.Byte
     * @see java.lang.Short
     * @see java.lang.Integer
     * @see java.lang.Long
     * @see java.math.BigInteger
     * @see java.lang.Float
     * @see java.lang.Double
     * @see java.math.BigDecimal
     */
    public static Number convertNumberToTargetClass(Number number, Class targetClass)
            throws IllegalArgumentException {

        if (targetClass.isInstance(number)) {
            return number;
        } else if (targetClass.equals(Byte.class)) {
            long value = number.longValue();
            if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return number.byteValue();
        } else if (targetClass.equals(Short.class)) {
            long value = number.longValue();
            if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return number.shortValue();
        } else if (targetClass.equals(Integer.class)) {
            long value = number.longValue();
            if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
                raiseOverflowException(number, targetClass);
            }
            return number.intValue();
        } else if (targetClass.equals(Long.class)) {
            return number.longValue();
        } else if (targetClass.equals(Float.class)) {
            return number.floatValue();
        } else if (targetClass.equals(Double.class)) {
            return number.doubleValue();
        } else if (targetClass.equals(BigInteger.class)) {
            return BigInteger.valueOf(number.longValue());
        } else if (targetClass.equals(BigDecimal.class)) {
            // using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double)
            // (see BigDecimal javadoc for details)
            return new BigDecimal(number.toString());
        } else {
            throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
                    number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]");
        }
    }

    /**
     * Raise an overflow exception for the given number and target class.
     *
     * @param number      the number we tried to convert
     * @param targetClass the target class we tried to convert to
     */
    private static void raiseOverflowException(Number number, Class targetClass) {
        throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" +
                number.getClass().getName() + "] to target class [" + targetClass.getName() + "]: overflow");
    }

    /**
     * Parse the given text into a number instance of the given target class,
     * using the corresponding default decode methods. Trims the
     * input String before attempting to parse the number. Supports
     * numbers in hex format (with leading 0x) and in octal format (with leading 0).
     *
     * @param text        the text to convert
     * @param targetClass the target class to parse into
     * @return the parsed number
     * @throws IllegalArgumentException if the target class is not supported
     *                                  (i.e. not a standard Number subclass as included in the JDK)
     * @see java.lang.Byte#decode
     * @see java.lang.Short#decode
     * @see java.lang.Integer#decode
     * @see java.lang.Long#decode
     * @see #decodeBigInteger(String)
     * @see java.lang.Float#valueOf
     * @see java.lang.Double#valueOf
     * @see java.math.BigDecimal#BigDecimal(String)
     */
    public static Number parseNumber(String text, Class targetClass) {
        String trimmed = text.trim();

        if (targetClass.equals(Byte.class)) {
            return Byte.decode(trimmed);
        } else if (targetClass.equals(Short.class)) {
            return Short.decode(trimmed);
        } else if (targetClass.equals(Integer.class)) {
            return Integer.decode(trimmed);
        } else if (targetClass.equals(Long.class)) {
            return Long.decode(trimmed);
        } else if (targetClass.equals(BigInteger.class)) {
            return decodeBigInteger(trimmed);
        } else if (targetClass.equals(Float.class)) {
            return Float.valueOf(trimmed);
        } else if (targetClass.equals(Double.class)) {
            return Double.valueOf(trimmed);
        } else if (targetClass.equals(BigDecimal.class) || targetClass.equals(Number.class)) {
            return new BigDecimal(trimmed);
        } else {
            throw new IllegalArgumentException(
                    "Cannot convert String [" + text + "] to target class [" + targetClass.getName() + "]");
        }
    }

    /**
     * Parse the given text into a number instance of the given target class,
     * using the given NumberFormat. Trims the input String
     * before attempting to parse the number.
     *
     * @param text         the text to convert
     * @param targetClass  the target class to parse into
     * @param numberFormat the NumberFormat to use for parsing (if null,
     *                     this method falls back to parseNumber(String, Class))
     * @return the parsed number
     * @throws IllegalArgumentException if the target class is not supported
     *                                  (i.e. not a standard Number subclass as included in the JDK)
     * @see java.text.NumberFormat#parse
     * @see #convertNumberToTargetClass
     * @see #parseNumber(String,Class)
     */
    public static Number parseNumber(String text, Class targetClass, NumberFormat numberFormat) {
        if (numberFormat != null) {
            try {
                Number number = numberFormat.parse(text.trim());
                return convertNumberToTargetClass(number, targetClass);
            }
            catch (ParseException ex) {
                throw new IllegalArgumentException(ex.getMessage());
            }
        } else {
            return parseNumber(text, targetClass);
        }
    }

    /**
     * Decode a {@link java.math.BigInteger} from a {@link String} value.
     * Supports decimal, hex and octal notation.
     *
     * @see BigInteger#BigInteger(String,int)
     */
    private static BigInteger decodeBigInteger(String value) {
        int radix = 10;
        int index = 0;
        boolean negative = false;

        // Handle minus sign, if present.
        if (value.startsWith("-")) {
            negative = true;
            index++;
        }

        // Handle radix specifier, if present.
        if (value.startsWith("0x", index) || value.startsWith("0X", index)) {
            index += 2;
            radix = 16;
        } else if (value.startsWith("#", index)) {
            index++;
            radix = 16;
        } else if (value.startsWith("0", index) && value.length() > 1 + index) {
			index++;
			radix = 8;
		}

		BigInteger result = new BigInteger(value.substring(index), radix);
		return (negative ? result.negate() : result);
	}

    /**
     * Convenience method for converting a string to an Integer object
     * @param value string value
     * @return Null if the value is null, otherwise the converted integer
     */
    public static Integer readInteger(String value) {
        if (value == null) {
            return null;
        }
        return Integer.valueOf(value);
    }

}


text:
package com.taoswork.tallycheck.dataservice.query;

/**
 * @author Jeff Fischer
 */
public enum SortDirection {
    ASCENDING, DESCENDING
}


text:
package org.openqa.selenium.support.pagefactory;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ByIdOrName;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class DefaultElementLocatorTest {

  protected ElementLocator newLocator(WebDriver driver, Field field) {
    return new DefaultElementLocator(driver, field);
  }

  @Test
  public void shouldDelegateToDriverInstanceToFindElement() throws Exception {
    Field f = Page.class.getDeclaredField("first");
    final WebDriver driver = mock(WebDriver.class);
    final By by = new ByIdOrName("first");
    final WebElement element = mock(WebElement.class);

    when(driver.findElement(by)).thenReturn(element);

    ElementLocator locator = newLocator(driver, f);
    WebElement returnedElement = locator.findElement();

    assertThat(returnedElement).isEqualTo(element);
  }

  @Test
  public void shouldDelegateToDriverInstanceToFindElementList() throws Exception {
    Field f = Page.class.getDeclaredField("list");
    final WebDriver driver = mock(WebDriver.class);
    final By by = new ByIdOrName("list");
    final WebElement element1 = mock(WebElement.class, "webElement1");
    final WebElement element2 = mock(WebElement.class, "webElement2");
    final List<WebElement> list = Arrays.asList(element1, element2);

    when(driver.findElements(by)).thenReturn(list);

    ElementLocator locator = newLocator(driver, f);
    List<WebElement> returnedList = locator.findElements();

    assertThat(returnedList).isEqualTo(list);
  }

  @Test
  public void cachedElementShouldBeCached() throws Exception {
    Field f = Page.class.getDeclaredField("cached");
    final WebDriver driver = mock(WebDriver.class);
    final By by = new ByIdOrName("cached");
    final WebElement element = mock(WebElement.class);

    when(driver.findElement(by)).thenReturn(element);

    ElementLocator locator = newLocator(driver, f);
    locator.findElement();
    locator.findElement();

    verify(driver, times(1)).findElement(by);
  }

  @Test
  public void cachedElementListShouldBeCached() throws Exception {
    Field f = Page.class.getDeclaredField("cachedList");
    final WebDriver driver = mock(WebDriver.class);
    final By by = new ByIdOrName("cachedList");
    final WebElement element1 = mock(WebElement.class, "webElement1");
    final WebElement element2 = mock(WebElement.class, "webElement2");
    final List<WebElement> list = Arrays.asList(element1, element2);

    when(driver.findElements(by)).thenReturn(list);

    ElementLocator locator = newLocator(driver, f);
    locator.findElements();
    locator.findElements();

    verify(driver, times(1)).findElements(by);
  }

  @Test
  public void shouldNotCacheNormalElement() throws Exception {
    Field f = Page.class.getDeclaredField("first");
    final WebDriver driver = mock(WebDriver.class);
    final By by = new ByIdOrName("first");
    final WebElement element = mock(WebElement.class);

    when(driver.findElement(by)).thenReturn(element);

    ElementLocator locator = newLocator(driver, f);
    locator.findElement();
    locator.findElement();

    verify(driver, times(2)).findElement(by);
  }

  @Test
  public void shouldNotCacheNormalElementList() throws Exception {
    Field f = Page.class.getDeclaredField("list");
    final WebDriver driver = mock(WebDriver.class);
    final By by = new ByIdOrName("list");
    final WebElement element1 = mock(WebElement.class, "webElement1");
    final WebElement element2 = mock(WebElement.class, "webElement2");
    final List<WebElement> list = Arrays.asList(element1, element2);

    when(driver.findElements(by)).thenReturn(list);

    ElementLocator locator = newLocator(driver, f);
    locator.findElements();
    locator.findElements();

    verify(driver, times(2)).findElements(by);
  }

  @Test
  public void shouldUseFindByAnnotationsWherePossible() throws Exception {
    Field f = Page.class.getDeclaredField("byId");
    final WebDriver driver = mock(WebDriver.class);
    final By by = By.id("foo");
    final WebElement element = mock(WebElement.class);

    when(driver.findElement(by)).thenReturn(element);

    ElementLocator locator = newLocator(driver, f);
    locator.findElement();
  }

  @Test
  public void shouldUseFindAllByAnnotationsWherePossible() throws Exception {
    Field f = Page.class.getDeclaredField("listById");
    final WebDriver driver = mock(WebDriver.class);
    final By by = By.id("foo");
    final WebElement element1 = mock(WebElement.class, "webElement1");
    final WebElement element2 = mock(WebElement.class, "webElement2");
    final List<WebElement> list = Arrays.asList(element1, element2);

    when(driver.findElements(by)).thenReturn(list);

    ElementLocator locator = newLocator(driver, f);
    locator.findElements();
  }

  @Test
  public void shouldNotMaskNoSuchElementExceptionIfThrown() throws Exception {
    Field f = Page.class.getDeclaredField("byId");
    final WebDriver driver = mock(WebDriver.class);
    final By by = By.id("foo");

    when(driver.findElement(by)).thenThrow(new NoSuchElementException("Foo"));

    ElementLocator locator = newLocator(driver, f);

    assertThatExceptionOfType(NoSuchElementException.class)
        .isThrownBy(locator::findElement);
  }

  @Test
  public void shouldWorkWithCustomAnnotations() {
    final WebDriver driver = mock(WebDriver.class);

    AbstractAnnotations npeAnnotations = new AbstractAnnotations() {
      @Override
      public boolean isLookupCached() {
        return false;
      }

      @Override
      public By buildBy() {
        throw new NullPointerException();
      }
    };

    assertThatExceptionOfType(NullPointerException.class)
        .isThrownBy(() -> new DefaultElementLocator(driver, npeAnnotations));
  }

  private static class Page {
    @SuppressWarnings("unused")
    private WebElement first;

    @SuppressWarnings("unused")
    private List<WebElement> list;

    @SuppressWarnings("unused")
    @CacheLookup
    private WebElement cached;

    @SuppressWarnings("unused")
    @CacheLookup
    private List<WebElement> cachedList;

    @SuppressWarnings("unused")
    @FindBy(how = How.ID, using = "foo")
    private WebElement byId;

    @SuppressWarnings("unused")
    @FindBy(how = How.ID, using = "foo")
    private List<WebElement> listById;
  }
}


text:
using System.Collections.Generic;
using Azure.Core;
using Azure.ResourceManager.HybridContainerService;

namespace Azure.ResourceManager.HybridContainerService.Models
{
    /// <summary> The VirtualNetworksListResult. </summary>
    internal partial class VirtualNetworksListResult
    {
        /// <summary> Initializes a new instance of VirtualNetworksListResult. </summary>
        internal VirtualNetworksListResult()
        {
            Value = new ChangeTrackingList<HybridContainerServiceVirtualNetworkData>();
        }

        /// <summary> Initializes a new instance of VirtualNetworksListResult. </summary>
        /// <param name="value"></param>
        /// <param name="nextLink"></param>
        internal VirtualNetworksListResult(IReadOnlyList<HybridContainerServiceVirtualNetworkData> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> Gets the value. </summary>
        public IReadOnlyList<HybridContainerServiceVirtualNetworkData> Value { get; }
        /// <summary> Gets the next link. </summary>
        public string NextLink { get; }
    }
}


text:
package com.intenthq.pucket.writer

import com.intenthq.pucket.{PucketDescriptor, TestLogging}
import com.intenthq.pucket.TestUtils.PucketWrapper
import org.apache.hadoop.fs.Path
import org.specs2.Specification
import com.intenthq.pucket.TestUtils._
import org.specs2.scalaz.DisjunctionMatchers

import scalaz.\/

trait IncrementalPartitionedWriterSpec[T] extends Specification with DisjunctionMatchers with TestLogging {
  import IncrementalPartitionedWriterSpec._

  val wrapper: PucketWrapper[T]
  def newData(i: Long): T

  val data = partitions.map(x => newData(x))

  def is =
    s2"""
        Creates subdirectories according to partitioning scheme $writeAndVerify
        Removes the temp dir ${step(wrapper.close())}
     """

  def writeAndVerify = write and verifyDirs

  def write =
    writer.flatMap(writeData(data, _)) must beRightDisjunction.like {
      case a => a.close must be_\/-
    }

  def verifyDirs =
    dirs must beRightDisjunction.like {
      case a =>
        (a.map(_.getName) must containAllOf(partitions.map(_ % 20).distinct.map(_.toString))) and
        (a.filter(_.getName.contains(".parquet")) must beEmpty) and
        (a.map(x => (x.getName, fs.listStatus(x).size)).filter(_ == 3) must beEmpty)
    }

  def dirs: Throwable \/ Seq[Path] =
    wrapper.pucket.flatMap(p => wrapper.pucket.map(x => p.fs.listStatus(x.path).
      map(_.getPath).
      filterNot(_.getName == PucketDescriptor.descriptorFilename)))

  def writer: Throwable \/ IncrementalPartitionedWriter[T] =
    wrapper.pucket.map(IncrementalPartitionedWriter(_, maxWrites, 5))

}

object IncrementalPartitionedWriterSpec {
  val partitions = 0.to(2500)
  val maxWrites = 50
}


text:
package com.facebook.login;

/**
 * Specifies the behaviors to try during login.
 */
public enum LoginBehavior {
    /**
     * Specifies that login should attempt login in using the Facebook App, and if that
     * does not work fall back to web dialog auth. This is the default behavior.
     */
    NATIVE_WITH_FALLBACK(true, true),

    /**
     * Specifies that login should only attempt to login using the Facebook App.
     * If the Facebook App cannot be used then the login fails.
     */
    NATIVE_ONLY(true, false),

    /**
     * Specifies that only the web dialog auth should be used.
     */
    WEB_ONLY(false, true);

    private final boolean allowsKatanaAuth;
    private final boolean allowsWebViewAuth;

    private LoginBehavior(boolean allowsKatanaAuth, boolean allowsWebViewAuth) {
        this.allowsKatanaAuth = allowsKatanaAuth;
        this.allowsWebViewAuth = allowsWebViewAuth;
    }

    boolean allowsKatanaAuth() {
        return allowsKatanaAuth;
    }

    boolean allowsWebViewAuth() {
        return allowsWebViewAuth;
    }
}


text:
package com.gzsll.hupu.components.notifier;

import android.app.Notification;
import android.app.NotificationManager;

import javax.inject.Inject;

/**
 * Created by sll on 2016/6/2.
 */
public class Notifier {
    public static final int OfflineThreads = 9001;// 离线帖子

    public static final int OfflineReplies = 9002;// 离线回复

    public static final int OfflinePicture = 9003;// 离线图片

    @Inject
    NotificationManager notificationManager;

    protected void notify(int id, Notification notification) {
        notificationManager.notify(id, notification);
    }

    public void cancelNotification(int request) {
        notificationManager.cancel(request);
    }

    public void cancelAll() {
        notificationManager.cancel(OfflineThreads);
        notificationManager.cancel(OfflineReplies);
        notificationManager.cancel(OfflinePicture);
    }
}


text: ocamlfind ocamlc -package camlp4.quotations.o -syntax camlp4o -c ${1}


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

import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;
import javax.management.MBeanServer;
import javax.management.ObjectName;

public abstract class AbstractCommitLogExecutorService extends AbstractExecutorService implements ICommitLogExecutorService
{
    protected volatile long completedTaskCount = 0;

    protected static void registerMBean(Object o)
    {
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        try
        {
            mbs.registerMBean(o, new ObjectName("org.apache.cassandra.db:type=Commitlog"));
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * Get the current number of running tasks
     */
    public int getActiveCount()
    {
        return 1;
    }

    /**
     * Get the number of completed tasks
     */
    public long getCompletedTasks()
    {
        return completedTaskCount;
    }

    public boolean isTerminated()
    {
        throw new UnsupportedOperationException();
    }

    public boolean isShutdown()
    {
        throw new UnsupportedOperationException();
    }

    public List<Runnable> shutdownNow()
    {
        throw new UnsupportedOperationException();
    }

    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException
    {
        throw new UnsupportedOperationException();
    }
}


text:
static Import*  import_alloc();
static void     import_delete(Import*);

int imports_initialize(Imports* p)
{
  llist_initialize(&p->set, (llistNodeDelete)import_delete);
  return SUCCESS;
}

int imports_terminate(Imports* p)
{
  return SUCCESS;
}

Import* imports_add(Imports* p, const char* name)
{
  Import* o = import_alloc();

  string_copy_cstr(&o->name, name);
  llist_add_end(&p->set, (LListNode*)o);

  return o;
}

Import* imports_add_alias(Imports* p, const char* name, const char* alias)
{
  Import* o = imports_add(p, name);

  string_copy_cstr(&o->as, alias);

  return o;
}

Import* import_alloc()
{
  Import* o = (Import*)malloc(sizeof(Import));

  llist_node_initialize(&o->node);
  string_initialize(&o->name);
  string_initialize(&o->as);

  return o;
}

void import_delete(Import* p)
{
  string_terminate(&p->name);
  string_terminate(&p->as);
  free(p);
}


text:
package com.yammer.dropwizard.logging;

import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.classic.spi.StackTraceElementProxy;
import ch.qos.logback.core.CoreConstants;

public class PrefixedThrowableProxyConverter extends ThrowableProxyConverter {
    private static final String PREFIX = "! ";

    @Override
    protected String throwableProxyToString(IThrowableProxy tp) {
        final StringBuilder buf = new StringBuilder(32);
        IThrowableProxy currentThrowable = tp;
        while (currentThrowable != null) {
            subjoinThrowableProxy(buf, currentThrowable);
            currentThrowable = currentThrowable.getCause();
        }
        return buf.toString();
    }

    void subjoinThrowableProxy(StringBuilder buf, IThrowableProxy tp) {
        subjoinFirstLine(buf, tp);

        buf.append(CoreConstants.LINE_SEPARATOR);
        final StackTraceElementProxy[] stepArray = tp.getStackTraceElementProxyArray();
        final int commonFrames = tp.getCommonFrames();

        int maxIndex = stepArray.length;
        if (commonFrames > 0) {
            maxIndex -= commonFrames;
        }

        for (int i = 0; i < maxIndex; i++) {
            final String string = stepArray[i].toString();
            buf.append(PREFIX);
            buf.append(string);
            extraData(buf, stepArray[i]); // allow other data to be added
            buf.append(CoreConstants.LINE_SEPARATOR);
        }

        if (commonFrames > 0) {
            buf.append("!... ").append(tp.getCommonFrames()).append(
                    " common frames omitted").append(CoreConstants.LINE_SEPARATOR);
        }
    }

    private void subjoinFirstLine(StringBuilder buf, IThrowableProxy tp) {
        final int commonFrames = tp.getCommonFrames();
        if (commonFrames > 0) {
            buf.append(CoreConstants.CAUSED_BY);
        }
        subjoinExceptionMessage(buf, tp);
    }

    private void subjoinExceptionMessage(StringBuilder buf, IThrowableProxy tp) {
        buf.append(PREFIX).append(tp.getClassName()).append(": ").append(tp.getMessage());
    }
}


text:
module Lurker
  module Json
    class Orderer
      EXTENSIONS = 'extensions'.freeze

      class << self
        def reorder(schema)
          new.reorder(schema)
        end
      end

      def reorder(schema)
        extensions = schema.delete(EXTENSIONS).try(:reorder!)
        schema.reorder!
        schema[EXTENSIONS] = extensions
      end
    end
  end
end


text:
<q-grid [caption]="title"
        interactionMode="readonly"
        [rows]="rows | async">
        <q-grid-columns generation="deep">
                <q-grid-column key="test"
                               title="Test Detached"
                               [index]="0">
                        <ng-template for="body">
                                <button mat-button
                                        (click)="testAttached()">
                                        Alert
                                </button>
                        </ng-template>
                </q-grid-column>
        </q-grid-columns>
</q-grid>


text:
<?php

/**
 * TCallbackEventParameter class.
 *
 * The TCallbackEventParameter provides the parameter passed during the callback
 * request in the {@link getCallbackParameter CallbackParameter} property. The
 * callback response content (e.g. new HTML content) must be rendered
 * using an THtmlWriter obtained from the {@link getNewWriter NewWriter}
 * property, which returns a <b>NEW</b> instance of TCallbackResponseWriter.
 *
 * Each instance TCallbackResponseWriter is associated with a unique
 * boundary delimited. By default each panel only renders its own content.
 * To replace the content of ONE panel with that of rendered from multiple panels
 * use the same writer instance for the panels to be rendered.
 *
 * The response data (i.e., passing results back to the client-side
 * callback handler function) can be set using {@link setResponseData ResponseData} property.
 *
 * @author Wei Zhuo <weizhuo[at]gamil[dot]com>
 * @version $Id: TActivePageAdapter.php 1648 2007-01-24 05:52:22Z wei $
 * @package System.Web.UI.ActiveControls
 * @since 3.1
 */
class TCallbackEventParameter extends TEventParameter
{
	/**
	 * @var THttpResponse output content.
	 */
	private $_response;
	/**
	 * @var mixed callback request parameter.
	 */
	private $_parameter;

	/**
	 * Creates a new TCallbackEventParameter.
	 */
	public function __construct($response, $parameter)
	{
		$this->_response = $response;
		$this->_parameter = $parameter;
	}

	/**
	 * @return TCallbackResponseWriter holds the response content.
	 */
	public function getNewWriter()
	{
		return $this->_response->createHtmlWriter(null);
	}

	/**
	 * @return mixed callback request parameter.
	 */
	public function getCallbackParameter()
	{
		return $this->_parameter;
	}

	/**
	 * @param mixed callback response data.
	 */
	public function setResponseData($value)
	{
		$this->_response->getAdapter()->setResponseData($value);
	}

	/**
	 * @return mixed callback response data.
	 */
	public function getResponseData()
	{
		return $this->_response->getAdapter()->getResponseData();
	}
}


text:
package com.meetisan.meetisan.notifications;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

import com.meetisan.meetisan.R;

public class TagRejectedActivity extends Activity {
	private static final String TAG = TagRejectedActivity.class.getSimpleName();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_notification_create_tag_rejected);
		initTitle();
	}

	private void initTitle() {
		TextView textView = (TextView) findViewById(R.id.tv_title_text);
		textView.setText(R.string.tag_rejected);
		ImageButton mBackBtn = (ImageButton) findViewById(R.id.btn_title_left);
		mBackBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onBackPressed();
			}
		});
		mBackBtn.setVisibility(View.VISIBLE);
	}
}


text:
require 'spec/rake/spectask'

desc "Run the specs under spec"
Spec::Rake::SpecTask.new do |t|
  t.spec_opts = ['--options', "spec/spec.opts"]
  t.spec_files = FileList['spec/**/*_spec.rb']
end

namespace :spec do
  desc "Run specs with RCov"
  Spec::Rake::SpecTask.new('rcov') do |t|
    t.spec_files = FileList['spec/**/*_spec.rb']
    t.rcov = true
    t.rcov_opts = ['--exclude', '\/Library\/Ruby']
  end
end


text:
/*
 * Tests for the sqlite database manager
 */

package database

import (
	"database/sql"
	"errors"
	"os"
	"testing"

	sqlite "github.com/mattn/go-sqlite3"
	cmpb "github.com/nguyenmq/ytbox-go/internal/proto/common"
)

const (
	testDbLocation = "/tmp/test_db.db"
	testRoomId     = 1
	testRoomName   = "Wizard's Keep"
	testSongId     = 1
	testUserId     = 1
	testUserName   = "Zedd"
)

var testSong = cmpb.Song{"Bags!!", 0, testUserName, testUserId, cmpb.ServiceType_Youtube, "0xdeadbeef", testRoomId}

func initDatabase() (*SqliteManager, error) {
	dbManager := new(SqliteManager)
	err := dbManager.Init(testDbLocation)
	return dbManager, err
}

func cleanUp(dbManager *SqliteManager) {
	if dbManager != nil {
		dbManager.Close()
	}

	os.Remove(testDbLocation)
}

func TestInit_when_success(t *testing.T) {
	dbManager, err := initDatabase()

	if err != nil {
		t.Error("Error when initializing the database", err)
	}

	cleanUp(dbManager)
}

func TestAddRoom_when_success(t *testing.T) {
	dbManager, err := initDatabase()

	if err != nil {
		t.Error("Error when initializing the database", err)
	}

	expectedRoomName := testRoomName
	expectedRoomId := uint32(testRoomId)
	actualRoomData, err := dbManager.AddRoom(testRoomName)
	if err != nil {
		t.Error("Error when adding new room", err)
	}

	if actualRoomData.Room.Name != expectedRoomName {
		t.Error("DB manager should return expected room name", expectedRoomName, "but was", actualRoomData.Room.Name)
	}

	if actualRoomData.Room.Id != expectedRoomId {
		t.Error("DB manager should return expected room id", expectedRoomId, "but was", actualRoomData.Room.Id)
	}

	cleanUp(dbManager)
}

func TestAddUser_when_success(t *testing.T) {
	dbManager, err := initDatabase()

	if err != nil {
		t.Error("Error when initializing the database", err)
	}

	_, err = dbManager.AddRoom(testRoomName)
	if err != nil {
		t.Error("Error when adding new room", err)
	}

	userData, err := dbManager.AddUser(testUserName, testRoomId)
	if err != nil {
		t.Error("Error when adding new user", err)
	}

	expectedUserName := testUserName
	if userData.User.Username != expectedUserName {
		t.Error("Username should be", expectedUserName, "but was", userData.User.Username)
	}

	expectedUserId := uint32(testUserId)
	if userData.User.UserId != expectedUserId {
		t.Error("User id should be", expectedUserId, "but was", userData.User.UserId)
	}

	expectedRoomId := uint32(testRoomId)
	if userData.User.RoomId != expectedRoomId {
		t.Error("User's room id should be", expectedRoomId, "but was", userData.User.RoomId)
	}

	cleanUp(dbManager)
}

func TestAddSong_when_success(t *testing.T) {
	dbManager, err := initDatabase()

	if err != nil {
		t.Error("Error when initializing the database", err)
	}

	_, err = dbManager.AddRoom(testRoomName)
	if err != nil {
		t.Error("Error when adding new room", err)
	}

	_, err = dbManager.AddUser(testUserName, testRoomId)
	if err != nil {
		t.Error("Error when adding new user", err)
	}

	actualSong := testSong
	err = dbManager.AddSong(&actualSong)
	if err != nil {
		t.Error("Error when adding new song", err)
	}

	if actualSong.SongId != testSongId {
		t.Error("DB manager should set the song id to", testSongId)
	}

	cleanUp(dbManager)
}

func TestAddSong_whenRoomDoesNotExist_failToAdd(t *testing.T) {
	dbManager, err := initDatabase()

	if err != nil {
		t.Error("Error when initializing the database", err)
	}

	_, err = dbManager.AddRoom(testRoomName)
	if err != nil {
		t.Error("Error when adding new room", err)
	}

	_, err = dbManager.AddUser(testUserName, testRoomId)
	if err != nil {
		t.Error("Error when adding new user", err)
	}

	actualSong := testSong
	actualSong.RoomId = testRoomId + 1
	err = dbManager.AddSong(&actualSong)
	if err == nil {
		t.Error("DB manager did not return an error when adding a song with a room id that doesn't exist")
	}

	if err.(sqlite.Error).Code != sqlite.ErrConstraint {
		t.Error("DB manager did not fail with a constraint mismatch error:", err.(sqlite.Error))
	}

	cleanUp(dbManager)
}

func TestGetRoomByName_when_success(t *testing.T) {
	dbManager, err := initDatabase()

	if err != nil {
		t.Error("Error when initializing the database", err)
	}

	_, err = dbManager.AddRoom(testRoomName)
	if err != nil {
		t.Error("Error when adding new room", err)
	}

	expectedRoomName := testRoomName
	expectedRoomId := uint32(testRoomId)

	roomData, err := dbManager.GetRoomByName(expectedRoomName)
	if err != nil {
		t.Error("Get room by name failed with error:", err)
	}

	if roomData.Room.Name != expectedRoomName {
		t.Error("DB manager did not fetch the correct room name:", roomData.Room.Name)
	}

	if roomData.Room.Id != expectedRoomId {
		t.Error("DB manager did not fetch the correct room id:", roomData.Room.Id)
	}

	cleanUp(dbManager)
}

func TestGetRoomByName_whenRoomDoesNotExist_returnsNil(t *testing.T) {
	dbManager, err := initDatabase()

	if err != nil {
		t.Error("Error when initializing the database", err)
	}

	expectedRoomName := testRoomName
	roomData, err := dbManager.GetRoomByName(expectedRoomName)
	if !errors.Is(err, sql.ErrNoRows) {
		t.Error("DB manager should return no rows error when room doesn't exist")
	}

	if roomData != nil {
		t.Error("DB manager should return nil room data when the room doesn't exist")
	}

	cleanUp(dbManager)
}


text:
Set-Alias .<  Read-EntireFile
Set-Alias ~>  Copy-Files
Set-Alias =>  Copy-FilesAndStructure
Set-Alias .// Replace-InFile
Set-Alias =// Replace-InFiles
Set-Alias ?:  Invoke-Ternary
Set-Alias ??  Coalesce

# -- PUBLIC ---------------------------------------

function Read-EntireFile([string]$src) {
    return [string]::Join("`n", (Get-Content -Raw $src))
}

function Copy-Files([string]$srcPattern, [string]$destPattern) {
    return copy-filesFromPattern $srcPattern $destPattern
}

function Copy-FilesAndStructure([string]$srcPattern, [string]$destPattern) {
    return copy-filesFromPattern $srcPattern $destPattern -preserveStructure
}

function Replace-InFile([string]$file, [string]$pattern, [string]$replacement) {
    Replace-InFiles @{$file=$file} @{$pattern=$replacement}
}

function Replace-InFiles([hashtable]$files, [hashtable]$replacements) {

    foreach($source in $files.Keys) {
        $text = .< $files[$source]

        foreach($pattern in $replacements.Keys) {
            $replacement = $replacements[$pattern]
            $text = [regex]::Replace($text, $pattern, $replacement, "singleline")
        }

        $destination = $files[$source]
        set-content -path $destination -value "$text" -force
    }
}

# shorthand if-then-else function
# borrowed from: http://blogs.msdn.com/b/powershell/archive/2006/12/29/dyi-ternary-operator.aspx
function Invoke-Ternary([scriptblock]$decider, [scriptblock]$ifTrue, [scriptblock]$ifFalse) {
   if (&$decider) {
      &$ifTrue
   } else {
      &$ifFalse
   }
}

# coalesce function:
# borrowed from: http://stackoverflow.com/questions/10623907/null-coalescing-in-powershell
function Coalesce($a, $b) { if ($a -ne $null) { $a } else { $b } }

# -- PRIVATE --------------------------------------

# copy files specified by ANT styled paths
# ref: http://ant.apache.org/manual/dirtasks.html#patterns
function copy-filesFromPattern([string]$srcPattern, [string]$destPattern, [switch]$preserveStructure) {
    $baseDir = get-basePathFromPattern $srcPattern
    get-filesFromPattern $srcPattern | foreach-object {
        $path = ?: { $preserveStructure } { return $_.FullName.Replace($baseDir, "") } { return "" }
        $destination = ?: { [System.IO.Path]::HasExtension($destPattern) } { return $destPattern } { return join-path $destPattern $path }
        $destDir = [System.IO.Path]::GetDirectoryName($destination)

        if (!(test-path $destDir)) {
            new-item $destDir -type directory -force
        }

        write-host "Copying $_ -> $destination"
        copy-item $_.FullName -destination $destination -recurse -force
    }
}

function get-filesFromPattern($pattern) {
    $regex = convert-antSearchPatternToRegex $pattern
    $baseDir = get-basePathFromPattern $pattern
    return get-filesFromRegex $baseDir $regex
}

function get-basePathFromPattern($pattern) {
    $separatorIndex = 0

    for($i=0; $i -lt $pattern.length; $i++) {
        $char = $pattern[$i]
        if ($char -match '(\\|/)') { $separatorIndex = $i }
        if ($char -match '(\*|\?)') { break }
    }

    $base = $pattern.substring(0, $separatorIndex + 1)
    return $base
}

# ref: http://ant.apache.org/manual/dirtasks.html#patterns
function convert-antSearchPatternToRegex($searchPattern) {

    # shorthand: /dir/subdir/ is interpreted as /dir/subdir/**
    if (test-isDirectoryPattern $searchPattern) {
        $searchPattern += "**"
    }

    $regex = "^{0}`$" -f [regex]::Escape($searchPattern)
    $regex = $regex.replace("\?", ".+").replace("\*\*\\", ".*").replace("\*\*", ".*").replace("\*", "[^\\]*")
    return $regex
}

function get-filesFromRegex($baseDir, $regex) {
    return get-childitem $baseDir -recurse | where-object {
        !$_.PsIsContainer -and
        $_.FullName -match $regex
    }
}

function test-isDirectoryPattern($pattern) {
    return $pattern.EndsWith("/") -or $pattern.EndsWith("\")
}

# -- EXPORT --------------------------------------
Export-ModuleMember `
    -function Read-EntireFile, Copy-Files, Copy-FilesAndStructure, Replace-InFile, Replace-InFiles, Invoke-Ternary, Coalesce `
    -alias .<, ~>, =>, .//, =//, ?:, ??


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="search.css"/>

Loading...

  value
  Steinberg::Vst::NoteExpressionValueEvent

  valueDesc
  Steinberg::Vst::NoteExpressionTypeInfo

  valueNormalized
  Steinberg::Vst::Parameter

  velocity

    Steinberg::Vst::NoteOnEvent::velocity()
    Steinberg::Vst::NoteOffEvent::velocity()

  vendor

    Steinberg::PFactoryInfo::vendor()
    Steinberg::PClassInfo2::vendor()
    Steinberg::PClassInfoW::vendor()
    Steinberg::Vst::RepresentationInfo::vendor()

  version

    Steinberg::PClassInfo2::version()
    Steinberg::PClassInfoW::version()
    Steinberg::Vst::RepresentationInfo::version()

  visiblePresetBrowserViewController
  Steinberg::Vst::InterAppAudio::PresetManager

  visibleSavePresetViewController
  Steinberg::Vst::InterAppAudio::PresetManager

  VKEY_FIRST_ASCII
  Steinberg

  VKEY_FIRST_CODE
  Steinberg

  VKEY_LAST_CODE
  Steinberg

  vstPlug
  Steinberg::Vst::VstTestBase

Searching...

No Matches


text:
This sample shows a method of sharing a SharePoint site calendar with any calendar client via iCalendar.  The sample reads events from a SharePoint calendar and converts those events
into a standard iCalendar format utilizing SharePoint CSOM, Azure Active Directory Graph Client Library, SQL Azure via Entity Framework,
and Azure Web Apps.

### Full walkthrough ###

A full walkthrough of the development process can be found at -
[http://blog.jonathanhuss.com/sharing-a-sharepoint-online-calendar-via-icalendar/](http://blog.jonathanhuss.com/sharing-a-sharepoint-online-calendar-via-icalendar/)

### Applies to ###
- Office 365 / SharePoint Online

### Prerequisites ###
N/A

### Solution ###
Solution | Author(s)
---------|----------
BusinessApps.RemoteCalendarAccess | Jonathan Huss (**Microsoft**)

### Version history ###

Version  | Date | Comments
---------| -----| --------
1.0 | July 20th, 2015 | Initial Release

### Disclaimer ###
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

----------

### Creating the iCalendar ###

The basic flow in this sample is as follows:

1.  Calendar client requests calendar via GUID based URL from Azure Web App.
2.  Application retrieves user and SharePoint calendar connected to GUID from SQL Azure Database using Entity Framework.
3.  Application looks up user in Azure Active Directory and confirms user account exists and is active.
4.  Application gathers events from SharePoint calendar via CSOM and converts them to iCalendar format.
5.  iCalendar file is returned to calendar client.

The MVC action that does the bulk of the work looks like this:

```
public FileResult Index(Guid? Id)
{
    if (Id == null)
        return AccessDenied();

    RemoteCalendarAccessManager manager = new RemoteCalendarAccessManager();
    BLM.RemoteCalendarAccess remoteCalendarAccess = manager.GetRemoteCalendarAccess(Id.Value);

    if (remoteCalendarAccess == null)
        return AccessDenied();

    AzureActiveDirectory azureAD = new AzureActiveDirectory();

    IUser user = null;
    try
    {
        user = azureAD.GetUser(remoteCalendarAccess.UserId).Result;
    }
    catch (AggregateException e)
    {
        if (!e.InnerExceptions.Any(i => i.Message == "User " + remoteCalendarAccess.UserId + " not found."))
            throw;
    }

    if (user == null || user.AccountEnabled == false)
        return AccessDenied();

    manager.UpdateLastAccessTime(remoteCalendarAccess);

    Uri uri = new Uri(remoteCalendarAccess.SiteAddress);
    string realm = TokenHelper.GetRealmFromTargetUrl(uri);
    var token = TokenHelper.GetAppOnlyAccessToken("00000003-0000-0ff1-ce00-000000000000", uri.Authority, realm);
    ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(uri.ToString(), token.AccessToken);

    clientContext.Load(clientContext.Web.Lists);
    clientContext.ExecuteQuery();

    List list = clientContext.Web.Lists.Where(l => l.Id == remoteCalendarAccess.CalendarId).First();

    if (list == null)
        return AccessDenied();

    ListItemCollection items = list.GetItems(CamlQuery.CreateAllItemsQuery());
    clientContext.Load(items);

    clientContext.Load(clientContext.Web);
    clientContext.Load(clientContext.Web.RegionalSettings);
    clientContext.Load(clientContext.Web.RegionalSettings.TimeZone);
    clientContext.Load(clientContext.Web, w => w.Title);

    clientContext.ExecuteQuery();

    Calendar calendar = new Calendar();
    calendar.Title = clientContext.Web.Title + " - " + list.Title;
    calendar.Timezone = Timezone.Parse(clientContext.Web.RegionalSettings.TimeZone.Description);
    calendar.Events = items.Select(i => Event.Parse(i)).ToList<Event>();

    FileContentResult result = File(System.Text.Encoding.Default.GetBytes(calendar.ToString()), "text/calendar", "calendar.ics");

    return result;
}
```

### Events ###

Converting SharePoint events to iCalendar events is really fairly straightfoward.  It's just a matter of taking the SharePoint event data and injecting it into the iCalendar format.  The iCalendar
RFC can be found here:  [http://tools.ietf.org/html/rfc5545](http://tools.ietf.org/html/rfc5545).  The process for doing so looks like this:

```
public string ToString(List<Event> Events)
{
    StringBuilder builder = new StringBuilder();

    builder.AppendLine("BEGIN:VEVENT");
    builder.AppendLine("SUMMARY:" + CleanText(Title));
    builder.AppendLine("DTSTAMP:" + Created.ToString("yyyyMMddTHHmmssZ"));
    builder.AppendLine("DESCRIPTION:" + CleanText(Description));
    builder.AppendLine("LOCATION:" + CleanText(Location));
    builder.AppendLine("CATEGORIES:" + CleanText(Category));
    builder.AppendLine("UID:" + UID);
    builder.AppendLine("STATUS:CONFIRMED");
    builder.AppendLine("LAST-MODIFIED:" + LastModified.ToString("yyyyMMddTHHmmssZ"));

    if(AllDayEvent)
    {
        builder.AppendLine("DTSTART;VALUE=DATE:" + EventDate.ToString("yyyyMMdd"));

        double days = Math.Round(((Double)Duration / (double)(60 * 60 * 24)));
        builder.AppendLine("DTEND;VALUE=DATE:" + EventDate.AddDays(days).ToString("yyyyMMdd"));
    }
    else
    {
        builder.AppendLine("DTSTART:" + EventDate.ToString("yyyyMMddTHHmmssZ"));
        builder.AppendLine("DTEND:" + EventDate.AddSeconds(Duration).ToString("yyyyMMddTHHmmssZ"));
    }

    IEnumerable<Event> deletedEvents = Events.Where(e => e.MasterSeriesItemID == ID && e.EventType == EventType.Deleted);
    foreach(Event deletedEvent in deletedEvents)
    {
        if(AllDayEvent)
            builder.AppendLine("EXDATE;VALUE=DATE:" + deletedEvent.RecurrenceID.ToString("yyyyMMdd"));
        else
            builder.AppendLine("EXDATE:" + deletedEvent.RecurrenceID.ToString("yyyyMMddTHHmmssZ"));
    }

    if(RecurrenceID != DateTime.MinValue && EventType == EventType.Exception) //  Event is exception to recurring item
    {
        if(AllDayEvent)
            builder.AppendLine("RECURRENCE-ID;VALUE=DATE:" + RecurrenceID.ToString("yyyyMMdd"));
        else
            builder.AppendLine("RECURRENCE-ID:" + RecurrenceID.ToString("yyyyMMddTHHmmssZ"));
    }
    else if (Recurrence && !RecurrenceData.Contains("V3RecurrencePattern"))
    {
        RecurrenceHelper recurrenceHelper = new RecurrenceHelper();
        builder.AppendLine(recurrenceHelper.BuildRecurrence(RecurrenceData, EndDate));
    }

    if(EventType == CalendarModel.EventType.Exception)
    {
        List<Event> exceptions = Events.Where(e => e.MasterSeriesItemID == MasterSeriesItemID).OrderBy(e => e.Created).ToList<Event>();
        builder.AppendLine("SEQUENCE:" + (exceptions.IndexOf(this) + 1));
    }
    else
        builder.AppendLine("SEQUENCE:0");

    builder.AppendLine("BEGIN:VALARM");
    builder.AppendLine("ACTION:DISPLAY");
    builder.AppendLine("TRIGGER:-PT10M");
    builder.AppendLine("DESCRIPTION:Reminder");
    builder.AppendLine("END:VALARM");

    builder.AppendLine("END:VEVENT");

    return builder.ToString();
}

private string CleanText(string text)
{
    if (text != null)
        text = text.Replace(""", "DQUOTE")
                    .Replace("\", "\\")
                    .Replace(",", "\,")
                    .Replace(":", "":"")
                    .Replace(";", "\;")
                    .Replace("rn", "\n")
                    .Replace("n", "\n");

    return text;
}
```

### Using the iCalendar ###

The system generates a unique URL for the particular user and particular calendar.  Once the user has that URL,
they can then load it into OWA.  The following image shows a SharePoint calendar.  It has a single event
 on the 9th, a weekly recurring event that occurs every Tuesday, and an exception to the recurring event
 on the 29th.

![Image of SharePoint calendar](http://blog.jonathanhuss.com/wp-content/uploads/2015/07/image14.png)

Using the iCalendar application, that same calendar loaded into OWA looks like this:

![Image of SharePoint calendar above in OWA](http://blog.jonathanhuss.com/wp-content/uploads/2015/07/image19.png)

### Bonus! ###

If the user syncs their Office 365 e-mail to their mobile devices, their OWA calendar can be automatically
synced as well.  This means that they can easily add any SharePoint calendar to their mobile device with very
little effort.

<img src="https://telemetry.sharepointpnp.com/pnp/samples/BusinessApps.remoteCalendarAccess" />


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PcapDotNet.Base.Test
{
    /// <summary>
    /// Summary description for SequenceTest
    /// </summary>
    [TestClass]
    public class SequenceTest
    {
        /// <summary>
        /// Gets or sets the test context which provides
        /// information about and functionality for the current test run.
        /// </summary>
        public TestContext TestContext { get; set; }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        public void GetHashCodeNullValue1Test()
        {
            Assert.AreEqual(1.GetHashCode(), Sequence.GetHashCode(null, 1));
        }

        [TestMethod]
        public void GetHashCodeNullValue2Test()
        {
            Assert.AreEqual(1.GetHashCode(), Sequence.GetHashCode(1, null));
        }

        [TestMethod]
        public void GetHashCodeNullValue3Test()
        {
            Assert.AreEqual(Sequence.GetHashCode(1, 2), Sequence.GetHashCode(1, 2, null));
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException), AllowDerivedTypes = false)]
        public void GetHashCodeNullValuesTest()
        {
            Assert.IsNotNull(Sequence.GetHashCode(null));
            Assert.Fail();
        }
    }
}