text:
namespace System.ServiceModel.Syndication
{
    public class ReferencedCategoriesDocument : CategoriesDocument
    {
        public ReferencedCategoriesDocument()
        {
        }

        public ReferencedCategoriesDocument(Uri link) : base()
        {
            Link = link ?? throw new ArgumentNullException(nameof(link));
        }

        public Uri Link { get; set; }

        internal override bool IsInline => false;
    }
}


text:
let promise = new Promise((fulfill, reject) => {
  setTimeout(() => {
    fulfill('FULFILLED!');
  }, 300);
});

promise.then((msg) => console.log(msg));

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Acme\BugBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
use FOS\UserBundle\Controller\SecurityController as BaseController;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SecurityController extends BaseController
{

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE467_Use_of_sizeof_on_Pointer_Type__short_18.c
Label Definition File: CWE467_Use_of_sizeof_on_Pointer_Type.label.xml
Template File: point-flaw-18.tmpl.c
*/
/*
 * @description
 * CWE: 467 Use of sizeof() on a Pointer Type
 * Sinks: short
 *    GoodSink: Use sizeof() the data type
 *    BadSink : Use sizeof() the pointer and not the data type
 * Flow Variant: 18 Control flow: goto statements
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

void CWE467_Use_of_sizeof_on_Pointer_Type__short_18_bad()
{
    goto sink;
sink:
    {
        short * badShort = NULL;
        /* FLAW: Using sizeof the pointer and not the data type in malloc() */
        badShort = (short *)malloc(sizeof(badShort));
        if (badShort == NULL) {exit(-1);}
        *badShort = 5;
        printShortLine(*badShort);
        free(badShort);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() reverses the blocks on the goto statement */
static void good1()
{
    goto sink;
sink:
    {
        short * goodShort = NULL;
        /* FIX: Using sizeof the data type in malloc() */
        goodShort = (short *)malloc(sizeof(*goodShort));
        if (goodShort == NULL) {exit(-1);}
        *goodShort = 6;
        printShortLine(*goodShort);
        free(goodShort);
    }
}

void CWE467_Use_of_sizeof_on_Pointer_Type__short_18_good()
{
    good1();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE467_Use_of_sizeof_on_Pointer_Type__short_18_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE467_Use_of_sizeof_on_Pointer_Type__short_18_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text: require File.join(File.dirname(__FILE__), '..', 'lib', 'saucerly')


text:
<?php

/**
 * Interface import
 */
require_once('HTTPFetcher.php');

/**
 * This class implements a plain, hand-built socket-based fetcher
 * which will be used in the event that CURL is unavailable.
 *
 * @package Yadis
 */
class Services_Yadis_PlainHTTPFetcher extends Services_Yadis_HTTPFetcher {
    function get($url, $extra_headers = null)
    {
        if (!$this->allowedURL($url)) {
            trigger_error("Bad URL scheme in url: " . $url,
                          E_USER_WARNING);
            return null;
        }

        $redir = true;

        $stop = time() + $this->timeout;
        $off = $this->timeout;

        while ($redir && ($off > 0)) {

            $parts = parse_url($url);

            $specify_port = true;

            // Set a default port.
            if (!array_key_exists('port', $parts)) {
                $specify_port = false;
                if ($parts['scheme'] == 'http') {
                    $parts['port'] = 80;
                } elseif ($parts['scheme'] == 'https') {
                    $parts['port'] = 443;
                } else {
                    trigger_error("fetcher post method doesn't support " .
                                  " scheme '" . $parts['scheme'] .
                                  "', no default port available",
                                  E_USER_WARNING);
                    return null;
                }
            }

            $host = $parts['host'];

            if ($parts['scheme'] == 'https') {
                $host = 'ssl://' . $host;
            }

            $user_agent = "PHP Yadis Library Fetcher";

            $headers = array(
                             "GET ".$parts['path'].
                             (array_key_exists('query', $parts) ?
                              "?".$parts['query'] : "").
                                 " HTTP/1.0",
                             "User-Agent: $user_agent",
                             "Host: ".$parts['host'].
                                ($specify_port ? ":".$parts['port'] : ""),
                             "Port: ".$parts['port']);

            $errno = 0;
            $errstr = '';

            if ($extra_headers) {
                foreach ($extra_headers as $h) {
                    $headers[] = $h;
                }
            }

            @$sock = fsockopen($host, $parts['port'], $errno, $errstr,
                               $this->timeout);
            if ($sock === false) {
                return false;
            }

            stream_set_timeout($sock, $this->timeout);

            fputs($sock, implode("\r\n", $headers) . "\r\n\r\n");

            $data = "";
            while (!feof($sock)) {
                $data .= fgets($sock, 1024);
            }

            fclose($sock);

            // Split response into header and body sections
            list($headers, $body) = explode("\r\n\r\n", $data, 2);
            $headers = explode("\r\n", $headers);

            $http_code = explode(" ", $headers[0]);
            $code = $http_code[1];

            if (in_array($code, array('301', '302'))) {
                $url = $this->_findRedirect($headers);
                $redir = true;
            } else {
                $redir = false;
            }

            $off = $stop - time();
        }

        $new_headers = array();

        foreach ($headers as $header) {
            if (preg_match("/:/", $header)) {
                list($name, $value) = explode(": ", $header, 2);
                $new_headers[$name] = $value;
            }

        }

        return new Services_Yadis_HTTPResponse($url, $code, $new_headers, $body);
    }

    function post($url, $body, $extra_headers = null)
    {
        if (!$this->allowedURL($url)) {
            trigger_error("Bad URL scheme in url: " . $url,
                          E_USER_WARNING);
            return null;
        }

        $parts = parse_url($url);

        $headers = array();

        $post_path = $parts['path'];
        if (isset($parts['query'])) {
            $post_path .= '?' . $parts['query'];
        }

        $headers[] = "POST ".$post_path." HTTP/1.0";
        $headers[] = "Host: " . $parts['host'];
        $headers[] = "Content-type: application/x-www-form-urlencoded";
        $headers[] = "Content-length: " . strval(strlen($body));

        if ($extra_headers &&
            is_array($extra_headers)) {
            $headers = array_merge($headers, $extra_headers);
        }

        // Join all headers together.
        $all_headers = implode("\r\n", $headers);

        // Add headers, two newlines, and request body.
        $request = $all_headers . "\r\n\r\n" . $body;

        // Set a default port.
        if (!array_key_exists('port', $parts)) {
            if ($parts['scheme'] == 'http') {
                $parts['port'] = 80;
            } elseif ($parts['scheme'] == 'https') {
                $parts['port'] = 443;
            } else {
                trigger_error("fetcher post method doesn't support scheme '" .
                              $parts['scheme'] .
                              "', no default port available",
                              E_USER_WARNING);
                return null;
            }
        }

        if ($parts['scheme'] == 'https') {
            $parts['host'] = sprintf("ssl://%s", $parts['host']);
        }

        // Connect to the remote server.
        $errno = 0;
        $errstr = '';

        $sock = fsockopen($parts['host'], $parts['port'], $errno, $errstr,
                          $this->timeout);

        if ($sock === false) {
            trigger_error("Could not connect to " . $parts['host'] .
                          " port " . $parts['port'],
                          E_USER_WARNING);
            return null;
        }

        stream_set_timeout($sock, $this->timeout);

        // Write the POST request.
        fputs($sock, $request);

        // Get the response from the server.
        $response = "";
        while (!feof($sock)) {
            if ($data = fgets($sock, 128)) {
                $response .= $data;
            } else {
                break;
            }
        }

        // Split the request into headers and body.
        list($headers, $response_body) = explode("\r\n\r\n", $response, 2);

        $headers = explode("\r\n", $headers);

        // Expect the first line of the headers data to be something
        // like HTTP/1.1 200 OK.  Split the line on spaces and take
        // the second token, which should be the return code.
        $http_code = explode(" ", $headers[0]);
        $code = $http_code[1];

        $new_headers = array();

        foreach ($headers as $header) {
            if (preg_match("/:/", $header)) {
                list($name, $value) = explode(": ", $header, 2);
                $new_headers[$name] = $value;
            }

        }

        return new Services_Yadis_HTTPResponse($url, $code,
                                               $headers, $response_body);
    }
}

?>


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" />

    <title>sparknlp_jsl.updateModels — Spark NLP 4.0.0 documentation</title>

  <link href="../../../../static/styles/theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">
<link href="../../../../static/styles/pydata-sphinx-theme.css?digest=1e1de1a1873e13ef5536" rel="stylesheet">

  <link rel="stylesheet"
    href="../../../../static/vendor/fontawesome/6.1.2/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-brands-400.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="../../../../static/vendor/fontawesome/6.1.2/webfonts/fa-regular-400.woff2">

    <link rel="stylesheet" type="text/css" href="../../../../static/pygments.css" />
    <link rel="stylesheet" type="text/css" href="../../../../static/graphviz.css" />
    <link rel="stylesheet" type="text/css" href="../../../../static/css/custom.css" />

  <link rel="preload" as="script" href="../../../../static/scripts/pydata-sphinx-theme.js?digest=1e1de1a1873e13ef5536">

    <link rel="shortcut icon" href="../../../../static/fav.ico"/>
    <link rel="index" title="Index" href="../../../../genindex.html" />
    <link rel="search" title="Search" href="../../../../search.html" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="docsearch:language" content="en">

  <input type="checkbox" class="sidebar-toggle" name="__primary" id="__primary">

  <input type="checkbox" class="sidebar-toggle" name="__secondary" id="__secondary">

<form class="bd-search d-flex align-items-center" action="../../../../search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
  Ctrl+K
</form>

        Site Navigation

                        Getting Started

                        API Reference

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

<button class="btn btn-sm navbar-btn search-button search-button__button" title="Search" data-toggle="tooltip">

</button>

        Site Navigation

                        Getting Started

                        API Reference

sparknlp_jsl.updateModels#

Helper class that allow us to update pretrained models located in the cache folder

Module Contents#

Classes#

UpdateModels

class UpdateModels[source]#

static updateCacheModels(cache_folder='')[source]#

This method refreshes all pretrained models located in the cache pretrained folder.

This method check what are the existing models in the cache pretrained folder and check if there is a new
version for that model.If there are a new model then this model will be downloaded

Parameters:

cache_folderstr

Path where the models will be refreshed. i.e ("hdfs:..","file:…")

static updateModels(date_cutoff, cache_folder='')[source]#

This method download all new pretrained models since the date_cutoff.

Parameters:

date_cutoff:str

Date since

It is the date from which the new models will be downloaded.

cache_folderstr

Path where the models will be downloaded. i.e ("hdfs:..","file:…")

     On this page

   Module Contents

     Classes

         UpdateModels

           UpdateModels.updateCacheModels()

           UpdateModels.updateModels()

       UpdateModels

         updateCacheModels

         updateModels

         Show Source

    © Copyright 2022, John Snow Labs.

Created using Sphinx 5.3.0.


text:
import React from 'react';
import { Badge } from 'reactstrap';

function Example(props) {
  return (
    <div>
      <Badge href="#" color="primary">
        Primary
      </Badge>
      <Badge href="#" color="secondary">
        Secondary
      </Badge>
      <Badge href="#" color="success">
        Success
      </Badge>
      <Badge href="#" color="danger">
        Danger
      </Badge>
      <Badge href="#" color="warning">
        Warning
      </Badge>
      <Badge href="#" color="info">
        Info
      </Badge>
      <Badge href="#" color="light">
        Light
      </Badge>
      <Badge href="#" color="dark">
        Dark
      </Badge>
    </div>
  );
}

export default Example;


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

  <title>Nicholas Matragkas - Nicholas Matragkas</title>

  <meta name="author" content="Nicholas Matragkas" />

  <link rel="alternate" type="application/rss+xml" title="Nicholas Matragkas - Nicholas Matragkas" href="/feed.xml" />

  <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.0/css/font-awesome.min.css" />

      <link rel="stylesheet" href="/css/bootstrap.min.css" />

      <link rel="stylesheet" href="/css/bootstrap-social.css" />

      <link rel="stylesheet" href="/css/main.css" />

      <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />

      <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" />

  <meta property="og:title" content="Nicholas Matragkas" />

  <meta property="og:description" content="I am a lecturer in the [Department of Computer Science](https://www.cs.york.ac.uk/) at the University of York, where I teach and research software engineering. From July 2015 until August 2018, I was a lecturer at the [University of Hull](https://www.hull.ac.uk/). I received my PhD in Computer Science from the University of York in...">

  <meta property="og:type" content="website" />

  <meta property="og:url" content="http://localhost:4000/" />
  <link rel="canonical" href="http://localhost:4000/" />

  <meta property="og:image" content="http://localhost:4000/img/avatar-icon.png" />

  <meta name="twitter:card" content="summary" />
  <meta name="twitter:site" content="@" />
  <meta name="twitter:creator" content="@" />

  <meta name="twitter:title" content="Nicholas Matragkas" />

  <meta name="twitter:description" content="I am a lecturer in the [Department of Computer Science](https://www.cs.york.ac.uk/) at the University of York, where I teach and research software engineering. From July 2015 until August 2018, I was a lecturer at the [University of Hull](https://www.hull.ac.uk/). I received my PhD in Computer Science from the University of York in...">

  <meta name="twitter:image" content="http://localhost:4000/img/avatar-icon.png" />

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar">
        Toggle navigation

      </button>

        Nicholas Matragkas

Publications

Projects

Teaching

Contact

Looking of a PhD?

I am a lecturer in the Department of Computer Science at the University of York, where I teach and research software engineering. From July 2015 until August 2018, I was a lecturer at the University of Hull. I received my PhD in Computer Science from the University of York in 2011 under the supervision of Richard Paige and Kiran Fernandes.

My research falls into the broad area of systems and software engineering. My goal is to help engineers produce more reliable systems in an economic and timely manner. My main line of research is in automated and model-driven engineering. Beyond automated and model-driven engineering I am interested in data analytics for software engineering, software quality and testing, and in technologies for persisting and analysing large volumes of heterogeneous data. In my research I integrate knowledge  from fields as diverse as model-driven engineering, machine learning, distributed systems, and software analysis and testing.

If you are interested in doing a PhD with me, please read on.

                Email me

                Twitter

                LinkedIn

                Phone

      Nicholas Matragkas
       •
      2021

      Theme by
      beautiful-jekyll


text:
import React from "react";
import { Movie } from "./Movie.js";
import "../App.css";
import { connect } from "react-redux";

const MovieBoard = ({ movies }) => {
  let moviesList = (

      {movies.map(movie => {
        return <Movie {...movie.data} key={movie.data.imdbID} />;
      })}

  );
  return (

{moviesList}

  );
};

const mapStateToProps = state => {
  const { movies } = state;
  return {
    movies
  };
};

export default connect(mapStateToProps)(MovieBoard);


text:
all:
	zip -j9 --filesync Play.alfredworkflow src/*


text:
Sms Authentication Service
==========================

### Additionnal resources:

1. https://www.twilio.com/      - create **Twilio** account
2. https://www.clickatell.com   - or **Clickatell** account
3. http://www.receive-sms-online.info/read-sms.php?phone=14053264519 - Read test messages

### HOWTO Start:

**0. Prepare Clickatell Library:**

    $ git clone https://github.com/sealTLV/Clickatell4j
    $ cd Clickatell4j
    $ mvn clean compile install -Dmaven.test.skip=true

**1. Clone project:**

    $ git clone https://github.com/sealTLV/SmsAuthService

**2. Edit configurations:**

    $ cd SmsAuthService/complete/src/main/resources
    $ gedit application.properties
    $ gedit application-database.properties

  **ATTENTION: You have to fill credentials for Twilio or Clickatell messenger API:**

    $ gedit application-sms-twilio.properties
    # or:
    $ gedit application-sms-clickatell.properties

**3. Run:**

    $ cd SmsAuthService/complete
    $ mvn spring-boot:run -Dserver.port=9988

**4. Read API-documentation:** http://localhost:9988/swagger-ui.html

### HOWTO DOCKER:

**1. Register repository `sms-verification-service`**

**2. Build and upload image to Docker**

    $ cd SmsAuthService/complete
    $ mvn clean package docker:build -Dmaven.test.skip=true
    $ docker login --username=luizavladislavna --email=luizavladislavna@gmail.com
    $ docker push luizavladislavna/sms-verification-service

**3. Run image:**

    $ docker run -p 9988:8080 luizavladislavna/sms-verification-service

**Go to:**
http://localhost:9988/swagger-ui.html


text:
import oauth2 as oauth
import datetime

from django.conf import settings

from oauth_provider.store import InvalidConsumerError, InvalidTokenError, Store
from oauth_provider.models import Nonce, Token, Consumer, Scope, VERIFIER_SIZE

NONCE_VALID_PERIOD = getattr(settings, "OAUTH_NONCE_VALID_PERIOD", None)

class ModelStore(Store):
    """
    Store implementation using the Django models defined in `piston.models`.
    """
    def get_consumer(self, request, oauth_request, consumer_key):
        try:
            return Consumer.objects.get(key=consumer_key)
        except Consumer.DoesNotExist:
            raise InvalidConsumerError()

    def get_consumer_for_request_token(self, request, oauth_request, request_token):
        return request_token.consumer

    def get_consumer_for_access_token(self, request, oauth_request, access_token):
        return access_token.consumer

    def create_request_token(self, request, oauth_request, consumer, callback):
        try:
            scope = Scope.objects.get(name=oauth_request.get_parameter('scope'))
        except oauth.Error:
            # oauth.Error means that scope wasn't specified
            scope = None
        except Scope.DoesNotExist:
            # Scope.DoesNotExist means that specified scope doesn't exist in db
            raise oauth.Error('Scope does not exist.')

        token = Token.objects.create_token(
            token_type=Token.REQUEST,
            consumer=Consumer.objects.get(key=oauth_request['oauth_consumer_key']),
            timestamp=oauth_request['oauth_timestamp'],
            scope=scope,
        )
        token.set_callback(callback)
        token.save()

        return token

    def get_request_token(self, request, oauth_request, request_token_key):
        try:
            return Token.objects.get(key=request_token_key, token_type=Token.REQUEST)
        except Token.DoesNotExist:
            raise InvalidTokenError()

    def authorize_request_token(self, request, oauth_request, request_token):
        request_token.is_approved = True
        request_token.user = request.user
        request_token.verifier = oauth.generate_verifier(VERIFIER_SIZE)
        request_token.save()
        return request_token

    def create_access_token(self, request, oauth_request, consumer, request_token):
        scope = request_token.scope
        access_token = Token.objects.create_token(
            token_type=Token.ACCESS,
            timestamp=oauth_request['oauth_timestamp'],
            consumer=Consumer.objects.get(key=consumer.key),
            user=request_token.user,
            scope=scope,
        )
        request_token.delete()
        return access_token

    def get_access_token(self, request, oauth_request, consumer, access_token_key):
        try:
            return Token.objects.get(key=access_token_key, token_type=Token.ACCESS)
        except Token.DoesNotExist:
            raise InvalidTokenError()

    def get_user_for_access_token(self, request, oauth_request, access_token):
        return access_token.user

    def get_user_for_consumer(self, request, oauth_request, consumer):
        return consumer.user

    def check_nonce(self, request, oauth_request, nonce, timestamp):
        timestamp = int(timestamp)

        if NONCE_VALID_PERIOD and int(datetime.datetime.now().strftime("%s")) - timestamp > NONCE_VALID_PERIOD:
            return False

        nonce, created = Nonce.objects.get_or_create(
            consumer_key=oauth_request['oauth_consumer_key'],
            token_key=oauth_request.get('oauth_token', ''),
            key=nonce, timestamp=timestamp,
        )
        return created


text:
using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace TNLauncher
{
    public class Model : BindableBase
    {
        ///ブックマークアイテムのリスト
        public ObservableCollection<Item> Items { get; } = new ObservableCollection<Item>();
        ///URIスキーム コロンは含んでいない
        public string UriScheme { get { return _UriScheme; } set { SetProperty(ref _UriScheme, value); } }
        private string _UriScheme;

        protected const string SCHEME_PREFIX = "tn-launcher";

        ///ランダムなスキームを新規作成
        private string NewUriScheme => $"{SCHEME_PREFIX}-{Path.GetRandomFileName().Replace(".", "")}";
        private const string GUID = "{61C94E2B-8FFD-43C9-AB3F-4213BB5D3017}";

        public Model() { }

        ///レジストリからURIスキームを取得 無ければnull
        ///<remarks>不整合があった場合上書きする 複数登録されていた場合は最初のキーを採用する</remarks>
        protected string GetUriScheme()
        {
            //HKCU\SOFTWARE\Classes
            using(var classesKey = Registry.CurrentUser.OpenSubKey(@"Software\Classes", false))
            {
                if(classesKey == null) return null; //レジストリに登録がなかった場合

                var keys = classesKey.GetSubKeyNames().Where(x => x.StartsWith(SCHEME_PREFIX));
                foreach(var scheme in keys)
                {
                    //HKCU\SOFTWARE\Classes\tn-launcher で始まるキー
                    using(var schemeKey = classesKey.OpenSubKey(scheme, true))
                    //HKCU\SOFTWARE\Classes\tn-launcher-********\shell\open\command
                    using(var CommandKey = schemeKey.CreateSubKey("shell").CreateSubKey("open").CreateSubKey("command"))
                    {
                        var g = schemeKey.GetValue("GUID") as string;
                        if(g != GUID) continue;

                        var s = schemeKey.GetValue("") as string;
                        if(s != $"URL:{scheme}")
                            schemeKey.SetValue("", $"URL:{scheme}");

                        var p = schemeKey.GetValue("URL Protocol") as string;
                        if(p != "")
                            schemeKey.SetValue("URL Protocol", "");

                        var exePath = Assembly.GetExecutingAssembly().Location;
                        var e = CommandKey.GetValue("") as string;
                        if(e != $"\"{exePath}\" \"%1\"")
                            CommandKey.SetValue("", $"\"{exePath}\" \"%1\"");

                        //複数登録がある可能性があるが最初のを採用 不整合が起きた場合はGUI上での変更で対応
                        return scheme;
                    }
                }
            }
            return null; //レジストリに登録がなかった場合
        }
        ///新規でスキーム作成 レジストリ登録
        protected string CreateUriScheme() => RegisterUriScheme(NewUriScheme);
        ///レジストリにURIスキームを登録
        protected string RegisterUriScheme(string scheme)
        {
            //HKCU\SOFTWARE\Classes\tn-launcher-********
            using(var schemeKey = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("Classes").CreateSubKey(scheme))
            //HKCU\SOFTWARE\Classes\tn-launcher-********\shell\open\command
            using(var CommandKey = schemeKey.CreateSubKey("shell").CreateSubKey("open").CreateSubKey("command"))
            {
                schemeKey.SetValue("", $"URL:{scheme}");
                schemeKey.SetValue("URL Protocol", "");
                schemeKey.SetValue("GUID", GUID);

                var exePath = Assembly.GetExecutingAssembly().Location;
                CommandKey.SetValue("", $"\"{exePath}\" \"%1\"");
            }
            return scheme;
        }
        ///自分で書いたレジストリを削除(GUIDで確認)
        protected void DeleteUriScheme()
        {
            //HKCU\SOFTWARE\Classes
            using(var classesKey = Registry.CurrentUser.OpenSubKey($"Software\\Classes", true))
            {
                if(classesKey == null) return;

                var keys = classesKey.GetSubKeyNames().Where(x => x.StartsWith(SCHEME_PREFIX));
                foreach(var scheme in keys)
                {
                    //HKCU\SOFTWARE\Classes\tn-launcher で始まるキー
                    using(var schemeKey = classesKey.OpenSubKey(scheme, false))
                    {
                        var guid = schemeKey.GetValue("GUID") as string;
                        if(guid == GUID)
                            classesKey.DeleteSubKeyTree(scheme);
                    }
                }
            }
        }
        ///ファイル名からブックマークアイテムを作成し追加
        protected void AddItem(string path)
        {
            var item = new Item();
            if(Win32.GetFileInfo(path, ref item))
                Items.Add(item);
        }
        ///パス?コマンドライン と来る前提でProcess.Start
        protected void ProcessStart(string str)
        {
            var unescape = Uri.UnescapeDataString(str);
            var split = unescape.Split('?');
            var path = split[0];
            var commandLine = split.ElementAtOrDefault(1); ;
            Process.Start(path, commandLine);
        }
        ///指定パスにNetscape Bookmark Formatで書き出し。
        protected void Export(string path)
        {
            var text = @"<!DOCTYPE NETSCAPE-Bookmark-file-1>

<META HTTP-EQUIV=""Content-Type"" CONTENT=""text/html; charset=UTF-8"">
<TITLE>Bookmarks</TITLE>

Bookmarks

";
            foreach(var item in Items)
            {
                var commandLine = "";
                if(!string.IsNullOrEmpty(item.CommandLine))
                    commandLine = $"?{item.CommandLine}";
                text += $"
{item.Title}\n";
            }
            text += "

\n";

            using(var sw = new StreamWriter(path, false, Encoding.UTF8))
                sw.Write(text);

            //インポートファイルを出した以上、スキームがないとまずいので整理して登録
            DeleteUriScheme();
            RegisterUriScheme(UriScheme);
        }
    }
}


text:
"""The default :attr:`custom_layouts_module
<lino.core.site.Site.custom_layouts_module>` for Lino Avanti.

"""

from lino.api import dd, rt, _

rt.models.system.SiteConfigs.set_detail_layout("""
site_company next_partner_id:10
default_build_method simulate_today
site_calendar default_event_type #pupil_guestrole
max_auto_events hide_events_before
""", window_size=(60, 'auto'))

rt.models.countries.Places.detail_layout = """
name country
type parent zip_code id
PlacesByPlace contacts.PartnersByCity
"""

rt.models.courses.AllEnrolments.column_names = \
'id #request_date #start_date #end_date #user course \
pupil__birth_date pupil__age pupil__country pupil__city \
pupil__gender state'

dd.update_field(
    rt.models.contacts.Partner, 'language',
    verbose_name=_("Contact language"))

# rt.models.cv.LanguageKnowledgesByPerson.display_mode = 'grid'

from lino_avanti.lib.avanti.roles import ClientsUser
if dd.is_installed('calview'):
    rt.models.calview.CalendarView.required_roles = dd.login_required(
        ClientsUser)
    rt.models.calview.DailySlaveBase.required_roles = dd.login_required(ClientsUser)

if dd.is_installed('extensible'):
    rt.models.extensible.CalendarPanel.required_roles = dd.login_required(
        ClientsUser)

from lino_xl.lib.cv.roles import CareerUser
for t in (rt.models.households.SiblingsByPerson,
          rt.models.changes.ChangesByMaster,
          rt.models.households.MembersByHousehold):
    t.required_roles = dd.login_required(CareerUser)


text:
                <form class="form-horizontal">
                    <fieldset>

                                <input type="number" id="level" data-ng-model="vm.weapon.level" class="form-control"
                                       min="1" max="72">
                                {{vm.errors.level}}

                                <select id="rarity2" data-ng-model="vm.weapon.rarity"
                                        data-ng-options="r.name for r in vm.rarities track by r.id"
                                        class="form-control">
                                </select>
                                {{vm.errors.rarity}}

                                <input type="text" id="name" data-ng-model="vm.weapon.name"
                                       placeholder="Practicable Butcher" class="form-control">
                                {{vm.errors.name}}

                                <input type="text" id="gibbedCode" data-ng-model="vm.weapon.gibbedCode"
                                       placeholder="BL2(...)" class="form-control">
                                {{vm.errors.gibbedCode}}

                                    <input type="text" id="damage" data-ng-model="vm.weapon.damage" placeholder="5463"
                                           class="form-control">
                                    {{vm.errors.damage}}

                                    <input type="text" id="multiplicator" data-ng-model="vm.weapon.multiplicator"
                                           placeholder="3" class="form-control">
                                    {{vm.errors.multiplicator}}

                                <input type="text" id="accuracy" data-ng-model="vm.weapon.accuracy" placeholder="61.9"
                                       class="form-control">
                                {{vm.errors.accuracy}}

                                <input type="text" id="fireRate" data-ng-model="vm.weapon.fireRate" placeholder="7.0"
                                       class="form-control">
                                {{vm.errors.fireRate}}

                                <input type="text" id="reloadSpeed" data-ng-model="vm.weapon.reloadSpeed"
                                       placeholder="3.7" class="form-control">
                                {{vm.errors.reloadSpeed}}

                                <input type="text" id="magazineSize" data-ng-model="vm.weapon.magazineSize"
                                       placeholder="13" class="form-control">
                                {{vm.errors.magazineSize}}

                                <select id="damageType" data-ng-model="vm.weapon.damageType"
                                        data-ng-options="dmg.name for dmg in vm.damageTypes track by dmg.id"
                                        class="form-control" data-ng-change="vm.changeDamageType()">
                                    <option>-none-</option>
                                </select>
                            {{vm.errors.damageType}}

                            {{vm.weapon.damageType.damageLabel}}

                                <input type="text" id="elemDamage" data-ng-model="vm.weapon.elemDamage"
                                       placeholder="3605.9" class="form-control">
                                {{vm.errors.elemDamage}}

                            {{vm.weapon.damageType.chanceLabel}}

                                    %
                                    <input type="text" id="elemChance" data-ng-model="vm.weapon.elemChance"
                                           placeholder="12.0" class="form-control">

                                {{vm.errors.elemChance}}

                                <input type="text" id="uniqueText" data-ng-model="vm.weapon.uniqueText" placeholder=""
                                       class="form-control">
                                {{vm.errors.uniqueText}}

                                <textarea id="additionalText" data-ng-model="vm.weapon.additionalText" placeholder=""
                                          class="form-control" rows="5">
                                </textarea>
                                {{vm.errors.additionalText}}

                                <select id="manufacturer" data-ng-model="vm.weapon.manufacturer"
                                        data-ng-options="man.name for man in vm.manufacturers track by man.id"
                                        class="form-control">
                                </select>
                            {{vm.errors.manufacturer}}

                                <button type="submit" class="btn btn-default" data-ng-click="vm.save()"
                                        data-translate="weapons.details.button.save">save
                                </button>

                                <button type="button" class="btn btn-primary" data-ng-click="vm.cancel()"
                                        data-translate="weapons.details.button.cancel"></button>

                    </fieldset>
                </form>

        <display-item data-item="vm.weapon" data-item-type="weapon"></display-item>


text:
NS_ASSUME_NONNULL_BEGIN

// Provides trusted vault functions to ChromeWebView.
@interface ShellTrustedVaultProvider : NSObject <CWVTrustedVaultProvider>

- (instancetype)initWithAuthService:(ShellAuthService*)authService
    NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;

- (void)showFetchKeysFlowForIdentity:(CWVIdentity*)identity
                  fromViewController:(UIViewController*)viewController;
- (void)showFixDegradedRecoverabilityFlowForIdentity:(CWVIdentity*)identity
                                  fromViewController:
                                      (UIViewController*)viewController;

@end

NS_ASSUME_NONNULL_END

#endif  // IOS_WEB_VIEW_SHELL_SHELL_TRUSTED_VAULT_PROVIDER_H_


text:
<?php

require_once 'core/App.php';
require_once 'core/Controller.php';

$root = $_SERVER['DOCUMENT_ROOT'];
$host = 'http://'.$_SERVER['HTTP_HOST'];

define("ASSETS", $host."/");
define("ROOT", $root);
define("WIDGETS", $root."/views/widgets/");

define("GWEBMASTER", 'yQCRgjSyXaEP6ZitoJHS7sOXgVj7xJg8c0cq3aSexkY');


text:
package org.apache.hadoop.hdfs.server.datanode;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_LIFELINE_INTERVAL_SECONDS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_LIFELINE_RPC_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_INTERVAL_KEY;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManagerFaultInjector;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeStatistics;
import org.apache.hadoop.hdfs.server.protocol.SlowDiskReports;
import static org.apache.hadoop.test.MetricsAsserts.getLongCounter;
import static org.apache.hadoop.test.MetricsAsserts.getMetrics;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.anyLong;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocolPB.DatanodeLifelineProtocolClientSideTranslatorPB;
import org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolClientSideTranslatorPB;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.datanode.metrics.DataNodeMetrics;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.protocol.DatanodeRegistration;
import org.apache.hadoop.hdfs.server.protocol.HeartbeatResponse;
import org.apache.hadoop.hdfs.server.protocol.SlowPeerReports;
import org.apache.hadoop.hdfs.server.protocol.StorageReport;
import org.apache.hadoop.test.GenericTestUtils;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;

import java.util.function.Supplier;

/**
 * Test suite covering lifeline protocol handling in the DataNode.
 */
public class TestDataNodeLifeline {

  private static final Logger LOG = LoggerFactory.getLogger(
      TestDataNodeLifeline.class);

  static {
    GenericTestUtils.setLogLevel(DataNode.LOG, Level.TRACE);
  }

  @Rule
  public Timeout timeout = new Timeout(60000);

  private MiniDFSCluster cluster;
  private HdfsConfiguration conf;
  private DatanodeLifelineProtocolClientSideTranslatorPB lifelineNamenode;
  private DataNodeMetrics metrics;
  private DatanodeProtocolClientSideTranslatorPB namenode;
  private FSNamesystem namesystem;
  private DataNode dn;
  private BPServiceActor bpsa;
  private final BlockManagerFaultInjector injector = new BlockManagerFaultInjector() {
    @Override
    public void mockAnException() {
      throw new UnknownError("Unknown exception");
    }
  };

  @Before
  public void setup() throws Exception {
    // Configure cluster with lifeline RPC server enabled, and down-tune
    // heartbeat timings to try to force quick dead/stale DataNodes.
    conf = new HdfsConfiguration();
    conf.setInt(DFS_DATANODE_LIFELINE_INTERVAL_SECONDS_KEY, 2);
    conf.setInt(DFS_HEARTBEAT_INTERVAL_KEY, 1);
    conf.setInt(DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 1);
    conf.set(DFS_NAMENODE_LIFELINE_RPC_ADDRESS_KEY, "0.0.0.0:0");
    conf.setInt(DFS_NAMENODE_STALE_DATANODE_INTERVAL_KEY, 6 * 1000);

    cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
    namesystem = cluster.getNameNode().getNamesystem();

    // Set up spies on RPC proxies so that we can inject failures.
    dn = cluster.getDataNodes().get(0);
    metrics = dn.getMetrics();
    assertNotNull(metrics);
    List<BPOfferService> allBpos = dn.getAllBpOs();
    assertNotNull(allBpos);
    assertEquals(1, allBpos.size());

    BPOfferService bpos = allBpos.get(0);
    List<BPServiceActor> allBpsa = bpos.getBPServiceActors();
    assertNotNull(allBpsa);
    assertEquals(1, allBpsa.size());

    bpsa = allBpsa.get(0);
    assertNotNull(bpsa);

    // Lifeline RPC proxy gets created on separate thread, so poll until found.
    GenericTestUtils.waitFor(new Supplier<Boolean>() {
          @Override
          public Boolean get() {
            if (bpsa.getLifelineNameNodeProxy() != null) {
              lifelineNamenode = spy(bpsa.getLifelineNameNodeProxy());
              bpsa.setLifelineNameNode(lifelineNamenode);
            }
            return lifelineNamenode != null;
          }
        }, 100, 10000);

    assertNotNull(bpsa.getNameNodeProxy());
    namenode = spy(bpsa.getNameNodeProxy());
    bpsa.setNameNode(namenode);
  }

  @After
  public void shutdown() {
    if (cluster != null) {
      cluster.shutdown();
      GenericTestUtils.assertNoThreadsMatching(".*lifeline.*");
    }
  }

  @Test
  public void testSendLifelineIfHeartbeatBlocked() throws Exception {
    // Run the test for the duration of sending 10 lifeline RPC messages.
    int numLifelines = 10;
    CountDownLatch lifelinesSent = new CountDownLatch(numLifelines);

    // Intercept heartbeat to inject an artificial delay, until all expected
    // lifeline RPC messages have been sent.
    doAnswer(new LatchAwaitingAnswer<HeartbeatResponse>(lifelinesSent))
        .when(namenode).sendHeartbeat(
            any(DatanodeRegistration.class),
            any(StorageReport[].class),
            anyLong(),
            anyLong(),
            anyInt(),
            anyInt(),
            anyInt(),
            any(),
            anyBoolean(),
            any(SlowPeerReports.class),
            any(SlowDiskReports.class));

    // Intercept lifeline to trigger latch count-down on each call.
    doAnswer(new LatchCountingAnswer<Void>(lifelinesSent))
        .when(lifelineNamenode).sendLifeline(
            any(DatanodeRegistration.class),
            any(StorageReport[].class),
            anyLong(),
            anyLong(),
            anyInt(),
            anyInt(),
            anyInt(),
            any());

    // While waiting on the latch for the expected number of lifeline messages,
    // poll DataNode tracking information.  Thanks to the lifeline, we expect
    // that the DataNode always stays alive, and never goes stale or dead.
    while (!lifelinesSent.await(1, SECONDS)) {
      assertEquals("Expect DataNode to be kept alive by lifeline.", 1,
          namesystem.getNumLiveDataNodes());
      assertEquals("Expect DataNode not marked dead due to lifeline.", 0,
          namesystem.getNumDeadDataNodes());
      assertEquals("Expect DataNode not marked stale due to lifeline.", 0,
          namesystem.getNumStaleDataNodes());
      // add a new volume on the next heartbeat
      cluster.getDataNodes().get(0).reconfigurePropertyImpl(
          DFS_DATANODE_DATA_DIR_KEY,
          cluster.getDataDirectory().concat("/data-new"));
    }

    // Verify that we did in fact call the lifeline RPC.
    verify(lifelineNamenode, atLeastOnce()).sendLifeline(
        any(DatanodeRegistration.class),
        any(StorageReport[].class),
        anyLong(),
        anyLong(),
        anyInt(),
        anyInt(),
        anyInt(),
        any());

    // Also verify lifeline call through metrics.  We expect at least
    // numLifelines, guaranteed by waiting on the latch.  There is a small
    // possibility of extra lifeline calls depending on timing, so we allow
    // slack in the assertion.
    assertTrue("Expect metrics to count at least " + numLifelines + " calls.",
        getLongCounter("LifelinesNumOps", getMetrics(metrics.name())) >=
            numLifelines);
  }

  @Test
  public void testNoLifelineSentIfHeartbeatsOnTime() throws Exception {
    // Run the test for the duration of sending 10 heartbeat RPC messages.
    int numHeartbeats = 10;
    CountDownLatch heartbeatsSent = new CountDownLatch(numHeartbeats);

    // Intercept heartbeat to trigger latch count-down on each call.
    doAnswer(new LatchCountingAnswer<HeartbeatResponse>(heartbeatsSent))
        .when(namenode).sendHeartbeat(
            any(DatanodeRegistration.class),
            any(StorageReport[].class),
            anyLong(),
            anyLong(),
            anyInt(),
            anyInt(),
            anyInt(),
            any(),
            anyBoolean(),
            any(SlowPeerReports.class),
            any(SlowDiskReports.class));

    // While waiting on the latch for the expected number of heartbeat messages,
    // poll DataNode tracking information.  We expect that the DataNode always
    // stays alive, and never goes stale or dead.
    while (!heartbeatsSent.await(1, SECONDS)) {
      assertEquals("Expect DataNode to be kept alive by lifeline.", 1,
          namesystem.getNumLiveDataNodes());
      assertEquals("Expect DataNode not marked dead due to lifeline.", 0,
          namesystem.getNumDeadDataNodes());
      assertEquals("Expect DataNode not marked stale due to lifeline.", 0,
          namesystem.getNumStaleDataNodes());
    }

    // Verify that we did not call the lifeline RPC.
    verify(lifelineNamenode, never()).sendLifeline(
        any(DatanodeRegistration.class),
        any(StorageReport[].class),
        anyLong(),
        anyLong(),
        anyInt(),
        anyInt(),
        anyInt(),
        any());

    // Also verify no lifeline calls through metrics.
    assertEquals("Expect metrics to count no lifeline calls.", 0,
        getLongCounter("LifelinesNumOps", getMetrics(metrics.name())));
  }

  @Test
  public void testLifelineForDeadNode() throws Exception {
    long initialCapacity = cluster.getNamesystem(0).getCapacityTotal();
    assertTrue(initialCapacity > 0);
    dn.setHeartbeatsDisabledForTests(true);
    cluster.setDataNodesDead();
    assertEquals("Capacity should be 0 after all DNs dead", 0, cluster
        .getNamesystem(0).getCapacityTotal());
    bpsa.sendLifelineForTests();
    assertEquals("Lifeline should be ignored for dead node", 0, cluster
        .getNamesystem(0).getCapacityTotal());
    // Wait for re-registration and heartbeat
    dn.setHeartbeatsDisabledForTests(false);
    final DatanodeDescriptor dnDesc = cluster.getNamesystem(0).getBlockManager()
        .getDatanodeManager().getDatanodes().iterator().next();
    GenericTestUtils.waitFor(new Supplier<Boolean>() {

      @Override
      public Boolean get() {
        return dnDesc.isAlive() && dnDesc.isHeartbeatedSinceRegistration();
      }
    }, 100, 5000);
    assertEquals("Capacity should include only live capacity", initialCapacity,
        cluster.getNamesystem(0).getCapacityTotal());
  }

  /**
   * Waits on a {@link CountDownLatch} before calling through to the method.
   */
  private final class LatchAwaitingAnswer<T> implements Answer<T> {
    private final CountDownLatch latch;

    public LatchAwaitingAnswer(CountDownLatch latch) {
      this.latch = latch;
    }

    @Override
    @SuppressWarnings("unchecked")
    public T answer(InvocationOnMock invocation)
        throws Throwable {
      LOG.info("Awaiting, remaining latch count is {}.", latch.getCount());
      latch.await();
      return (T)invocation.callRealMethod();
    }
  }

  /**
   * Counts on a {@link CountDownLatch} after each call through to the method.
   */
  private final class LatchCountingAnswer<T> implements Answer<T> {
    private final CountDownLatch latch;

    public LatchCountingAnswer(CountDownLatch latch) {
      this.latch = latch;
    }

    @Override
    @SuppressWarnings("unchecked")
    public T answer(InvocationOnMock invocation)
        throws Throwable {
      T result = (T)invocation.callRealMethod();
      latch.countDown();
      LOG.info("Countdown, remaining latch count is {}.", latch.getCount());
      return result;
    }
  }

  /**
   * Mock an exception in HeartbeatManager#updateHeartbeat and HeartbeatManager#updateLifeline
   * respectively, and trigger the heartbeat and lifeline in sequence. The capacityTotal obtained
   * before and after this operation should be the same.
   * @throws Exception
   */
  @Test
  public void testHeartbeatAndLifelineOnError() throws Exception {
    final Configuration config = new HdfsConfiguration();
    config.set(DFS_NAMENODE_LIFELINE_RPC_ADDRESS_KEY, "0.0.0.0:0");

    try(MiniDFSCluster cluster =
            new MiniDFSCluster.Builder(config).numDataNodes(1).build()) {
      cluster.waitActive();
      final FSNamesystem fsNamesystem = cluster.getNamesystem();

      // Get capacityTotal before triggering heartbeat and lifeline.
      DatanodeStatistics datanodeStatistics =
          fsNamesystem.getBlockManager().getDatanodeManager().getDatanodeStatistics();
      long capacityTotalBefore = datanodeStatistics.getCapacityTotal();

      // Mock an exception in HeartbeatManager#updateHeartbeat and HeartbeatManager#updateLifeline.
      BlockManagerFaultInjector.instance = injector;
      DataNode dataNode = cluster.getDataNodes().get(0);
      BlockPoolManager blockPoolManager = dataNode.getBlockPoolManager();
      for (BPOfferService bpos : blockPoolManager.getAllNamenodeThreads()) {
        if (bpos != null) {
          for (BPServiceActor actor : bpos.getBPServiceActors()) {
            try {
              actor.triggerHeartbeatForTests();
              actor.sendLifelineForTests();
            } catch (Throwable e) {
              assertTrue(e.getMessage().contains("Unknown exception"));
            }
          }
        }
      }

      // Get capacityTotal after triggering heartbeat and lifeline.
      long capacityTotalAfter = datanodeStatistics.getCapacityTotal();
      // The capacityTotal should be same.
      assertEquals(capacityTotalBefore, capacityTotalAfter);
    }
  }
}


text:
package uk.gov.hmrc.ct.accounts.frs105.boxes

import uk.gov.hmrc.ct.accounts.frs105.calculations.NetCurrentAssetsLiabilitiesCalculator
import uk.gov.hmrc.ct.accounts.frs105.retriever.Frs105AccountsBoxRetriever
import uk.gov.hmrc.ct.box.{Calculated, CtBoxIdentifier, CtOptionalInteger}

case class AC61(value: Option[Int]) extends CtBoxIdentifier(name = "Net current assets or liabilities (previous PoA)") with CtOptionalInteger

object AC61 extends Calculated[AC61, Frs105AccountsBoxRetriever] with NetCurrentAssetsLiabilitiesCalculator {

  override def calculate(boxRetriever: Frs105AccountsBoxRetriever): AC61 = {
    import boxRetriever._
    calculatePreviousNetCurrentAssetsLiabilities(ac456(), ac466(), ac59())
  }
}


text:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany</groupId>
    <artifactId>myproject</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>0.5.0.BUILD-SNAPSHOT</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet-api.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>0.5.0.BUILD-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://maven.springframework.org/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://maven.springframework.org/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://maven.springframework.org/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://maven.springframework.org/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>


text:
package org.apache.wicket.extensions.wizard;

import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.model.ResourceModel;

/**
 * Base class for buttons that work with {@link IWizard the wizard component}. It uses resource
 * bundles to display the button label.
 * <p>
 * When wizard buttons are presses (and they pass validation if that is relevant), they pass control
 * to {@link #onClick() their action method}, which should do the real work.
 * </p>
 *
 * @author Eelco Hillenius
 */
public abstract class WizardButton extends Button
{
	private static final long serialVersionUID = 1L;

	/**
	 * The enclosing wizard.
	 */
	private final IWizard wizard;

	/**
	 * Construct.
	 *
	 * @param id
	 *            The component id
	 * @param wizard
	 *            The wizard
	 * @param labelResourceKey
	 *            The resource key of the button's label
	 */
	public WizardButton(String id, IWizard wizard, String labelResourceKey)
	{
		super(id, new ResourceModel(labelResourceKey));
		this.wizard = wizard;
	}

	/**
	 * Gets the {@link IWizard}.
	 *
	 * @return The wizard
	 */
	protected final IWizard getWizard()
	{
		return wizard;
	}

	/**
	 * Gets the {@link IWizardModel wizard model}.
	 *
	 * @return The wizard model
	 */
	protected final IWizardModel getWizardModel()
	{
		return getWizard().getWizardModel();
	}

	/**
	 * Called when this button is clicked.
	 */
	protected abstract void onClick();

	/**
	 * @see org.apache.wicket.markup.html.form.Button#onSubmit()
	 */
	@Override
	public final void onSubmit()
	{
		onClick();
	}
}


text:
#pragma once
#include <tilck/common/basic_defs.h>
#include <tilck/kernel/sched.h>
#include <tilck/kernel/interrupts.h>
#include <tilck/kernel/hal.h>

/* Internal stuff (used by process.c, process32.c, misc.c, sched.c, fork.c) */
extern char *kernel_initial_stack[KERNEL_STACK_SIZE];
void switch_to_initial_kernel_stack(void);
void free_common_task_allocs(struct task *ti);
void process_free_mappings_info(struct process *pi);

static ALWAYS_INLINE void set_curr_task(struct task *ti)
{
   extern struct task *__current;

#ifndef UNIT_TEST_ENVIRONMENT
   DEBUG_ONLY(check_not_in_irq_handler());
   ASSERT(!are_interrupts_enabled());
#endif

   __current = ti;
}


text:
#ifndef QTMWIDGETS__PRIVATE__SCROLLAREA_P_HPP__INCLUDED
#define QTMWIDGETS__PRIVATE__SCROLLAREA_P_HPP__INCLUDED

// QtMWidgets include.
#include "abstractscrollarea_p.hpp"
#include "../scrollarea.hpp"

// Qt include.
#include <QPointer>
#include <QWidget>

namespace QtMWidgets {

//
// ScrollAreaPrivate
//

class ScrollAreaPrivate
	:	public AbstractScrollAreaPrivate
{
public:
	explicit ScrollAreaPrivate( ScrollArea * parent )
		:	AbstractScrollAreaPrivate( parent )
		,	resizable( false )
	{
	}

	virtual ~ScrollAreaPrivate()
	{
	}

	void updateScrolledSize();
	void updateWidgetPosition();
	void paintEvent( QPaintEvent * e );

	inline ScrollArea * q_func() { return static_cast< ScrollArea* >( q ); }
	inline const ScrollArea * q_func() const { return static_cast< const ScrollArea* >( q ); }

	QPointer< QWidget > widget;
	bool resizable;
	Qt::Alignment alignment;
}; // class ScrollAreaPrivate

} /* namespace QtMWidgets */

#endif // QTMWIDGETS__PRIVATE__SCROLLAREA_P_HPP__INCLUDED


text:
package org.opensaml.saml1.core.impl;

import org.opensaml.common.impl.AbstractSAMLObjectBuilder;
import org.opensaml.common.xml.SAMLConstants;
import org.opensaml.saml1.core.SubjectConfirmation;

/**
 * Builder of {@link org.opensaml.saml1.core.impl.SubjectConfirmationImpl} objects.
 */
public class SubjectConfirmationBuilder extends AbstractSAMLObjectBuilder<SubjectConfirmation> {

    /**
     * Constructor
     */
    public SubjectConfirmationBuilder() {

    }

    /** {@inheritDoc} */
    public SubjectConfirmation buildObject() {
        return buildObject(SAMLConstants.SAML1_NS, SubjectConfirmation.DEFAULT_ELEMENT_LOCAL_NAME, SAMLConstants.SAML1_PREFIX);
    }

    /** {@inheritDoc} */
    public SubjectConfirmation buildObject(String namespaceURI, String localName, String namespacePrefix) {
        return new SubjectConfirmationImpl(namespaceURI, localName, namespacePrefix);
    }
}


text:
Este repo es una [Wiki](https://github.com/jatubio/5minutos_git/wiki) dónde recojo mis notas rápidas sobre Git.

La idea es que sea una guía rápida de consulta para cualquier cosa que quieras hacer en Git.

Por eso cada nota es concreta, pequeña y se lee más o menos en 5 minutos.[1](#myfootnote1)

Si quieres modificar, corregir o agregar información, eres bienvenid@.

Puedes modificar la [Wiki](https://github.com/jatubio/5minutos_git/wiki) directamente o [Clonarla](https://github.com/jatubio/5minutos_git.wiki.git) como un repositorio.

Espero que te sea útil

**1**: **5 minutos** en castellano es una expresión 'atemporal', es decir, que se usa mucho en expresiones como 'tardo sólo 5 minutos', sólo 5 minutos más', etc... y queda implícito que esos 5 minutos pueden alargarse indefinidamente ;)