text:
package com.sgu.infowksporga.business.service.rest.serialized.api;

import com.sgu.core.framework.pivot.AbstractIn;
import com.sgu.core.framework.pivot.AbstractOut;

/**
 * The Interface ISerializedBusinessService.
 *
 * @param <IN> the generic type
 * @param <OUT> the generic type
 */
public interface ISerializedBusinessService<IN extends AbstractIn, OUT extends AbstractOut> {

  /**
   * Execute service.
   *
   * @param in the in
   * @return the out
   */
  OUT executeService(IN in);

}

redpajama_set_name: RedPajamaGithub


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
// Connection url
var url = 'mongodb://localhost:27017/blog';

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next){
	// Connect using MongoClient
	MongoClient.connect(url, function(err, db) {
	 if(err){
		 console.log(err);
	 }
	 req.db = db;
	 next();
	});
});

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;


text:
package org.jbb.e2e.serenity;

public final class Tags {

    public static class Release {
        public static final String VER_0_3_0 = "release:0.3.0";
        public static final String VER_0_4_0 = "release:0.4.0";
        public static final String VER_0_5_0 = "release:0.5.0";
        public static final String VER_0_6_0 = "release:0.6.0";
        public static final String VER_0_7_0 = "release:0.7.0";
        public static final String VER_0_8_0 = "release:0.8.0";
        public static final String VER_0_9_0 = "release:0.9.0";
        public static final String VER_0_10_0 = "release:0.10.0";
        public static final String VER_0_11_0 = "release:0.11.0";
        public static final String VER_0_12_0 = "release:0.12.0";
        public static final String VER_0_13_0 = "release:0.13.0";
    }

    public static class Feature {
        public static final String GENERAL = "feature:general";
        public static final String REGISTRATION = "feature:registration";
        public static final String AUTHENTICATION = "feature:authentication";
        public static final String SECURITY = "feature:security";
        public static final String PROFILE = "feature:profile";
        public static final String ACCOUNTS = "feature:accounts";
        public static final String BOARD_SETTINGS = "feature:board_settings";
        public static final String DATABASE_SETTINGS = "feature:database_settings";
        public static final String STACKTRACE_VISIBILITY_SETTINGS = "feature:stacktrace_visibility_settings";
        public static final String MEMBER_LOCKOUT = "feature:member_lockout";
        public static final String LOGGING_SETTINGS = "feature:logging_settings";
        public static final String FORUM_MANAGEMENT = "feature:forum_management";
        public static final String SESSION_SETTINGS = "feature:session_settings";
        public static final String CACHE_SETTINGS = "feature:cache_settings";
        public static final String FAQ_MANAGEMENT = "feature:faq_management";
        public static final String REST_API = "feature:rest_api";
        public static final String PERMISSIONS_MANAGEMENT = "feature:permissions_management";
        public static final String METRICS_MANAGEMENT = "feature:metrics_management";
        public static final String HEALTH_CHECK = "feature:health_check";
        public static final String PASSWORD_POLICY = "feature:password_policy";
        public static final String OAUTH_CLIENT = "feature:oauth_client";
    }

    public static class Type {
        public static final String SMOKE = "type:smoke";
        public static final String REGRESSION = "type:regression";
        public static final String EPIC = "type:epic";
    }

    public static class Interface {
        public static final String WEB = "interface:web";
        public static final String REST = "interface:rest";
    }

}


text:
import React from "react";
import * as Gatsby from "gatsby";
import { render } from "@testing-library/react";
// Type
import { InterviewType } from "@type/Interview";
// Testing-Component
import { InterviewSliderWrapper } from ".";
// Mock
import { InterviewListQueryResult } from "./InterviewSliderWrapper.test.mock";
// Assets
import { SUBTITLE, TITLE } from "assets/static/phrases";
// Lib
import { strainMdxInfo } from "lib/utils";
import { TestProvider } from "lib/testUtils";

describe("<InterviewSliderWrapper>", () => {
  const renderInterviewSliderWrapper = () =>
    render(
      <TestProvider>
        <InterviewSliderWrapper />
      </TestProvider>
    );
  const useStaticQuery = jest.spyOn(Gatsby, "useStaticQuery");
  useStaticQuery.mockImplementation(() => InterviewListQueryResult);
  const { interviewList }: { interviewList: InterviewType[] } =
    strainMdxInfo(InterviewListQueryResult);
  it("컴포넌트의 제목과 부제목이 보여진다.", () => {
    const { getByText } = renderInterviewSliderWrapper();

    getByText(TITLE.GRADUATE_INTERVIEW);
    getByText(SUBTITLE.MASTERS_COURSE_2021);
  });
  it("각 인터뷰어들의 내용들이 보여진다.", () => {
    const { getByText } = renderInterviewSliderWrapper();

    interviewList.forEach(({ nutshell, writerInfo }) => {
      getByText(nutshell);
      getByText(writerInfo);
    });
  });
});


text:
package com.forest.web.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author markito
 */
public class MD5Util {

    public static String generateMD5(String value) {

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(value.getBytes());

            BigInteger number = new BigInteger(1, messageDigest);
            return number.toString(16);

        } catch (NoSuchAlgorithmException nsae) {
            return null;
        }
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syn. meth. fung. (Göttingen) 2: 657 (1801)

#### Original name
Peziza amorpha var. amorpha Pers., 1801

### Remarks
null


text:
<?php
	require_once '../class/user.php';
	require_once 'config.php';
	if($_SESSION['user']['id'] !== ''){
	  	$user->userPage();
	}else{
		header('Location: landing.php');
	}
?>


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="48dp"
    android:viewportWidth="48"
    android:viewportHeight="48"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M26.15,38.2 L3.8,24 26.15,9.8 18.65,22.35H43.65V25.65H18.65Z"/>
</vector>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Ultimate Github Page Deployment</title>

    <meta name="description" content="Deploy strony w Jekyllu (takiej jak ta) na GitHuba jest bajecznie prosty. No chyba, że korzysta z pluginów spoza whitelisty... ale nadal da się to łatwo zrobić.">

    <meta name="author" content="Adam Świderski">

    <meta name="google-site-verification" content="16LpcrHd_M03vADtS0inK7Nh5AcO1iTZQe6q57vCJfo"/>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="/pl/assets/resources/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="/pl/assets/resources/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <link href="/pl/assets/resources/syntax/syntax.css" rel="stylesheet">
    <link href="/pl/assets/css/style.css" rel="stylesheet">

    <link rel="apple-touch-icon" sizes="57x57" href="/pl/assets/ico/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/pl/assets/ico/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/pl/assets/ico/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/pl/assets/ico/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/pl/assets/ico/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/pl/assets/ico/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/pl/assets/ico/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/pl/assets/ico/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/pl/assets/ico/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="/pl/assets/ico/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/pl/assets/ico/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="/pl/assets/ico/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/pl/assets/ico/favicon-16x16.png">
    <link rel="manifest" href="/pl/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/assets/ico/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

    <link rel="alternate" type="application/rss+xml" title="" href="/pl/feed.xml">
    <meta http-equiv="Content-Language" content="pl">
<link rel="alternate" hreflang="en" href="http://asvid.github.io//github-page-deployment"/>
<link rel="alternate" hreflang="pl" href="http://asvid.github.io//pl/github-page-deployment"/>

<title>Ultimate Github Page Deployment</title>
<meta name="generator" content="Jekyll v4.2.2" />
<meta property="og:title" content="Ultimate Github Page Deployment" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="Deploy strony w Jekyllu (takiej jak ta) na GitHuba jest bajecznie prosty. No chyba, że korzysta z pluginów spoza whitelisty… ale nadal da się to łatwo zrobić." />
<meta property="og:description" content="Deploy strony w Jekyllu (takiej jak ta) na GitHuba jest bajecznie prosty. No chyba, że korzysta z pluginów spoza whitelisty… ale nadal da się to łatwo zrobić." />
<link rel="canonical" href="http://asvid.github.io//pl/github-page-deployment" />
<meta property="og:url" content="http://asvid.github.io//github-page-deployment" />
<meta property="og:image" content="http://asvid.github.io//assets/posts/ghpages/cover.jpg" />
<meta property="og:type" content="article" />
<meta property="article:published_time" content="2020-08-04T22:00:00+00:00" />
<meta name="twitter:card" content="summary_large_image" />
<meta property="twitter:image" content="http://asvid.github.io//assets/posts/ghpages/cover.jpg" />
<meta property="twitter:title" content="Ultimate Github Page Deployment" />

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

        </button>

Blog

O mnie

Tagi

			Siema jestem Adam

	I jestem programistą

Blog

O mnie

Tagi

Ultimate Github Page Deployment

	   August
	   4th,

	   2020

Pan Hyde

Standardowy proces

Zachciało się pluginów

Ale ja chce ten plugin

Pan Hyde

Tekst który czytasz, znajduje się na stronie postawionej na Jekyll'u i hostowanej na GitHubie, za pomocą darmowych Github Pages.
Tak w skrócie: Jekyll to silnik szablonów, zamieniający markdown na statyczne strony HTML, które potem można sobie hostować gdziekolwiek,
bo nie ma potrzeby podpinania bazy danych, czy obsługi PHP czy innego Pythona po stronie serwera.

Standardowy proces

Standardowy proces wrzucenia nowego posta wygląda następująco:

piszę post w markdown ustawiając parametry takie jak tytuł, data czy tagi.

kiedy jestem zadowolony z tego co napisałem (nigdy), commituję zmiany i wrzucam na repozytorium na GitHubie, które nazywa się od mojego nicku asvid.github.io

Github po pushu na branch master buduje stronę HTML ze źródeł, korzystając z silnika Jekyll - czyli pewnie odpala jekyll build

to co, Jekyll wypluje, nie jest widoczne w repozytorium, ale po wejściu pod adres bloga jest widoczne jako statyczna strona WWW

Powyższy proces działa zupełnie automatycznie, nie trzeba nic konfigurować po stronie repozytorium czy GitHuba, wystarczy, że repozytorium nazywa się wg szablonu: {nazwa_użytkownika}.github.io.
I zwykle to wystarcza. Ale…

Zachciało się pluginów

Czasami chce się dodać coś fajnego na stronę. Mi zachciało się mieć ją po polsku i po angielsku. Jekyll natywnie tego nie wspiera… ale też nie uniemożliwia
Znalazłem więc plugin Polyglot, który daje mi możliwość mieć wiele języków na jednej stronie i robi to bez większego bólu ze zmianą struktury projektu czy konfiguracją.
Dodałem go do strony, po chwili zabawy zaczął troche działać. Po dłuższej chwili działał, jak chciałem. Lokalnie.

Po wrzuceniu na Githuba niestety strona się posypała. Okazuje się, że Github nie buduje tak po prostu wszystkiego jak leci,
ale ma whitelistę (pewnie niedługo zmienią tą nazwę…) pluginów, które wspiera.
Polyglot nie ma na tej liście mimo starań autora. Sama idea whitelist'y jest zrozumiała ze względów bezpieczeństwa, nie chcemy, żeby GitHub padł, bo ktoś odpalił złośliwy plugin albo kopał bitcoiny na ich serwerach.

Ale ja chce ten plugin

Na szczęście da się ten problem rozwiązać. I to nawet na kilka sposobów. Najprościej jest zbudować stronę lokalnie i wrzucić zawartość na branch master a samą stronę rozwijać np. na branchu develop.
Jest też paczka do NodeJS, która publikuje aplikacje w NodeJS jako strony na GitHubie.

Ale że jestem leniwy i nie chce za każdym razem budować ręcznie i wrzucać na 2 branche źródeł i strony, i nie mam aplikacji na NodeJS, korzystam z 3 sposobu.

GitHub Actions

GitHub Actions to taki bardzo podstawowy CI dostępny za darmo na dla każdego repozytorium.
W ramach tego CI tworzymy sobie Workflows które w pliku yaml określają co i kiedy ma się zadziać. Dostępnych akcji jest cały katalog,
a jeśli czegoś brakuje zawsze można stworzyć samemu, lub połączyć w jeden workflow kilka akcji.
Dodać workflow do repozytorium można przez repository->actions->New workflow i kliknięcie w link set up a workflow yourself.

Doda to plik yaml z konfitugracją w repozytorium w katalogu .github/workflows

Do publikacji bloga z nieobsługiwanymi pluginami użyłem akcji Jekyll-Actions skonfigurowanej w Workflow:

name: GitHub Pages publication

on:
  push

jobs:
  jekyll:
    runs-on: ubuntu-16.04
    steps:
    - uses: actions/checkout@v2

    # Use GitHub Actions' cache to shorten build times and decrease load on servers
    - uses: actions/cache@v1
      with:
        path: vendor/bundle
        key: $-gems-$
        restore-keys: |
          $-gems-
    # Standard usage
    - uses:  helaili/jekyll-action@2.0.3
      env:
        JEKYLL_PAT: $

    # Specify the Jekyll source location as a parameter
    - uses: helaili/jekyll-action@2.0.3
      env:
        JEKYLL_PAT: $

Widać, że akcja odpala się w kontenerze z ubuntu-16.04, a następnie:

pobiera repozytorium po każdym pushu (na dowolny branch co generuje pewien problem)

korzysta z cache żeby nie pobierać tych samych Gemów za każdym razem

odpala akcję, czyli buduje stronę i publikuje na branchu master, za pomocą pusha z wykorzystaniem secrets.JEKYLL_PAT

I publikacja na branchu master sprawia, że nie możemy na niego wypychać zmian na stronie.
Jeśli chcemy korzystać z tej akcji, musimy zmiany wrzucać np. na develop a master zostawić tylko na potrzeby plików wygenerowanych przez skrypt.

Jak stworzyć secret.JEKYLL_PAT

Skrypt sam z siebie działa w odizolowanym kontenerze i nie ma dostępu do zapisu w naszym repozytorium. Odczytać może, bo to publiczne repozytorium.
Żeby to umożliwić, potrzebujemy wygenerować token dostępu do public_repo, a następnie podać go w repozytorium jako sekret pod nazwą podaną w konfiguracji workflow.

Token generujemy, przechodząc do ustawień konta Github: Settings->Developer Settings->Personal Access Tokens.
Po kliknięciu na Generate new token uzupełniamy nazwę i zaznaczamy checkbox public_repo.

Po kliknięciu zielonego przycisku na dole strony Generate token będziemy mieć jedyną szansę na skopiowanie go, polecam skorzystać

Skopiowany token wklejamy do sekretów repozytorium: Settings->Secrets->New secret. Nazwa jak w konfiguracji secrets.JEKYLL_PAT a wartość to nowy token.

I powinno działać. Przynajmniej u mnie działa, bo czytasz ten tekst

                    Github Pages (1)
                    ,

                    Jekyll (1)
                    ,

                    Github Actions (1)

                    Like the post? Disagree? Let me know

                        with email.

Share Post

                    Twitter

                    Facebook

                    Google+

Adam Świderski

software engineer

← Previous

Next
                →

            © 2022 Adam Świderski with Jekyll. Theme: dbyll by dbtek.


text:
package jp.fieldnotes.hatunatu.dao.node;

import jp.fieldnotes.hatunatu.api.beans.BeanDesc;
import jp.fieldnotes.hatunatu.api.beans.PropertyDesc;
import jp.fieldnotes.hatunatu.dao.CommandContext;
import jp.fieldnotes.hatunatu.util.beans.factory.BeanDescFactory;
import jp.fieldnotes.hatunatu.util.lang.StringUtil;

public class BindVariableNode extends AbstractNode {

    private String expression;

    private String[] names;

    public BindVariableNode(String expression) {
        this.expression = expression;
        names = StringUtil.split(expression, ".");
        // baseName_ = array[0];
        // if (array.length > 1) {
        // propertyName_ = array[1];
        // }
    }

    public String getExpression() {
        return expression;
    }

    @Override
    public void accept(CommandContext ctx) {
        Object value = ctx.getArg(names[0]);
        Class clazz = ctx.getArgType(names[0]);
        for (int pos = 1; pos < names.length; pos++) {
            BeanDesc beanDesc = BeanDescFactory.getBeanDesc(clazz);
            PropertyDesc pd = beanDesc.getPropertyDesc(names[pos]);
            if (value == null) {
                break;
            }
            value = pd.getValue(value);
            clazz = pd.getPropertyType();
        }
        ctx.addSql("?", value, clazz);
    }
}


text:
package com.microsoft.azure.management.compute.v2019_03_01.implementation;

import com.microsoft.azure.management.compute.v2019_03_01.UpgradeOperationHistoricalStatusInfoProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Virtual Machine Scale Set OS Upgrade History operation response.
 */
public class UpgradeOperationHistoricalStatusInfoInner {
    /**
     * Information about the properties of the upgrade operation.
     */
    @JsonProperty(value = "properties", access = JsonProperty.Access.WRITE_ONLY)
    private UpgradeOperationHistoricalStatusInfoProperties properties;

    /**
     * Resource type.
     */
    @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY)
    private String type;

    /**
     * Resource location.
     */
    @JsonProperty(value = "location", access = JsonProperty.Access.WRITE_ONLY)
    private String location;

    /**
     * Get information about the properties of the upgrade operation.
     *
     * @return the properties value
     */
    public UpgradeOperationHistoricalStatusInfoProperties properties() {
        return this.properties;
    }

    /**
     * Get resource type.
     *
     * @return the type value
     */
    public String type() {
        return this.type;
    }

    /**
     * Get resource location.
     *
     * @return the location value
     */
    public String location() {
        return this.location;
    }

}


text:
package uk.ac.ed.ph.snuggletex;

import uk.ac.ed.ph.snuggletex.definitions.BuiltinCommand;
import uk.ac.ed.ph.snuggletex.definitions.BuiltinEnvironment;
import uk.ac.ed.ph.snuggletex.definitions.CorePackageDefinitions;
import uk.ac.ed.ph.snuggletex.internal.util.ConstraintUtilities;
import uk.ac.ed.ph.snuggletex.utilities.DefaultTransformerFactoryChooser;
import uk.ac.ed.ph.snuggletex.utilities.SimpleStylesheetCache;
import uk.ac.ed.ph.snuggletex.utilities.StylesheetCache;
import uk.ac.ed.ph.snuggletex.utilities.StylesheetManager;
import uk.ac.ed.ph.snuggletex.utilities.TransformerFactoryChooser;

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

/**
 * This is the main entry point into SnuggleTeX.
 *
 *
Usage

 *
 *

 *

 *     Create an instance of this engine and register any extra {@link SnugglePackage}s you have
 *     created or want to use by calling {@link #addPackage(SnugglePackage)}.
 *

 *

 *     Use {@link #createSession()} to create a "session" that will take one (or more) input
 *     documents and produce a DOM.
 *

 *     Each {@link SnuggleSession} created will use a _copy_ of
 *     the {@link SnugglePackage}s registered with the engine and _copies_ of
 *     the current {@link #defaultSessionConfiguration}, {@link #defaultDOMOutputOptions},
 *     and {@link #defaultXMLStringOutputOptions}. On the other hand, it will use the shared
 *     {@link StylesheetManager} set for this engine.
 *

 *

 *     As of SnuggleTeX 1.3.0, an instance of this Class can be fully shared by multiple Threads.
 *

 *

 *     Don't let the usual connotations associated with the name of this Class worry you that
 *     instantiating it is going to be expensive!
 *

 *

 *
 * @author  David McKain
 * @version $Revision$
 */
public final class SnuggleEngine {

    /** List of all currently registered {@link SnugglePackage}s used by this Engine. */
    private final List<SnugglePackage> packages;

    /** Helper class to manage XSLT Stylesheets */
    private final StylesheetManager stylesheetManager;

    /** Default {@link SessionConfiguration} */
    private SessionConfiguration defaultSessionConfiguration;

    /** Default {@link DOMOutputOptions} */
    private DOMOutputOptions defaultDOMOutputOptions;

    /** Default {@link XMLStringOutputOptions} */
    private XMLStringOutputOptions defaultXMLStringOutputOptions;

    /**
     * Creates a new {@link SnuggleEngine} using a very simple internal cache for any
     * XSLT stylesheets required that simply stores them internally for the lifetime
     * of the engine. The {@link DefaultTransformerFactoryChooser} is used to choose
     * XSLT implementations.
     *

     * This will be fine in most cases. If you want more control over
     * this, consider the alternative constructor.
     */
    public SnuggleEngine() {
        this(DefaultTransformerFactoryChooser.getInstance(), new SimpleStylesheetCache());
    }

    /**
     * Creates a new {@link SnuggleEngine} using the given {@link StylesheetCache}
     * for managing stylesheets. Use this if you want to integrate XSLT caching
     * with your own code or want more control over how things get cached.
     * The {@link DefaultTransformerFactoryChooser} is used to choose
     * XSLT implementations.
     */
    public SnuggleEngine(StylesheetCache stylesheetCache) {
        this(DefaultTransformerFactoryChooser.getInstance(), stylesheetCache);
    }

    /**
     * Creates a new {@link SnuggleEngine} using the given {@link StylesheetCache}
     * for managing stylesheets and given {@link TransformerFactoryChooser} for choosing which
     * XSLT implementation to use. Use this if you want to integrate XSLT caching
     * with your own code, want more control over how things get cached or want to control
     * the selection of XSLT implementations.
     */
    public SnuggleEngine(TransformerFactoryChooser transformerFactoryChooser, StylesheetCache stylesheetCache) {
        this(new StylesheetManager(transformerFactoryChooser, stylesheetCache));
    }

    /**
     * Creates a new {@link SnuggleEngine} using the given {@link StylesheetManager}
     * for managing stylesheets. Use this if you want to integrate XSLT caching
     * with your own code, want more control over how things get cached or want to control
     * the selection of XSLT implementations.
     */
    public SnuggleEngine(StylesheetManager stylesheetManager) {
        this.packages = Collections.synchronizedList(new ArrayList<SnugglePackage>());
        this.defaultSessionConfiguration = new SessionConfiguration();
        this.defaultDOMOutputOptions = new DOMOutputOptions();
        this.defaultXMLStringOutputOptions = new XMLStringOutputOptions();

        /* Create manager for XSLT stylesheets using the given cache */
        this.stylesheetManager = stylesheetManager;

        /* Add in core package */
        packages.add(CorePackageDefinitions.getPackage());
    }

    //-------------------------------------------------

    /**
     * Convenience method to extract the underlying {@link StylesheetManager} used by
     * this engine. Most people won't care about this, but it might be useful if you're
     * trying to integrate stylesheet caching.
     */
    public StylesheetManager getStylesheetManager() {
        return stylesheetManager;
    }

    //-------------------------------------------------

    /**
     * Returns a synchronized {@link List} of all {@link SnugglePackage}s registered
     * with this engine.
     *
     * @since 1.3.0
     */
    public List<SnugglePackage> getPackages() {
        return packages;
    }

    /**
     * Registers the given {@link SnugglePackage} with this {@link SnuggleEngine}.
     * All commands, environments and error codes defined by the {@link SnugglePackage} will
     * then become available for use.
     */
    public void addPackage(SnugglePackage snugglePackage) {
        ConstraintUtilities.ensureNotNull(snugglePackage, "snugglePackage");
        packages.add(snugglePackage);
    }

    //-------------------------------------------------

    /**
     * Creates a new {@link SnuggleSession} using the default {@link SessionConfiguration}
     * or a fresh {@link SessionConfiguration} if no default has been set.
     */
    public SnuggleSession createSession() {
        return createSession(defaultSessionConfiguration);
    }

    /**
     * Creates a new {@link SnuggleSession} using the given {@link SessionConfiguration}
     *
     * @param sessionConfiguration {@link SessionConfiguration} to use, which must not be null.
     */
    public SnuggleSession createSession(SessionConfiguration sessionConfiguration) {
        ConstraintUtilities.ensureNotNull(sessionConfiguration, "sessionConfiguration");
        return new SnuggleSession(this, sessionConfiguration);
    }

    //-------------------------------------------------

    public SnuggleSimpleMathRunner createSimpleMathRunner() {
        return new SnuggleSimpleMathRunner(createSession());
    }

    public SnuggleSimpleMathRunner createSimpleMathRunner(SessionConfiguration sessionConfiguration) {
        return new SnuggleSimpleMathRunner(createSession(sessionConfiguration));
    }

    //-------------------------------------------------

    /**
     * Returns the {@link BuiltinCommand} corresponding to LaTeX command called
     * <tt>\texName</tt>, or null if this command is not defined.
     */
    public BuiltinCommand getBuiltinCommandByTeXName(String texName) {
        ConstraintUtilities.ensureNotNull(texName, "texName");
        BuiltinCommand result = null;
        for (SnugglePackage snugglePackage : packages) {
            result = snugglePackage.getBuiltinCommandByTeXName(texName);
            if (result!=null) {
                break;
            }
        }
        return result;
    }

    /**
     * Returns the {@link BuiltinEnvironment} corresponding to LaTeX environment
     * called <tt>texName</tt>, or null if this environment is not defined.
     */
    public BuiltinEnvironment getBuiltinEnvironmentByTeXName(String texName) {
        ConstraintUtilities.ensureNotNull(texName, "texName");
        BuiltinEnvironment result = null;
        for (SnugglePackage snugglePackage : packages) {
            result = snugglePackage.getBuiltinEnvironmentByTeXName(texName);
            if (result!=null) {
                break;
            }
        }
        return result;
    }

    //-------------------------------------------------

    /**
     * Gets the selected default {@link SessionConfiguration} for this {@link SnuggleEngine},
     * which will not be null.
     */
    public SessionConfiguration getDefaultSessionConfiguration() {
        return defaultSessionConfiguration;
    }

    /**
     * Sets the default {@link SessionConfiguration} for this {@link SnuggleEngine}.
     * This will be used when creating a new {@link SnuggleSession} via
     * {@link #createSession()}.
     *
     * @param defaultSessionConfiguration new default {@link SessionConfiguration}, which
     *   must not be null.
     */
    public void setDefaultSessionConfiguration(SessionConfiguration defaultSessionConfiguration) {
        ConstraintUtilities.ensureNotNull(defaultSessionConfiguration, "defaultSessionConfiguration");
        this.defaultSessionConfiguration = defaultSessionConfiguration;
    }

    /**
     * Gets the default {@link DOMOutputOptions} for this {@link SnuggleEngine}, which will not
     * be null.
     */
    public DOMOutputOptions getDefaultDOMOutputOptions() {
        return defaultDOMOutputOptions;
    }

    /**
     * Sets the default {@link DOMOutputOptions} for this {@link SnuggleEngine}. These
     * will be used when calling {@link SnuggleSession#buildDOMSubtree()}.
     *
     * @param defaultDOMOutputOptions new {@link DOMOutputOptions}, which must not be null.
     */
    public void setDefaultDOMOutputOptions(DOMOutputOptions defaultDOMOutputOptions) {
        ConstraintUtilities.ensureNotNull(defaultDOMOutputOptions, "defaultDOMOutputOptions");
        this.defaultDOMOutputOptions = defaultDOMOutputOptions;
    }

    /**
     * Gets the default {@link XMLStringOutputOptions} for this {@link SnuggleEngine}, which
     * will not be null.
     */
    public XMLStringOutputOptions getDefaultXMLStringOutputOptions() {
        return defaultXMLStringOutputOptions;
    }

    /**
     * Sets the default {@link XMLStringOutputOptions} for this {@link SnuggleEngine}.
     * These will be used when calling {@link SnuggleSession#buildXMLString()}.
     *
     * @param defaultXMLOutputOptions new {@link XMLStringOutputOptions}, which must not be null.
     */
    public void setDefaultXMLStringOutputOptions(XMLStringOutputOptions defaultXMLOutputOptions) {
        ConstraintUtilities.ensureNotNull(defaultXMLOutputOptions, "defaultXMLOutputOptions");
        this.defaultXMLStringOutputOptions = defaultXMLOutputOptions;
    }

    /**
     * @deprecated Use {@link #getDefaultDOMOutputOptions()}
     */
    @Deprecated
    public DOMOutputOptions getDefaultDOMOptions() {
        return defaultDOMOutputOptions;
    }

    /**
     * @deprecated Use {@link #setDefaultDOMOutputOptions(DOMOutputOptions)}
     */
    @Deprecated
    public void setDefaultDOMOptions(DOMOutputOptions defaultDOMOptions) {
        ConstraintUtilities.ensureNotNull(defaultDOMOptions, "defaultDOMOptions");
        this.defaultDOMOutputOptions = defaultDOMOptions;
    }
}


text:
"""This example illustrates how to get all campaigns and log details to

Google Cloud Logging using a custom logging interceptor.
"""

import argparse
import sys

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
from cloud_logging_interceptor import CloudLoggingInterceptor

_API_VERSION = "v12"

def main(client, customer_id):
    # Instantiate the GoogleAdsService object with a custom interceptor.
    ga_service = client.get_service(
        "GoogleAdsService",
        interceptors=[CloudLoggingInterceptor(api_version=_API_VERSION)],
    )

    query = """
        SELECT
          campaign.id,
          campaign.name
        FROM campaign
        ORDER BY campaign.id
        LIMIT 10"""

    # Issues a search request using streaming.
    stream = ga_service.search_stream(customer_id=customer_id, query=query)

    for batch in stream:
        for row in batch.results:
            print(
                f"Campaign with ID {row.campaign.id} and name "
                f'"{row.campaign.name}" was found.'
            )

if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version=_API_VERSION)

    parser = argparse.ArgumentParser(
        description="Lists all campaigns for specified customer."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    args = parser.parse_args()

    try:
        main(googleads_client, args.customer_id)
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)


text:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;

namespace DelimitedDataDeserializer.Tests.Dynamic
{
	public abstract class DynamicContext
	{
		protected readonly string[] _fields = new[] { "Field01", "Field02", "Field03" };
		protected readonly string[] _values = new[] { "Value01", "Value02", "Value03" };

		protected dynamic InitializeDynamic(string[] fields, string[] values)
		{
			dynamic parseLine = new ExpandoObject();
			for (var i = 0; i < fields.Count(); i++)
			{
				var p = parseLine as IDictionary<string, object>;
				p[_fields[i]] = values[i];
			}
			return parseLine;
		}
	}
}


text:
layout: post
title: How I manage my github notifications with Gmail
category: posts

---

A lot of [Mozilla mobile][3] product development is now hosted on Github, which is what many of our contributors prefer as a platform too. This leads to a lot of noise from Github's notification system and I've had some troubles managing it over the years.

As a follow-up to [how you can manage bugmail with gmail][0], I found a similar way to manage my most important Github notifications via Gmail:

![][1]

You can apply the same filters with the rules below:

```

Matches: from:(notifications@github.com)
Do this: Skip Inbox, Apply label "GitHub", Categorize as Forums

Matches: to:(author@noreply.github.com)
Do this: Apply label "GitHub/Author", Mark it as important

Matches: cc:comment@noreply.github.com
Do this: Skip Inbox, Apply label "GitHub/Comments"

Matches: to:(mention@noreply.github.com)
Do this: Skip Inbox, Apply label "GitHub/Mentions"

Matches: to:(review_requested@noreply.github.com) "requested your review"
Do this: Apply label "GitHub/Review Requested", Mark it as important

Matches: to:(review_requested@noreply.github.com)
Do this: Apply label "GitHub/Reviews"

```
<br>

The filters above are sorted in the same order as the screenshot if you'd like to only use a select few.

If you're feeling ambitious, you can [download the filters][2] in the appropriate XML format for Gmail so that you can import them for your account. This is probably not advisable because I'm someone on the internet that you probably do not know. :)

[0]: https://blog.margaretleibovic.com/2012/09/21/how-i-manage-my-bugmail-with-gmail.html
[1]: /images/20211014/gmail-sidebar.png
[2]: /images/20211014/mailFilters.xml
[3]: https://github.com/mozilla-mobile/


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
com.amazonaws.services.elastictranscoder.model (AWS SDK for Java - 1.4.7)
</TITLE>

<META NAME="date" CONTENT="2013-06-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../JavaDoc.css" TITLE="Style">

com.amazonaws.services.elastictranscoder.model

Classes

AudioParameters

CancelJobRequest

CancelJobResult

CreateJobOutput

CreateJobPlaylist

CreateJobRequest

CreateJobResult

CreatePipelineRequest

CreatePipelineResult

CreatePresetRequest

CreatePresetResult

DeletePipelineRequest

DeletePipelineResult

DeletePresetRequest

DeletePresetResult

Job

JobInput

JobOutput

ListJobsByPipelineRequest

ListJobsByPipelineResult

ListJobsByStatusRequest

ListJobsByStatusResult

ListPipelinesRequest

ListPipelinesResult

ListPresetsRequest

ListPresetsResult

Notifications

Permission

Pipeline

PipelineOutputConfig

Playlist

Preset

ReadJobRequest

ReadJobResult

ReadPipelineRequest

ReadPipelineResult

ReadPresetRequest

ReadPresetResult

TestRoleRequest

TestRoleResult

Thumbnails

UpdatePipelineNotificationsRequest

UpdatePipelineNotificationsResult

UpdatePipelineRequest

UpdatePipelineResult

UpdatePipelineStatusRequest

UpdatePipelineStatusResult

VideoParameters

Exceptions

AccessDeniedException

IncompatibleVersionException

InternalServiceException

LimitExceededException

ResourceInUseException

ResourceNotFoundException

ValidationException


text:
FROM qnib/alpn-consul

ENV REG_VER=2.3.0
VOLUME ["/var/lib/registry"]
RUN apk --no-cache add wget jq \
 && wget -qO /usr/local/bin/docker-registry https://github.com/ChristianKniep/distribution/releases/download/v${REG_VER}/registry_${REG_VER}_Liunx \
 && chmod +x /usr/local/bin/docker-registry
ADD etc/supervisord.d/docker-registry.ini /etc/supervisord.d/
ADD etc/consul.d/docker-registry.json /etc/consul.d/
ADD etc/docker-registry/config.yml /etc/docker-registry/


text:
django-comments-xtd |gha-tests-badge|_
===================

.. |gha-tests-badge| image:: https://github.com/danirus/django-comments-xtd/workflows/tests/badge.svg
.. _gha-tests-badge: https://github.com/danirus/django-comments-xtd/actions/workflows/ci-pipeline.yml

A Django pluggable application that adds comments to your project.

.. image:: https://github.com/danirus/django-comments-xtd/blob/master/docs/images/cover.png

It extends the once official `django-contrib-comments <https://pypi.python.org/pypi/django-contrib-comments>`_ with the following features:

#. Thread support, so comments can be nested.
#. Customizable maximum thread level, either for all models or on a per app.model basis.
#. Optional notifications on follow-up comments via email.
#. Mute links to allow cancellation of follow-up notifications.
#. Comment confirmation via email when users are not authenticated.
#. Comments hit the database only after they have been confirmed.
#. Registered users can like/dislike comments and can suggest comments removal.
#. Template tags to list/render the last N comments posted to any given list of app.model pairs.
#. Emails sent through threads (can be disable to allow other solutions, like a Celery app).
#. Fully functional JavaScript plugin using ReactJS, jQuery, Bootstrap, Remarkable and MD5.

Example sites and tests work under officially Django `supported versions <https://www.djangoproject.com/download/#supported-versions>`_:

* Django 4.1, 4.0, 3.2
* Python 3.10, 3.9, 3.8

Additional Dependencies:

* django-contrib-comments >=1.8
* djangorestframework >=3.12,<3.15

Checkout the Docker image `danirus/django-comments-xtd-demo <https://hub.docker.com/r/danirus/django-comments-xtd-demo/>`_.

`Read The Docs <http://readthedocs.org/docs/django-comments-xtd/>`_.


text:
import xlrd
import xlwt
import sys
from datetime import date,datetime
import os
def read_excel(filename):

    workbook = xlrd.open_workbook(filename)
    # print sheet2.name,sheet2.nrows,sheet2.ncols
    sheet2 = workbook.sheet_by_index(0)

    f = file('tmp.csv','w')
    data_list =[]
    for row in xrange(0, sheet2.nrows):
        rows = sheet2.row_values(row)
        def _tostr(cell):
            if type(u'') == type(cell):
                return "%s" % cell.encode('utf8')
            else:
                return "%s" % str(cell)

        line_info = ','.join([_tostr(cell) for cell in rows ])
        if row==0:
            print line_info
            print len(line_info.split(','))
        data_list.append(line_info)
        f.write(line_info+'\n')
    f.close()
    return data_list
if __name__ == '__main__':
  filename = sys.argv[1]
  read_excel(filename)


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Smithson. Contr. bot. 25: 28 (1975)

#### Original name
Parmelia chicitae Hale

### Remarks
null


text:
package org.openyolo.demoapp.passwordlogin;

import android.app.Application;
import android.databinding.ObservableField;
import android.support.annotation.AnyThread;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.WorkerThread;
import android.view.View;
import java.lang.ref.WeakReference;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import org.openyolo.demoapp.passwordlogin.userdata.User;
import org.openyolo.demoapp.passwordlogin.userdata.UserDataSource;

/**
 * The view model for the main activity, which is displayed when the user has authenticated
 * successfully.
 */
@WorkerThread
public final class MainViewModel extends ObservableViewModel {

    /**
     * The user's display name for display on screen, if known.
     */
    public final ObservableField<String> displayName = new ObservableField<>("");

    /**
     * The user's email address for display on screen.
     */
    public final ObservableField<String> email = new ObservableField<>("");

    /**
     * The user's display picture for display on screen, if known.
     */
    public final ObservableField<String> displayPicture = new ObservableField<>("");

    private final AtomicBoolean mFirstLoad = new AtomicBoolean(true);
    private final UserDataSource mUserDataSource;
    private WeakReference<MainNavigator> mNavigator;

    /**
     * Creates the view model, with the required application reference.
     */
    public MainViewModel(@NonNull Application application) {
        super(application);
        mUserDataSource = ((OpenYoloDemoApplication)application).getUserRepository();
    }

    /**
     * Specifies the navigator for use in communicating with the activity environment.
     */
    @MainThread
    public void setNavigator(@NonNull MainNavigator navigator) {
        mNavigator = new WeakReference<>(navigator);
    }

    /**
     * The entry point to the view model's behavior. Determines whether a user is currently
     * authenticated, and if not, redirects to the login activity. Otherwise, the currently
     * authenticated user is displayed on screen.
     */
    public void start() {
        if (!mFirstLoad.compareAndSet(true, false)) {
            // already started
            return;
        }

        User currentUser = mUserDataSource.getCurrentUser();
        if (currentUser == null) {
            // no user available, go to login screen
            mNavigator.get().goToLogin();
            return;
        }

        this.email.set(currentUser.getEmail());
        this.displayName.set(currentUser.getName());
        this.displayPicture.set(currentUser.getProfilePictureUri());
    }

    /**
     * Delegates handling of sign-out to a background thread, which de-authenticates the current
     * user and redirects to the login activity.
     */
    @MainThread
    public void onSignOutClicked(View view) {
        getExecutor().execute(() -> {
            mUserDataSource.signOut();
            mNavigator.get().goToLogin();
        });
    }

    @AnyThread
    private ScheduledExecutorService getExecutor() {
        return OpenYoloDemoApplication.getInstance(getApplication()).getExecutor();
    }
}


text:
<archimate:Product
    xmlns:archimate="http://www.archimatetool.com/archimate"
    name="Go.js"
    id="7c856a2f-43be-41cd-8b14-393671ed927c"
    documentation="GoJS: a proprietary JavaScript / TypeScript library for building interactive diagrams and graphs.
at https://gojs.net/latest/index.html
Not free, expensive
Potential use with an evaluation licence
Great features"/>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Windows Virtual Shields for Arduino: Email Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Windows Virtual Shields for Arduino

Main Page

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Public Member Functions |
List of all members

Email Class Reference

#include <Email.h>

Inherits Sensor.

Public Member Functions

 	Email (const VirtualShield &shield)

 	Initializes a new instance of the Email class.  More...

int 	send (String to, String subject, String message, String cc=(const char *) 0, String attachment=(const char *) 0)

 	Initiates an email.  More...

void 	onJsonReceived (JsonObject &root, ShieldEvent *shieldEvent) override

 	Event called when a valid json message was received. Consumes the proper values for this sensor.  More...

 Public Member Functions inherited from Sensor

 	Sensor (const VirtualShield &shield, const char sensorType)

 	Initializes a new instance of the Sensor class.  More...

int 	start (double delta=0, long interval=0)

 	Starts the sensor, triggered when longer than the interval and larger than the delta.  More...

virtual int 	stop ()

 	Stops this sensor.  More...

int 	get ()

 	Gets a single, current sensor reading.  More...

int 	getOnChange (double delta=0)

 	Requests a single reading when more than the delta beyond the current reading.  More...

bool 	isUpdated ()

 	Determines whether this sensor has an updated value. Resets to false after this call.  More...

int 	writeAll (const char *serviceName, EPtr values[], int count, Attr extraAttributes[]=0, int extraAttributeCount=0)

 	Writes all EPtr values to the communication channel.  More...

int 	sensorAction (SensorAction sensorAction, double delta=0, long interval=0) const

 	Sends the specific action to start/stop/get/onChange the sensor using a delta and interval.  More...

virtual bool 	isEvent (const char *tag, const char *action, ShieldEvent *shieldEvent)

 	Determines whether the specified shieldEvent matches the tag and action.  More...

virtual bool 	isEvent (int id, const char *action, ShieldEvent *shieldEvent)

 	Determines whether the specified shieldEvent matches the id and action.  More...

void 	setOnEvent (void(*onEvent)(ShieldEvent *shieldEvent))

int 	sendStop (const char *serviceName)

Additional Inherited Members

 Public Attributes inherited from Sensor

void(* 	onEvent )(ShieldEvent *shieldEvent)

VirtualShield & 	shield

ShieldEvent 	recentEvent

const char 	sensorType

bool 	isRunning = false

 Protected Attributes inherited from Sensor

bool 	_isUpdated = false

Constructor & Destructor Documentation

          Email::Email
          (
          const VirtualShield &
          shield	)

Initializes a new instance of the Email class.

Parameters

shield	The shield.

Member Function Documentation

          void Email::onJsonReceived
          (
          JsonObject &
          root,

          ShieldEvent *
          shieldEvent

          )

overridevirtual

Event called when a valid json message was received. Consumes the proper values for this sensor.

Parameters

root	The root json object.

shieldEvent	The shield event.

Reimplemented from Sensor.

          int Email::send
          (
          String
          to,

          String
          subject,

          String
          message,

          String
          cc = (const char *)0,

          String
          attachment = (const char *)0

          )

Initiates an email.

Parameters

to	To email address.

subject	The subject.

message	The message.

cc	The cc email address.

attachment	The attachment url.

Returns

The id of the message. Negative if an error.

The documentation for this class was generated from the following files:

C:/Users/jgord/Documents/ms-iot/virtual-shields-arduino/VirtualShield/Email.h

C:/Users/jgord/Documents/ms-iot/virtual-shields-arduino/VirtualShield/Email.cpp

<address class="footer">
Generated on Wed Apr 29 2015 17:37:05 for Windows Virtual Shields for Arduino by

 1.8.9.1
</address>


text:
package org.roaringbitmap;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

public class LABRoaringInspection {

//    public static RoaringBitmap[] split(RoaringBitmap bitmap) {
//        RoaringArray array = bitmap.highLowContainer;
//        int size = array.size();
//        RoaringBitmap[] split = new RoaringBitmap[size];
//        for (int i = 0; i < size; i++) {
//            split[i] = new RoaringBitmap();
//            split[i].highLowContainer.append(array.getKeyAtIndex(i), array.getContainerAtIndex(i));
//        }
//        return split;
//    }

//    public static RoaringBitmap join(RoaringBitmap[] split) {
//        RoaringBitmap bitmap = new RoaringBitmap();
//        RoaringArray array = bitmap.highLowContainer;
//        array.extendArray(split.length);
//        for (int i = 0; i < split.length; i++) {
//            array.append(split[i].highLowContainer.getKeyAtIndex(0), split[i].highLowContainer.getContainerAtIndex(0));
//        }
//        return bitmap;
//    }

//    public static RoaringBitmap[] extract(RoaringBitmap bitmap, int[] ukeys) {
//        RoaringArray array = bitmap.highLowContainer;
//        short[] keys = intToShortKeys(ukeys);
//        RoaringBitmap[] extract = new RoaringBitmap[keys.length];
//        for (int i = 0; i < keys.length; i++) {
//            Container container = array.getContainer(keys[i]);
//            if (container != null) {
//                extract[i] = new RoaringBitmap();
//                extract[i].highLowContainer.append(keys[i], container);
//            }
//        }
//        return extract;
//    }

    private static int lastSetIndex(Container container) {
        if (container instanceof ArrayContainer) {
            ArrayContainer arrayContainer = (ArrayContainer) container;
            int cardinality = arrayContainer.cardinality;
            if (cardinality > 0) {
                char last = arrayContainer.content[cardinality - 1];
                return toIntUnsigned(last);
            }
        } else if (container instanceof RunContainer) {
            RunContainer runContainer = (RunContainer) container;
            if (runContainer.nbrruns > 0) {
                int maxlength = toIntUnsigned(runContainer.getLength(runContainer.nbrruns - 1));
                int base = toIntUnsigned(runContainer.getValue(runContainer.nbrruns - 1));
                return (base + maxlength);
            }
        } else {
            // <-- trailing              leading -->
            // [ 0, 0, 0, 0, 0 ... , 0, 0, 0, 0, 0 ]
            BitmapContainer bitmapContainer = (BitmapContainer) container;
            long[] longs = bitmapContainer.bitmap;
            for (int i = longs.length - 1; i >= 0; i--) {
                long l = longs[i];
                int leadingZeros = Long.numberOfLeadingZeros(l);
                if (leadingZeros < 64) {
                    char last = (char) ((i * 64) + 64 - leadingZeros - 1);
                    return toIntUnsigned(last);
                }
            }
        }
        return -1;
    }

//    public static long sizeInBits(RoaringBitmap bitmap) {
//        int pos = bitmap.highLowContainer.size() - 1;
//        if (pos >= 0) {
//            return (toIntUnsigned(bitmap.highLowContainer.getKeyAtIndex(pos)) + 1) << 16;
//        } else {
//            return 0;
//        }
//    }

//    public static void cardinalityInBuckets(RoaringBitmap bitmap, int[][] indexes, long[][] buckets) {
//        // indexes = { 10, 20, 30, 40, 50 } length=5
//        // buckets = { 10-19, 20-29, 30-39, 40-49 } length=4
//        int numContainers = bitmap.highLowContainer.size();
//        //System.out.println("NumContainers=" + numContainers);
//        int bucketLength = buckets.length;
//        int[] currentBucket = new int[bucketLength];
//        Arrays.fill(currentBucket, 0);
//        int[] currentBucketStart = new int[bucketLength];
//        int[] currentBucketEnd = new int[bucketLength];
//        for (int bi = 0; bi < bucketLength; bi++) {
//            currentBucketStart[bi] = indexes[bi][currentBucket[bi]];
//            currentBucketEnd[bi] = indexes[bi][currentBucket[bi] + 1];
//        }
//
//        int numExhausted = 0;
//        boolean[] exhausted = new boolean[bucketLength];
//
//        for (int pos = 0; pos < numContainers; pos++) {
//            //System.out.println("pos=" + pos);
//            int min = containerMin(bitmap, pos);
//            for (int bi = 0; bi < bucketLength; bi++) {
//                while (!exhausted[bi] && min >= currentBucketEnd[bi]) {
//                    //System.out.println("Advance1 min:" + min + " >= currentBucketEnd:" + currentBucketEnd);
//                    currentBucket[bi]++;
//                    if (currentBucket[bi] == buckets[bi].length) {
//                        numExhausted++;
//                        exhausted[bi] = true;
//                        break;
//                    }
//                    currentBucketStart[bi] = indexes[bi][currentBucket[bi]];
//                    currentBucketEnd[bi] = indexes[bi][currentBucket[bi] + 1];
//                }
//            }
//            if (numExhausted == bucketLength) {
//                break;
//            }
//
//            boolean[] candidate = new boolean[bucketLength];
//            boolean anyCandidates = false;
//            for (int bi = 0; bi < bucketLength; bi++) {
//                candidate[bi] = (min < currentBucketEnd[bi]);
//                anyCandidates |= candidate[bi];
//            }
//
//            if (anyCandidates) {
//                Container container = bitmap.highLowContainer.values[pos];
//                int max = min + (1 << 16);
//                boolean[] bucketContainsPos = new boolean[bucketLength];
//                boolean allContainPos = true;
//                boolean anyContainPos = false;
//                for (int bi = 0; bi < bucketLength; bi++) {
//                    bucketContainsPos[bi] = (currentBucketStart[bi] <= min && max <= currentBucketEnd[bi]);
//                    allContainPos &= bucketContainsPos[bi];
//                    anyContainPos |= bucketContainsPos[bi];
//                }
//
//                if (anyContainPos) {
//                    int cardinality = container.getCardinality();
//                    for (int bi = 0; bi < bucketLength; bi++) {
//                        if (bucketContainsPos[bi]) {
//                            //System.out.println("BucketContainsPos");
//                            buckets[bi][currentBucket[bi]] += cardinality;
//                        }
//                    }
//                }
//
//                if (!allContainPos) {
//                    if (container instanceof ArrayContainer) {
//                        //System.out.println("ArrayContainer");
//                        ArrayContainer arrayContainer = (ArrayContainer) container;
//                        for (int i = 0; i < arrayContainer.cardinality && numExhausted < bucketLength; i++) {
//                            int index = toIntUnsigned(arrayContainer.content[i]) | min;
//                            next:
//                            for (int bi = 0; bi < bucketLength; bi++) {
//                                if (!candidate[bi] || bucketContainsPos[bi] || exhausted[bi]) {
//                                    continue;
//                                }
//                                while (index >= currentBucketEnd[bi]) {
//                                    currentBucket[bi]++;
//                                    if (currentBucket[bi] == buckets[bi].length) {
//                                        numExhausted++;
//                                        exhausted[bi] = true;
//                                        continue next;
//                                    }
//                                    currentBucketStart[bi] = indexes[bi][currentBucket[bi]];
//                                    currentBucketEnd[bi] = indexes[bi][currentBucket[bi] + 1];
//                                }
//                                if (index >= currentBucketStart[bi]) {
//                                    buckets[bi][currentBucket[bi]]++;
//                                }
//                            }
//                        }
//                    } else if (container instanceof RunContainer) {
//                        RunContainer runContainer = (RunContainer) container;
//                        for (int i = 0; i < runContainer.nbrruns && numExhausted < bucketLength; i++) {
//                            int base = toIntUnsigned(runContainer.getValue(i));
//
//                            int startInclusive = base | min;
//                            int endExclusive = startInclusive + 1 + toIntUnsigned(runContainer.getLength(i));
//                            for (int index = startInclusive; index < endExclusive && numExhausted < bucketLength; index++) {
//                                next:
//                                for (int bi = 0; bi < bucketLength; bi++) {
//                                    if (!candidate[bi] || bucketContainsPos[bi] || exhausted[bi]) {
//                                        continue;
//                                    }
//                                    while (index >= currentBucketEnd[bi]) {
//                                        currentBucket[bi]++;
//                                        if (currentBucket[bi] == buckets[bi].length) {
//                                            numExhausted++;
//                                            exhausted[bi] = true;
//                                            continue next;
//                                        }
//                                        currentBucketStart[bi] = indexes[bi][currentBucket[bi]];
//                                        currentBucketEnd[bi] = indexes[bi][currentBucket[bi] + 1];
//                                    }
//                                    if (index >= currentBucketStart[bi]) {
//                                        buckets[bi][currentBucket[bi]]++;
//                                    }
//                                }
//                            }
//                        }
//                    } else {
//                        //System.out.println("BitmapContainer");
//                        BitmapContainer bitmapContainer = (BitmapContainer) container;
//                        // nextSetBit no longer performs a bounds check
//                        int maxIndex = bitmapContainer.bitmap.length << 6;
//                        for (int i = bitmapContainer.nextSetBit(0);
//                             i >= 0 && numExhausted < bucketLength;
//                             i = (i + 1 >= maxIndex) ? -1 : bitmapContainer.nextSetBit(i + 1)) {
//                            int index = toIntUnsigned((short) i) | min;
//                            next:
//                            for (int bi = 0; bi < bucketLength; bi++) {
//                                if (!candidate[bi] || bucketContainsPos[bi] || exhausted[bi]) {
//                                    continue;
//                                }
//                                while (index >= currentBucketEnd[bi]) {
//                                    currentBucket[bi]++;
//                                    if (currentBucket[bi] == buckets[bi].length) {
//                                        numExhausted++;
//                                        exhausted[bi] = true;
//                                        continue next;
//                                    }
//                                    currentBucketStart[bi] = indexes[bi][currentBucket[bi]];
//                                    currentBucketEnd[bi] = indexes[bi][currentBucket[bi] + 1];
//                                }
//                                if (index >= currentBucketStart[bi]) {
//                                    buckets[bi][currentBucket[bi]]++;
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//    }

    public static int key(int position) {
        return Util.highbits(position);
    }

    public static int[] keys(RoaringBitmap bitmap) {
        char[] bitmapKeys = bitmap.highLowContainer.keys;
        int[] copyKeys = new int[bitmap.highLowContainer.size];
        for (int i = 0; i < copyKeys.length; i++) {
            copyKeys[i] = toIntUnsigned(bitmapKeys[i]);
        }
        return copyKeys;
    }

    public static int[] keysNotEqual(RoaringBitmap x1, RoaringBitmap x2) {
        int length1 = x1.highLowContainer.size();
        int length2 = x2.highLowContainer.size();
        int pos1 = 0;
        int pos2 = 0;

        int lastKey1 = length1 == 0 ? -1 : toIntUnsigned(x1.highLowContainer.getKeyAtIndex(length1 - 1));
        int lastKey2 = length2 == 0 ? -1 : toIntUnsigned(x2.highLowContainer.getKeyAtIndex(length2 - 1));
        int[] keys = new int[Math.max(lastKey1, lastKey2) + 1];

        int ki = 0;
        while (pos1 < length1 && pos2 < length2) {
            char k1 = x1.highLowContainer.getKeyAtIndex(pos1);
            char k2 = x2.highLowContainer.getKeyAtIndex(pos2);
            if (k1 == k2) {
                Container c1 = x1.highLowContainer.getContainerAtIndex(pos1);
                Container c2 = x2.highLowContainer.getContainerAtIndex(pos2);

                if (!c1.equals(c2)) {
                    keys[ki++] = toIntUnsigned(k1);
                }

                ++pos1;
                ++pos2;
            } else if (k1 < k2) {
                keys[ki++] = toIntUnsigned(k1);
                ++pos1;
            } else {
                keys[ki++] = toIntUnsigned(k2);
                ++pos2;
            }
        }
        while (pos1 < length1) {
            char s1 = x1.highLowContainer.getKeyAtIndex(pos1);
            keys[ki++] = toIntUnsigned(s1);
            ++pos1;
        }
        while (pos2 < length2) {
            char s2 = x2.highLowContainer.getKeyAtIndex(pos2);
            keys[ki++] = toIntUnsigned(s2);
            ++pos2;
        }

        if (ki == keys.length) {
            return keys;
        } else {
            int[] compact = new int[ki];
            System.arraycopy(keys, 0, compact, 0, ki);
            return compact;
        }
    }

//    public static int[] userialize(RoaringBitmap bitmap, DataOutput[] outContainers) throws IOException {
//        return shortToIntKeys(serialize(bitmap, outContainers));
//    }

    public static boolean[] userializeAtomized(RoaringBitmap index, int[] ukeys, DataOutput[] dataOutputs) throws IOException {
        RoaringArray array = index.highLowContainer;
        char[] keys = intToCharKeys(ukeys);
        boolean[] out = new boolean[keys.length];
        for (int i = 0; i < keys.length; i++) {
            if (dataOutputs[i] == null) {
                continue;
            }
            Container container = array.getContainer(keys[i]);
            if (container != null) {
                serializeAtomized(container, dataOutputs[i]);
                out[i] = true;
            } else {
                out[i] = false;
            }
        }
        return out;
    }

//    public static short[] serialize(RoaringBitmap bitmap, DataOutput[] outContainers) throws IOException {
//        RoaringArray array = bitmap.highLowContainer;
//
//        short[] keys = new short[outContainers.length];
//        for (int k = 0; k < array.size; ++k) {
//            keys[k] = array.keys[k];
//            serializeAtomized(array.values[k], outContainers[k]);
//        }
//        return keys;
//    }

    private static void serializeAtomized(Container value, DataOutput outContainer) throws IOException {
        outContainer.writeShort(lastSetIndex(value));
        outContainer.writeBoolean(value instanceof RunContainer);
        outContainer.writeShort(Short.reverseBytes((short) (value.getCardinality() - 1)));

        value.writeArray(outContainer);
    }

    public static long[] serializeSizeInBytes(RoaringBitmap bitmap, int[] ukeys) {
        RoaringArray array = bitmap.highLowContainer;
        char[] keys = intToCharKeys(ukeys);
        long[] sizes = new long[keys.length];
        for (int i = 0; i < keys.length; i++) {
            Container container = array.getContainer(keys[i]);
            sizes[i] = (container == null) ? -1 : container.serializedSizeInBytes();
        }
        return sizes;
    }

    public static boolean udeserialize(LABBitmapAndLastId<RoaringBitmap> result, LABStreamAtoms streamAtoms) throws IOException {
        try {
            List<ContainerAndLastSetBit> containers = Lists.newArrayList();
            boolean v = streamAtoms.stream((key, dataInput) -> {
                containers.add(deserializeContainer(intToCharKey(key), dataInput));
                return true;
            });
            if (containers.isEmpty()) {
                result.clear();
            } else {
                boolean isAscending = true;
                boolean isDescending = true;
                for (int i = 1; i < containers.size(); i++) {
                    char lastKey = containers.get(i - 1).key;
                    char nextKey = containers.get(i).key;
                    if (lastKey > nextKey) {
                        isAscending = false;
                    } else if (lastKey < nextKey) {
                        isDescending = false;
                    }
                }
                if (isAscending) {
                    // do nothing
                } else if (isDescending) {
                    Collections.reverse(containers);
                } else {
                    Collections.sort(containers);
                }
                RoaringBitmap bitmap = new RoaringBitmap();
                int lastSetBit = deserialize(bitmap, containers);
                result.set(bitmap, lastSetBit);
            }
            return v;
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    public static int lastSetBit(int ukey, DataInput inContainer) throws IOException {
        int last = inContainer.readShort() & 0xFFFF;
        int hs = ukey << 16;
        return last | hs;
    }

    @VisibleForTesting
    static int deserialize(RoaringBitmap bitmap, List<ContainerAndLastSetBit> containers) {
        RoaringArray array = bitmap.highLowContainer;

        array.clear();
        array.size = containers.size();

        if ((array.keys == null) || (array.keys.length < array.size)) {
            array.keys = new char[array.size];
            array.values = new Container[array.size];
        }

        int lastSetBit = -1;
        //Reading the containers
        for (int k = 0; k < containers.size(); ++k) {
            ContainerAndLastSetBit container = containers.get(k);
            array.keys[k] = container.key;
            array.values[k] = container.container;
            lastSetBit = Math.max(lastSetBit, container.lastSetBit);
        }
        return lastSetBit;
    }

    private static ContainerAndLastSetBit deserializeContainer(char key, DataInput inContainer) throws IOException {

        int last = inContainer.readShort() & 0xFFFF;
        boolean isRun = inContainer.readBoolean();
        int cardinality = 1 + (0xFFFF & Short.reverseBytes(inContainer.readShort()));
        boolean isBitmap = cardinality > ArrayContainer.DEFAULT_MAX_SIZE;

        int hs = toIntUnsigned(key) << 16;
        int lastSetBit = last | hs;

        Container val;
        if (!isRun && isBitmap) {
            final long[] bitmapArray = new long[BitmapContainer.MAX_CAPACITY / 64];
            // little endian
            for (int l = 0; l < bitmapArray.length; ++l) {
                bitmapArray[l] = Long.reverseBytes(inContainer.readLong());
            }
            val = new BitmapContainer(bitmapArray, cardinality);
        } else if (isRun) {
            // cf RunContainer.writeArray()
            int nbrruns = toIntUnsigned(Character.reverseBytes(inContainer.readChar()));
            final char[] lengthsAndValues = new char[2 * nbrruns];

            for (int j = 0; j < 2 * nbrruns; ++j) {
                lengthsAndValues[j] = Character.reverseBytes(inContainer.readChar());
            }
            val = new RunContainer(lengthsAndValues, nbrruns);
        } else {
            final char[] charArray = new char[cardinality];
            for (int l = 0; l < charArray.length; ++l) {
                charArray[l] = Character.reverseBytes(inContainer.readChar());
            }
            val = new ArrayContainer(charArray);
        }
        return new ContainerAndLastSetBit(key, val, lastSetBit);
    }

    public static void optimize(RoaringBitmap bitmap, int[] ukeys) {
        RoaringArray array = bitmap.highLowContainer;
        char[] keys = intToCharKeys(ukeys);
        for (char key : keys) {
            int index = array.getIndex(key);
            if (index >= 0) {
                Container container = array.getContainerAtIndex(index);
                array.setContainerAtIndex(index, container.runOptimize());
            }
        }
    }

private static class ContainerAndLastSetBit implements Comparable<ContainerAndLastSetBit> {
    private final char key;
    private final Container container;
    private final int lastSetBit;

    private ContainerAndLastSetBit(char key, Container container, int lastSetBit) {
        this.key = key;
        this.container = container;
        this.lastSetBit = lastSetBit;
    }

    @Override
    public int compareTo(ContainerAndLastSetBit o) {
        return Character.compare(key, o.key);
    }
}

    public static short intToShortKey(int ukey) {
        return (short) (ukey & 0xFFFF);
    }

    public static short[] intToShortKeys(int[] ukeys) {
        short[] keys = new short[ukeys.length];
        for (int i = 0; i < keys.length; i++) {
            keys[i] = intToShortKey(ukeys[i]);
        }
        return keys;
    }

    private static char intToCharKey(int ukey) {
        return (char) ukey;
    }

    private static char[] intToCharKeys(int[] ukeys) {
        char[] keys = new char[ukeys.length];
        for (int i = 0; i < keys.length; i++) {
            keys[i] = intToCharKey(ukeys[i]);
        }
        return keys;
    }

    private static int toIntUnsigned(char x) {
        return x & 0xFFFF;
    }

//    public static int[] shortToIntKeys(short[] keys) {
//        int[] ukeys = new int[keys.length];
//        for (int i = 0; i < ukeys.length; i++) {
//            ukeys[i] = toIntUnsigned(keys[i]);
//        }
//        return ukeys;
//    }
//
//    public static int containerCount(RoaringBitmap bitmap) {
//        return bitmap.highLowContainer.size;
//    }

//    public static int naiveFirstIntersectingBit(RoaringBitmap x1, RoaringBitmap x2) {
//        int length1 = x1.highLowContainer.size();
//        int length2 = x2.highLowContainer.size();
//        int pos1 = 0;
//        int pos2 = 0;
//
//        while (pos1 < length1 && pos2 < length2) {
//            short s1 = x1.highLowContainer.getKeyAtIndex(pos1);
//            short s2 = x2.highLowContainer.getKeyAtIndex(pos2);
//            if (s1 == s2) {
//                Container c1 = x1.highLowContainer.getContainerAtIndex(pos1);
//                Container c2 = x2.highLowContainer.getContainerAtIndex(pos2);
//                if (c1.intersects(c2)) {
//                    Container and = c1.and(c2);
//                    int hs = toIntUnsigned(s1) << 16;
//                    return and.first() | hs;
//                }
//
//                ++pos1;
//                ++pos2;
//            } else if (Util.compareUnsigned(s1, s2) < 0) {
//                pos1 = x1.highLowContainer.advanceUntil(s2, pos1);
//            } else {
//                pos2 = x2.highLowContainer.advanceUntil(s1, pos2);
//            }
//        }
//
//        return -1;
//    }
//
//    public static int firstIntersectingBit(RoaringBitmap x1, RoaringBitmap x2) {
//        int length1 = x1.highLowContainer.size();
//        int length2 = x2.highLowContainer.size();
//        int pos1 = 0;
//        int pos2 = 0;
//
//        while (pos1 < length1 && pos2 < length2) {
//            short s1 = x1.highLowContainer.getKeyAtIndex(pos1);
//            short s2 = x2.highLowContainer.getKeyAtIndex(pos2);
//            if (s1 == s2) {
//                Container c1 = x1.highLowContainer.getContainerAtIndex(pos1);
//                Container c2 = x2.highLowContainer.getContainerAtIndex(pos2);
//                int r = firstIntersectingBit(c1, c2);
//                if (r != -1) {
//                    int hs = toIntUnsigned(s1) << 16;
//                    return r | hs;
//                }
//
//                ++pos1;
//                ++pos2;
//            } else if (Util.compareUnsigned(s1, s2) < 0) {
//                pos1 = x1.highLowContainer.advanceUntil(s2, pos1);
//            } else {
//                pos2 = x2.highLowContainer.advanceUntil(s1, pos2);
//            }
//        }
//
//        return -1;
//    }

//    @VisibleForTesting
//    static int firstIntersectingBit(Container c1, Container c2) {
//        if (c1 instanceof RunContainer) {
//            if (c2 instanceof RunContainer) {
//                return firstIntersectingBit((RunContainer) c1, (RunContainer) c2);
//            } else if (c2 instanceof BitmapContainer) {
//                return firstIntersectingBit((RunContainer) c1, (BitmapContainer) c2);
//            } else if (c2 instanceof ArrayContainer) {
//                return firstIntersectingBit((RunContainer) c1, (ArrayContainer) c2);
//            }
//        } else if (c1 instanceof BitmapContainer) {
//            if (c2 instanceof RunContainer) {
//                return firstIntersectingBit((RunContainer) c2, (BitmapContainer) c1);
//            } else if (c2 instanceof BitmapContainer) {
//                return firstIntersectingBit((BitmapContainer) c1, (BitmapContainer) c2);
//            } else if (c2 instanceof ArrayContainer) {
//                return firstIntersectingBit((BitmapContainer) c1, (ArrayContainer) c2);
//            }
//        } else if (c1 instanceof ArrayContainer) {
//            if (c2 instanceof RunContainer) {
//                return firstIntersectingBit((RunContainer) c2, (ArrayContainer) c1);
//            } else if (c2 instanceof BitmapContainer) {
//                return firstIntersectingBit((BitmapContainer) c2, (ArrayContainer) c1);
//            } else if (c2 instanceof ArrayContainer) {
//                return firstIntersectingBit((ArrayContainer) c1, (ArrayContainer) c2);
//            }
//        }
//        return -1;
//    }

//    private static int firstIntersectingBit(RunContainer c1, RunContainer c2) {
//        int rlepos = 0;
//        int xrlepos = 0;
//        int start = toIntUnsigned(c1.getValue(rlepos));
//        int end = start + toIntUnsigned(c1.getLength(rlepos)) + 1;
//        int xstart = toIntUnsigned(c2.getValue(xrlepos));
//        int xend = xstart + toIntUnsigned(c2.getLength(xrlepos)) + 1;
//
//        while (rlepos < c1.nbrruns && xrlepos < c2.nbrruns) {
//            if (end <= xstart) {
//                // [start -> end]
//                //                [xstart -> xend]
//                ++rlepos;
//                if (rlepos < c1.nbrruns) {
//                    start = toIntUnsigned(c1.getValue(rlepos));
//                    end = start + toIntUnsigned(c1.getLength(rlepos)) + 1;
//                }
//            } else {
//                // [start -> end]
//                //        [xstart -> xend]
//
//                // [start    ->    end]
//                //   [xstart -> xend]
//
//                // [start  ->  end]
//                // [xstart -> xend]
//
//                //   [start -> end]
//                // [xstart  ->  xend]
//
//                //   [start -> end]
//                // [xstart -> xend]
//
//                //                  [start  ->  end]
//                // [xstart -> xend]
//
//                if (xend > start) {
//                    // [start    ->    end]
//                    //   [xstart -> xend]
//
//                    // [start  ->  end]
//                    // [xstart -> xend]
//
//                    //   [start  ->  end]
//                    // [xstart   ->   xend]
//
//                    //        [start -> end]
//                    // [xstart -> xend]
//                    return Math.max(start, xstart);
//                }
//
//                ++xrlepos;
//                if (xrlepos < c2.nbrruns) {
//                    xstart = toIntUnsigned(c2.getValue(xrlepos));
//                    xend = xstart + toIntUnsigned(c2.getLength(xrlepos)) + 1;
//                }
//            }
//        }
//
//        return -1;
//    }
//
//    private static int firstIntersectingBit(RunContainer c1, ArrayContainer c2) {
//        if (c1.nbrruns == 0) {
//            return -1;
//        } else {
//            int rlepos = 0;
//            int arraypos = 0;
//            int rleval = toIntUnsigned(c1.getValue(rlepos));
//
//            for (int rlelength = toIntUnsigned(c1.getLength(rlepos)); arraypos < c2.cardinality; arraypos = Util.advanceUntil(c2.content, arraypos,
//                c2.cardinality, c1.getValue(rlepos))) {
//                int arrayval;
//                for (arrayval = toIntUnsigned(c2.content[arraypos]); rleval + rlelength < arrayval; rlelength = toIntUnsigned(c1.getLength(rlepos))) {
//                    ++rlepos;
//                    if (rlepos == c1.nbrruns) {
//                        return -1;
//                    }
//
//                    rleval = toIntUnsigned(c1.getValue(rlepos));
//                }
//
//                if (rleval <= arrayval) {
//                    return arrayval;
//                }
//            }
//
//            return -1;
//        }
//    }
//
//    private static int firstIntersectingBit(RunContainer c1, BitmapContainer c2) {
//        for (int rlepos = 0; rlepos < c1.nbrruns; ++rlepos) {
//            int runStart = toIntUnsigned(c1.getValue(rlepos));
//            int runEnd = runStart + toIntUnsigned(c1.getLength(rlepos));
//
//            for (int runValue = runStart; runValue <= runEnd; ++runValue) {
//                if (c2.contains((short) runValue)) {
//                    return runValue;
//                }
//            }
//        }
//
//        return -1;
//    }

//    private static int firstIntersectingBit(BitmapContainer c1, BitmapContainer c2) {
//        for (int k = 0; k < c1.bitmap.length; ++k) {
//            long x = c1.bitmap[k] & c2.bitmap[k];
//            if (x != 0L) {
//                return (k * 64) + Long.numberOfTrailingZeros(x);
//            }
//        }
//
//        return -1;
//    }
//
//    private static int firstIntersectingBit(BitmapContainer c1, ArrayContainer c2) {
//        int c = c2.cardinality;
//
//        for (int k = 0; k < c; ++k) {
//            if (c1.contains(c2.content[k])) {
//                return toIntUnsigned(c2.content[k]);
//            }
//        }
//
//        return -1;
//    }
//
//    private static int firstIntersectingBit(ArrayContainer c1, ArrayContainer c2) {
//        short[] set1 = c1.content;
//        int length1 = c1.getCardinality();
//        short[] set2 = c2.content;
//        int length2 = c2.getCardinality();
//        if (0 != length1 && 0 != length2) {
//            int k1 = 0;
//            int k2 = 0;
//            short s1 = set1[k1];
//            short s2 = set2[k2];
//
//            while (true) {
//                if (toIntUnsigned(s2) < toIntUnsigned(s1)) {
//                    do {
//                        ++k2;
//                        if (k2 == length2) {
//                            return -1;
//                        }
//
//                        s2 = set2[k2];
//                    }
//                    while (toIntUnsigned(s2) < toIntUnsigned(s1));
//                }
//
//                if (toIntUnsigned(s1) >= toIntUnsigned(s2)) {
//                    return Util.toIntUnsigned(s1);
//                }
//
//                while (true) {
//                    ++k1;
//                    if (k1 == length1) {
//                        return -1;
//                    }
//
//                    s1 = set1[k1];
//                    if (toIntUnsigned(s1) >= toIntUnsigned(s2)) {
//                        break;
//                    }
//                }
//            }
//        } else {
//            return -1;
//        }
//    }

//    private LABRoaringInspection() {
//    }
}


text:
package org.apache.kafka.streams.processor.internals.assignment;

import org.apache.kafka.streams.processor.TaskId;
import org.apache.kafka.streams.processor.internals.assignment.AssignorConfiguration.AssignmentConfigs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;

public class StickyTaskAssignor implements TaskAssignor {

    private static final Logger log = LoggerFactory.getLogger(StickyTaskAssignor.class);
    private Map<UUID, ClientState> clients;
    private Set<TaskId> allTaskIds;
    private Set<TaskId> standbyTaskIds;
    private final Map<TaskId, UUID> previousActiveTaskAssignment = new HashMap<>();
    private final Map<TaskId, Set<UUID>> previousStandbyTaskAssignment = new HashMap<>();
    private TaskPairs taskPairs;

    private final boolean mustPreserveActiveTaskAssignment;

    public StickyTaskAssignor() {
        this(false);
    }

    StickyTaskAssignor(final boolean mustPreserveActiveTaskAssignment) {
        this.mustPreserveActiveTaskAssignment = mustPreserveActiveTaskAssignment;
    }

    @Override
    public boolean assign(final Map<UUID, ClientState> clients,
                          final Set<TaskId> allTaskIds,
                          final Set<TaskId> statefulTaskIds,
                          final AssignmentConfigs configs) {
        this.clients = clients;
        this.allTaskIds = allTaskIds;
        this.standbyTaskIds = statefulTaskIds;

        final int maxPairs = allTaskIds.size() * (allTaskIds.size() - 1) / 2;
        taskPairs = new TaskPairs(maxPairs);
        mapPreviousTaskAssignment(clients);

        assignActive();
        assignStandby(configs.numStandbyReplicas);
        return false;
    }

    private void assignStandby(final int numStandbyReplicas) {
        for (final TaskId taskId : standbyTaskIds) {
            for (int i = 0; i < numStandbyReplicas; i++) {
                final Set<UUID> ids = findClientsWithoutAssignedTask(taskId);
                if (ids.isEmpty()) {
                    log.warn("Unable to assign {} of {} standby tasks for task [{}]. " +
                                     "There is not enough available capacity. You should " +
                                     "increase the number of threads and/or application instances " +
                                     "to maintain the requested number of standby replicas.",
                             numStandbyReplicas - i,
                             numStandbyReplicas, taskId);
                    break;
                }
                allocateTaskWithClientCandidates(taskId, ids, false);
            }
        }
    }

    private void assignActive() {
        final int totalCapacity = sumCapacity(clients.values());
        final int tasksPerThread = allTaskIds.size() / totalCapacity;
        final Set<TaskId> assigned = new HashSet<>();

        // first try and re-assign existing active tasks to clients that previously had
        // the same active task
        for (final Map.Entry<TaskId, UUID> entry : previousActiveTaskAssignment.entrySet()) {
            final TaskId taskId = entry.getKey();
            if (allTaskIds.contains(taskId)) {
                final ClientState client = clients.get(entry.getValue());
                if (mustPreserveActiveTaskAssignment || client.hasUnfulfilledQuota(tasksPerThread)) {
                    assignTaskToClient(assigned, taskId, client);
                }
            }
        }

        final Set<TaskId> unassigned = new HashSet<>(allTaskIds);
        unassigned.removeAll(assigned);

        // try and assign any remaining unassigned tasks to clients that previously
        // have seen the task.
        for (final Iterator<TaskId> iterator = unassigned.iterator(); iterator.hasNext(); ) {
            final TaskId taskId = iterator.next();
            final Set<UUID> clientIds = previousStandbyTaskAssignment.get(taskId);
            if (clientIds != null) {
                for (final UUID clientId : clientIds) {
                    final ClientState client = clients.get(clientId);
                    if (client.hasUnfulfilledQuota(tasksPerThread)) {
                        assignTaskToClient(assigned, taskId, client);
                        iterator.remove();
                        break;
                    }
                }
            }
        }

        // assign any remaining unassigned tasks
        final List<TaskId> sortedTasks = new ArrayList<>(unassigned);
        Collections.sort(sortedTasks);
        for (final TaskId taskId : sortedTasks) {
            allocateTaskWithClientCandidates(taskId, clients.keySet(), true);
        }
    }

    private void allocateTaskWithClientCandidates(final TaskId taskId, final Set<UUID> clientsWithin, final boolean active) {
        final ClientState client = findClient(taskId, clientsWithin);
        taskPairs.addPairs(taskId, client.assignedTasks());
        if (active) {
            client.assignActive(taskId);
        } else {
            client.assignStandby(taskId);
        }
    }

    private void assignTaskToClient(final Set<TaskId> assigned, final TaskId taskId, final ClientState client) {
        taskPairs.addPairs(taskId, client.assignedTasks());
        client.assignActive(taskId);
        assigned.add(taskId);
    }

    private Set<UUID> findClientsWithoutAssignedTask(final TaskId taskId) {
        final Set<UUID> clientIds = new HashSet<>();
        for (final Map.Entry<UUID, ClientState> client : clients.entrySet()) {
            if (!client.getValue().hasAssignedTask(taskId)) {
                clientIds.add(client.getKey());
            }
        }
        return clientIds;
    }

    private ClientState findClient(final TaskId taskId, final Set<UUID> clientsWithin) {

        // optimize the case where there is only 1 id to search within.
        if (clientsWithin.size() == 1) {
            return clients.get(clientsWithin.iterator().next());
        }

        final ClientState previous = findClientsWithPreviousAssignedTask(taskId, clientsWithin);
        if (previous == null) {
            return leastLoaded(taskId, clientsWithin);
        }

        if (shouldBalanceLoad(previous)) {
            final ClientState standby = findLeastLoadedClientWithPreviousStandByTask(taskId, clientsWithin);
            if (standby == null || shouldBalanceLoad(standby)) {
                return leastLoaded(taskId, clientsWithin);
            }
            return standby;
        }

        return previous;
    }

    private boolean shouldBalanceLoad(final ClientState client) {
        return client.reachedCapacity() && hasClientsWithMoreAvailableCapacity(client);
    }

    private boolean hasClientsWithMoreAvailableCapacity(final ClientState client) {
        for (final ClientState clientState : clients.values()) {
            if (clientState.hasMoreAvailableCapacityThan(client)) {
                return true;
            }
        }
        return false;
    }

    private ClientState findClientsWithPreviousAssignedTask(final TaskId taskId, final Set<UUID> clientsWithin) {
        final UUID previous = previousActiveTaskAssignment.get(taskId);
        if (previous != null && clientsWithin.contains(previous)) {
            return clients.get(previous);
        }
        return findLeastLoadedClientWithPreviousStandByTask(taskId, clientsWithin);
    }

    private ClientState findLeastLoadedClientWithPreviousStandByTask(final TaskId taskId, final Set<UUID> clientsWithin) {
        final Set<UUID> ids = previousStandbyTaskAssignment.get(taskId);
        if (ids == null) {
            return null;
        }
        final HashSet<UUID> constrainTo = new HashSet<>(ids);
        constrainTo.retainAll(clientsWithin);
        return leastLoaded(taskId, constrainTo);
    }

    private ClientState leastLoaded(final TaskId taskId, final Set<UUID> clientIds) {
        final ClientState leastLoaded = findLeastLoaded(taskId, clientIds, true);
        if (leastLoaded == null) {
            return findLeastLoaded(taskId, clientIds, false);
        }
        return leastLoaded;
    }

    private ClientState findLeastLoaded(final TaskId taskId,
                                        final Set<UUID> clientIds,
                                        final boolean checkTaskPairs) {
        ClientState leastLoaded = null;
        for (final UUID id : clientIds) {
            final ClientState client = clients.get(id);
            if (client.assignedTaskCount() == 0) {
                return client;
            }

            if (leastLoaded == null || client.hasMoreAvailableCapacityThan(leastLoaded)) {
                if (!checkTaskPairs) {
                    leastLoaded = client;
                } else if (taskPairs.hasNewPair(taskId, client.assignedTasks())) {
                    leastLoaded = client;
                }
            }

        }
        return leastLoaded;

    }

    private void mapPreviousTaskAssignment(final Map<UUID, ClientState> clients) {
        for (final Map.Entry<UUID, ClientState> clientState : clients.entrySet()) {
            for (final TaskId activeTask : clientState.getValue().prevActiveTasks()) {
                previousActiveTaskAssignment.put(activeTask, clientState.getKey());
            }

            for (final TaskId prevAssignedTask : clientState.getValue().prevStandbyTasks()) {
                previousStandbyTaskAssignment.computeIfAbsent(prevAssignedTask, t -> new HashSet<>());
                previousStandbyTaskAssignment.get(prevAssignedTask).add(clientState.getKey());
            }
        }

    }

    private int sumCapacity(final Collection<ClientState> values) {
        int capacity = 0;
        for (final ClientState client : values) {
            capacity += client.capacity();
        }
        return capacity;
    }

    private static class TaskPairs {
        private final Set<Pair> pairs;
        private final int maxPairs;

        TaskPairs(final int maxPairs) {
            this.maxPairs = maxPairs;
            this.pairs = new HashSet<>(maxPairs);
        }

        boolean hasNewPair(final TaskId task1,
                           final Set<TaskId> taskIds) {
            if (pairs.size() == maxPairs) {
                return false;
            }
            for (final TaskId taskId : taskIds) {
                if (!pairs.contains(pair(task1, taskId))) {
                    return true;
                }
            }
            return false;
        }

        void addPairs(final TaskId taskId, final Set<TaskId> assigned) {
            for (final TaskId id : assigned) {
                pairs.add(pair(id, taskId));
            }
        }

        Pair pair(final TaskId task1, final TaskId task2) {
            if (task1.compareTo(task2) < 0) {
                return new Pair(task1, task2);
            }
            return new Pair(task2, task1);
        }

        private static class Pair {
            private final TaskId task1;
            private final TaskId task2;

            Pair(final TaskId task1, final TaskId task2) {
                this.task1 = task1;
                this.task2 = task2;
            }

            @Override
            public boolean equals(final Object o) {
                if (this == o) {
                    return true;
                }
                if (o == null || getClass() != o.getClass()) {
                    return false;
                }
                final Pair pair = (Pair) o;
                return Objects.equals(task1, pair.task1) &&
                        Objects.equals(task2, pair.task2);
            }

            @Override
            public int hashCode() {
                return Objects.hash(task1, task2);
            }
        }

    }

}