text:
require_relative '../helper'

class Repositext

  describe RFile do

    let(:contents) { 'contents' }
    let(:language) { Language::English.new }
    let(:content_type_name) { 'general' }
    let(:repo_name) { 'rt-english' }
    let(:path_to_repo) {
      File.join(Repository::Test.repos_folder, repo_name, '')
    }
    let(:repo) {
      Repository::Test.create!(repo_name)
      Repository::Content.new(path_to_repo)
    }
    let(:path_to_content_type) {
      File.join(repo.base_dir, "ct-#{ content_type_name }", '')
    }
    let(:content_type) {
      ContentType.new(path_to_content_type)
    }
    let(:file_basename) {
      "eng57-0103-1234.txt"
    }
    let(:content_type_relative_path_segments) {
      "content/57"
    }
    let(:filename) {
      File.join(path_to_content_type, content_type_relative_path_segments, file_basename)
    }
    let(:default_rfile) {
      RFile.new(contents, language, filename, content_type)
    }

    describe '.relative_path_from_to' do
      [
        [
          '/path/to/rt-spanish/ct-general/content/15/',
          '/path/to/rt-english/ct-general/content/15/eng15-1231_1234.at',
          '../../../../rt-english/ct-general/content/15/eng15-1231_1234.at',
        ],
        [
          '/path/to/rt-spanish/ct-general/content/15/',
          '/path/to/rt-english/ct-general/content/15/eng15-1231_1234.subtitle_markers.csv',
          '../../../../rt-english/ct-general/content/15/eng15-1231_1234.subtitle_markers.csv',
        ],
      ].each do |source_path, target_path, xpect|
        it "handles #{ source_path.inspect }" do
          RFile.relative_path_from_to(
            source_path,
            target_path
          ).must_equal(xpect)
        end
      end
    end

    describe '.get_class_for_filename' do
      [
        [
          '/repositext/rt-english/ct-general/content/57/eng57-0103_1234.subtitle_markers.csv',
          RFile::SubtitleMarkersCsv
        ],
        [
          '/repositext/rt-english/ct-general/content/57/eng57-0103_1234.data.json',
          RFile::DataJson
        ],
        [
          '/repositext/rt-english/ct-general/docx_import/57/eng57-0103_1234.docx',
          RFile::Docx
        ],
        [
          '/repositext/rt-english/ct-general/pdf_export/57/eng57-0103_1234.translator.pdf',
          RFile::Pdf
        ],
        [
          '/repositext/rt-english/ct-general/content/57/eng57-0103_1234.at',
          RFile::ContentAt
        ],
        [
          '/repositext/rt-english/ct-general/html_export/57/eng57-0103_1234.html',
          RFile::Content
        ],
        [
          '/repositext/rt-english/ct-general/reports/some_report.txt',
          RFile::Text
        ],
      ].each do |filename, xpect|
        it "handles #{ filename.inspect }" do
          RFile.get_class_for_filename(filename).must_equal(xpect)
        end
      end
    end

    describe '#initialize' do
      it 'initializes contents' do
        default_rfile.contents.must_equal(contents)
      end

      it 'initializes language' do
        default_rfile.language.must_equal(language)
      end

      it 'initializes filename' do
        default_rfile.filename.must_equal(filename)
      end
    end

    describe '#basename' do
      it 'handles default data' do
        default_rfile.basename.must_equal(file_basename)
      end
    end

    describe '#dir' do
      it 'handles default data' do
        default_rfile.dir.must_equal(filename.sub("/#{ file_basename }", ''))
      end
    end

    describe '#is_binary' do
      it 'returns false' do
        default_rfile.is_binary.must_equal(false)
      end
    end

    describe '#lang_code_3' do
      it 'returns correct value' do
        default_rfile.lang_code_3.must_equal(:eng)
      end
    end

    describe '#repo_relative_path' do
      it 'returns path without repo root by default' do
        default_rfile.repo_relative_path.must_equal(
          'ct-general/content/57/eng57-0103-1234.txt'
        )
      end

      it 'returns path with repo root if passed true' do
        default_rfile.repo_relative_path(true).must_equal(
          'rt-english/ct-general/content/57/eng57-0103-1234.txt'
        )
      end
    end

  end
end


text:
package ru.pavlenov.bio.chapter.rosalind.string_algoritm;

import net.sf.jfasta.impl.FASTAElementIterator;
import net.sf.jfasta.impl.FASTAFileReaderImpl;
import org.apache.commons.lang.StringUtils;
import ru.pavlenov.bio.genome.Motif;
import ru.pavlenov.bio.utils.Dump;
import ru.pavlenov.bio.utils.File;

import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Какой сам ☭
 * User: Павленов Семён
 * Date: 11.01.14 14:56
 */
public class Cons {

    /**
     * Consensus and Profile
     * http://rosalind.info/problems/cons/
     *
     * Given: A collection of at most 10 DNA strings of equal length (at most 1 kbp) in FASTA format.
     * Return: A consensus string and profile matrix for the collection.
     * (If several possible consensus strings exist, then you may return any one of them.)
     *
     */
    public static void start() throws IOException {

        String data = File.readFile("/home/laser13/IdeaProjects/bio/src/ru/pavlenov/bio/chapter/rosalind/string_algoritm/Cons.data", Charset.defaultCharset());

        FASTAFileReaderImpl fasta = new FASTAFileReaderImpl(new StringReader(data));
        final FASTAElementIterator it = fasta.getIterator();

        List<String> kmerList = new ArrayList<>();

        while (it.hasNext()) {
            kmerList.add(it.next().getSequence());
        }

        Motif motif = new Motif(kmerList.toArray(new String[kmerList.size()]));

        Dump.println(motif.getConsensus());
        Dump.print("A: "); Dump.println(StringUtils.join(motif.getCount()[0], " "));
        Dump.print("C: "); Dump.println(StringUtils.join(motif.getCount()[1], " "));
        Dump.print("G: "); Dump.println(StringUtils.join(motif.getCount()[2], " "));
        Dump.print("T: "); Dump.println(StringUtils.join(motif.getCount()[3], " "));

    }

}

redpajama_set_name: RedPajamaGithub


text: Extended filter plugin for annotator.js


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>qesp : qespta.pro Example File (examples/qespta/qespta.pro)</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

Home · All Classes ·

qespta.pro Example File

examples/qespta/qespta.pro

    TEMPLATE = app
    DEPENDPATH += .
    QT += core gui
    contains(QT_VERSION, ^5\\..*\\..*): QT += widgets
    HEADERS += MainWindow.h \
                    MessageWindow.h \
            QespTest.h

    SOURCES += main.cpp \
                    MainWindow.cpp \
                    MessageWindow.cpp \
                    QespTest.cpp

    include(../../src/qextserialport.pri)

<address>

Copyright © 2000-2012
QextSerialPort Project

QextSerialPort Manual

</address>


text:
/**
 * @fileoverview Button
 * @author burning <iburning@live.cn>
 * @version 2017.08.30
 */

//Aliases
// console.log('PIXI', PIXI)
const Container = PIXI.Container
const Loader = PIXI.loader
const Renderer = PIXI.autoDetectRenderer
const Resources = PIXI.loader.resources

const UNIT = 8
const GRAVITY = 1
const COLOR_BLACK = 0x333333
const COLOR_WHITE = 0xFFFFFF

// Create a Pixi stage and renderer
const stage = new Container()
const renderer = Renderer(750, 1200)
// renderer.view.style.border = "1px solid #ccc"
renderer.backgroundColor = COLOR_WHITE
document.body.appendChild(renderer.view)

// Scale the canvas to the maximum window
let scale = scaleToWindow(renderer.view)

// Set the initial game state
let state = play
let gameScene

// Create a new instance of Bump, the collision module
const bump = new Bump(PIXI)

// Create a new instance of Tink, the interactive module.
// const tink = new Tink(PIXI, renderer.view, scale)
const tink = new Tink(PIXI, renderer.view, scale)

// Define any variables that might be used in more than one function

// Append link tag to html header
linkFont("assets/Pixilator.ttf")

// Load resources (images and fonts) and then run the 'setup' function
Loader.add([
  "assets/Pixilator.ttf",
  "assets/button.json"
]).load(setup)

function setup() {
  // Get a reference to the texture atlas frame ids
  let frameIds = Resources["assets/button.json"].textures
  let buttonFrames = [
    frameIds["up.png"],
    frameIds["over.png"],
    frameIds["down.png"]
  ]

  gameScene = new Container()
  stage.addChild(gameScene)

  let playButton = tink.button(buttonFrames, 32, 96)
  playButton.x = (renderer.view.width - playButton.width) / 2
  playButton.y = (renderer.view.height - playButton.height) / 2
  gameScene.addChild(playButton)

  playButton.press = () => {
    console.log('playButton press')
  }

  // Start the game loop
  gameLoop()
}

function gameLoop() {
  // Loop this function 60 times per second
  requestAnimationFrame(gameLoop)

  // Run the current state
  state()

  tink.update()

  //Render the stage
  renderer.render(stage)
}

function play() {
  // Any animation or game logic code goes here
}

function end() {
  console.log("end")
}

function linkFont(source) {
  // console.log("linkFont", source)
  // Use the font's filename as the 'fontFamily' name.
  // This code captures the font file's name without the extension or file path
  let fontFamily = source.split("/").pop().split(".")[0]

  // Append an '@font-face' style rule to the head of the HTML document
  let newStyle = document.createElement("style")
  let fontFace = `@font-face {
    font-family: "${fontFamily}";
    src: url("${source}");
  }`
  newStyle.appendChild(document.createTextNode(fontFace))
  document.head.appendChild(newStyle)
}


text:
package org.jlcf.core;

/**
 * Interface used by Receptacle implementations.
 * It provides the basic functionality to add and remove interceptors at runtime.
 *
 * @author Petros Pissias
 *
 */
public interface IReceptacle {

	/**
	 * adds an interceptor at the end of the call chain.
	 * @param interceptor the interceptor implementation
	 */
	public void addInterceptor(Interceptor interceptor);

	/**
	 * Removes the interfceptor from the call chain.
	 * @param interceptor
	 */
	public void removeInterceptor(Interceptor interceptor);

}


text:
using Microsoft.AspNetCore.Razor.Hosting;
using Microsoft.Extensions.Primitives;
using Moq;

namespace Microsoft.AspNetCore.Mvc.Razor.Compilation;

public class DefaultRazorPageFactoryProviderTest
{
    [Fact]
    public void CreateFactory_ReturnsViewDescriptor_ForUnsuccessfulResults()
    {
        // Arrange
        var path = "/file-does-not-exist";
        var expirationTokens = new[]
        {
                Mock.Of<IChangeToken>(),
                Mock.Of<IChangeToken>(),
            };
        var descriptor = new CompiledViewDescriptor
        {
            RelativePath = path,
            ExpirationTokens = expirationTokens,
        };
        var compilerCache = new Mock<IViewCompiler>();
        compilerCache
            .Setup(f => f.CompileAsync(It.IsAny<string>()))
            .ReturnsAsync(descriptor);

        var factoryProvider = new DefaultRazorPageFactoryProvider(GetCompilerProvider(compilerCache.Object));

        // Act
        var result = factoryProvider.CreateFactory(path);

        // Assert
        Assert.False(result.Success);
        Assert.Same(descriptor, result.ViewDescriptor);
    }

    [Fact]
    public void CreateFactory_ReturnsViewDescriptor_ForSuccessfulResults()
    {
        // Arrange
        var relativePath = "/file-exists";
        var expirationTokens = new[]
        {
                Mock.Of<IChangeToken>(),
                Mock.Of<IChangeToken>(),
            };
        var descriptor = new CompiledViewDescriptor
        {
            RelativePath = relativePath,
            Item = TestRazorCompiledItem.CreateForView(typeof(TestRazorPage), relativePath),
            ExpirationTokens = expirationTokens,
        };
        var compilerCache = new Mock<IViewCompiler>();
        compilerCache
            .Setup(f => f.CompileAsync(It.IsAny<string>()))
            .ReturnsAsync(descriptor);

        var factoryProvider = new DefaultRazorPageFactoryProvider(GetCompilerProvider(compilerCache.Object));

        // Act
        var result = factoryProvider.CreateFactory(relativePath);

        // Assert
        Assert.True(result.Success);
        Assert.Equal(expirationTokens, descriptor.ExpirationTokens);
    }

    [Fact]
    public void CreateFactory_ProducesDelegateThatSetsPagePath()
    {
        // Arrange
        var relativePath = "/file-exists";
        var descriptor = new CompiledViewDescriptor
        {
            RelativePath = relativePath,
            Item = TestRazorCompiledItem.CreateForView(typeof(TestRazorPage), relativePath),
            ExpirationTokens = Array.Empty<IChangeToken>(),
        };
        var viewCompiler = new Mock<IViewCompiler>();
        viewCompiler
            .Setup(f => f.CompileAsync(It.IsAny<string>()))
            .ReturnsAsync(descriptor);

        var factoryProvider = new DefaultRazorPageFactoryProvider(GetCompilerProvider(viewCompiler.Object));

        // Act
        var result = factoryProvider.CreateFactory(relativePath);

        // Assert
        Assert.True(result.Success);
        var actual = result.RazorPageFactory();
        Assert.Equal("/file-exists", actual.Path);
    }

    private IViewCompilerProvider GetCompilerProvider(IViewCompiler cache)
    {
        var compilerCacheProvider = new Mock<IViewCompilerProvider>();
        compilerCacheProvider
            .Setup(c => c.GetCompiler())
            .Returns(cache);

        return compilerCacheProvider.Object;
    }

    private class TestRazorPage : RazorPage
    {
        public override Task ExecuteAsync()
        {
            throw new NotImplementedException();
        }
    }
}


text:
package com.hoyotech.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.log4j.Logger;

import com.hoyotech.bean.SpProduct;
import com.hoyotech.bean.VirtualBrowser;
import com.hoyotech.thread.MySSLProtocolSocketFactory;

public class HttpsTool {
    public static final String phone = "13212712555";
    private static Logger logger = Logger.getLogger(HttpsTool.class);
    /**
     * strean 转换为字符串
     * @param in
     * @return
     * @throws IOException
     */
    public static String inputStream2String(InputStream in,String encoding) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            out.append(new String(b, 0, n,encoding));
        }
        return out.toString();
    }
    /**
     * httpGet请求
     * @param url
     * @param header
     * @return
     */
    public static VirtualBrowser get(String url,Map<String,String> header,String encoding){
        VirtualBrowser vb = new VirtualBrowser();
        HttpClient httpclient = new HttpClient();
        GetMethod httpget = new GetMethod(url);
        try {
            Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
            Protocol.registerProtocol("https", myhttps);
            for(String li:header.keySet()){
                httpget.addRequestHeader(li, header.get(li));
            }
            String cookieString = header.get("Cookie");
            Map<String,String> cookies = new HashMap<String,String>();
            if(cookieString != null){
                String[] keyValue = cookieString.split(";");
                for(String li:keyValue){
                    if(li.length() > 0 && li.contains("=")){
                        String key = li.substring(0, li.indexOf("="));
                        String value = li.substring(li.indexOf("=")+1,li.length());
                        cookies.put(key,value);
                    }
                }
            }
            int respCode = httpclient.executeMethod(httpget);
            vb.setStatus(respCode);
            Header[] respHeader = httpget.getResponseHeaders();
            InputStream stream = httpget.getResponseBodyAsStream();
            String respString = inputStream2String(stream,encoding);
            vb.setHtml(respString);
            //服务器返回的Set-Cookie字段处理,更新cookie
            for(Header li:respHeader){
                String headerName = li.getName();
                String headerValue = li.getValue();
                if("Set-Cookie".equals(headerName)){
                    String[] cookieKeyValue = headerValue.split(";");
                    for(String cookie:cookieKeyValue){
                        if(cookie.length() > 0 && cookie.contains("=")){
                            String key = cookie.substring(0, cookie.indexOf("="));
                            String value = cookie.substring(cookie.indexOf("=")+1,cookie.length());
                            cookies.put(key,value);
                        }
                    }
                }
            }
            vb.setCookies(cookies);
            httpget.abort();
        }catch(Exception e){
            logger.error(e.getMessage());
        }finally{
            httpget.releaseConnection();
//            httpclient.getHttpConnectionManager().closeIdleConnections(0);
        }
        return vb;
    }
    /**
     * httpPost请求
     * @param url
     * @param header
     * @param params
     * @param encoding
     * @return
     */
    public static VirtualBrowser post(String url,Map<String,String> header,Map<String,String> params,String encoding){
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(url);
        VirtualBrowser vb = new VirtualBrowser();
        for(String li:header.keySet()){
            post.addRequestHeader(li,header.get(li));
        }
        for(String li:params.keySet()){
            post.addParameter(li,params.get(li));
        }
        //请求中的cookie
        String cookieString = header.get("Cookie");
        Map<String,String> cookies = new HashMap<String,String>();
        if(cookieString != null){
            String[] keyValue = cookieString.split(";");
            for(String li:keyValue){
                if(li.length() > 0 && li.contains("=")){
                    String key = li.substring(0, li.indexOf("="));
                    String value = li.substring(li.indexOf("=")+1,li.length());
                    cookies.put(key,value);
                }
            }
        }
        try {
            Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
            Protocol.registerProtocol("https", myhttps);
            int respCode = httpclient.executeMethod(post);
            vb.setStatus(respCode);
            InputStream stream = post.getResponseBodyAsStream();
            String respString = inputStream2String(stream,encoding);
            vb.setHtml(respString);
            Header[] respHeader = post.getResponseHeaders();
            //服务器返回的Set-Cookie字段处理,更新cookie
            for(Header li:respHeader){
                String headerName = li.getName();
                String headerValue = li.getValue();
                if("Set-Cookie".equals(headerName)){
                    String[] cookieKeyValue = headerValue.split(";");
                    for(String cookie:cookieKeyValue){
                        if(cookie.length() > 0 && cookie.contains("=")){
                            String key = cookie.substring(0, cookie.indexOf("="));
                            String value = cookie.substring(cookie.indexOf("=")+1,cookie.length());
                            cookies.put(key,value);
                        }
                    }
                }
            }
            vb.setCookies(cookies);
            post.abort();
        }
        catch (HttpException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }finally{
            post.releaseConnection();
//            httpclient.getHttpConnectionManager().closeIdleConnections(0);
        }

        return vb;
    }
    /**
     * @param url
     * @param header
     * @param savePath
     */
    public static Map<String,String> downloadPicture(String url,Map<String,String> header,String savePath){
        HttpClient httpclient = new HttpClient();
        GetMethod httpget = new GetMethod(url);
        Map<String,String> cookies = new HashMap<String,String>();
        try {
            Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
            Protocol.registerProtocol("https", myhttps);
            for(String li:header.keySet()){
                httpget.addRequestHeader(li, header.get(li));
            }
            //请求中的cookie
            String cookieString = header.get("Cookie");
            if(cookieString != null){
                String[] keyValue = cookieString.split(";");
                for(String li:keyValue){
                    if(li.length() > 0 && li.contains("=")){
                        String key = li.substring(0, li.indexOf("="));
                        String value = li.substring(li.indexOf("=")+1,li.length());
                        cookies.put(key,value);
                    }
                }
            }
            httpclient.executeMethod(httpget);
            File storeFile = new File(savePath);
            FileOutputStream fileOutputStream = new FileOutputStream(storeFile);
            FileOutputStream output = fileOutputStream;
            InputStream stream = httpget.getResponseBodyAsStream();
            byte[] buf = new byte[1024];
            while (stream.read(buf) != -1) {
                output.write(buf);
            }
            output.close();
            Header[] respHeader = httpget.getResponseHeaders();
            //服务器返回的Set-Cookie字段处理,更新cookie
            for(Header li:respHeader){
                String headerName = li.getName();
                String headerValue = li.getValue();
                if("Set-Cookie".equals(headerName)){
                    String[] cookieKeyValue = headerValue.split(";");
                    for(String cookie:cookieKeyValue){
                        if(cookie.length() > 0 && cookie.contains("=")){
                            String key = cookie.substring(0, cookie.indexOf("="));
                            String value = cookie.substring(cookie.indexOf("=")+1,cookie.length());
                            cookies.put(key,value);
                        }
                    }
                }
            }
            httpget.abort();
        }catch(Exception e){
            logger.error(e.getMessage());
        }finally{
            httpget.releaseConnection();
//            httpclient.getHttpConnectionManager().closeIdleConnections(0);
        }
        return cookies;
    }
    /**
     *
     * 根据cbss系统,对密码进行加密
     *
     */
    public static String encryptPasswd(String passwd){
        String pass = "";
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine se = sem.getEngineByName("js");
        try
        {
          String script = FileHelper.readFile("./doc/js/sha1.js", "utf-8");
          se.eval(script);
          String CryptoJS = FileHelper.readFile("./doc/js/core-min.js", "utf-8");
          se.eval(CryptoJS);
          script = FileHelper.readFile("./doc/js/enc-base64-min.js", "utf-8");
          se.eval(script);
          Invocable inv2 = (Invocable) se;
          Object result = inv2.invokeFunction("passwdEncryption", passwd);
          pass = result.toString();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return pass;
    }
    public static String cookieMapToString(Map<String,String> map){
        if(map == null || map.isEmpty()){
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for(String li:map.keySet()){
            sb.append(li);
            sb.append("=");
            sb.append(map.get(li));
            sb.append(";");
        }
        return sb.toString();
    }

    public static List<SpProduct> extractProductResult(String html){
        List<SpProduct> list = new ArrayList<SpProduct>();
        Pattern productPattern = Pattern.compile("
(.+?)
",Pattern.DOTALL);
        Matcher productMatcher = productPattern.matcher(html);
        while(productMatcher.find()){
            String productString = productMatcher.group(1);
            Pattern prdouctDetailPattern = Pattern.compile("(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	"
                      ,Pattern.DOTALL);
            Matcher productDetailMatcher = prdouctDetailPattern.matcher(productString);
            if(productDetailMatcher.find()){
                SpProduct product = new SpProduct(productDetailMatcher.group(1).trim(),
                    productDetailMatcher.group(2).trim(),productDetailMatcher.group(3).trim(),
                    productDetailMatcher.group(4).trim(),productDetailMatcher.group(5).trim(),
                    productDetailMatcher.group(6).trim(),productDetailMatcher.group(7).trim(),
                    productDetailMatcher.group(8).trim(),productDetailMatcher.group(9).trim(),
                    productDetailMatcher.group(10).trim());
                list.add(product);
            }
        }
        return list;
    }

    public static List<SpProduct> extractProductList(String html){
        List<SpProduct> list = new ArrayList<SpProduct>();
        Pattern productPattern = Pattern.compile("
(.+?)
",Pattern.DOTALL);
        Matcher productMatcher = productPattern.matcher(html);
        while(productMatcher.find()){
            String productString = productMatcher.group(1);
            Pattern prdouctDetailPattern = Pattern.compile("(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	.*" +
                  "(.+?)	"
                      ,Pattern.DOTALL);
            Matcher productDetailMatcher = prdouctDetailPattern.matcher(productString);
            if(productDetailMatcher.find()){
                SpProduct product = new SpProduct(productDetailMatcher.group(1).trim(),
                    productDetailMatcher.group(2).trim(),productDetailMatcher.group(3).trim(),
                    productDetailMatcher.group(4).trim(),productDetailMatcher.group(5).trim(),
                    productDetailMatcher.group(6).trim(),productDetailMatcher.group(7).trim(),
                    productDetailMatcher.group(8).trim(),productDetailMatcher.group(9).trim(),
                    productDetailMatcher.group(10).trim(),productDetailMatcher.group(11).trim(),
                    productDetailMatcher.group(12).trim());
                list.add(product);
            }
        }
        return list;
    }
}


text:
define([
  'dojo/_base/declare',
  'jimu/BaseFeatureAction',
  'jimu/WidgetManager',
  'dojo/Deferred',
  'esri/tasks/query',
  'dojo/_base/lang',
  'dojo/dom-class'
], function (declare, BaseFeatureAction, WidgetManager, Deferred, Query, lang, domClass) {
  var clazz = declare(BaseFeatureAction, {
    map: null,
    iconFormat: 'png',

    isFeatureSupported: function (featureSet) {
      if (featureSet.features.length !== 1 || !featureSet.features[0].geometry) {
        return false;
      }
      return true;
    },

    onExecute: function (featureSet) {
      return WidgetManager.getInstance().triggerWidgetOpen(this.widgetId)
        .then(lang.hitch(this, function (widget) {
          var f = featureSet.features[0];
          this._getFeatureGeometry(f, widget).then(lang.hitch(this, function (g) {
            f.geometry = g;
            if (domClass.contains(widget.panelContainer, "loading")) {
              domClass.remove(widget.panelContainer, "loading");
            }
            //Added timeout so that map resize should not impact the setExtent
            setTimeout(function() {
              widget._setEventLocation({
                feature: f,
                type: 'add'
              });
            }, 500);
          }));
        }));
    },

    _getFeatureGeometry: function (feature, widget) {
      var def = new Deferred();
      if (feature && feature.getSourceLayer) {
        var layer = feature.getSourceLayer();
        if (layer.queryFeatures && layer.objectIdField &&
          layer.getMaxAllowableOffset && layer.getMaxAllowableOffset() > 0 &&
          feature.attributes.hasOwnProperty(layer.objectIdField)) {
          domClass.add(widget.panelContainer, "loading");

          var query = new Query();
          query.returnGeometry = true;
          query.maxAllowableOffset = 0;
          query.objectIds = [feature.attributes[layer.objectIdField]];
          query.outSpatialReference = this.map.spatialReference;
          layer.queryFeatures(query).then(function (r) {
            if (r && r.features && r.features[0] && r.features[0].geometry) {
              def.resolve(r.features[0].geometry);
            } else {
              def.resolve(feature.geometry);
            }
          }, function (err) {
            console.log(err);
            def.resolve(feature.geometry);
          });
        } else {
          def.resolve(feature.geometry);
        }
      } else {
        def.resolve(feature.geometry);
      }
      return def;
    }
  });
  return clazz;
});


text:
jest.dontMock("query-string");
jest.dontMock("../AuthActions");

const RequestUtil = require("mesosphere-shared-reactjs").RequestUtil;

const ActionTypes = require("../../constants/ActionTypes");
const AppDispatcher = require("../../events/AppDispatcher");
const AuthActions = require("../AuthActions");
const Config = require("../../config/Config");

describe("AuthActions", function() {
  describe("extra params", function() {
    it("passes extra parameters down to the auth service via query string params", function() {
      spyOn(RequestUtil, "json");

      AuthActions.login(undefined, "boo");

      expect(RequestUtil.json.calls.mostRecent().args[0].url).toEqual(
        Config.acsAPIPrefix + "/auth/login?target=boo"
      );
    });
  });

  describe("#login", function() {
    beforeEach(function() {
      spyOn(RequestUtil, "json");
      AuthActions.login();
      this.configuration = RequestUtil.json.calls.mostRecent().args[0];
    });

    it("calls #json from the RequestUtil", function() {
      expect(RequestUtil.json).toHaveBeenCalled();
    });

    it("fetches data from the correct URL", function() {
      expect(this.configuration.url).toEqual(
        Config.acsAPIPrefix + "/auth/login"
      );
    });

    it("dispatches the correct action when successful", function() {
      var id = AppDispatcher.register(function(payload) {
        var action = payload.action;
        AppDispatcher.unregister(id);
        expect(action.type).toEqual(ActionTypes.REQUEST_LOGIN_SUCCESS);
      });

      this.configuration.success();
    });

    it("dispatches the correct action when unsuccessful", function() {
      var id = AppDispatcher.register(function(payload) {
        var action = payload.action;
        AppDispatcher.unregister(id);
        expect(action.type).toEqual(ActionTypes.REQUEST_LOGIN_ERROR);
      });

      this.configuration.error({ responseJSON: { description: "bar" } });
    });

    it("dispatches the correct error when unsuccessful", function() {
      var id = AppDispatcher.register(function(payload) {
        var action = payload.action;
        AppDispatcher.unregister(id);
        expect(action.data).toEqual("bar");
      });

      this.configuration.error({ responseJSON: { description: "bar" } });
    });

    it("dispatches the xhr when unsuccessful", function() {
      var id = AppDispatcher.register(function(payload) {
        var action = payload.action;
        AppDispatcher.unregister(id);
        expect(action.xhr).toEqual({
          foo: "bar",
          responseJSON: { description: "baz" }
        });
      });

      this.configuration.error({
        foo: "bar",
        responseJSON: { description: "baz" }
      });
    });
  });

  describe("#logout", function() {
    beforeEach(function() {
      spyOn(RequestUtil, "json");
      AuthActions.logout();
      this.configuration = RequestUtil.json.calls.mostRecent().args[0];
    });

    it("calls #json from the RequestUtil", function() {
      expect(RequestUtil.json).toHaveBeenCalled();
    });

    it("fetches data from the correct URL", function() {
      expect(this.configuration.url).toEqual(
        Config.acsAPIPrefix + "/auth/logout"
      );
    });

    it("dispatches the correct action when successful", function() {
      var id = AppDispatcher.register(function(payload) {
        var action = payload.action;
        AppDispatcher.unregister(id);
        expect(action.type).toEqual(ActionTypes.REQUEST_LOGOUT_SUCCESS);
      });

      this.configuration.success();
    });

    it("dispatches the correct action when unsuccessful", function() {
      var id = AppDispatcher.register(function(payload) {
        var action = payload.action;
        AppDispatcher.unregister(id);
        expect(action.type).toEqual(ActionTypes.REQUEST_LOGOUT_ERROR);
      });

      this.configuration.error({ responseJSON: { description: "bar" } });
    });

    it("dispatches the correct error when unsuccessful", function() {
      var id = AppDispatcher.register(function(payload) {
        var action = payload.action;
        AppDispatcher.unregister(id);
        expect(action.data).toEqual("bar");
      });

      this.configuration.error({ responseJSON: { description: "bar" } });
    });

    it("dispatches the xhr when unsuccessful", function() {
      var id = AppDispatcher.register(function(payload) {
        var action = payload.action;
        AppDispatcher.unregister(id);
        expect(action.xhr).toEqual({
          foo: "bar",
          responseJSON: { description: "baz" }
        });
      });

      this.configuration.error({
        foo: "bar",
        responseJSON: { description: "baz" }
      });
    });
  });
});


text:
"""
Description : Centripetal force is the force acting on an object in
curvilinear motion directed towards the axis of rotation
or centre of curvature.

The unit of centripetal force is newton.

The centripetal force is always directed perpendicular to the
direction of the object's displacement. Using Newton's second
law of motion, it is found that the centripetal force of an object
moving in a circular path always acts towards the centre of the circle.
The Centripetal Force Formula is given as the product of mass (in kg)
and tangential velocity (in meters per second) squared, divided by the
radius (in meters) that implies that on doubling the tangential velocity,
the centripetal force will be quadrupled. Mathematically it is written as:
F = mv²/r
Where, F is the Centripetal force, m is the mass of the object, v is the
speed or velocity of the object and r is the radius.

Reference: https://byjus.com/physics/centripetal-and-centrifugal-force/
"""

def centripetal(mass: float, velocity: float, radius: float) -> float:
    """
    The Centripetal Force formula is given as: (m*v*v)/r

    >>> round(centripetal(15.5,-30,10),2)
    1395.0
    >>> round(centripetal(10,15,5),2)
    450.0
    >>> round(centripetal(20,-50,15),2)
    3333.33
    >>> round(centripetal(12.25,40,25),2)
    784.0
    >>> round(centripetal(50,100,50),2)
    10000.0
    """
    if mass < 0:
        raise ValueError("The mass of the body cannot be negative")
    if radius <= 0:
        raise ValueError("The radius is always a positive non zero integer")
    return (mass * (velocity) ** 2) / radius

if __name__ == "__main__":
    import doctest

    doctest.testmod(verbose=True)


text:
// @comments: true

import foo = require('./foo');


text:
#import "ACKUtilitiesTab.h"

@interface ACKFileInspector : ACKUtilitiesTab

@end


text:
// Version 0.1

'use strict';

console.log('Started', self);

self.addEventListener('install', function(event) {
  self.skipWaiting();
  console.log('Installed', event);
});

self.addEventListener('activate', function(event) {
  console.log('Activated', event);
});

self.addEventListener('push', function(event) {
  console.log('Push message', event);

  var title = 'New blog post at tthompson.me';

  event.waitUntil(
    self.registration.showNotification(title, {
      'body': 'Click here to see newest posts.',
      // 'icon': 'images/icon.png'
    }));
});

self.addEventListener('notificationclick', function(event) {
  console.log('Notification click: tag', event.notification.tag);
  // Android doesn't close the notification when you click it
  // See http://crbug.com/463146
  event.notification.close();
  var url = 'https://tthompson.me/blog/';
  // Check if there's already a tab open with this URL.
  // If yes: focus on the tab.
  // If no: open a tab with the URL.
  event.waitUntil(
    clients.matchAll({
      type: 'window'
    })
    .then(function(windowClients) {
      console.log('WindowClients', windowClients);
      for (var i = 0; i < windowClients.length; i++) {
        var client = windowClients[i];
        console.log('WindowClient', client);
        if (client.url === url && 'focus' in client) {
          return client.focus();
        }
      }
      if (clients.openWindow) {
        return clients.openWindow(url);
      }
    })
  );
});


text:
using InsideInning.Helper;
using InsideInning.Models;
using InsideInning.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
using Color = InsideInning.Helper.Color;
using ImageCircle.Forms.Plugin.Abstractions;
namespace InsideInning.Pages
{
    public class EmpDetailsViewPage : ContentPage
    {
        Int32 _EmployeeID;

        #region Access binded properties
        private EmployeeViewModel ViewModel
        {
            get;
            set;//Type cast BindingContex as HomeViewModel to access binded properties
        }
        #endregion

        #region Main stack Layout
        public EmpDetailsViewPage(Employee emp ,EmployeeViewModel empViewModel)
        {
            ViewModel = empViewModel;
            ViewModel.EmployeeDetail = emp;
            BindingContext = ViewModel.EmployeeDetail;
            //ViewModel = viewModel; //Passed from List or Dashboard
            _EmployeeID = emp.EmployeeID;
            BackgroundImage = "back";
           // BindingContext = ViewModel.EmployeeDetail;
           // ViewModel.LoadEmpDetail.Execute(_EmployeeID);
            Content = new StackLayout
            {
                HorizontalOptions = LayoutOptions.FillAndExpand,
                Spacing = 10,
                Padding = new Thickness(0, 0, 0, 0),
                Children =
                {
                    {CreateRealtiveLayoutFor()},
                    Layout(),
                }
            };
        }
        #endregion

        #region Stacklayout with Spacing
        private StackLayout Layout()
        {
            var customLayout = new StackLayout
            {
                BackgroundColor = Xamarin.Forms.Color.Transparent,
                Padding = new Thickness(30, 60, 30, 0),
                Spacing = 7,

                Children =
                {
                    GenGrid(),
                    { iiControls.CreateLabelFor("ContactNumber",Color.White)},
                    { iiControls.CreateLabelFor("EmailAddress",Color.White)},
                    { iiControls.CreateLabelFor("CompanyProfile",Color.White)}
                }
            };
            return customLayout;
        }

        #endregion

        #region Relative layout for coverpage and profile picture
        public StackLayout CreateRealtiveLayoutFor()
        {
            RelativeLayout MainView = new RelativeLayout
            {
                HorizontalOptions = LayoutOptions.Start,
                BackgroundColor = Xamarin.Forms.Color.Blue,
                Padding = new Thickness(1, 1, 1, 1),
                HeightRequest = 10,
            };
            var CoverPage = new iiImage { HorizontalOptions = LayoutOptions.CenterAndExpand };

            var CircleImage = new CircleImage
            {
                // BorderColor = Color.White.ToFormsColor(),
                // BorderThickness = 2,
                HorizontalOptions = LayoutOptions.Fill,

            };
            CircleImage.SetBinding(Image.SourceProperty, "EmpProfileImage");

            var tapGestureRecognizer = new TapGestureRecognizer();
            tapGestureRecognizer.Tapped += (s, e) =>
            {
                Console.WriteLine("Yes Clicked");
            };

            CircleImage.GestureRecognizers.Add(tapGestureRecognizer);

            MainView.Children.Add(CoverPage, Constraint.Constant(0), Constraint.Constant(0),
                Constraint.RelativeToParent(parent => { return parent.Width; }),
                Constraint.RelativeToParent(parent => { return parent.Height; }));

            MainView.Children.Add(CircleImage, Constraint.Constant(0),
            Constraint.RelativeToView(CoverPage, (parent, sibling) => { return sibling.Height -50; }), Constraint.Constant(100), Constraint.Constant(100));

            var st = new StackLayout
            {
                HeightRequest=150,
                Children = { MainView }
            };
            return st;
        }

        #endregion

        #region Custom control for main layout
        private Grid GenGrid()
        {
            var grid = new Grid
            {
                Padding = new Thickness(0, -10, 0, 0),
                HorizontalOptions = LayoutOptions.FillAndExpand,
                ColumnSpacing = 5,
                RowSpacing = 10,

            };

            grid.Children.Add(iiControls.CreateLabelFor("FullName", Color.White), 0, 0);
            //grid.Children.Add(iiControls.CreateLabelFor("LastName", Color.White), 1, 0);
            var birthLabel = iiControls.CreateLabelFor("DateOfBirth", Color.White);
            birthLabel.SetBinding(Label.TextProperty, new Binding("DateOfBirth") { StringFormat = "{0:dd-MMM-yyyy}" });
            grid.Children.Add(birthLabel, 0, 1);
            var joinLabel = iiControls.CreateLabelFor("JoinningDate", Color.White);
            joinLabel.SetBinding(Label.TextProperty, new Binding("JoinningDate") { StringFormat = "{0:dd-MMM-yyyy}" });
            grid.Children.Add(joinLabel, 1, 1);

            return grid;
        }
        public View CreateButtonFor(string propertyName, LayoutOptions layout, string id = "")
        {

            iiButton iiButton = new iiButton
            {
                //HorizontalOptions = LayoutOptions.FillAndExpand,
                // Image=(FileImageSource)ImageSource.FromFile(imgscr),
                BackgroundColor = Xamarin.Forms.Color.Transparent,
                BorderColor = Xamarin.Forms.Color.White,
                BorderWidth = 2,
                WidthRequest = 70,
                HeightRequest = 40,
                HorizontalOptions = layout,
                ClassId = id,
            };
            //iiButton.SetBinding(Button.TextColorProperty, propertyName);
            return iiButton;
        }
        public View CreateDatePickerFor(string propertyName, string bindProperty, string id = "")
        {
            iiDatePicker iiDatePicker = new iiDatePicker
            {
                HorizontalOptions = LayoutOptions.FillAndExpand,
                BackgroundColor = Xamarin.Forms.Color.Transparent,
                //Color.iiEditTextColor.ToFormsColor(),
                ClassId = id,

            };
            iiDatePicker.SetBinding(iiDatePicker.DateProperty, bindProperty);
            return iiDatePicker;
        }
        #endregion

        #region Load employee deatil
        protected override void OnAppearing()
        {
            base.OnAppearing();

            //TODO : Have to get from local no more second API call
            ViewModel.LoadEmpDetail.Execute(_EmployeeID);
        }

        #endregion

    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
              Any modifications will be overwritten.
              To include a user specific buildfile here, simply create one in the same
              directory with the processing instruction <?eclipse.ant.import?>
              as the first entry and export the buildfile again. --><project basedir="." default="build" name="OpenEphyra">
    <property environment="env"/>
    <property name="debuglevel" value="source,lines,vars"/>
    <property name="target" value="1.7"/>
    <property name="source" value="1.7"/>
    <path id="OpenEphyra.classpath">
        <pathelement location="bin"/>
        <pathelement location="lib/learn/jsoup-1.8.3.jar"/>
        <pathelement location="lib/ml/maxent.jar"/>
        <pathelement location="lib/ml/minorthird.jar"/>
        <pathelement location="lib/nlp/jwnl.jar"/>
        <pathelement location="lib/nlp/lingpipe.jar"/>
        <pathelement location="lib/nlp/opennlp-tools.jar"/>
        <pathelement location="lib/nlp/plingstemmer.jar"/>
        <pathelement location="lib/nlp/snowball.jar"/>
        <pathelement location="lib/nlp/stanford-ner.jar"/>
        <pathelement location="lib/nlp/stanford-parser.jar"/>
        <pathelement location="lib/nlp/stanford-postagger.jar"/>
        <pathelement location="lib/qa/javelin.jar"/>
        <pathelement location="lib/search/bing-search-java-sdk.jar"/>
        <pathelement location="lib/search/googleapi.jar"/>
        <pathelement location="lib/search/indri.jar"/>
        <pathelement location="lib/search/yahoosearch.jar"/>
        <pathelement location="lib/thrift/libthrift-0.9.2.jar"/>
        <pathelement location="lib/thrift/log4j-1.2.14.jar"/>
        <pathelement location="lib/thrift/slf4j-api-1.5.8.jar"/>
        <pathelement location="lib/thrift/slf4j-log4j12-1.5.8.jar"/>
        <pathelement location="lib/util/commons-logging.jar"/>
        <pathelement location="lib/util/gson.jar"/>
        <pathelement location="lib/util/htmlparser.jar"/>
        <pathelement location="lib/util/jetty-all.jar"/>
        <pathelement location="lib/util/log4j.jar"/>
        <pathelement location="lib/util/servlet-api.jar"/>
        <pathelement location="lib/util/trove.jar"/>
        <pathelement location="lib/db/mongo-java-driver-3.2.2.jar"/>
    </path>
    <target name="init">
        <mkdir dir="bin"/>
        <copy includeemptydirs="false" todir="bin">
            <fileset dir="src">
                <exclude name="**/*.java"/>
            </fileset>
        </copy>
    </target>
    <target name="clean">
        <delete dir="bin"/>
    </target>
    <target depends="clean" name="cleanall"/>
    <target depends="build-subprojects,build-project" name="build"/>
    <target name="build-subprojects"/>
    <target depends="init" name="build-project">
        <echo message="${ant.project.name}: ${ant.file}"/>
        <javac debug="true" debuglevel="${debuglevel}" destdir="bin" includeantruntime="false" source="${source}" target="${target}">
            <src path="src"/>
            <classpath refid="OpenEphyra.classpath"/>
        </javac>
    </target>
    <target description="Build all projects which reference this project. Useful to propagate changes." name="build-refprojects"/>
    <target description="copy Eclipse compiler jars to ant lib directory" name="init-eclipse-compiler">
        <copy todir="${ant.library.dir}">
            <fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
        </copy>
        <unzip dest="${ant.library.dir}">
            <patternset includes="jdtCompilerAdapter.jar"/>
            <fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
        </unzip>
    </target>
    <target description="compile project with Eclipse compiler" name="build-eclipse-compiler">
        <property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
        <antcall target="build"/>
    </target>
    <target name="lucida.main.QADaemon">
        <java classname="lucida.main.QADaemon" failonerror="true" fork="yes">
            <env key="LUCIDAROOT" value="/home/yba/Documents/clarity/lucida/lucida"/>
            <jvmarg line="-Djava.library.path=lib/search/"/>
            <classpath refid="OpenEphyra.classpath"/>
        </java>
    </target>
    <target name="QAClient">
        <java classname="lucida.test.QAClient" failonerror="true" fork="yes">
            <classpath refid="OpenEphyra.classpath"/>
        </java>
    </target>
</project>


text:
<!DOCTYPE html>

  <title>RallyX Live Scoring</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="shortcut icon" type="image/png" href="{{ url_for('static', filename='favicon.png') }}" />

  {% if g.auto_refresh %}
  <meta http-equiv="refresh" content="{{g.auto_refresh}}">
  {% endif %}

RallyX Live Scoring

  All scores are provisional pending fianal audit by event officials.

Event Scores

Latest Runs

        Class
        Car
        Raw
        C
        G
        Total
        Run

        {% for run in g.latest_runs %}

          {{g.entry_dict[run.entry_id].car_class}}
          {{g.entry_dict[run.entry_id].car_number}}
          {{run.raw_time}}
          {{run.cones if run.cones > 0 else '-'}}
          {{run.gates if run.gates > 0 else '-'}}
          {{run.total_time}}
          {{run.run_count}} {{'FINAL RUN!' if run.run_count >= g.rules.max_runs}}

        {% else %}

          None

        {% endfor %}


text:
package me.jasoncampos.inject.persist.hibernate;

import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;

import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.inject.persist.UnitOfWork;

/**
 * Hibernate {@code UnitOfWork} implementation which manages a ThreadLocal {@code Session} instance. Invoking
 * {@link #begin()} will open a new {@code Session} if one is not already open. Subsequent invocations of {@link #get()}
 * will return the same {@code Session} instance until {@link #end()} is invoked.

 *

 *
 * This class may also be used as a {@code Provider<Session>} without the {@code UnitOfWork} context. Note that any
 * session not created during a {@link #begin()} invocation *must* be manually closed. Invoking {@link #get()} and then
 * {@link #end()} will *not* close the session created from {@link #get()}.
 *
 * @author Jason Campos <jcampos8782@gmail.com>
 */
@Singleton
public class HibernateUnitOfWork implements Provider<Session>, UnitOfWork {
	private static final Logger logger = LoggerFactory.getLogger(HibernateUnitOfWork.class);

	private final ThreadLocal<Session> sessions = new ThreadLocal<>();
	private final HibernatePersistService sessionFactory;

	@Inject
	public HibernateUnitOfWork(final HibernatePersistService sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Session get() {
		// If a unit of work has begun, return that session.
		// Otherwise, assume the session will be manually managed.
		if (isWorking()) {
			return sessions.get();
		} else {
			logger.warn("Opening hibernate Session with no current UnitOfWork. This session must be manually closed.");
			return sessionFactory.get().openSession();
		}
	}

	public boolean isWorking() {
		return sessions.get() != null;
	}

	@Override
	public void begin() {
		if (!isWorking()) {
			final Session session = sessionFactory.get().openSession();
			sessions.set(session);
			logger.debug("UnitOfWork started. session={}", session);
		}
	}

	@Override
	public void end() {
		Preconditions.checkState(isWorking(), "UnitOfWork.end() invoked with no corresponding UnitOfWork.begin()");
		final Session session = sessions.get();
		try {
			if (session.isOpen() && session.isJoinedToTransaction()) {
				session.flush();
			}
		} finally {
			if (session.isOpen()) {
				session.close();
			}
			sessions.remove();
			logger.debug("UnitOfWork complete. session={}", session);
		}
	}
}


text:
<!DOCTYPE html>
<html style="min-width: 400px">
<head>
  <meta charset="utf-8">
  <title>OpenTelemetry Browser Extension</title>
</head>
<body>
  <div id="root">
  </div>
</body>

</html>


text:
package io.getquill.dsl

import scala.reflect.macros.whitebox.{ Context => MacroContext }
import io.getquill.Embedded
import io.getquill.util.OptionalTypecheck
import io.getquill.util.MacroContextExt._

trait ValueComputation {
  val c: MacroContext
  import c.universe._

  sealed trait Value {
    val term: Option[TermName]
    def nestedAndOptional: Boolean
  }
  case class Nested(term: Option[TermName], tpe: Type, params: List[List[Value]], optional: Boolean) extends Value {
    def nestedAndOptional: Boolean = optional
  }
  case class Scalar(term: Option[TermName], tpe: Type, decoder: Tree, optional: Boolean) extends Value {
    def nestedAndOptional: Boolean = false
  }

  private def is[T](tpe: Type)(implicit t: TypeTag[T]) =
    tpe <:< t.tpe

  private[getquill] def value(encoding: String, tpe: Type, exclude: Tree*): Value = {

    def nest(tpe: Type, term: Option[TermName]): Nested =
      caseClassConstructor(tpe) match {
        case None =>
          c.fail(s"Found the embedded '$tpe', but it is not a case class")
        case Some(constructor) =>
          val params =
            constructor.paramLists.map {
              _.map { param =>
                apply(
                  param.typeSignature.asSeenFrom(tpe, tpe.typeSymbol),
                  Some(param.name.toTermName),
                  nested = !isTuple(tpe)
                )
              }
            }
          Nested(term, tpe, params, optional = false)
      }

    def apply(tpe: Type, term: Option[TermName], nested: Boolean): Value = {
      OptionalTypecheck(c)(q"implicitly[${c.prefix}.${TypeName(encoding)}[$tpe]]") match {
        case Some(encoding) =>
          Scalar(term, tpe, encoding, optional = is[Option[Any]](tpe))
        case None =>

          def value(tpe: Type) =
            tpe match {
              case tpe if !is[Embedded](tpe) && nested =>
                c.fail(
                  s"""Can't find implicit `$encoding[$tpe]`. Please, do one of the following things:
                     |1. ensure that implicit `$encoding[$tpe]` is provided and there are no other conflicting implicits;
                     |2. make `$tpe` `Embedded` case class or `AnyVal`.
                   """.stripMargin
                )

              case tpe =>
                nest(tpe, term)
            }

          if (isNone(tpe)) {
            c.fail("Cannot handle untyped `None` objects. Use a cast e.g. `None:Option[String]` or `Option.empty`.")
          } else if (is[Option[Any]](tpe)) {
            value(tpe.typeArgs.head).copy(optional = true)
          } else {
            value(tpe)
          }
      }
    }

    def filterExcludes(value: Value) = {
      val paths =
        exclude.map {
          case f: Function =>
            def path(tree: Tree): List[TermName] =
              tree match {
                case q"$a.$b"                => path(a) :+ b
                case q"$a.map[$t]($b => $c)" => path(a) ++ path(c)
                case _                       => Nil
              }
            path(f.body)
        }

      def filter(value: Value, path: List[TermName] = Nil): Option[Value] =
        value match {
          case value if paths.contains(path ++ value.term) =>
            None
          case Nested(term, tpe, params, optional) =>
            Some(Nested(term, tpe, params.map(_.flatMap(filter(_, path ++ term))), optional))
          case value =>
            Some(value)
        }

      filter(value).getOrElse {
        c.fail("Can't exclude all entity properties")
      }
    }

    filterExcludes(apply(tpe, term = None, nested = false))
  }

  private def isNone(tpe: Type) =
    tpe.typeSymbol.name.toString == "None"

  private def isTuple(tpe: Type) =
    tpe.typeSymbol.name.toString.startsWith("Tuple")

  private def caseClassConstructor(t: Type) =
    t.members.collect {
      case m: MethodSymbol if m.isPrimaryConstructor => m
    }.headOption

  def flatten(base: Tree, value: Value): List[Tree] = {
    def nest(tree: Tree, term: Option[TermName]) =
      term match {
        case None       => tree
        case Some(term) => q"$tree.$term"
      }

    def apply(base: Tree, params: List[List[Value]]): List[Tree] =
      params.flatten.flatMap(flatten(base, _))

    value match {
      case Scalar(term, _, _, _) =>
        List(nest(base, term))
      case Nested(term, _, params, optional) =>
        if (optional)
          apply(q"v", params)
            .map(body => q"${nest(base, term)}.map(v => $body)")
        else
          apply(nest(base, term), params)
    }
  }
}


text:
/**
 */
package gluemodel.substationStandard.LNNodes.LNGroupR;

import gluemodel.substationStandard.Dataclasses.ACT;
import gluemodel.substationStandard.Dataclasses.INC;
import gluemodel.substationStandard.Dataclasses.ING;
import gluemodel.substationStandard.Dataclasses.INS;
import gluemodel.substationStandard.Dataclasses.SPC;
import gluemodel.substationStandard.Dataclasses.SPS;

/**
 *
 * A representation of the model object 'RREC'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getOpCntRs Op Cnt Rs}

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getBlkRec Blk Rec}

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getChkRec Chk Rec}

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getAuto Auto}

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getOp Op}

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getAutoRecSt Auto Rec St}

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getRec1Tmms Rec1 Tmms}

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getRec2Tmms Rec2 Tmms}

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getRec3Tmms Rec3 Tmms}

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getPlsTmms Pls Tmms}

 *
{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getRclTmms Rcl Tmms}

 *

 *
 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC()
 * @model
 * @generated
 */
public interface RREC extends GroupR {
	/**
	 * Returns the value of the 'Op Cnt Rs' reference.
	 *
	 *

	 * If the meaning of the 'Op Cnt Rs' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Op Cnt Rs' reference.
	 * @see #setOpCntRs(INC)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_OpCntRs()
	 * @model required="true"
	 * @generated
	 */
	INC getOpCntRs();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getOpCntRs Op Cnt Rs}' reference.
	 *
	 *
	 * @param value the new value of the 'Op Cnt Rs' reference.
	 * @see #getOpCntRs()
	 * @generated
	 */
	void setOpCntRs(INC value);

	/**
	 * Returns the value of the 'Blk Rec' reference.
	 *
	 *

	 * If the meaning of the 'Blk Rec' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Blk Rec' reference.
	 * @see #setBlkRec(SPC)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_BlkRec()
	 * @model required="true"
	 * @generated
	 */
	SPC getBlkRec();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getBlkRec Blk Rec}' reference.
	 *
	 *
	 * @param value the new value of the 'Blk Rec' reference.
	 * @see #getBlkRec()
	 * @generated
	 */
	void setBlkRec(SPC value);

	/**
	 * Returns the value of the 'Chk Rec' reference.
	 *
	 *

	 * If the meaning of the 'Chk Rec' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Chk Rec' reference.
	 * @see #setChkRec(SPC)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_ChkRec()
	 * @model required="true"
	 * @generated
	 */
	SPC getChkRec();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getChkRec Chk Rec}' reference.
	 *
	 *
	 * @param value the new value of the 'Chk Rec' reference.
	 * @see #getChkRec()
	 * @generated
	 */
	void setChkRec(SPC value);

	/**
	 * Returns the value of the 'Auto' reference.
	 *
	 *

	 * If the meaning of the 'Auto' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Auto' reference.
	 * @see #setAuto(SPS)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_Auto()
	 * @model required="true"
	 * @generated
	 */
	SPS getAuto();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getAuto Auto}' reference.
	 *
	 *
	 * @param value the new value of the 'Auto' reference.
	 * @see #getAuto()
	 * @generated
	 */
	void setAuto(SPS value);

	/**
	 * Returns the value of the 'Op' reference.
	 *
	 *

	 * If the meaning of the 'Op' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Op' reference.
	 * @see #setOp(ACT)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_Op()
	 * @model required="true"
	 * @generated
	 */
	ACT getOp();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getOp Op}' reference.
	 *
	 *
	 * @param value the new value of the 'Op' reference.
	 * @see #getOp()
	 * @generated
	 */
	void setOp(ACT value);

	/**
	 * Returns the value of the 'Auto Rec St' reference.
	 *
	 *

	 * If the meaning of the 'Auto Rec St' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Auto Rec St' reference.
	 * @see #setAutoRecSt(INS)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_AutoRecSt()
	 * @model required="true"
	 * @generated
	 */
	INS getAutoRecSt();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getAutoRecSt Auto Rec St}' reference.
	 *
	 *
	 * @param value the new value of the 'Auto Rec St' reference.
	 * @see #getAutoRecSt()
	 * @generated
	 */
	void setAutoRecSt(INS value);

	/**
	 * Returns the value of the 'Rec1 Tmms' reference.
	 *
	 *

	 * If the meaning of the 'Rec1 Tmms' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Rec1 Tmms' reference.
	 * @see #setRec1Tmms(ING)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_Rec1Tmms()
	 * @model required="true"
	 * @generated
	 */
	ING getRec1Tmms();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getRec1Tmms Rec1 Tmms}' reference.
	 *
	 *
	 * @param value the new value of the 'Rec1 Tmms' reference.
	 * @see #getRec1Tmms()
	 * @generated
	 */
	void setRec1Tmms(ING value);

	/**
	 * Returns the value of the 'Rec2 Tmms' reference.
	 *
	 *

	 * If the meaning of the 'Rec2 Tmms' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Rec2 Tmms' reference.
	 * @see #setRec2Tmms(ING)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_Rec2Tmms()
	 * @model required="true"
	 * @generated
	 */
	ING getRec2Tmms();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getRec2Tmms Rec2 Tmms}' reference.
	 *
	 *
	 * @param value the new value of the 'Rec2 Tmms' reference.
	 * @see #getRec2Tmms()
	 * @generated
	 */
	void setRec2Tmms(ING value);

	/**
	 * Returns the value of the 'Rec3 Tmms' reference.
	 *
	 *

	 * If the meaning of the 'Rec3 Tmms' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Rec3 Tmms' reference.
	 * @see #setRec3Tmms(ING)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_Rec3Tmms()
	 * @model required="true"
	 * @generated
	 */
	ING getRec3Tmms();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getRec3Tmms Rec3 Tmms}' reference.
	 *
	 *
	 * @param value the new value of the 'Rec3 Tmms' reference.
	 * @see #getRec3Tmms()
	 * @generated
	 */
	void setRec3Tmms(ING value);

	/**
	 * Returns the value of the 'Pls Tmms' reference.
	 *
	 *

	 * If the meaning of the 'Pls Tmms' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Pls Tmms' reference.
	 * @see #setPlsTmms(ING)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_PlsTmms()
	 * @model required="true"
	 * @generated
	 */
	ING getPlsTmms();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getPlsTmms Pls Tmms}' reference.
	 *
	 *
	 * @param value the new value of the 'Pls Tmms' reference.
	 * @see #getPlsTmms()
	 * @generated
	 */
	void setPlsTmms(ING value);

	/**
	 * Returns the value of the 'Rcl Tmms' reference.
	 *
	 *

	 * If the meaning of the 'Rcl Tmms' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Rcl Tmms' reference.
	 * @see #setRclTmms(ING)
	 * @see gluemodel.substationStandard.LNNodes.LNGroupR.LNGroupRPackage#getRREC_RclTmms()
	 * @model required="true"
	 * @generated
	 */
	ING getRclTmms();

	/**
	 * Sets the value of the '{@link gluemodel.substationStandard.LNNodes.LNGroupR.RREC#getRclTmms Rcl Tmms}' reference.
	 *
	 *
	 * @param value the new value of the 'Rcl Tmms' reference.
	 * @see #getRclTmms()
	 * @generated
	 */
	void setRclTmms(ING value);

} // RREC


text:
using System.Numerics;
using OpenSage.Graphics;
using OpenSage.Graphics.Rendering;
using OpenSage.Graphics.Shaders;
using OpenSage.Mathematics;

namespace OpenSage.Diagnostics.AssetViews
{
    [AssetView(typeof(Model))]
    internal sealed class ModelView : AssetView
    {
        private readonly RenderedView _renderedView;
        private readonly ModelInstance _modelInstance;

        public ModelView(DiagnosticViewContext context, Model model)
            : base(context)
        {
            _modelInstance = AddDisposable(model.CreateInstance(context.Game.AssetStore.LoadContext));
            _modelInstance.Update(TimeInterval.Zero);

            var enclosingBoundingBox = GetEnclosingBoundingBox(_modelInstance);

            _renderedView = AddDisposable(new RenderedView(
                context,
                enclosingBoundingBox.GetCenter(),
                Vector3.Distance(enclosingBoundingBox.Min, enclosingBoundingBox.Max)));

            void OnBuildingRenderList(object sender, BuildingRenderListEventArgs e)
            {
                _modelInstance.SetWorldMatrix(Matrix4x4.Identity);
                _modelInstance.BuildRenderList(
                    e.RenderList,
                    e.Camera,
                    true,
                    new MeshShaderResources.RenderItemConstantsPS
                    {
                        HouseColor = Vector3.One,
                        Opacity = 1.0f
                    });
            }

            _renderedView.RenderPipeline.BuildingRenderList += OnBuildingRenderList;
            AddDisposeAction(() => _renderedView.RenderPipeline.BuildingRenderList -= OnBuildingRenderList);
        }

        private static AxisAlignedBoundingBox GetEnclosingBoundingBox(ModelInstance modelInstance)
        {
            var boundingBox = default(AxisAlignedBoundingBox);

            var first = true;
            foreach (var subObject in modelInstance.Model.SubObjects)
            {
                var transformedBoundingBox = AxisAlignedBoundingBox.Transform(subObject.RenderObject.BoundingBox,
                    modelInstance.ModelBoneInstances[subObject.Bone.Index].Matrix);

                if (first)
                {
                    boundingBox = transformedBoundingBox;
                    first = false;
                }
                else
                {
                    boundingBox = AxisAlignedBoundingBox.CreateMerged(
                        boundingBox,
                        transformedBoundingBox);
                }
            }

            return boundingBox;
        }

        public override void Draw()
        {
            _renderedView.Draw();
        }
    }
}