text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Leaflet Maps with Open Data APIs | Hands-On Data Visualization</title>
  <meta name="description" content="Tell your story and show it with data, using free and easy-to-learn tools on the web. This introductory book teaches you how to design interactive charts and customized maps for your website, beginning with easy drag-and-drop tools, such as Google Sheets, Datawrapper, and Tableau Public. You will also gradually learn how to edit open-source code templates built with Chart.js, Highcharts, and Leaflet on GitHub. Follow along with the step-by-step tutorials, real-world examples, and online resources. This book is ideal for students, non-profit organizations, small business owners, local governments, journalists, academics, or anyone who wants to tell their story and show the data. No coding experience is required." />
  <meta name="generator" content="bookdown 0.22 and GitBook 2.6.7" />

  <meta property="og:title" content="Leaflet Maps with Open Data APIs | Hands-On Data Visualization" />
  <meta property="og:type" content="book" />
  <meta property="og:url" content="http://handsondataviz.github.io/" />
  <meta property="og:image" content="http://handsondataviz.github.io//images/cover-400wide.jpg" />
  <meta property="og:description" content="Tell your story and show it with data, using free and easy-to-learn tools on the web. This introductory book teaches you how to design interactive charts and customized maps for your website, beginning with easy drag-and-drop tools, such as Google Sheets, Datawrapper, and Tableau Public. You will also gradually learn how to edit open-source code templates built with Chart.js, Highcharts, and Leaflet on GitHub. Follow along with the step-by-step tutorials, real-world examples, and online resources. This book is ideal for students, non-profit organizations, small business owners, local governments, journalists, academics, or anyone who wants to tell their story and show the data. No coding experience is required." />
  <meta name="github-repo" content="handsondataviz/book" />

  <meta name="twitter:card" content="summary" />
  <meta name="twitter:title" content="Leaflet Maps with Open Data APIs | Hands-On Data Visualization" />
  <meta name="twitter:site" content="@handsondataviz" />
  <meta name="twitter:description" content="Tell your story and show it with data, using free and easy-to-learn tools on the web. This introductory book teaches you how to design interactive charts and customized maps for your website, beginning with easy drag-and-drop tools, such as Google Sheets, Datawrapper, and Tableau Public. You will also gradually learn how to edit open-source code templates built with Chart.js, Highcharts, and Leaflet on GitHub. Follow along with the step-by-step tutorials, real-world examples, and online resources. This book is ideal for students, non-profit organizations, small business owners, local governments, journalists, academics, or anyone who wants to tell their story and show the data. No coding experience is required." />
  <meta name="twitter:image" content="http://handsondataviz.github.io//images/cover-400wide.jpg" />

<meta name="author" content="Jack Dougherty" />
<meta name="author" content="Ilya Ilyankou" />

<meta name="date" content="2021-06-23" />

  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />

  <link rel="shortcut icon" href="images/favicon.png" type="image/x-icon" />
<link rel="prev" href="leaflet-searchable-map.html"/>
<link rel="next" href="transform.html"/>

<link href="libs/gitbook-2.6.7/css/style.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-table.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-bookdown.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-highlight.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-search.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-fontsettings.css" rel="stylesheet" />
<link href="libs/gitbook-2.6.7/css/plugin-clipboard.css" rel="stylesheet" />

<link href="libs/anchor-sections-1.0.1/anchor-sections.css" rel="stylesheet" />

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

Hands-On Data Visualization
by Jack Dougherty & Ilya Ilyankou

Preface

Audience and Overview

Authors & Acknowledgements

About Open-Access Web Edition

Introduction: Why Data Visualization?

What Can You Believe?

Some Pictures Are More Persuasive

Different Shades of the Truth

Organization of the Book

1 Choose Tools to Tell Your Story

Start Sketching Your Data Story

Ten Factors When Considering Tools

Our Recommended Tools

Use a Password Manager

2 Strengthen Your Spreadsheet Skills

Select your Spreadsheet Tools

Download to CSV or ODS Format

Make a Copy of a Google Sheet

Share Your Google Sheets

Upload and Convert to Google Sheets

Geocode Addresses in Google Sheets

Collect Data with Google Forms

Sort and Filter Data

Calculate with Formulas

Summarize Data with Pivot Tables

Match Columns with VLOOKUP

Spreadsheet vs. Relational Database

3 Find and Question Your Data

Guiding Questions for Your Search

Public and Private Data

Mask or Aggregate Sensitive Data

Open Data Repositories

Source Your Data

Recognize Bad Data

Question Your Data

4 Clean Up Messy Data

Smart Cleanup with Google Sheets

Find and Replace with Blank

Transpose Rows and Columns

Split Data into Separate Columns

Combine Data into One Column

Extract Tables from PDFs with Tabula

Clean Data with OpenRefine

5 Make Meaningful Comparisons

Precisely Describe Comparisons

Normalize Your Data

Beware of Biased Comparisons

6 Chart Your Data

Chart Design Principles

Google Sheets Charts

- Bar and Column Charts

- Histograms

- Pie, Line, and Area Charts

Datawrapper Charts

- Annotated Charts

- Range Charts

- Scatter and Bubble Charts

Tableau Public Charts

- Scatter Chart

- Filtered Line Chart

7 Map Your Data

Map Design Principles

Design Choropleth Colors & Intervals

Normalize Choropleth Map Data

Point Map with Google My Maps

Symbol Point Map with Datawrapper

Choropleth Map with Datawrapper

Choropleth Map with Tableau Public

Current Map with Socrata Open Data

8 Table Your Data

Table Design Principles

Datawrapper Table with Sparklines

Other Table-Making Tools

9 Embed On the Web

Static Image vs Interactive iframe

Get the Embed Code or iframe Tag

Paste Code or iframe to Website

10 Edit and Host Code with GitHub

Copy, Edit, and Host a Simple Leaflet Map Template

Convert GitHub Pages Link to iframe

Create a New Repo and Upload Files on GitHub

GitHub Desktop and Atom Editor to Code Efficiently

11 Chart.js and Highcharts Templates

Bar or Column Chart with Chart.js

Error Bars with Chart.js

Line Chart with Chart.js

Annotated Line Chart with Highcharts

Scatter Chart with Chart.js

Bubble Chart with Chart.js

12 Leaflet Map Templates

Leaflet Maps with Google Sheets

Leaflet Storymaps with Google Sheets

Get Your Google Sheets API Key

Leaflet Maps with CSV Data

Leaflet Heatmap Points with CSV Data

Leaflet Searchable Point Map

Leaflet Maps with Open Data APIs

13 Transform Your Map Data

Geospatial Data and GeoJSON

Find GeoJSON Boundary Files

Draw and Edit with GeoJson.io

Edit and Join with Mapshaper

Convert Compressed KMZ to KML

Georeference with Map Warper

Bulk Geocode with US Census

Pivot Points into Polygon Data

14 Detect Lies and Reduce Bias

How to Lie with Charts

How to Lie with Maps

Recognize and Reduce Data Bias

Recognize and Reduce Spatial Bias

15 Tell and Show Your Data Story

Build a Narrative on a Storyboard

Draw Attention to Meaning

Acknowledge Sources & Uncertainty

Decide On Your Data Story Format

Appendix

A Fix Common Problems

A.1 Tool or platform problems

A.2 Try a different browser

A.3 Diagnose with developer tools

A.4 Mac or Chromebook problems

A.5 Watch out for bad data

A.6 Common iframe errors

A.7 Fix your code on GitHub

B Publishing with Bookdown

Install and Set Up Bookdown

File Structure and Headers

Style Guide for Hands-On Data Visualization

Images and R Code-chunk Formatting

Tables in Markdown Format

Zotero and Better BibTeX for Notes and Biblio

Alternative Book Publishing Tools

References

Open-access web edition

Built with Bookdown + RStudio

            Hands-On Data Visualization

Leaflet Maps with Open Data APIs

Learn how to code your own Leaflet map with an application programming interface (API) that continuously pulls the most current information directly from an open-data repository, similar to the Socrata Open Data map you learned about in Chapter 7. Leaflet maps can pull and display data from various open data repositories using APIs.
Figure 12.40 shows an interactive map of North Dakota counties,
colored by population density, with hospitals and emergency medical service (EMS) locations.

This map template pulls data from three different open repository sources:

Hospital information is pulled directly from Medicare.org Socrata database.

County boundaries and population density are pulled from North Dakota GIS ArcGIS server.

EMS stations are fetched from Homeland Infrastructure Foundation-Level Data ArcGIS server.

Figure 12.40: Explore the interactive Leaflet Map with Open Data.

You can enable Leaflet to pull data from ArcGIS servers using a free esri-leaflet plugin.
Data from Socrata can be pulled using jQuery's $.getJSON() function,
and then passed to Leaflet directly using L.geoJSON() function.

To adapt this template for your own project:

Visit the GitHub repository that contains the code for the map in Figure 12.40,
and press the Use this template button to copy the repo to your own GitHub account.

All data is pulled form the code inside the <script> tag of index.html. To pull
data from Socrata or another JSON/GeoJSON endpoint, modify the following code snippet
with the appropriate URL and icon:

/*
  From Medicare's Socrata database, add general hospitals in North Dakota
  using simple filtering on the `state` column, and a GeoJSON endpoint.
  Each point is a custom .png icon with a tooltip containing hospital's name,
  city, and zipcode.
*/
$.getJSON("https://data.medicare.gov/resource/xubh-q36u.geojson?state=ND",

  function(data) {

    var hospitals = L.geoJSON(data, {
      pointToLayer: function(feature, latlng) {
        return L.marker(latlng, {
          icon: L.icon({
            iconUrl: 'images/hospital.png',
            iconSize: [24, 24],
            iconAnchor: [12, 12],
            opacity: 0.5
          })
        }).bindTooltip(
          feature.properties.hospital_name
            + '<br>' + feature.properties.city
            + '<br>' + feature.properties.zip_code
        )
      }
    }).addTo(map)

  }

)

The following code snippet uses esri-leaflet plugin to pull polygon data
from an ArcGIS server, and creates a choropleth layer based on population density
(stored in POP10_SQMI variable of each feature, or polygon).

var counties = L.esri.featureLayer({
  url:'https://ndgishub.nd.gov/arcgis/rest/services/All_GovtBoundaries/MapServer/20',
  style: function(feature) {
    return {
      fillOpacity: 0.5,
      weight: 0.5,
      color: 'silver',
      fillColor: getDensityColor(feature.properties.POP10_SQMI)
    }
  }
}).addTo(map)

Here, the getDensityColor() function returns a color for a given value
based on pre-defined thresholds. In case of the North Dakota example,
population density of over 100 people per square mile is assigned the darkest shade of red,
while the density of 5 and under is shown with the lightest.

var getDensityColor = function(d) {
  return d > 100  ? '#7a0177' :
          d > 50  ? '#c51b8a' :
          d > 20  ? '#f768a1' :
          d > 5   ? '#fbb4b9' :
                    '#feebe2'
}

While it is convenient to pull data directly from the source databases,
remember that those resources are out of your control (unless you administer them, of course).
Data changes often come unannounced. For example, if the dataset owner decides
to rename the population density field from POP10_SQMI to Pop10_sqmi,
your map will stop showing values correctly. Datasets may get moved
to a different domain name or get deleted entirely, so
it is wise to have a back-up file saved locally.

If you are more concerned about the long-term functioning of your map as opposed
to displaying the most up-to-date version of the dataset, you may consider serving
your data from local GeoJSON files instead (but ensure first that it is permitted by the data license).

Summary

In this chapter, we introduced Leaflet map templates for common map problems,
such as telling stories about places using scrollable interface,
showing point data from databases like Socrata, and creating heatmaps
to visualize areas of high event density.

You can use these templates as a base to kickstart your own mapping projects.
Leaflet.js is well-documented, and we recommend
looking at their tutorials for more inspiration.

In the next chapter, we will talk about geospatial data and introduce several
tools that can convert, create, and edit geospatial files.

      Buy the print book at
      Amazon -
      Barnes & Noble -
      Bookshop -
      Powell's - or your local bookstore.

      Or begin a 30-day free trial to all books and digital content on the O'Reilly online learning platform.

      Share your feedback about the book by tagging @handsondataviz on Twitter or
      contact the authors.

      © 2021 Jack Dougherty & Ilya Ilyankou / Picturedigits Ltd.


text:
package exceptions;

public class InvalidCommandException extends SlogoException {
	public InvalidCommandException() {
		super("Invalid command!");
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.mapred;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;

/**
 * This is used to track task completion events on
 * job tracker.
 *
 */
public class TaskCompletionEvent implements Writable{
    static public enum Status {FAILED, SUCCEEDED};

    private int eventId ;
    private String taskTrackerHttp ;
    private String taskId ;
    Status status ;
    public static final TaskCompletionEvent[] EMPTY_ARRAY =
        new TaskCompletionEvent[0];
    /**
     * Default constructor for Writable.
     *
     */
    public TaskCompletionEvent(){}
    /**
     * Constructor. eventId should be created externally and incremented
     * per event for each job.
     * @param eventId event id, event id should be unique and assigned in
     *  incrementally, starting from 0.
     * @param taskId task id
     * @param status task's status
     * @param taskTrackerHttp task tracker's host:port for http.
     */
    public TaskCompletionEvent(int eventId,
        String taskId,
        Status status,
        String taskTrackerHttp){

        this.taskId = taskId ;
        this.eventId = eventId ;
        this.status =status ;
        this.taskTrackerHttp = taskTrackerHttp ;
    }
    /**
     * Returns event Id.
     * @return event id
     */
    public int getEventId() {
        return eventId;
    }
    /**
     * Returns task id.
     * @return task id
     */
    public String getTaskId() {
        return taskId;
    }
    /**
     * Returns enum Status.SUCESS or Status.FAILURE.
     * @return task tracker status
     */
    public Status getTaskStatus() {
        return status;
    }
    /**
     * http location of the tasktracker where this task ran.
     * @return http location of tasktracker user logs
     */
    public String getTaskTrackerHttp() {
        return taskTrackerHttp;
    }
    /**
     * set event Id. should be assigned incrementally starting from 0.
     * @param eventId
     */
    public void setEventId(
        int eventId) {
        this.eventId = eventId;
    }
    /**
     * Sets task id.
     * @param taskId
     */
    public void setTaskId(
        String taskId) {
        this.taskId = taskId;
    }
    /**
     * Set task status.
     * @param status
     */
    public void setTaskStatus(
        Status status) {
        this.status = status;
    }
    /**
     * Set task tracker http location.
     * @param taskTrackerHttp
     */
    public void setTaskTrackerHttp(
        String taskTrackerHttp) {
        this.taskTrackerHttp = taskTrackerHttp;
    }

    public String toString(){
        StringBuffer buf = new StringBuffer();
        buf.append("Task Id : ");
        buf.append( taskId ) ;
        buf.append(", Status : ");
        buf.append( status.name() ) ;
        return buf.toString();
    }

    //////////////////////////////////////////////
    // Writable
    //////////////////////////////////////////////
    public void write(DataOutput out) throws IOException {
        WritableUtils.writeString(out, taskId);
        WritableUtils.writeEnum(out, status);
        WritableUtils.writeString(out, taskTrackerHttp);
    }

    public void readFields(DataInput in) throws IOException {
        this.taskId = WritableUtils.readString(in) ;
        this.status = WritableUtils.readEnum(in, Status.class);
        this.taskTrackerHttp = WritableUtils.readString(in);
    }
}


text:
<!DOCTYPE HTML>

<title>SqlLineHighlighter (sqlline 1.11.0 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2021-02-25">
<meta name="description" content="declaration: package: sqlline, class: SqlLineHighlighter">
<meta name="generator" content="javadoc/ClassWriterImpl">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../script-dir/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Package sqlline

Class SqlLineHighlighter

java.lang.Object

org.jline.reader.impl.DefaultHighlighter

sqlline.SqlLineHighlighter

All Implemented Interfaces:

org.jline.reader.Highlighter

public class SqlLineHighlighter
extends org.jline.reader.impl.DefaultHighlighter

Highlighter class to implement logic of sql
 and command syntax highlighting in sqlline.

Constructor Summary

Constructors

Constructor
Description

SqlLineHighlighter(SqlLine sqlLine)

Method Summary

<button role="tab" aria-selected="true" aria-controls="memberSummary_tabpanel" tabindex="0" onkeydown="switchTab(event)" id="t0" class="activeTableTab">All Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t2" class="tableTab" onclick="show(2);">Instance Methods</button><button role="tab" aria-selected="false" aria-controls="memberSummary_tabpanel" tabindex="-1" onkeydown="switchTab(event)" id="t4" class="tableTab" onclick="show(8);">Concrete Methods</button>

Modifier and Type
Method
Description

org.jline.utils.AttributedString
highlight(org.jline.reader.LineReader reader,
java.lang.String buffer)

Methods inherited from class org.jline.reader.impl.DefaultHighlighter

setErrorIndex, setErrorPattern

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Details

SqlLineHighlighter

public SqlLineHighlighter(SqlLine sqlLine)

Method Details

highlight

public org.jline.utils.AttributedString highlight(org.jline.reader.LineReader reader,
java.lang.String buffer)

Specified by:

highlight in interface org.jline.reader.Highlighter

Overrides:

highlight in class org.jline.reader.impl.DefaultHighlighter

Skip navigation links

Package

Class

Use

Tree

Deprecated

Index

Help

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2002–2021 Julian Hyde. All rights reserved.


text:
var reload      = require('require-reload')(require),
	Cleverbot   = reload('cleverbot-node'),
	Waifu       = new Cleverbot(),
	entities    = require('entities'),
	logger      = new (reload('../utils/Logger.js'))((reload('../config.json')).logTimestamp, 'yellow'),
	antiSpam    = {};

Cleverbot.prepare(() => {});

function reset() {
	Cleverbot = reload('cleverbot-node');
	Waifu = new Cleverbot();
	Cleverbot.prepare(() => {});
}

function spamCheck(userId, text) {
	if (!antiSpam.hasOwnProperty(userId)) { //If user not there add them
		antiSpam[userId] = text;
		return true;
	}
	if (antiSpam[userId] == text) //If user sent the same message ignore it
		return false;
	antiSpam[userId] = text;
	return true;
}

function trimText(cleanContent, name) {
	return cleanContent.replace(`@${name}`, '').trim(); //Removes the @Bot part
}

function processUnicode(text) {
	if (/\|/g.test(text)) //Cleverbot returns unicode like |1234 for some reason. This fixes it
		return text.replace(/\|/g, '\\u').replace(/\\u([\d\w]{4})/gi, (match, grp) => String.fromCharCode(parseInt(grp, 16))); //unescape unicode
	return text;
}

module.exports = function(bot, msg, config, settingsManager) {
	if (msg.channel.guild !== undefined && !msg.channel.permissionsOf(msg.author.id).has('manageChannels') && settingsManager.isCommandIgnored('', 'cleverbot', msg.channel.guild.id, msg.channel.id, msg.author.id) === true)
		return;
	let text = msg.channel.guild === undefined ? msg.cleanContent : trimText(msg.cleanContent, msg.channel.guild.members.get(bot.user.id).nick || bot.user.username);
	if (spamCheck(msg.author.id, text)) {
		cleverbotTimesUsed++;
		logger.logCommand(msg.channel.guild === undefined ? null : msg.channel.guild.name, msg.author.username, '@' + bot.user.username, text);
		if (text === '') //If they just did @Botname
			msg.channel.createMessage('Yes?');
		else {
			msg.channel.sendTyping();
			Waifu.write(text, response => {
				response = processUnicode(response.message);
				if (response)
					msg.channel.createMessage('💬 ' + entities.decodeHTML(response));
				else { //API returned nothing back
					reset();
					logger.warn('Nothing was returned by the cleverbot API. Reloading it now.');
					msg.channel.createMessage('⚠ There was an error, try again.');
				}
			});
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Common;
using Common.Log;
using MarginTrading.Backend.Core;

namespace MarginTrading.Backend.Services
{
    public class OrderCacheManager : TimerPeriod
    {
        private readonly OrdersCache _orderCache;
        private readonly IMarginTradingBlobRepository _marginTradingBlobRepository;
        private readonly ILog _log;
        private readonly IAccountsCacheService _accountsCacheService;
        private const string BlobName= "orders";

        public OrderCacheManager(OrdersCache orderCache,
            IMarginTradingBlobRepository marginTradingBlobRepository,
            ILog log, IAccountsCacheService accountsCacheService)
            : base(nameof(OrderCacheManager), 5000, log)
        {
            _orderCache = orderCache;
            _marginTradingBlobRepository = marginTradingBlobRepository;
            _log = log;
            _accountsCacheService = accountsCacheService;
        }

        public override void Start()
        {
            var orders = _marginTradingBlobRepository.Read<List<Order>>(LykkeConstants.StateBlobContainer, BlobName) ?? new List<Order>();

            orders.ForEach(o =>
            {
                // migrate orders to add LegalEntity field
                // todo: can be removed once published to prod
                if (o.LegalEntity == null)
                    o.LegalEntity = _accountsCacheService.Get(o.ClientId, o.AccountId).LegalEntity;
            });

            _orderCache.InitOrders(orders);

            base.Start();
        }

        public override async Task Execute()
        {
            await DumpToRepository();
        }

        public override void Stop()
        {
            DumpToRepository().Wait();
            base.Stop();
        }

        private async Task DumpToRepository()
        {

            try
            {
                var orders = _orderCache.GetAll();

                if (orders != null)
                {
                    await _marginTradingBlobRepository.Write(LykkeConstants.StateBlobContainer, BlobName, orders);
                }
            }
            catch (Exception ex)
            {
                await _log.WriteErrorAsync(nameof(OrdersCache), "Save orders", "", ex);
            }
        }
    }
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of PHP CS Fixer.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *     Dariusz Rumiński <dariusz.ruminski@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace PhpCsFixer\Tests\Tokenizer\Analyzer;

use PhpCsFixer\Tests\TestCase;
use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer;
use PhpCsFixer\Tokenizer\Tokens;

/**
 * @author Kuba Werłos <werlos@gmail.com>
 *
 * @internal
 *
 * @covers \PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer
 */
final class CommentsAnalyzerTest extends TestCase
{
    public function testWhenNotPointingToComment(): void
    {
        $analyzer = new CommentsAnalyzer();
        $tokens = Tokens::fromCode('<?php $no; $comment; $here;');

        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Given index must point to a comment.');

        $analyzer->getCommentBlockIndices($tokens, 4);
    }

    /**
     * @param list<int> $borders
     *
     * @dataProvider provideCommentsCases
     */
    public function testComments(string $code, int $index, array $borders): void
    {
        $tokens = Tokens::fromCode($code);
        $analyzer = new CommentsAnalyzer();

        static::assertSame($borders, $analyzer->getCommentBlockIndices($tokens, $index));
        static::assertFalse($analyzer->isHeaderComment($tokens, $index));
    }

    public function provideCommentsCases(): array
    {
        return [
            'discover all 4 comments for the 1st comment with slash' => [
                '<?php
$foo;
// one
// two
// three
// four
$bar;',
                4,
                [4, 6, 8, 10],
            ],
            'discover all 4 comments for the 1st comment with hash' => [
                '<?php
$foo;
# one
# two
# three
# four
$bar;',
                4,
                [4, 6, 8, 10],
            ],
            'discover 3 comments out of 4 for the 2nd comment' => [
                '<?php
$foo;
// one
// two
// three
// four
$bar;',
                6,
                [6, 8, 10],
            ],
            'discover 3 comments when empty line separates 4th' => [
                '<?php
$foo;
// one
// two
// three

// four
$bar;',
                4,
                [4, 6, 8],
            ],
            'discover 3 comments when empty line of CR separates 4th' => [
                str_replace("\n", "\r", '<?php
$foo;
// one
// two
// three

// four
$bar;'),
                4,
                [4, 6, 8],
            ],
            'discover correctly when mix of slash and hash' => [
                '<?php
$foo;
// one
// two
# three
// four
$bar;',
                4,
                [4, 6],
            ],
            'do not group asterisk comments' => [
                '<?php
$foo;
/* one */
/* two */
/* three */
$bar;',
                4,
                [4],
            ],
            'handle fancy indent' => [
                '<?php
$foo;
        // one
       //  two
      //   three
     //    four
$bar;',
                4,
                [4, 6, 8, 10],
            ],
        ];
    }

    public function testHeaderCommentAcceptsOnlyComments(): void
    {
        $tokens = Tokens::fromCode('<?php 1; 2; 3;');
        $analyzer = new CommentsAnalyzer();

        $this->expectException(\InvalidArgumentException::class);

        $analyzer->isHeaderComment($tokens, 2);
    }

    /**
     * @dataProvider provideHeaderCommentCases
     */
    public function testHeaderComment(string $code, int $index): void
    {
        $tokens = Tokens::fromCode($code);
        $analyzer = new CommentsAnalyzer();

        static::assertTrue($analyzer->isHeaderComment($tokens, $index));
    }

    public function provideHeaderCommentCases(): array
    {
        return [
            ['<?php /* Comment */ namespace Foo;', 1],
            ['<?php /** Comment */ namespace Foo;', 1],
            ['<?php declare(strict_types=1); /* Comment */ namespace Foo;', 9],
            ['<?php /* We test this one */ /* Foo */ namespace Bar;', 1],
            ['<?php /** Comment */ namespace Foo; declare(strict_types=1); /* Comment */ namespace Foo;', 1],
        ];
    }

    /**
     * @dataProvider provideNotHeaderCommentCases
     */
    public function testNotHeaderComment(string $code, int $index): void
    {
        $tokens = Tokens::fromCode($code);
        $analyzer = new CommentsAnalyzer();

        static::assertFalse($analyzer->isHeaderComment($tokens, $index));
    }

    public function provideNotHeaderCommentCases(): array
    {
        return [
            ['<?php $foo; /* Comment */ $bar;', 4],
            ['<?php foo(); /* Comment */ $bar;', 6],
            ['<?php namespace Foo; /* Comment */ class Bar {};', 6],
            ['<?php /* It is not header when no content after */', 1],
            ['<?php /* Foo */ /* We test this one */ namespace Bar;', 3],
            ['<?php /* Foo */ declare(strict_types=1); /* We test this one */ namespace Bar;', 11],
        ];
    }

    public function testPhpdocCandidateAcceptsOnlyComments(): void
    {
        $tokens = Tokens::fromCode('<?php 1; 2; 3;');
        $analyzer = new CommentsAnalyzer();

        $this->expectException(\InvalidArgumentException::class);

        $analyzer->isBeforeStructuralElement($tokens, 2);
    }

    /**
     * @dataProvider providePhpdocCandidateCases
     */
    public function testPhpdocCandidate(string $code): void
    {
        $tokens = Tokens::fromCode($code);
        $index = $tokens->getNextTokenOfKind(0, [[T_COMMENT], [T_DOC_COMMENT]]);
        $analyzer = new CommentsAnalyzer();

        static::assertTrue($analyzer->isBeforeStructuralElement($tokens, $index));
    }

    public function providePhpdocCandidateCases(): array
    {
        return [
            ['<?php /* @var Foo */ $bar = "baz";'],
            ['<?php /* Before namespace */ namespace Foo;'],
            ['<?php /* Before class */ class Foo {}'],
            ['<?php /* Before class */ abstract class Foo {}'],
            ['<?php /* Before class */ final class Foo {}'],
            ['<?php /* Before trait */ trait Foo {}'],
            ['<?php /* Before interface */ interface Foo {}'],
            ['<?php /* Before anonymous function */ function () {};'],
            ['<?php class Foo { /* Before property */ private $bar; }'],
            ['<?php class Foo { /* Before property */ protected $bar; }'],
            ['<?php class Foo { /* Before property */ public $bar; }'],
            ['<?php class Foo { /* Before property */ var $bar; }'],
            ['<?php class Foo { /* Before function */ function bar() {} }'],
            ['<?php class Foo { /* Before use */ use Bar; }'],
            ['<?php class Foo { /* Before function */ final function bar() {} }'],
            ['<?php class Foo { /* Before function */ private function bar() {} }'],
            ['<?php class Foo { /* Before function */ protected function bar() {} }'],
            ['<?php class Foo { /* Before function */ public function bar() {} }'],
            ['<?php class Foo { /* Before function */ static function bar() {} }'],
            ['<?php class Foo { /* Before function */ abstract function bar(); }'],
            ['<?php class Foo { /* Before constant */ const FOO = 42; }'],
            ['<?php /* Before require */ require "foo/php";'],
            ['<?php /* Before require_once */ require_once "foo/php";'],
            ['<?php /* Before include */ include "foo/php";'],
            ['<?php /* Before include_once */ include_once "foo/php";'],
            ['<?php /* @var array $foo */ foreach ($foo as $bar) {};'],
            ['<?php /* @var int $foo */ if ($foo === -1) {};'],
            ['<?php /* @var SomeClass $foo */ switch ($foo) { default: exit; };'],
            ['<?php /* @var bool $foo */ while ($foo) { $foo--; };'],
            ['<?php /* @var int $i */ for ($i = 0; $i < 16; $i++) {};'],
            ['<?php /* @var int $i @var int $j */ list($i, $j) = getValues();'],
            ['<?php /* @var string $s */ print($s);'],
            ['<?php /* @var string $s */ echo($s);'],
            ['<?php /* @var User $bar */ ($baz = tmp())->doSomething();'],
            ['<?php /* @var User $bar */ list($bar) = a();'],
        ];
    }

    /**
     * @dataProvider provideNotPhpdocCandidateCases
     */
    public function testNotPhpdocCandidate(string $code): void
    {
        $tokens = Tokens::fromCode($code);
        $index = $tokens->getNextTokenOfKind(0, [[T_COMMENT], [T_DOC_COMMENT]]);
        $analyzer = new CommentsAnalyzer();

        static::assertFalse($analyzer->isBeforeStructuralElement($tokens, $index));
    }

    public function provideNotPhpdocCandidateCases(): array
    {
        return [
            ['<?php class Foo {} /* At the end of file */'],
            ['<?php class Foo { public $baz; public function baz(); /* At the end of class */ }'],
            ['<?php /* Before increment */ $i++;'],
            ['<?php /* Comment, but not doc block */ if ($foo === -1) {};'],
            ['<?php
                $a = $b[1]; // @phpstan-ignore-line

                static::bar();',
            ],
        ];
    }

    public function testPhpdocCandidate71(): void
    {
        $tokens = Tokens::fromCode('<?php /* @var int $x */ [$x] = [2];');
        $analyzer = new CommentsAnalyzer();

        static::assertTrue($analyzer->isHeaderComment($tokens, 1));
    }

    public function testNotPhpdocCandidate71(): void
    {
        $tokens = Tokens::fromCode('<?php /* @var int $a */ [$b] = [2];');
        $analyzer = new CommentsAnalyzer();

        static::assertFalse($analyzer->isBeforeStructuralElement($tokens, 1));
    }

    /**
     * @dataProvider providePhpdocCandidatePhp74Cases
     */
    public function testPhpdocCandidatePhp74(string $code): void
    {
        $tokens = Tokens::fromCode($code);
        $index = $tokens->getNextTokenOfKind(0, [[T_COMMENT], [T_DOC_COMMENT]]);
        $analyzer = new CommentsAnalyzer();

        static::assertTrue($analyzer->isBeforeStructuralElement($tokens, $index));
    }

    public function providePhpdocCandidatePhp74Cases(): array
    {
        return [
            ['<?php /* Before anonymous function */ $fn = fn($x) => $x + 1;'],
        ];
    }

    /**
     * @dataProvider providePhpdocCandidatePhp80Cases
     *
     * @requires PHP 8.0
     */
    public function testPhpdocCandidatePhp80(string $code): void
    {
        $tokens = Tokens::fromCode($code);
        $index = $tokens->getNextTokenOfKind(0, [[T_COMMENT], [T_DOC_COMMENT]]);
        $analyzer = new CommentsAnalyzer();

        static::assertTrue($analyzer->isBeforeStructuralElement($tokens, $index));
    }

    public function providePhpdocCandidatePhp80Cases(): array
    {
        return [
            ['<?php
/**
 * @Annotation
 */
#[CustomAnnotationA]
Class MyAnnotation3 {}'],
        ];
    }

    /**
     * @dataProvider providePhpdocCandidatePhp81Cases
     *
     * @requires PHP 8.1
     */
    public function testPhpdocCandidatePhp81(string $code): void
    {
        $tokens = Tokens::fromCode($code);
        $index = $tokens->getNextTokenOfKind(0, [[T_COMMENT], [T_DOC_COMMENT]]);
        $analyzer = new CommentsAnalyzer();

        static::assertTrue($analyzer->isBeforeStructuralElement($tokens, $index));
    }

    public function providePhpdocCandidatePhp81Cases(): iterable
    {
        yield 'public readonly' => [
            '<?php class Foo { /* */ public readonly int $a1; }',
        ];

        yield 'readonly public' => [
            '<?php class Foo { /* */ readonly public int $a1; }',
        ];

        yield 'readonly union' => [
            '<?php class Foo { /* */ readonly A|B $a1; }',
        ];

        yield 'public final const' => [
            '<?php final class Foo2 extends B implements A
            {
                /* */
                public final const Y = "i";
            }',
        ];

        yield 'final public const' => [
            '<?php final class Foo2 extends B implements A
            {
                /* */
                final public const Y = "i";
            }',
        ];

        yield 'enum' => [
            '<?php /* Before enum */ enum Foo {}',
        ];
    }
}


text:
package com.asura.resource.service;
import com.asura.framework.base.paging.PagingResult;
import com.asura.framework.base.paging.SearchMap;
import com.asura.framework.dao.mybatis.paginator.domain.PageBounds;
import com.asura.common.service.BaseService;
import com.asura.resource.entity.CmdbResourceGroupsEntity;
import com.asura.resource.dao.CmdbResourceGroupsDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 *

 *

 *

 *

 *
-----------------------------------------------
 *

 *

 *
 * @author zhaozq14
 * @version 1.0
 * @date 2016-07-28 11:31:36
 * @since 1.0
 */
@Service("com.asura.resource.service.CmdbResourceGroupsService")
public class CmdbResourceGroupsService extends BaseService<CmdbResourceGroupsEntity,CmdbResourceGroupsDao>{

    @Resource(name="com.asura.resource.dao.CmdbResourceGroupsDao")
    private CmdbResourceGroupsDao dao;

    /**
     * 查询所有
     * @param searchMap
     * @param pageBounds
     * @return
     */
    public PagingResult<CmdbResourceGroupsEntity> findAll(SearchMap searchMap, PageBounds pageBounds){
        return dao.findAll(searchMap,pageBounds);
    }
}


text:
package org.wso2.appcloud.core.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.appcloud.common.AppCloudException;
import org.wso2.appcloud.core.DBUtil;
import org.wso2.appcloud.core.SQLQueryConstants;
import org.wso2.appcloud.core.dto.Application;
import org.wso2.appcloud.core.dto.Event;

import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * DAO class for persisting or retrieving application creation related events
 */

public class EventsDAO {

    private static final Log log = LogFactory.getLog(EventsDAO.class);

    /**
     * Method for adding application creation events to database
     *
     * @param applicationId application id
     * @param event application creation event
     * @return
     * @throws AppCloudException
     */
    public boolean addAppCreationEvent(int applicationId, Event event) throws AppCloudException {

        Connection dbConnection = DBUtil.getDBConnection();
        PreparedStatement preparedStatement = null;

        try {
            preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.ADD_APP_CREATION_EVENT);
            preparedStatement.setInt(1, applicationId);
            preparedStatement.setString(2, event.getEventName());
            preparedStatement.setString(3, event.getEventStatus());
            preparedStatement.setTimestamp(4, event.getTimestamp());
            preparedStatement.setString(5, event.getEventDescription());

            boolean result = preparedStatement.execute();
            dbConnection.commit();
            log.info("DB insert query result: " + result);

        } catch (SQLException e) {
            String msg = "Error occurred while adding app creation event: " + event.getEventName() + " status: " + event
                    .getEventStatus() + " timestamp: " + event.getTimestamp();
            log.error(msg, e);
            throw new AppCloudException(msg, e);

        } finally {
            DBUtil.closePreparedStatement(preparedStatement);
            DBUtil.closeConnection(dbConnection);
        }
        return true;
    }

    /**
     *  Method to get event stream of an application
     *
     * @param applicationId application id
     * @return
     * @throws AppCloudException
     */
    public List<Event> getEventsOfApplication(int applicationId) throws AppCloudException {

        Connection dbConnection = DBUtil.getDBConnection();
        PreparedStatement preparedStatement = null;

        List<Event> eventList = new ArrayList<>();

        try {
            preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.GET_ALL_EVENTS_OF_APPLICATION);
            preparedStatement.setInt(1, applicationId);

            ResultSet resultSet = preparedStatement.executeQuery();
            Event event;
            while (resultSet.next()) {
                event = new Event();
                event.setEventName(resultSet.getString(SQLQueryConstants.EVENT_NAME));
                event.setEventStatus(resultSet.getString(SQLQueryConstants.EVENT_STATUS));
                event.setTimestamp(resultSet.getTimestamp(SQLQueryConstants.EVENT_TIMESTAMP));
                event.setEventDescription(resultSet.getString(SQLQueryConstants.EVENT_DESCRIPTION));

                eventList.add(event);
            }

        } catch (SQLException e) {
            String msg = "Error while retrieving Application creation event stream for applicationId: " + applicationId;
            log.error(msg, e);
            throw new AppCloudException(msg, e);
        } finally {
            DBUtil.closePreparedStatement(preparedStatement);
            DBUtil.closeConnection(dbConnection);
        }
        return eventList;
    }
}


text:
from pydoc import locate

from django.conf import settings
from django.urls import include, path

from .views.auth import LoginEndpoint, LogoutEndpoint
from .views.attachments import AttachmentsEndpoint
from .views.activities import ActivitiesEndpoint
from .views.comments import CommentsEndpoint
from .views.download import DownloadEndpoint
from .views.expenses import ExpensesEndpoint
from .views.expense_exports import ExpenseExportsEndpoint
from .views.profiles import ProfilesEndpoint
from .views.responders import RespondersEndpoint
from .views.reviews import ReviewsEndpoint
from .views.review_stats import ReviewStatsEndpoint
from .views.review_exports import ReviewExportsEndpoint
from .views.session import SessionEndpoint
from .views.subscribers import SubscribersEndpoint
from .views.tickets import TicketsEndpoint
from .views.ticket_stats import TicketStatsEndpoint
from .views.ticket_exports import TicketExportsEndpoint

router = locate(settings.ROUTER_CLASS)(trailing_slash=False)
router.register(r'attachments', AttachmentsEndpoint)
router.register(r'activities', ActivitiesEndpoint)
router.register(r'comments', CommentsEndpoint)
router.register(r'download', DownloadEndpoint, basename='download')
router.register(r'me', SessionEndpoint, basename='me')
router.register(r'profiles', ProfilesEndpoint)
router.register(r'responders', RespondersEndpoint)
router.register(r'reviews', ReviewsEndpoint)
router.register(r'review-stats', ReviewStatsEndpoint, basename='review_stats')
router.register(
    r'review-exports',
    ReviewExportsEndpoint,
    basename='review_exports'
)
router.register(r'subscribers', SubscribersEndpoint)
router.register(r'expenses', ExpensesEndpoint)
router.register(
    r'expense-exports',
    ExpenseExportsEndpoint,
    basename='expense_exports')
router.register(r'tickets', TicketsEndpoint)
router.register(r'ticket-stats', TicketStatsEndpoint, basename='ticket_stats')
router.register(
    r'ticket-exports',
    TicketExportsEndpoint,
    basename='ticket_exports')

auth_router = locate(settings.ROUTER_CLASS)(trailing_slash=False)
auth_router.register(r'login', LoginEndpoint, basename='login')
auth_router.register(r'logout', LogoutEndpoint, basename='logout')

urlpatterns = [
    path('api/v3/', include(router.urls)),
    path('accounts/', include(auth_router.urls)),
    path('accounts/social/', include('social_django.urls', namespace='social'))
]


text:
package de.unistuttgart.ipvs.pmp.model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import de.unistuttgart.ipvs.pmp.shared.Log;

/**
 * This is a helper for opening the database used by PMP.

 * It automatically creates the required tables in the SQLite database.

 * A database instance can be got by calling {@link DatabaseOpenHelper#getWritableDatabase()}.
 *
 * @author Jakob Jarosch
 */
public class DatabaseOpenHelper extends SQLiteOpenHelper {

    private static final String TAG = "DatabaseOpenHelper";

    /**
     * Name of the database.
     */
    private static final String DB_NAME = "pmp-database";

    /**
     * Current database version.
     */
    private static final int DB_VERSION = 5;

    /**
     * The context used to open the files from assets folder.
     */
    private Context context;

    /**
     * The query builder
     */
    private SQLiteQueryBuilder sqlqb;

    /**
     * List of all SQL-files for database-creation, the key is the version of the database.
     */
    private static final String whereIsSql(int dbVersion) {
        return String.format("database-v%d.sql", dbVersion);
    }

    /**
     * List of all SQL-files for database-clean, the key is the version of the database.
     */
    private static final String whereIsCleanSql(int dbVersion) {
        return String.format("database-v%d-clean.sql", dbVersion);
    }

    /**
     * DatabaseHelper-Constructor.
     */
    public DatabaseOpenHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.context = context;
        this.sqlqb = new SQLiteQueryBuilder();
    }

    /**
     * Called when the database is opened first time.
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(this, "Creating database structure");

        String sqlQueries = readSqlFile(whereIsSql(DB_VERSION));

        if (sqlQueries != null) {
            Log.d(this, "Executing " + whereIsSql(DB_VERSION) + " ...");
            if (DatabaseOpenHelper.executeMultipleQueries(db, sqlQueries)) {
                Log.d(this, "Created database");
            } else {
                Log.w(this, "Database not created");
            }

        }
    }

    /**
     * Called when upgrading from a previous version of the database.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d(this, "Update request " + oldVersion + " to " + newVersion);

        if ((newVersion == DB_VERSION) && (oldVersion < DB_VERSION)) {
            Log.d(this, "Forcing db re-creation");

            // delete everything in sight
            Cursor c = db.rawQuery(
                    "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'android_metadata'", null);
            if (c.moveToFirst()) {
                do {
                    db.execSQL("DROP TABLE " + c.getString(c.getColumnIndex("name")));
                } while (c.moveToNext());
            }
            c.close();

            // rerun creation
            onCreate(db);
        }
    }

    /**
     * Cleans all data from the tables.
     */
    public void cleanTables() {
        Log.d(this, "Cleaning database.");

        String sqlQueries = readSqlFile(whereIsCleanSql(DB_VERSION));

        if (sqlQueries != null) {
            Log.d(this, "Executing " + whereIsCleanSql(DB_VERSION) + " ...");
            SQLiteDatabase sqldb = getWritableDatabase();
            try {
                if (DatabaseOpenHelper.executeMultipleQueries(sqldb, sqlQueries)) {
                    Log.d(this, "Cleaned database");
                } else {
                    Log.w(this, "Database not cleaned");
                }
            } finally {
                sqldb.close();
            }
        }
    }

    /**
     * Read a SQL file from assets folder.
     *
     * @param filename
     *            Filename of the SQL file.
     *
     * @return String represented SQL query from the file. null if the file could not be READ.
     */
    public String readSqlFile(String filename) {
        String sqlQuery = null;

        try {
            InputStream is = this.context.getAssets().open(filename);
            InputStreamReader bis = new InputStreamReader(is, Charset.forName("UTF-8"));
            BufferedReader br = new BufferedReader(bis, 4096);
            StringBuilder sb = new StringBuilder();
            try {
                String curLine = null;
                while ((curLine = br.readLine()) != null) {
                    sb.append(curLine);
                    sb.append("\n");
                }

            } finally {
                br.close();
                bis.close();
                is.close();
            }

            sqlQuery = sb.toString();

        } catch (IOException e) {
            Log.e(this, "Reading the SQL file from " + filename + " failed.", e);
            sqlQuery = null;
        }

        return sqlQuery;
    }

    /**
     * This method executes multiple queries, which are concatenated by a semicolon.
     *
     * @param db
     *            The {@link SQLiteDatabase} which should be used to execute the queries.
     * @param queries
     *            The queries which should be executed.
     * @return true, if and only if all queries were executed
     */
    public static boolean executeMultipleQueries(SQLiteDatabase db, String queries) {
        boolean result = true;

        Log.v(TAG, "------- Executing SQL Queries  ------");

        for (String query : queries.split(";")) {

            /* Skipping, empty query */
            if (query.trim().length() == 0) {
                continue;
            }

            Log.v(TAG, query);

            try {
                db.execSQL(query);
            } catch (SQLException e) {
                Log.e(TAG, "Got an SQLException while executing query", e);
                result = false;
            }
        }

        Log.v(TAG, "------- SQL Queries Complete   ------");

        return result;
    }

    public SQLiteQueryBuilder builder() {
        return this.sqlqb;
    }

    /**
     * Go in there, print everything you can find on LogCat.
     */
    public void debug() {
        SQLiteDatabase db = getReadableDatabase();
        try {
            Cursor c = db.rawQuery(
                    "SELECT name FROM sqlite_master WHERE type = 'table' AND name != 'android_metadata'", null);
            if (c.moveToFirst()) {
                do {
                    String tbl = c.getString(c.getColumnIndex("name"));
                    Log.d(this, "TABLE '" + tbl + "'");
                    this.sqlqb.setTables(tbl);

                    // null anyone?
                    Cursor c2 = this.sqlqb.query(db, null, null, null, null, null, null);
                    if (c2.moveToFirst()) {
                        do {
                            Log.d(this, "  row " + (1 + c2.getPosition()) + " of " + c2.getCount());

                            for (int i = 0; i < c2.getColumnCount(); i++) {
                                Log.d(this, "     " + c2.getColumnName(i) + " => '" + c2.getString(i) + "'");
                            }

                        } while (c2.moveToNext());
                    } else {
                        Log.d(this, "  empty table");
                    }
                    c2.close();

                } while (c.moveToNext());
            }
            c.close();
        } finally {
            db.close();
        }
    }

}


text:
Simrunners
==========

.. automodule:: active_subspaces.utils.simrunners
    :members:


text:
package com.coodays.pushservicelib.push;

import android.content.Context;
import android.text.TextUtils;
import com.coodays.pushservicelib.utils.CdLogUtils;
import com.coodays.pushservicelib.utils.CdSharedPreferencesUtils;
import com.coodays.pushservicelib.utils.CdTools;
import com.xiaomi.channel.commonutils.logger.LoggerInterface;
import com.xiaomi.mipush.sdk.Logger;
import com.xiaomi.mipush.sdk.MiPushClient;

/**
 * @author zhuj
 * 小米推送
 */
class MiuiPush extends BasePush{

  private final static String TAG = "MiuiPush";

  private String APP_ID = "";
  private String APP_KEY = "";

  MiuiPush(Context mContext) {
    super(mContext);
  }

  private static volatile BasePush mBashPush;

  public static BasePush getInstance(Context context){
    if (mBashPush==null) {
      synchronized (MiuiPush.class) {
        if(mBashPush==null) {
          mBashPush = new MiuiPush(context);
        }
      }
    }
    return mBashPush;
  }

  @Override public void init() {
    //小米4  token
    if(CdTools.isMainProcess(mContext)) {
     // String appUserId = (String) CdSharedPreferencesUtils.get(mContext, CdSharedPreferencesUtils.KEY_APP_USER_ID, "");
      String uploadToken = CdSharedPreferencesUtils.getTokenSingle(mContext, ""+PushManager.PHONE_TYPE_MIUI);
      if(TextUtils.isEmpty(uploadToken)) {//没有上传过, 才注册上传token
        getSDKInfo();
        MiPushClient.registerPush(mContext, APP_ID, APP_KEY);
      }
      CdLogUtils.v("miuiPush", " init(). token " +uploadToken);
      Logger.setLogger(mContext, newLogger);
    }
  }

  LoggerInterface newLogger = new LoggerInterface() {

    @Override
    public void setTag(String tag) {
      // ignore
    }

    @Override
    public void log(String content, Throwable t) {
      CdLogUtils.d(TAG, content + " " + t.getMessage());
    }

    @Override
    public void log(String content) {
      CdLogUtils.d(TAG, content);
    }
  };

  @Override public void login(String app_user_id, String password) {
    CdSharedPreferencesUtils.put(mContext, CdSharedPreferencesUtils.KEY_APP_USER_ID, app_user_id);
    String token = CdSharedPreferencesUtils.getTokenSingle(mContext, ""+PushManager.PHONE_TYPE_MIUI);
    //登入时, 还未获取到token值,
    if (TextUtils.isEmpty(token)) { //请求一次token, 请求成功,会再次触发上传token
      getSDKInfo();
      MiPushClient.registerPush(mContext, APP_ID, APP_KEY);
    }
  }

  @Override public void loginOut() {
    MiPushClient.unregisterPush(mContext);
    loginOutClean();
    //MiPushClient.setUserAccount(mContext, "" ,null);
  }

  @Override public String getStatus() {
    return "";
  }

  @Override public boolean isLogin() {
    String appUserId = (String) CdSharedPreferencesUtils.get(mContext, CdSharedPreferencesUtils.KEY_APP_USER_ID, "");
    String regId = (String) CdSharedPreferencesUtils.get(mContext, appUserId, "");
    return TextUtils.isEmpty(regId);
  }

  private void getSDKInfo() {
    if (TextUtils.isEmpty(APP_ID)) {
      APP_ID = CdTools.getMetaDataValue(mContext, "com.xiaomi.push.sdk.app_id");
    }
    if (TextUtils.isEmpty(APP_KEY)) {
      APP_KEY = CdTools.getMetaDataValue(mContext, "com.xiaomi.push.sdk.app_key");
    }
  }

}


text:
package publichealthcomplaint.userinterface.impl.util.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import publichealthcomplaint.userinterface.impl.util.spec.prov.IUtil;
import publichealthcomplaint.userinterface.impl.util.spec.prov.IHTMLPageMgt;
import publichealthcomplaint.userinterface.impl.util.spec.prov.IManager;

class Manager implements IManager {

	private HashMap providedInterfaces;
	private HashMap requiredInterfaces;

	Manager(){
		this.providedInterfaces = new HashMap();
		this.requiredInterfaces = new HashMap();

		IHTMLPageMgt htmlPage = new FacadeHTMLPageMgt();
		providedInterfaces.put("IHTMLPageMgt", htmlPage);

		IUtil util = new FacadeUtil();
		providedInterfaces.put("IUtil", util);
	}

	public Object getProvidedInterface(String name) {
		if( name != null)
			return this.providedInterfaces.get(name);
		else{
			System.err.println(this.getClass().getCanonicalName()+":Invalid argument");
			return null;

		}
	}

	public String[] listProvidedInterfaces() {
		return convertListToArray(this.providedInterfaces.values());
	}

	public String[] listRequiredInterfaces() {
		return convertListToArray(this.requiredInterfaces.values());
	}

	public void setRequiredInterface(String name, Object facade) {
		this.requiredInterfaces.put(name, facade);

	}

	private String[] convertListToArray(Collection stringCollection){
		String[] stringArray = new String[stringCollection.size()];
		int i=0;
		for (Iterator iter = stringCollection.iterator();iter.hasNext();){
			stringArray[i] = (String)iter.next();
			i++;
		}
		return stringArray;
	}

	public Object getRequiredInterface(String name) {
		if( name != null)
			return requiredInterfaces.get(name);
		else{
			System.err.println("Null argument!");
			return null;
		}
	}

	public void setProvidedInterface(String name, Object facade) {
		this.providedInterfaces.put(name, facade);

	}

}


text:
<?php

namespace Sensio\Bundle\DistributionBundle\Configurator;

use Sensio\Bundle\DistributionBundle\Configurator\Step\StepInterface;
use Symfony\Component\Yaml\Yaml;

/**
 * Configurator.
 *
 * @author Marc Weistroff <marc.weistroff@gmail.com>
 * @author Jérôme Vieilledent <lolautruche@gmail.com>
 */
class Configurator
{
    protected $filename;
    protected $steps;
    protected $sortedSteps;
    protected $parameters;

    public function __construct($kernelDir)
    {
        $this->kernelDir = $kernelDir;
        $this->filename = $kernelDir.'/config/parameters.yml';

        $this->steps = array();
        $this->parameters = $this->read();
    }

    public function isFileWritable()
    {
        return is_writable($this->filename);
    }

    public function clean()
    {
        if (file_exists($this->getCacheFilename())) {
            @unlink($this->getCacheFilename());
        }
    }

    /**
     * @param StepInterface $step
     * @param int $priority
     */
    public function addStep(StepInterface $step, $priority = 0)
    {
        if (!isset($this->steps[$priority])) {
            $this->steps[$priority] = array();
        }

        $this->steps[$priority][] = $step;
        $this->sortedSteps = null;
    }

    /**
     * @param integer $index
     *
     * @return StepInterface
     */
    public function getStep($index)
    {
        $steps = $this->getSteps();
        if (isset($steps[$index])) {
            return $steps[$index];
        }
    }

    /**
     * @return StepInterface[]
     */
    public function getSteps()
    {
        if ($this->sortedSteps === null) {
            $this->sortedSteps = $this->getSortedSteps();
            foreach ($this->sortedSteps as $step) {
                $step->setParameters($this->parameters);
            }
        }

        return $this->sortedSteps;
    }

    /**
     * Sort routers by priority.
     * The highest priority number is the highest priority (reverse sorting)
     *
     * @return StepInterface[]
     */
    private function getSortedSteps()
    {
        $sortedSteps = array();
        krsort($this->steps);

        foreach ($this->steps as $steps) {
            $sortedSteps = array_merge($sortedSteps, $steps);
        }

        return $sortedSteps;
    }

    /**
     * @return array
     */
    public function getParameters()
    {
        return $this->parameters;
    }

    /**
     * @return integer
     */
    public function getStepCount()
    {
        return count($this->getSteps());
    }

    /**
     * @param array $parameters
     */
    public function mergeParameters($parameters)
    {
        $this->parameters = array_merge($this->parameters, $parameters);
    }

    /**
     * @return array
     */
    public function getRequirements()
    {
        $majors = array();
        foreach ($this->getSteps() as $step) {
            foreach ($step->checkRequirements() as $major) {
                $majors[] = $major;
            }
        }

        return $majors;
    }

    /**
     * @return array
     */
    public function getOptionalSettings()
    {
        $minors = array();
        foreach ($this->getSteps() as $step) {
            foreach ($step->checkOptionalSettings() as $minor) {
                $minors[] = $minor;
            }
        }

        return $minors;
    }

    /**
     * Renders parameters as a string.
     *
     * @param int $expanded
     *
     * @return string
     */
    public function render($expanded = 10)
    {
        return Yaml::dump(array('parameters' => $this->parameters), $expanded);
    }

    /**
     * Writes parameters to parameters.yml or temporary in the cache directory.
     *
     * @param int $expanded
     *
     * @return int
     */
    public function write($expanded = 10)
    {
        $filename = $this->isFileWritable() ? $this->filename : $this->getCacheFilename();

        return file_put_contents($filename, $this->render($expanded));
    }

    /**
     * Reads parameters from file.
     *
     * @return array
     */
    protected function read()
    {
        $filename = $this->filename;
        if (!$this->isFileWritable() && file_exists($this->getCacheFilename())) {
            $filename = $this->getCacheFilename();
        }

        if (!file_exists($filename)) {
            return array();
        }

        $ret = Yaml::parse(file_get_contents($filename));
        if (false === $ret || array() === $ret) {
            throw new \InvalidArgumentException(sprintf('The %s file is not valid.', $filename));
        }

        if (isset($ret['parameters']) && is_array($ret['parameters'])) {
            return $ret['parameters'];
        } else {
            return array();
        }
    }

    /**
     * getCacheFilename
     *
     * @return string
     */
    protected function getCacheFilename()
    {
        return $this->kernelDir.'/cache/parameters.yml';
    }
}


text:
import java.io.*;

public class FileManager {
    public static String read(final File file) {
        StringBuilder text = new StringBuilder();
        BufferedReader bufferedReader = null;
        String result = "";
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

            String data;
            while ((data = bufferedReader.readLine()) != null) {
                text.append(data);
            }
            result = new String(text.toString().trim().getBytes("UTF-8"), "UTF-8");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try { bufferedReader.close(); } catch (IOException ioe) { ioe.printStackTrace(); }
            }
        }

        return result;
    }

    public static void write(final File url, final String contents) {
        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(url.getAbsolutePath() + ".txt"), "UTF-8"));
            bufferedWriter.write(contents);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            if (bufferedWriter != null) {
                try { bufferedWriter.close(); } catch (IOException ioe) { ioe.printStackTrace(); }
            }
        }
    }
}


text:
package com.github.nmorel.gwtjackson.client.deser.bean;

import com.github.nmorel.gwtjackson.client.JsonDeserializationContext;
import com.github.nmorel.gwtjackson.client.JsonDeserializer;
import com.github.nmorel.gwtjackson.client.stream.JsonReader;

/**
 * Deserializes a bean's property
 *
 * @author Nicolas Morel
 */
public abstract class AnySetterDeserializer<T, V> extends HasDeserializerAndParameters<V, JsonDeserializer<V>> {

    /**
     * Deserializes the property defined for this instance.
     *
     * @param reader reader
     * @param bean bean to set the deserialized property to
     * @param propertyName name of the property
     * @param ctx context of the deserialization process
     */
    public void deserialize( JsonReader reader, T bean, String propertyName, JsonDeserializationContext ctx ) {
        setValue( bean, propertyName, deserialize( reader, ctx ), ctx );
    }

    public abstract void setValue( T bean, String propertyName, V value, JsonDeserializationContext ctx );
}


text:
var searchWin = Ti.UI.currentWindow;
searchWin.backgroundColor = 'white';
//searchWin.modal=true;

var data = [];
var row;
var searchbar = Titanium.UI.createSearchBar({
	showCancel : true,
	hintText : 'Enter Name To Search',
	top : 0
});
searchbar.addEventListener('change', function(e) {
	e.value
});
searchbar.addEventListener('focus', function(e) {
	searchbar.value = '';
});

var tableView = tableView = Ti.UI.createTableView({
	minRowHeight : 50,
	scrollable : 'true',
	search : searchbar,
	//top:0,

	//zIndex:50,
});

var activityInd = Ti.UI.createActivityIndicator({
	color : 'green',
	font : {
		fontFamily : 'Helvetica Neue',
		fontSize : 16,
		fontWeight : 'bold'
	},
	message : 'Loading...',
	//style:Ti.UI.iPhone.ActivityIndicatorStyle.DARK,
	// bottom:10,
	//	left:10,
	height : 'auto',
	width : 'auto'
});
tableView.add(activityInd);
activityInd.show();
setTimeout(function(e) {
	activityInd.hide();
}, 1500);

//INIT FUNCTION
//searchList.init = function(){
var query = "SELECT uid, name, pic_square FROM user ";
query += "where uid IN (SELECT uid2 FROM friend WHERE uid1 = " + Titanium.Facebook.uid + ")";
query += "order by first_name limit 300";
Titanium.Facebook.request('fql.query', {
	query : query
}, function(r) {
	var result = JSON.parse(r.result);
	tableView.data = [];
	data = [];
	for (var c = 0; c < result.length; c++) {
		row = result[c];
		var tvRow = Ti.UI.createTableViewRow({
			height : 'auto',
			selectedBackgroundColor : '#fff',
			backgroundColor : '#fff',
			font : {
				fontSize : 14,
				fontWeight : 'bold'
			},
			title : row.name,
			//name:row.name,
			leftImage : row.pic_square,
			//right:0
		});
		data.push(tvRow);
	}
	tableView.data = data;
});

tableView.add(searchbar);
searchWin.add(tableView);


text:
bl_info = {
    "name": "Mifth Tools",
    "author": "Paul Geraskin",
    "version": (0, 1, 0),
    "blender": (2, 78, 0),
    "location": "3D Viewport",
    "description": "Mifth Tools",
    "warning": "",
    "wiki_url": "",
    "tracker_url": "",
    "category": "Tools"}

if "bpy" in locals():
    import imp
    imp.reload(mifth_tools_cloning)
    imp.reload(mifth_vertex_paint)
    imp.reload(mifth_tools)
else:
    from . import mifth_tools_cloning
    from . import mifth_vertex_paint
    from . import mifth_tools

import bpy
from bpy.props import *

# registration
def menu_vertex_paint_func(self, context):
    self.layout.separator()
    self.layout.menu(mifth_vertex_paint.MFTVertexPaintMenu.bl_idname)

def register():
    bpy.types.VIEW3D_MT_paint_vertex.append(menu_vertex_paint_func)

    class MFTProperties(bpy.types.PropertyGroup):

        # Output Settings
        outputFolder = StringProperty(
            name="outputFolder",
            subtype="NONE",
            default="seq"
        )

        outputSubFolder = StringProperty(
            name="outputSubFolder",
            subtype="NONE",
            default="ren"
        )

        outputSequence = StringProperty(
            name="outputSequence",
            subtype="NONE",
            default="render"
        )

        outputSequenceSize = IntProperty(
            default=8,
            min=1,
            max=60
        )

        doOutputSubFolder = BoolProperty(
            name="do Output SubFolder",
            description="do Output SubFolder...",
            default=False
        )

        # Curve Animator Settings
        doUseSceneFrames = BoolProperty(
            name="do use scene frames",
            description="do use scene frames...",
            default=False
        )

        curveAniStartFrame = IntProperty(
            default=1,
            min=1,
            max=10000
        )

        curveAniEndFrame = IntProperty(
            default=100,
            min=1,
            max=10000
        )

        curveAniStepFrame = IntProperty(
            default=10,
            min=1,
            max=10000
        )

        curveAniInterpolation = FloatProperty(
            default=0.3,
            min=0.0,
            max=1.0
        )

        # MorfCreator settings
        morfCreatorNames = StringProperty(
            name="MorfNames",
            subtype="NONE",
            default=""
        )

        morfUseWorldMatrix = BoolProperty(
            name="use world matrix",
            description="use world matrix...",
            default=False
        )

        morfApplyModifiers = BoolProperty(
            name="apply modifiers to morf",
            description="apply modifiers to morf...",
            default=False
        )

    bpy.utils.register_module(__name__)

    bpy.types.Scene.mifthTools = PointerProperty(
        name="Mifth Tools Variables",
        type=MFTProperties,
        description="Mifth Tools Properties"
    )

    bpy.types.Scene.mifthCloneTools = PointerProperty(
        name="Mifth Cloning Variables",
        type=mifth_tools_cloning.MFTCloneProperties,
        description="Mifth Cloning Properties"
    )

def unregister():
    import bpy

    bpy.types.VIEW3D_MT_object_specials.remove(menu_vertex_paint_func)

    del bpy.types.Scene.mifthTools
    del bpy.types.Scene.mifthCloneTools
    # del bpy.mifthTools
    # del bpy.mifthCloneTools
    bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
    register()


text:
package audit

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/cloudawan/cloudone_analysis/utility/database/elasticsearch"
	"github.com/cloudawan/cloudone_utility/audit"
	elasticsearchlib "github.com/cloudawan/cloudone_utility/database/elasticsearch"
	"strings"
)

func init() {
	createIndexTemplate()
}

func createIndexTemplate() error {

	tempateBody := `
	{
		"template": "` + indexAuditLogIndex + `",
		"mappings": {
			"_default_": {
				"_all": {
					"enabled": true
				},
				"dynamic_templates": [
					{
						"string_fields": {
							"match": "*",
							"match_mapping_type": "string",
							"mapping": {
								"type": "string",
								"index": "not_analyzed",
								"omit_norms": true
							}
						}
					}
				],
				"properties": {
					"Component": {
						"type": "string"
					},
					"Kind": {
						"type": "string"
					},
					"Path": {
						"type": "string"
					},
					"UserName": {
						"type": "string"
					},
					"RemoteAddress": {
						"type": "string",
						"index": "not_analyzed"
					},
					"RemoteHost": {
						"type": "string"
					},
					"CreatedTime": {
						"type": "date",
						"format": "dateOptionalTime"
					},
					"QueryParameterMap" : {
						"properties" : {
						}
					},
					"PathParameterMap" : {
						"properties" : {
						}
					},
					"RequestMethod": {
						"type": "string"
					},
					"RequestURI": {
						"type": "string",
						"index": "not_analyzed"
					},
					"RequestBody" : {
						"type": "string",
						"index": "not_analyzed"
					},
					"RequestHeader" : {
						"properties" : {
						}
					},
					"Description": {
						"type": "string",
						"index": "not_analyzed"
					}
				}
			}
		}
	}
	`

	connection := elasticsearch.ElasticSearchClient.GetConnection()
	request, err := connection.NewRequest("PUT", "/_template/template_"+indexAuditLogIndex, "")
	if err != nil {
		log.Error(err)
		return err
	}
	request.SetBodyString(tempateBody)
	statusCode, bodyBytes, err := request.Do(nil)
	if err != nil {
		log.Error(err)
		log.Error("statusCode %d", statusCode)
		log.Error(string(bodyBytes))
		return err
	} else {
		//log.Info("statusCode %d", statusCode)
		//log.Info(string(bodyBytes))
	}

	return nil
}

func checkFormatForElasticSearchData(auditLog *audit.AuditLog) {
	if auditLog.PathParameterMap != nil {
		for key, value := range auditLog.PathParameterMap {
			if strings.Contains(key, ".") {
				newKey := strings.Replace(key, ".", "_", -1)
				auditLog.PathParameterMap[newKey] = value
				delete(auditLog.PathParameterMap, key)
			}
		}
	}
	if auditLog.QueryParameterMap != nil {
		for key, value := range auditLog.QueryParameterMap {
			if strings.Contains(key, ".") {
				newKey := strings.Replace(key, ".", "_", -1)
				auditLog.QueryParameterMap[newKey] = value
				delete(auditLog.QueryParameterMap, key)
			}
		}
	}
	if auditLog.RequestHeader != nil {
		for key, value := range auditLog.RequestHeader {
			if strings.Contains(key, ".") {
				newKey := strings.Replace(key, ".", "_", -1)
				auditLog.RequestHeader[newKey] = value
				delete(auditLog.RequestHeader, key)
			}
		}
	}
}

func SaveAudit(auditLog *audit.AuditLog, refreshForSearch bool) error {
	checkFormatForElasticSearchData(auditLog)
	id := fmt.Sprintf("%d_%d", auditLog.CreatedTime.Unix(), auditLog.CreatedTime.UnixNano())
	connection := elasticsearch.ElasticSearchClient.GetConnection()
	_, err := connection.Index(indexAuditLogIndex, auditLog.UserName, id, nil, auditLog)
	if err != nil {
		log.Debug(auditLog)
		log.Error(err)
		return err
	} else {
		if refreshForSearch {
			if _, err := connection.Refresh(indexAuditLogIndex); err != nil {
				log.Error(err)
				return err
			} else {
				return nil
			}
		} else {
			return nil
		}
	}
}

// Bulk Process
const (
	maxConnection = 5
)

func createBulkProcessor() *elasticsearchlib.BulkProcessor {
	return elasticsearch.ElasticSearchClient.CreateBulkProcessor(maxConnection)
}

func searchAuditLogRawJson(index string, _type string, query interface{}) ([]byte, error) {
	connection := elasticsearch.ElasticSearchClient.GetConnection()
	searchResult, err := connection.Search(index, _type, nil, query)
	if err != nil {
		return nil, err
	} else {
		return searchResult.RawJSON, nil
	}
}

func DeleteAuditLogIndex(index string) error {
	connection := elasticsearch.ElasticSearchClient.GetConnection()
	_, err := connection.DeleteIndex(index)
	if err != nil {
		return err
	} else {
		return nil
	}
}

func GetAuditLog(documentType string, id string) (*audit.AuditLog, error) {
	connection := elasticsearch.ElasticSearchClient.GetConnection()
	baseResponse, err := connection.Get(indexAuditLogIndex, documentType, id, nil)
	if err != nil {
		log.Error(err)
		return nil, err
	} else {
		audit := &audit.AuditLog{}
		decoder := json.NewDecoder(bytes.NewReader(*baseResponse.Source))
		decoder.UseNumber()
		err := decoder.Decode(&audit)
		if err != nil {
			log.Error(err)
			return nil, err
		} else {
			return audit, nil
		}
	}
}


text:
#ifndef _RU_REFRESH_SQL_COMPOSER_H_
#define _RU_REFRESH_SQL_COMPOSER_H_

/* -*-C++-*-
******************************************************************************
*
* File:         RuSQLRefreshComposer.h
* Description:  Definition of class CRURefreshSQLComposer
*
*
* Created:      08/13/2000
* Language:     C++
*
*
*
******************************************************************************
*/

//--------------------------------------------------------------------------//
//	CRURefreshSQLComposer
//
//	This class composes the syntax of the INTERNAL REFRESH command
//	for the given task. The SQL generation is based on universal
//	building blocks to allow flexibility. These basic methods are used
//	in the derived composer classes.
//
//--------------------------------------------------------------------------//

#include "RuSQLComposer.h"
#include "RuRefreshTask.h"
#include "RuDeltaDef.h"
#include "RuForceOptions.h"

class REFRESH_LIB_CLASS CRURefreshSQLComposer : public CRUSQLComposer {
private:
	typedef CRUSQLComposer inherited;

public:
	CRURefreshSQLComposer(CRURefreshTask *pTask);
	virtual ~CRURefreshSQLComposer() {}

public:
	void ComposeCntrlTableMDAMText(CRUForceOptions::MdamOptions mdamOption,
							   const CDSString* pName=NULL);
	void ComposeResetCntrlTableMDAMText(const CDSString* pName=NULL);
	void ComposeDeleteContextLogTable();
	void ComposeControlQueryShape();
	void ComposeControlQueryShapeCut();
	void ComposeShowExplain();

protected:
	void StartInternalRefresh();
	void AddDeltaDefClause(const CRUDeltaDef *pDdef,
						   CDSString &fromEpoch,
						   CDSString &toEpoch);
	void AddPhaseParam();
	void AddPipeLineClause();
	void ComposeQueryShape();

	CDSString GetContextLogName() const;

protected:
	CRUMV& GetRootMV() const
	{
		return *pRootMV_;
	}

	CRURefreshTask &GetRefreshTask() const
	{
		RUASSERT(NULL != pTask_);
		return *pTask_;
	}

private:
	//-- Prevent copying
	CRURefreshSQLComposer(const CRURefreshSQLComposer &other);
	CRURefreshSQLComposer &operator = (const CRURefreshSQLComposer &other);

private:
	void AddRngDeltaStatisticsClause(const CRUDeltaDef *pDdef);
	void AddIUDDeltaStatisticsClause(const CRUDeltaDef *pDdef);
	void AddUpdatedColumnsClause(const CRUUpdateBitmap *pUpdateBitmap);

private:
	CRURefreshTask *pTask_;
	CRUMV *pRootMV_;
};

#endif


text:
module Turnt
  def method_missing(method, *args)
    super(method, *args) unless has?(method)
    @method = method; @value = send(instance_method); validate_data_types!
  end

  def nil_validation!
    nil? if @value.nil?
  end

  def numeric_validation!
    nil? if @value.is_a?(Numeric)
  end

  def string_validation!
    empty? if @value.is_a?(String)
  end

  def symbol_validation!
    nil? if @value.is_a?(Symbol)
  end

  def collection_validation!
    empty? if @value.is_a?(Array) || @value.is_a?(Hash)
  end

  private

  def validate_data_types!
    validation_parts.first
  end

  def validation_parts
    public_methods(true).grep(/_validation!$/).map{ |m| send(m) }.compact
  end

  def nil?
    if @value.nil?
      return false
    else
      return true
    end
  end

  def empty?
    if @value.empty?
      return false
    else
      return true
    end
  end

  def instance_method
    "#{@method}".slice!(4..@method.size - 2)
  end

  def has?(method)
    "#{method}".include?("has_")
  end
end


text:
using System;
using System.Text;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;

namespace HETSAPI.Models
{
    /// <summary>
    /// Local Area Rotation List Database Model
    /// </summary>
    public sealed class LocalAreaRotationList : AuditableEntity, IEquatable<LocalAreaRotationList>
    {
        /// <summary>
        /// Local Area Rotation List Database Model Constructor (required by entity framework)
        /// </summary>
        public LocalAreaRotationList()
        {
            Id = 0;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LocalAreaRotationList" /> class.
        /// </summary>
        /// <param name="id">Id (required).</param>
        /// <param name="districtEquipmentType">A foreign key reference to the system-generated unique identifier for an Equipment Type (required).</param>
        /// <param name="localArea">LocalArea (required).</param>
        /// <param name="askNextBlock1">The id of the next piece of Block 1 Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block 1..</param>
        /// <param name="askNextBlock1Seniority">The seniority score of the piece of equipment that is the next to be asked in Block 1..</param>
        /// <param name="askNextBlock2">The id of the next piece of Block 2 Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block 2..</param>
        /// <param name="askNextBlock2Seniority">The seniority score of the piece of equipment that is the next to be asked in Block 1..</param>
        /// <param name="askNextBlockOpen">The id of the next piece of Block Open Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block Open..</param>
        public LocalAreaRotationList(int id, DistrictEquipmentType districtEquipmentType, LocalArea localArea,
            Equipment askNextBlock1 = null, float? askNextBlock1Seniority = null, Equipment askNextBlock2 = null,
            float? askNextBlock2Seniority = null, Equipment askNextBlockOpen = null)
        {
            Id = id;
            DistrictEquipmentType = districtEquipmentType;
            LocalArea = localArea;
            AskNextBlock1 = askNextBlock1;
            AskNextBlock1Seniority = askNextBlock1Seniority;
            AskNextBlock2 = askNextBlock2;
            AskNextBlock2Seniority = askNextBlock2Seniority;
            AskNextBlockOpen = askNextBlockOpen;
        }

        /// <summary>
        /// Gets or Sets Id
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// A foreign key reference to the system-generated unique identifier for an Equipment Type
        /// </summary>
        /// <value>A foreign key reference to the system-generated unique identifier for an Equipment Type</value>
        [MetaData (Description = "A foreign key reference to the system-generated unique identifier for an Equipment Type")]
        public DistrictEquipmentType DistrictEquipmentType { get; set; }

        /// <summary>
        /// Foreign key for DistrictEquipmentType
        /// </summary>
        [ForeignKey("DistrictEquipmentType")]
		[JsonIgnore]
		[MetaData (Description = "A foreign key reference to the system-generated unique identifier for an Equipment Type")]
        public int? DistrictEquipmentTypeId { get; set; }

        /// <summary>
        /// Gets or Sets LocalArea
        /// </summary>
        public LocalArea LocalArea { get; set; }

        /// <summary>
        /// Foreign key for LocalArea
        /// </summary>
        [ForeignKey("LocalArea")]
		[JsonIgnore]
        public int? LocalAreaId { get; set; }

        /// <summary>
        /// The id of the next piece of Block 1 Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block 1.
        /// </summary>
        /// <value>The id of the next piece of Block 1 Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block 1.</value>
        [MetaData (Description = "The id of the next piece of Block 1 Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block 1.")]
        public Equipment AskNextBlock1 { get; set; }

        /// <summary>
        /// Foreign key for AskNextBlock1
        /// </summary>
        [ForeignKey("AskNextBlock1")]
		[JsonIgnore]
		[MetaData (Description = "The id of the next piece of Block 1 Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block 1.")]
        public int? AskNextBlock1Id { get; set; }

        /// <summary>
        /// The seniority score of the piece of equipment that is the next to be asked in Block 1.
        /// </summary>
        /// <value>The seniority score of the piece of equipment that is the next to be asked in Block 1.</value>
        [MetaData (Description = "The seniority score of the piece of equipment that is the next to be asked in Block 1.")]
        public float? AskNextBlock1Seniority { get; set; }

        /// <summary>
        /// The id of the next piece of Block 2 Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block 2.
        /// </summary>
        /// <value>The id of the next piece of Block 2 Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block 2.</value>
        [MetaData (Description = "The id of the next piece of Block 2 Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block 2.")]
        public Equipment AskNextBlock2 { get; set; }

        /// <summary>
        /// Foreign key for AskNextBlock2
        /// </summary>
        [ForeignKey("AskNextBlock2")]
		[JsonIgnore]
		[MetaData (Description = "The id of the next piece of Block 2 Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block 2.")]
        public int? AskNextBlock2Id { get; set; }

        /// <summary>
        /// The seniority score of the piece of equipment that is the next to be asked in Block 1.
        /// </summary>
        /// <value>The seniority score of the piece of equipment that is the next to be asked in Block 1.</value>
        [MetaData (Description = "The seniority score of the piece of equipment that is the next to be asked in Block 1.")]
        public float? AskNextBlock2Seniority { get; set; }

        /// <summary>
        /// The id of the next piece of Block Open Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block Open.
        /// </summary>
        /// <value>The id of the next piece of Block Open Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block Open.</value>
        [MetaData (Description = "The id of the next piece of Block Open Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block Open.")]
        public Equipment AskNextBlockOpen { get; set; }

        /// <summary>
        /// Foreign key for AskNextBlockOpen
        /// </summary>
        [ForeignKey("AskNextBlockOpen")]
		[JsonIgnore]
		[MetaData (Description = "The id of the next piece of Block Open Equipment to be asked for a Rental Request. If null, start from the first piece of equipment in Block Open.")]
        public int? AskNextBlockOpenId { get; set; }

        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.Append("class LocalAreaRotationList {\n");
            sb.Append("  Id: ").Append(Id).Append("\n");
            sb.Append("  DistrictEquipmentType: ").Append(DistrictEquipmentType).Append("\n");
            sb.Append("  LocalArea: ").Append(LocalArea).Append("\n");
            sb.Append("  AskNextBlock1: ").Append(AskNextBlock1).Append("\n");
            sb.Append("  AskNextBlock1Seniority: ").Append(AskNextBlock1Seniority).Append("\n");
            sb.Append("  AskNextBlock2: ").Append(AskNextBlock2).Append("\n");
            sb.Append("  AskNextBlock2Seniority: ").Append(AskNextBlock2Seniority).Append("\n");
            sb.Append("  AskNextBlockOpen: ").Append(AskNextBlockOpen).Append("\n");
            sb.Append("}\n");

            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="obj">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object obj)
        {
            if (obj is null) { return false; }
            if (ReferenceEquals(this, obj)) { return true; }
            return obj.GetType() == GetType() && Equals((LocalAreaRotationList)obj);
        }

        /// <summary>
        /// Returns true if LocalAreaRotationList instances are equal
        /// </summary>
        /// <param name="other">Instance of LocalAreaRotationList to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(LocalAreaRotationList other)
        {
            if (other is null) { return false; }
            if (ReferenceEquals(this, other)) { return true; }

            return
                (
                    Id == other.Id ||
                    Id.Equals(other.Id)
                ) &&
                (
                    DistrictEquipmentType == other.DistrictEquipmentType ||
                    DistrictEquipmentType != null &&
                    DistrictEquipmentType.Equals(other.DistrictEquipmentType)
                ) &&
                (
                    LocalArea == other.LocalArea ||
                    LocalArea != null &&
                    LocalArea.Equals(other.LocalArea)
                ) &&
                (
                    AskNextBlock1 == other.AskNextBlock1 ||
                    AskNextBlock1 != null &&
                    AskNextBlock1.Equals(other.AskNextBlock1)
                ) &&
                (
                    AskNextBlock1Seniority == other.AskNextBlock1Seniority ||
                    AskNextBlock1Seniority != null &&
                    AskNextBlock1Seniority.Equals(other.AskNextBlock1Seniority)
                ) &&
                (
                    AskNextBlock2 == other.AskNextBlock2 ||
                    AskNextBlock2 != null &&
                    AskNextBlock2.Equals(other.AskNextBlock2)
                ) &&
                (
                    AskNextBlock2Seniority == other.AskNextBlock2Seniority ||
                    AskNextBlock2Seniority != null &&
                    AskNextBlock2Seniority.Equals(other.AskNextBlock2Seniority)
                ) &&
                (
                    AskNextBlockOpen == other.AskNextBlockOpen ||
                    AskNextBlockOpen != null &&
                    AskNextBlockOpen.Equals(other.AskNextBlockOpen)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            // credit: http://stackoverflow.com/a/263416/677735
            unchecked // Overflow is fine, just wrap
            {
                int hash = 41;

                // Suitable nullity checks
                hash = hash * 59 + Id.GetHashCode();

                if (DistrictEquipmentType != null)
                {
                    hash = hash * 59 + DistrictEquipmentType.GetHashCode();
                }

                if (LocalArea != null)
                {
                    hash = hash * 59 + LocalArea.GetHashCode();
                }

                if (AskNextBlock1 != null)
                {
                    hash = hash * 59 + AskNextBlock1.GetHashCode();
                }

                if (AskNextBlock1Seniority != null)
                {
                    hash = hash * 59 + AskNextBlock1Seniority.GetHashCode();
                }

                if (AskNextBlock2 != null)
                {
                    hash = hash * 59 + AskNextBlock2.GetHashCode();
                }

                if (AskNextBlock2Seniority != null)
                {
                    hash = hash * 59 + AskNextBlock2Seniority.GetHashCode();
                }

                if (AskNextBlockOpen != null)
                {
                    hash = hash * 59 + AskNextBlockOpen.GetHashCode();
                }

                return hash;
            }
        }

        #region Operators

        /// <summary>
        /// Equals
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public static bool operator ==(LocalAreaRotationList left, LocalAreaRotationList right)
        {
            return Equals(left, right);
        }

        /// <summary>
        /// Not Equals
        /// </summary>
        /// <param name="left"></param>
        /// <param name="right"></param>
        /// <returns></returns>
        public static bool operator !=(LocalAreaRotationList left, LocalAreaRotationList right)
        {
            return !Equals(left, right);
        }

        #endregion Operators
    }
}


text:
__all__ = ["main", "Box", "AnswerSheet"]

from sample.web import helperFunction


text:
<?xml version="1.0" encoding="UTF-8"?>
<tns:config xmlns:tns="http://tel.dur.ac.uk/xml/schemas/tableconfiguration"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://tel.dur.ac.uk/xml/schemas/tableconfiguration ./schemas/tableconfiguration.xsd ">

	<tns:options>
		<tns:splashScreenResource>media/images/splashscreens/synergynet.png</tns:splashScreenResource>
		<tns:splashScreenEnabled>false</tns:splashScreenEnabled>
		<tns:mode>client</tns:mode>
	</tns:options>

	<tns:applications>
		<tns:application configpath="synergynet/table/apps/controlclient/synergynetapplication.xml" default="true"/>
		<tns:application configpath="synergynet/table/apps/dominos/synergynetapplication.xml" />
		<tns:application configpath="synergynet/table/apps/splasher/synergynetapplication.xml" />
		<tns:application configpath="synergynet/table/apps/docviewer/synergynetapplication.xml" />
		<tns:application configpath="synergynet/table/apps/jmpuzzles/xml/synergynetapplication.xml" />
		<tns:application configpath="synergynet/table/apps/mainmenu/synergynetapplication.xml" />
		<tns:application configpath="synergynet/table/apps/meteorstrike/synergynetapplication.xml" enabled="false" />
		<tns:application configpath="synergynet/table/apps/mysteries/synergynetapplication.xml" />
		<tns:application configpath="synergynet/table/apps/realgravity/synergynetapplication.xml" />
		<tns:application configpath="synergynet/table/apps/teapots/synergynetapplication.xml" enabled="false" />
		<tns:application configpath="synergynet/table/apps/watertank/synergynetapplication.xml" />
	</tns:applications>

	<tns:services>
		<tns:service
			classname="synergynet.services.net.tablecomms.client.TableCommsClientService"
			enabled="true">
			<tns:depends>
				<tns:service
					classname="synergynet.services.net.netservicediscovery.NetworkServiceDiscoveryService" />
			</tns:depends>
		</tns:service>

		<tns:service
			classname="synergynet.services.tablecontrolclient.TableControlClientService"
			enabled="true">
		</tns:service>

	</tns:services>
</tns:config>


text:
<?php

namespace SchulzeFelix\SearchConsole;

use Google_Client;
use Google_Service_Webmasters;
use GuzzleHttp\Client;
use Symfony\Component\Cache\Adapter\Psr16Adapter;

class SearchConsoleClientFactory
{
    /**
     * @param  array  $searchConsoleConfig
     * @return SearchConsoleClient
     */
    public static function createForConfig(array $searchConsoleConfig): SearchConsoleClient
    {
        $authenticatedClient = self::createAuthenticatedGoogleClient($searchConsoleConfig);

        return new SearchConsoleClient($authenticatedClient);
    }

    /**
     * @param  array  $config
     * @return Google_Client
     */
    public static function createAuthenticatedGoogleClient(array $config): Google_Client
    {
        $client = new Google_Client();

        self::configureAuthentication($client, $config);

        $client->addScope(Google_Service_Webmasters::WEBMASTERS);
        $client->setAccessType('offline');

        self::configureGzip($client, $config['application_name']);
        self::configureCache($client, $config['cache']);

        return $client;
    }

    /**
     * @param  Google_Client  $client
     * @param $config
     */
    protected static function configureCache(Google_Client $client, $config)
    {
        $config = collect($config);

        $store = \Cache::store($config->get('store'));

        $cache = new Psr16Adapter($store);

        $client->setCache($cache);

        $client->setCacheConfig(
            $config->except('store')->toArray()
        );
    }

    /**
     * @param  Google_Client  $client
     * @param $application_name
     */
    private static function configureGzip(Google_Client $client, $application_name)
    {
        $client->setApplicationName($application_name.' (gzip)');

        $options = [];
        $options['base_uri'] = Google_Client::API_BASE_PATH;
        $options['headers'] = [
            'User-Agent' => $application_name.' (gzip)',
            'Accept-Encoding' => 'gzip',
        ];

        $guzzleClient = new Client($options);

        $client->setHttpClient($guzzleClient);
    }

    /**
     * @param  Google_Client  $client
     * @param $config
     */
    private static function configureAuthentication(Google_Client $client, $config)
    {
        switch ($config['auth_type']) {
            case 'oauth':
                $client->setClientId($config['connections']['oauth']['client_id']);
                $client->setClientSecret($config['connections']['oauth']['client_secret']);
                break;
            case 'oauth_json':
                $client->setAuthConfig($config['connections']['oauth_json']['auth_config']);
                break;
            case 'service_account':
                $client->useApplicationDefaultCredentials($config['connections']['service_account']['application_credentials']);
                break;
        }
    }
}