text:
layout: page
title: Land Force International Show
date: 2016-05-24
author: Diane Weiss
tags: weekly links, java
status: published
summary: Proin elementum fringilla nunc, vitae porta ligula dictum.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 07/18/2019
  endDate: 07/22/2019
  ctyhocn: ATLMOHX
  groupCode: LFIS
published: true
---
Duis nec ultrices neque. Nam et finibus orci. Aenean id arcu nisi. Mauris vestibulum, tortor in tristique dictum, nulla nulla lacinia tortor, at pulvinar purus erat quis dolor. Curabitur bibendum hendrerit est non consectetur. Fusce vitae iaculis nisi, non efficitur sem. Donec eget egestas odio, a tincidunt arcu.

1 Praesent vel justo suscipit, rhoncus felis ac, pellentesque augue
1 Vivamus aliquam nibh tincidunt mauris facilisis interdum
1 Nunc fermentum quam vel nulla suscipit, et aliquet nulla elementum
1 Phasellus dictum tellus nec arcu fermentum convallis.

Sed vitae nisi consectetur, elementum nibh et, interdum nisl. Nullam et bibendum est. Proin semper ac justo id egestas. Nullam id venenatis leo. Mauris rutrum vulputate mi, nec pretium felis tristique non. Cras id felis vel risus molestie rhoncus in eu risus. Proin sit amet metus vitae erat convallis cursus vitae a arcu. Maecenas auctor, lectus vel dictum porta, metus tortor efficitur enim, non aliquet massa sem nec urna. Donec dapibus augue velit, a pulvinar sapien eleifend vel. Aliquam quis leo posuere, varius metus quis, tincidunt enim. Fusce et metus maximus, convallis mi commodo, fermentum ligula. In cursus odio non nisl auctor, ac luctus elit lobortis. Suspendisse laoreet erat in augue luctus cursus. Praesent hendrerit risus consequat, tempus erat non, molestie leo. Aliquam molestie, felis eget lacinia condimentum, leo ex dictum turpis, quis tristique erat libero eget leo.


text:
package codingbo.fishdaily.data.entity;

import android.support.annotation.NonNull;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;

import java.util.Comparator;

/**
 * 标签实体类
 */
@Entity
public class Tag implements Comparable<Tag> {
    @Id(autoincrement = true)
    private Long id;
    private String name;
    private String description;
    private float progress;//完成进度100为完成

    @Generated(hash = 702375943)
    public Tag(Long id, String name, String description, float progress) {
        this.id = id;
        this.name = name;
        this.description = description;
        this.progress = progress;
    }

    @Generated(hash = 1605720318)
    public Tag() {
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public float getProgress() {
        return this.progress;
    }

    public void setProgress(float progress) {
        this.progress = progress;
    }

    @Override
    public int compareTo(@NonNull Tag o) {
        int result = -1;
        Tag tag = (Tag) o;
        result = tag.getName().equals(this.name) && tag.getDescription().equals(this.description) ? 0 : 1;
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameServer.Model
{
    public enum GameSessionStatus
    {
        ACTIVE,
        ENDED
    }
}


text:
id: processing
title: The JSONata processing model
sidebar_label: Processing Model
---

## The JSONata type system

JSONata is a superset of JSON and the JSONata type system is a superset of the JSON data types.  In common with all functional programming languages, the function is also a first-class data type.  The following data types are supported by JSONata:

- string
- number
- Boolean
- null
- object
- array
- function

All but the last one are in common with JSON.

## Sequences

JSONata has been designed foremost as a query language, whereby a path expression can select zero, one or more than one values from the JSON document.  These values, each of which can be of any of the types listed above, are returned as a _result sequence_.  During the evaluation of expressions, which involves the results of subexpressions being combined or becoming the context inputs to other subexpressions, the sequences are subject to the process of _sequence flattening_.

The sequence flattening rules are as follows:

1. An __empty sequence__ is a sequence with no values and is considered to be 'nothing' or 'no match'.  It won't appear in the output of any expression. If it is associated with an object property (key/value) pair in a result object, then that object will not have that property.

2. A __singleton sequence__ is a sequence containing a single value.  It is considered equivalent to that value itself, and the output from any expression, or sub-expression will be that value without any surrounding structure.

3. A sequence containing more than one value is represented in the output as a JSON array.  This is still internally flagged as a sequence and subject to the next rule.  Note that if an expression matches an array from the input JSON, or a JSON array is explicitly constructed in the query using the [array constructor](construction#array-constructors), then this remains an array of values rather than a sequence of values and will not be subject to the sequence flattening rules.  However, if this array becomes the context of a subsequent expression, then the result of that _will_ be a sequence.

4. If a sequence contains one or more (sub-)sequences, then the values from the sub-sequence are pulled up to the level of the outer sequence.  A result sequence will never contain child sequences (they are flattened).

## JSONata path processing

The JSONata path expression is a _declarative functional_ language.

__Functional__ because it is based on the map/filter/reduce programming paradigm as supported by popular functional programming languages through the use of higher-order functions.

__Declarative__ because these higher-order functions are exposed through a lightweight syntax which lets the user focus on the intention of the query (declaration) rather than the programming constructs that control their evaluation.

A path expression is a sequence of one or more of the following functional stages:

Stage | Syntax | Action
---|---|---
 __Map__ | seq`.`expr | Evaluates the RHS expression in the context of each item in the input sequence.  Flattens results into result sequence.
 __Filter__ | seq`[`expr`]` | Filter results from previous stage by applying predicate expression between brackets to each item.
 __Sort__ | seq`^(`expr`)` | Sorts (re-orders) the input sequence according to the criteria in parentheses.
 __Index__ | seq`#`$var | Binds a named variable to the current context position (zero offset) in the sequence.
 __Join__ | seq`@`$var | Binds a named variable to the current current context item in the sequence.  Can only be used directly following a map stage.
__Reduce__ | seq`{` expr`:`expr`,` expr`:`expr ...`}` | Group and aggregate the input sequence to a single result object as defined by the name/value expressions.  Can only appear as the final stage in a path expression.

In the above table:

- In the 'Syntax' column, 'seq' refers to the input sequence for the current stage, which is the result sequence from the previous stage.
- The 'Action' column gives a brief outline of the stage's behavior; fuller details are in the [Path Operators](path-operators) reference page.
- The relative precedence of each operator affects the scope of its influence on the input sequence. Specifically,
  - The Filter operator binds tighter than the Map operator.  This means, for example, that `books.authors[0]` will select the all of the first authors from _each_ book rather than the first author from all of the books.
  - The Sort (order-by) operator has the lowest precedence, meaning that the full path to the left of it will be evaluated, and its result sequence will be sorted.
  - This operator precedence can be overridden by using parentheses.  For example, `(books.authors)[0]` will select the the first author from all of the books (single value).  Note, however, that parentheses also define a scope frame for variables, so any variables that have been bound within the parentheses block including those bound by the `@` and `#` operators will go out of scope at the end of the parens block.
- The variables bound by the `@` and `#` operators go out of scope at the end of the path expression.
  - The Reduce stage, if used, will terminate the current path expression.  Although a Map operator can immediately follow this, it will be interpreted as the start of a new path expression, meaning that any previously bound context or index variables will be out of scope.


text:
#pragma once

class ReadTaskTest : public CppUnit::TestFixture
{
    CPPUNIT_TEST_SUITE( ReadTaskTest );
    CPPUNIT_TEST( testRequest );
    CPPUNIT_TEST_SUITE_END();

public:
    void setUp();
    void tearDown();

    void testRequest();
};


text:
package org.jboss.pnc.common.monitor;

import org.jboss.pnc.common.concurrent.MDCExecutors;
import org.jboss.pnc.common.util.ReadEnvProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 *
 * @author Matej Lazar
 * @author Jakub Bartecek <jbartece@redhat.com>
 */
@ApplicationScoped
public class PollingMonitor {
    private static final Logger log = LoggerFactory.getLogger(PollingMonitor.class);

    /** Time how long to wait until all services are fully up and running (in seconds) */
    private static final int DEFAULT_TIMEOUT = 300;
    private static final String PULLING_MONITOR_TIMEOUT_KEY = "pulling_monitor_timeout";

    /** Interval between two checks if the services are fully up and running (in second) */
    private static final int DEFAULT_CHECK_INTERVAL = 1;
    private static final String PULLING_MONITOR_CHECK_INTERVAL_KEY = "pulling_monitor_check_interval";

    /** */
    private static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.SECONDS;

    private static final String PULLING_MONITOR_THREADPOOL_KEY = "pulling_monitor_threadpool";
    private static final int DEFAULT_EXECUTOR_THREADPOOL_SIZE = 4;

    private ScheduledExecutorService executorService;
    private ScheduledExecutorServiceWithTimeout scheduledExecutor;

    private int timeout;
    private int checkInterval;

    public PollingMonitor() {
        ReadEnvProperty reader = new ReadEnvProperty();

        timeout = reader.getIntValueFromPropertyOrDefault(PULLING_MONITOR_TIMEOUT_KEY, DEFAULT_TIMEOUT);
        checkInterval = reader
                .getIntValueFromPropertyOrDefault(PULLING_MONITOR_CHECK_INTERVAL_KEY, DEFAULT_CHECK_INTERVAL);

        int threadSize = reader
                .getIntValueFromPropertyOrDefault(PULLING_MONITOR_THREADPOOL_KEY, DEFAULT_EXECUTOR_THREADPOOL_SIZE);

        executorService = MDCExecutors.newScheduledThreadPool(threadSize);
        scheduledExecutor = new ScheduledExecutorServiceWithTimeout(executorService);
    }

    /**
     * Periodically checks the condition and calls onMonitorComplete when it returns true. If timeout is reached
     * onMonitorError is called.
     *
     * @param condition
     * @return CancellableCompletableFuture
     */
    public CancellableCompletableFuture<Void> monitor(Supplier<Boolean> condition) {
        return monitor(condition, checkInterval, timeout, DEFAULT_TIME_UNIT);
    }

    public CancellableCompletableFuture<Void> monitor(
            Supplier<Boolean> condition,
            int checkInterval,
            int timeout,
            TimeUnit timeUnit) {
        return scheduledExecutor.scheduleWithFixedDelayAndTimeout(condition, 0L, checkInterval, timeout, timeUnit);
    }

    public ScheduledFuture<?> timer(Runnable task, long delay, TimeUnit timeUnit) {
        return executorService.schedule(task, delay, timeUnit);
    }

    @PreDestroy
    public void destroy() {
        executorService.shutdownNow();
    }

}


text:
class Viewer::OrganizationsController < ApplicationController
  before_action :authenticate_user!
  before_action :find_viewable_organization_or_redirect

  layout "layouts/full_page_sidebar"

  # # GET /orgs/1/reports/data-requests
  # def data_requests
  # end

  # # GET /orgs/1/reports/data-requests/submitted
  # def data_requests_submitted
  # end

  # # GET /orgs/1/reports/data-requests/approved
  # def data_requests_approved
  # end

  # # GET /orgs/1/reports/data-requests/total
  # def data_requests_total
  # end

  # # GET /orgs/1/reports/data-downloads
  # def data_downloads
  # end

  # GET /orgs/:id/reports/data-requests/year-to-date
  def data_requests_year_to_date
    data_requests = @organization.data_requests
    @dataset = @organization.datasets.find_by_param(params[:dataset])
    data_requests = data_requests.joins(:requests).merge(Request.where(dataset: @dataset)) if @dataset
    @year = (params[:year].to_i.positive? ? params[:year].to_i : Time.zone.today.year)
    @chart_title = "#{"#{@dataset.slug.upcase} " if @dataset} Data Requests for #{@year}"
    @chart_subtitle = @organization.name
    @series = []
    max = 100
    (series, max) = add_average_submitted(data_requests, max)
    @series << series
    (series, max) = add_submitted_data_requests(data_requests, max)
    @series << series
    (series, max) = add_approved_data_requests(data_requests, max)
    @series << series

    @x_axis = { categories: Date::ABBR_MONTHNAMES.last(12), title: { text: "" } }
    @y_axis = { title: { text: "Data Requests" }, max: max }
  end

  # GET /orgs/:id/reports/data-requests/since-inception
  def data_requests_since_inception
    data_requests = @organization.data_requests
    @dataset = @organization.datasets.find_by_param(params[:dataset])
    data_requests = data_requests.joins(:requests).merge(Request.where(dataset: @dataset)) if @dataset
    @chart_title = "#{"#{@dataset.slug.upcase} " if @dataset} Data Requests Since Inception"
    @chart_subtitle = @organization.name
    @series = []

    (submitted, approved, categories) = add_total_submitted_data_requests(data_requests)
    @series << submitted
    @series << approved

    @x_axis = { categories: categories, title: { text: "" } }
    @y_axis = { title: { text: "Data Requests" } }
  end

  private

  def find_viewable_organization_or_redirect
    @organization = current_user.viewable_organizations.find_by_param(params[:id])
    empty_response_or_root_path(organizations_path) unless @organization
  end

  def month_start_date(year, month)
    Date.parse("#{year}-#{month}-01")
  end

  def month_end_date(year, month)
    month_start_date(year, month).end_of_month
  end

  def add_submitted_data_requests(data_requests, max)
    data = []
    (1..12).each do |month|
      data << data_requests.where("DATE(submitted_at) >= ? and DATE(submitted_at) <= ?", month_start_date(@year, month), month_end_date(@year, month)).count
    end
    max = ([max] + data).max
    [{ type: "line", showInLegend: true, name: "Submitted Data Requests", data: data, color: "#2196f3", legendIndex: 0 }, max]
  end

  def add_approved_data_requests(data_requests, max)
    data = []
    (1..12).each do |month|
      data << data_requests.where("DATE(approval_date) >= ? and DATE(approval_date) <= ?", month_start_date(@year, month), month_end_date(@year, month)).count
    end
    max = ([max] + data).max
    [{ type: "line", showInLegend: true, name: "Approved Data Requests", data: data, color: "#4caf50", legendIndex: 2 }, max]
  end

  def add_average_submitted(data_requests, max)
    first_submitted_data_request = data_requests.order(submitted_at: :asc).first
    first_year = first_submitted_data_request&.submitted_at&.year || Time.zone.today.year
    total_years = Time.zone.today.year - first_year + 1
    data = []
    (1..12).each do |month|
      data << data_requests.where("date_part('month', submitted_at) = ?", month).count / total_years
    end
    max = ([max] + data).max
    [{ type: "area", showInLegend: true, name: "Avg. Submitted Data Requests", data: data, color: "#e3f2fd", visible: true, dashStyle: "shortdot", legendIndex: 1 }, max]
  end

  def add_total_submitted_data_requests(data_requests)
    data_submitted = []
    data_approved = []
    categories = []

    first_submitted = data_requests.where.not(submitted_at: nil).order(submitted_at: :asc).first&.submitted_at&.beginning_of_month&.last_month
    last_submitted = data_requests.where.not(submitted_at: nil).order(submitted_at: :asc).last&.submitted_at&.beginning_of_month

    current_month = first_submitted

    if current_month
      loop do
        categories << current_month.strftime("%b '%y")
        data_submitted << data_requests.where("DATE(submitted_at) >= ? and DATE(submitted_at) <= ?", current_month.beginning_of_month, current_month.end_of_month).count
        data_approved << data_requests.where("DATE(approval_date) >= ? and DATE(approval_date) <= ?", current_month.beginning_of_month, current_month.end_of_month).count
        current_month = current_month.next_month
        break if current_month.beginning_of_month > last_submitted.beginning_of_month
      end
    end
    submitted = { type: "line", showInLegend: true, name: "Submitted Data Requests", data: data_submitted, color: "#2196f3", legendIndex: 0 }
    approved = { type: "line", showInLegend: true, name: "Approved Data Requests", data: data_approved, color: "#4caf50", legendIndex: 2 }
    [submitted, approved, categories]
  end
end


text:
module Textris
  module Delivery
    class Twilio < Textris::Delivery::Base
      def deliver(to)
        client.messages.create(
          :from => message.from_phone,
          :to   => to,
          :body => message.content)
      end

      private

      def client
        @client ||= ::Twilio::REST::Client.new
      end
    end
  end
end


text:
export * from './src/api';
export {IvyCompilation} from './src/compilation';
export {ivyTransformFactory} from './src/transform';
export {ImportManager, translateStatement} from './src/translator';


text:
require 'spec_helper'

class Configuration
  include Gmaps4railsHelper
end

describe Gmaps4rails::Config::YamlLoader do
  subject { Gmaps4rails::Config::YamlLoader.new }

  it 'should load a Hash from config file' do
    subject.load.should be_a Hash
  end

  it 'should have a config_file' do
    subject.config_file.should == 'gmaps4rails.yml'
  end

  it 'should have a config_path' do
    subject.config_path.to_s.should include('spec/dummy/config/gmaps4rails.yml')
  end

  describe '#config_file = ' do
    let(:config_file) { 'gmaps.yml' }

    before :each do
      subject.config_file = config_file
    end

    it 'should set it' do
      subject.config_file.should == config_file
    end

    it 'should load an empty Hash if no matching config file' do
      subject.load.should == {}
    end
  end
end

describe Gmaps4rails::Config do
  subject { Gmaps4rails.config }

  it 'should have a yaml loader' do
    subject.send(:yaml_loader).should be_a Gmaps4rails::Config::YamlLoader
  end

  it 'should load options from yaml file' do
    subject.options.should be_a Hash
    subject.options.should_not be_empty
  end

  it 'should load provider map_options from yaml file' do
    subject.options[:map_options][:provider].should == 'mapquest'
  end
end


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
---

# InAppBrowser

> Die `InAppBrowser` ist eine Web-Browser-Ansicht, die anzeigt, wann der Aufruf `window.open()` , oder als als bildeten einen Link öffnen`<a target="_blank">`.

    var ref = window.open('http://apache.org', '_blank', 'location=yes');

**Hinweis:** Das InAppBrowser-Fenster verhält sich wie einen standard-Webbrowser und Cordova APIs kann nicht zugegriffen werden kann.

## Beschreibung

Aus einem Aufruf zurückgegebenen Objekts`window.open`.

## Methoden

*   addEventListener
*   removeEventListener
*   Schließen
*   Karte
*   executeScript
*   insertCSS

## Zugriff auf die Funktion

Ab Version 3.0 implementiert Cordova Geräteebene APIs als *Plugins*. Verwenden Sie der CLI `plugin` Befehl, beschrieben in der Command-Line Interface, hinzufügen oder Entfernen dieses Feature für ein Projekt:

        $ cordova plugin add org.apache.cordova.inappbrowser
        $ cordova plugin ls
        [ 'org.apache.cordova.inappbrowser' ]
        $ cordova plugin rm org.apache.cordova.inappbrowser

Diese Befehle gelten für alle Zielplattformen, aber die unten beschriebenen Plattform-spezifische Konfigurationseinstellungen ändern:

*   Android (in`app/res/xml/config.xml`)

        <feature name="InAppBrowser">
            <param name="android-package" value="org.apache.cordova.InAppBrowser" />
        </feature>

*   iOS (in`config.xml`)

        <feature name="InAppBrowser">
            <param name="ios-package" value="CDVInAppBrowser" />
        </feature>

*   Windows Phone 7 und 8 (in`config.xml`)

        <feature name="InAppBrowser" />

Einige Plattformen können dieses Feature unterstützen, ohne dass eine besondere Konfiguration. Finden Sie unter *Plattform-Unterstützung* in der Übersicht.

# addEventListener

> Fügt einen Listener für eine Veranstaltung aus der`InAppBrowser`.

    ref.addEventListener(eventname, callback);

*   **Ref**: Bezugnahme auf die `InAppBrowser` Fenster *(InAppBrowser)*

*   **EventName**: das Ereignis zu warten *(String)*

    *   **Loadstart**: Ereignis wird ausgelöst, wenn die `InAppBrowser` beginnt, eine URL zu laden.
    *   **Loadstop**: Ereignis wird ausgelöst, wenn der `InAppBrowser` beendet ist, eine URL laden.
    *   **LoadError**: Ereignis wird ausgelöst, wenn der `InAppBrowser` ein Fehler auftritt, wenn Sie eine URL zu laden.
    *   **Ausfahrt**: Ereignis wird ausgelöst, wenn das `InAppBrowser` -Fenster wird geschlossen.

*   **Rückruf**: die Funktion, die ausgeführt wird, wenn das Ereignis ausgelöst wird. Die Funktion übergeben wird ein `InAppBrowserEvent` -Objekt als Parameter.

## Unterstützte Plattformen

*   Android
*   BlackBerry
*   iOS
*   Windows Phone 7 und 8

## Kleines Beispiel

    var ref = window.open('http://apache.org', '_blank', 'location=yes');
    ref.addEventListener('loadstart', function() { alert(event.url); });

## Vollständiges Beispiel

    <!DOCTYPE html>
    <html>
      <head>
        <title>InAppBrowser.addEventListener Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for device API libraries to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // device APIs are available
        //
        function onDeviceReady() {
             var ref = window.open('http://apache.org', '_blank', 'location=yes');
             ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
             ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
             ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
             ref.addEventListener('exit', function(event) { alert(event.type); });
        }

        </script>
      </head>
      <body>
      </body>
    </html>

# removeEventListener

> Entfernt einen Listener für eine Veranstaltung aus der`InAppBrowser`.

    ref.removeEventListener(eventname, callback);

*   **Ref**: Bezugnahme auf die `InAppBrowser` Fenster. *(InAppBrowser)*

*   **EventName**: das Ereignis zu warten. *(String)*

    *   **Loadstart**: Ereignis wird ausgelöst, wenn die `InAppBrowser` beginnt, eine URL zu laden.
    *   **Loadstop**: Ereignis wird ausgelöst, wenn der `InAppBrowser` beendet ist, eine URL laden.
    *   **LoadError**: Ereignis wird ausgelöst, wenn die `InAppBrowser` trifft einen Fehler beim Laden einer URLs.
    *   **Ausfahrt**: Ereignis wird ausgelöst, wenn das `InAppBrowser` -Fenster wird geschlossen.

*   **Rückruf**: die Funktion ausgeführt, wenn das Ereignis ausgelöst wird. Die Funktion übergeben wird ein `InAppBrowserEvent` Objekt.

## Unterstützte Plattformen

*   Android
*   BlackBerry
*   iOS
*   Windows Phone 7 und 8

## Kleines Beispiel

    var ref = window.open('http://apache.org', '_blank', 'location=yes');
    var myCallback = function() { alert(event.url); }
    ref.addEventListener('loadstart', myCallback);
    ref.removeEventListener('loadstart', myCallback);

## Vollständiges Beispiel

    <!DOCTYPE html>
    <html>
      <head>
        <title>InAppBrowser.removeEventListener Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for device API libraries to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // Global InAppBrowser reference
        var iabRef = null;

        function iabLoadStart(event) {
            alert(event.type + ' - ' + event.url);
        }

        function iabLoadStop(event) {
            alert(event.type + ' - ' + event.url);
        }

        function iabLoadError(event) {
            alert(event.type + ' - ' + event.message);
        }

        function iabClose(event) {
             alert(event.type);
             iabRef.removeEventListener('loadstart', iabLoadStart);
             iabRef.removeEventListener('loadstop', iabLoadStop);
             iabRef.removeEventListener('loaderror', iabLoadError);
             iabRef.removeEventListener('exit', iabClose);
        }

        // device APIs are available
        //
        function onDeviceReady() {
             iabRef = window.open('http://apache.org', '_blank', 'location=yes');
             iabRef.addEventListener('loadstart', iabLoadStart);
             iabRef.addEventListener('loadstop', iabLoadStop);
             iabRef.removeEventListener('loaderror', iabLoadError);
             iabRef.addEventListener('exit', iabClose);
        }

        </script>
      </head>
      <body>
      </body>
    </html>

# Schließen

> Schließt die `InAppBrowser` Fenster.

    ref.close();

*   **Ref**: Bezugnahme auf die `InAppBrowser` Fenster *(InAppBrowser)*

## Unterstützte Plattformen

*   Android
*   BlackBerry
*   iOS
*   Windows Phone 7 und 8

## Kleines Beispiel

    var ref = window.open('http://apache.org', '_blank', 'location=yes');
    ref.close();

## Vollständiges Beispiel

    <!DOCTYPE html>
    <html>
      <head>
        <title>InAppBrowser.close Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for device API libraries to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // device APIs are available
        //
        function onDeviceReady() {
             var ref = window.open('http://apache.org', '_blank', 'location=yes');
             // close InAppBrowser after 5 seconds
             setTimeout(function() {
                 ref.close();
             }, 5000);
        }

        </script>
      </head>
      <body>
      </body>
    </html>

# Karte

> Zeigt ein InAppBrowser-Fenster, das geöffnet wurde, versteckt. Aufrufen, dies hat keine Auswirkungen, wenn die InAppBrowser schon sichtbar war.

    ref.show();

*   **Ref:** Verweis auf die (InAppBrowser) Fenster`InAppBrowser`)

## Unterstützte Plattformen

*   Android
*   BlackBerry
*   iOS

## Kleines Beispiel

    var ref = window.open('http://apache.org', '_blank', 'hidden=yes');
    ref.show();

## Vollständiges Beispiel

    <!DOCTYPE html>
    <html>
      <head>
        <title>InAppBrowser.show Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for Cordova to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // Cordova is ready
        //
        function onDeviceReady() {
             var ref = window.open('http://apache.org', '_blank', 'hidden=yes');
             ref.addEventListener('loadstop', function(event) {
                 alert('background window loaded');
             });
             // close InAppBrowser after 5 seconds
             setTimeout(function() {
                 ref.close();
             }, 5000);
        }

        </script>
      </head>
      <body>
      </body>
    </html>

# executeScript

> Fügt JavaScript-Code in das `InAppBrowser` Fenster

    ref.executeScript(details, callback);

*   **Ref**: Bezugnahme auf die `InAppBrowser` Fenster. *(InAppBrowser)*

*   **InjectDetails**: Informationen über das Skript ausgeführt, angeben, entweder ein `file` oder `code` Schlüssel. *(Objekt)*

    *   **Datei**: URL des Skripts zu injizieren.
    *   **Code**: Text des Skripts zu injizieren.

*   **Rückruf**: die Funktion, die ausgeführt wird, nachdem der JavaScript-Code injiziert wird.

    *   Wenn das eingefügte Skript vom Typ ist `code` , der Rückruf führt mit einen einzelnen Parameter, der der Rückgabewert des Skripts ist, umwickelt ein `Array` . Bei Multi-Line-Skripten ist der Rückgabewert von der letzten Anweisung oder den letzten Ausdruck ausgewertet.

## Unterstützte Plattformen

*   Android
*   BlackBerry
*   iOS

## Kleines Beispiel

    var ref = window.open('http://apache.org', '_blank', 'location=yes');
    ref.addEventListener('loadstop', function() {
        ref.executeSript({file: "myscript.js"});
    });

## Vollständiges Beispiel

    <!DOCTYPE html>
    <html>
      <head>
        <title>InAppBrowser.executeScript Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for device API libraries to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // Global InAppBrowser reference
        var iabRef = null;

        // Inject our custom JavaScript into the InAppBrowser window
        //
        function replaceHeaderImage() {
            iabRef.executeScript({
                code: "var img=document.querySelector('#header img'); img.src='http://cordova.apache.org/images/cordova_bot.png';"
            }, function() {
                alert("Image Element Successfully Hijacked");
            }
        }

        function iabClose(event) {
             iabRef.removeEventListener('loadstop', replaceHeaderImage);
             iabRef.removeEventListener('exit', iabClose);
        }

        // device APIs are available
        //
        function onDeviceReady() {
             iabRef = window.open('http://apache.org', '_blank', 'location=yes');
             iabRef.addEventListener('loadstop', replaceHeaderImage);
             iabRef.addEventListener('exit', iabClose);
        }

        </script>
      </head>
      <body>
      </body>
    </html>

# insertCSS

> Injiziert CSS in der `InAppBrowser` Fenster.

    ref.insertCSS(details, callback);

*   **Ref**: Bezugnahme auf die `InAppBrowser` Fenster *(InAppBrowser)*

*   **InjectDetails**: Informationen über das Skript ausgeführt, angeben, entweder ein `file` oder `code` Schlüssel. *(Objekt)*

    *   **Datei**: URL des Stylesheets zu injizieren.
    *   **Code**: Text des Stylesheets zu injizieren.

*   **Rückruf**: die Funktion, die ausgeführt wird, nachdem die CSS injiziert wird.

## Unterstützte Plattformen

*   Android
*   BlackBerry
*   iOS

## Kleines Beispiel

    var ref = window.open('http://apache.org', '_blank', 'location=yes');
    ref.addEventListener('loadstop', function() {
        ref.insertCSS({file: "mystyles.css"});
    });

## Vollständiges Beispiel

    <!DOCTYPE html>
    <html>
      <head>
        <title>InAppBrowser.insertCSS Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">

        // Wait for device API libraries to load
        //
        document.addEventListener("deviceready", onDeviceReady, false);

        // Global InAppBrowser reference
        var iabRef = null;

        // Inject our custom CSS into the InAppBrowser window
        //
        function changeBackgroundColor() {
            iabRef.insertCSS({
                code: "body { background: #ffff00"
            }, function() {
                alert("Styles Altered");
            }
        }

        function iabClose(event) {
             iabRef.removeEventListener('loadstop', changeBackgroundColor);
             iabRef.removeEventListener('exit', iabClose);
        }

        // device APIs are available
        //
        function onDeviceReady() {
             iabRef = window.open('http://apache.org', '_blank', 'location=yes');
             iabRef.addEventListener('loadstop', changeBackgroundColor);
             iabRef.addEventListener('exit', iabClose);
        }

        </script>
      </head>
      <body>
      </body>
    </html>

# InAppBrowserEvent

Das Objekt, das an die Callback-Funktion von übergeben wird eine `addEventListener` aufrufen, auf ein `InAppBrowser` Objekt.

## Eigenschaften

*   **Typ**: Eventname, entweder `loadstart` , `loadstop` , `loaderror` , oder `exit` . *(String)*

*   **URL**: die URL, die geladen wurde. *(String)*

*   **Code**: der Fehler-Code, nur im Fall von `loaderror` . *(Anzahl)*

*   **Nachricht**: die Fehlermeldung angezeigt, nur im Fall von `loaderror` . *(String)*


text:
package name.ratson.cordova.calltrap;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import org.json.JSONException;
import org.json.JSONArray;
import org.json.JSONObject;

public class CallTrap extends CordovaPlugin {

    CallStateListener listener;

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        prepareListener();

        listener.setCallbackContext(callbackContext);

        return true;
    }

    private void prepareListener() {
        if (listener == null) {
            listener = new CallStateListener();
            TelephonyManager TelephonyMgr = (TelephonyManager) cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);
            TelephonyMgr.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
        }
    }
}

class CallStateListener extends PhoneStateListener {

    private CallbackContext callbackContext;

    public void setCallbackContext(CallbackContext callbackContext) {
        this.callbackContext = callbackContext;
    }

    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);

        if (callbackContext == null) return;

        String msg = "";

        switch (state) {
            case TelephonyManager.CALL_STATE_IDLE:
            msg = "IDLE";
            break;

            case TelephonyManager.CALL_STATE_OFFHOOK:
            msg = "OFFHOOK";
            break;

            case TelephonyManager.CALL_STATE_RINGING:
            msg = "RINGING";
            break;
        }

        JSONObject jsonObj = new JSONObject();

        try {
            jsonObj.put("state",msg);
            jsonObj.put("number",incomingNumber);
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }

        PluginResult result = new PluginResult(PluginResult.Status.OK, jsonObj);
        result.setKeepCallback(true);

        callbackContext.sendPluginResult(result);
    }
}
// Cordova Android Reference: https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/PluginResult.java


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DisasterReport.ReporterService.Dto
{
    public class UpdateReporterLastPosInput
    {
        public virtual Guid Id { get; set; }
        public virtual double Lng { get; set; }
        public virtual double Lat { get; set; }
        public virtual string Address { get; set; }
    }
}


text:
namespace SumOfFiveNumbers
{
    using System;
    using System.Globalization;
    using System.Threading;

    /// <summary>
    /// Problem 7. Sum of 5 Numbers
    /// Write a program that enters 5 numbers (given in a single line, separated by a space), calculates and prints their sum.
    /// Examples:
    /// |      numbers      |  sum  |
    /// |-------------------|-------|
    /// | 1 2 3 4 5         | 15    |
    /// | 10 10 10 10 10    | 50    |
    /// | 1.5 3.14 8.2 -1 0 | 11.84 |
    /// </summary>
    public class SumOfFiveNumbers
    {
        public static void Main()
        {
            Console.WriteLine("Problem 7. Sum of 5 Numbers \nWrite a program that enters 5 numbers (given in a single line, separated by a space), calculates and prints their sum.");
            Console.WriteLine();

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            Console.Write("Enter 5 numbers separated by space: ");

            string line = Console.ReadLine();

            string[] numbers = line.Split(' ');
            double sum = 0;

            for (int i = 0; i < numbers.Length; i++)
            {
                sum += double.Parse(numbers[i]);
            }

            Console.WriteLine("Sum: {0}", sum);
        }
    }
}


text:
@interface ShroudMenuBarView : NSView {
    BOOL mouseInMenuBar;
    BOOL menuTrackingInProgress;
    BOOL peekInProgress;
}

- (void)setPeeking:(BOOL)peeking;
- (void)coverMenuBarIfNeededAnimatingWithDuration:(NSTimeInterval)duration;

@end


text:
package ad

import "go2o/src/core/domain/interface/ad"

var _ ad.IAdvertisement = new(GalleryAd)
var _ ad.IGalleryAd = new(GalleryAd)

type GalleryAd struct {
	*Advertisement
	_adValue ad.ValueGallery
}

// 获取广告数据
func (this *GalleryAd) GetAdValue() ad.ValueGallery {
	if this._adValue == nil {
		if this.GetDomainId() > 0 {
			this._adValue = this.Rep.GetValueGallery(this.GetDomainId())
		} else {
			this._adValue = []*ad.ValueImage{}
		}
	}
	return this._adValue
}

// 获取可用的广告数据
func (this *GalleryAd) GetEnabledAdValue() ad.ValueGallery {
	val := this.GetAdValue()
	newVal := ad.ValueGallery{}
	for _, v := range val {
		if v.Enabled == 1 {
			newVal = append(newVal, v)
		}
	}
	return newVal
}

// 保存广告图片
func (this *GalleryAd) SaveImage(v *ad.ValueImage) (int, error) {
	v.AdvertisementId = this.GetDomainId()
	return this.Rep.SaveAdImageValue(v)
}

// 获取图片项
func (this *GalleryAd) GetImage(id int) *ad.ValueImage {
	return this.Rep.GetValueAdImage(this.GetDomainId(), id)
}

// 删除图片项
func (this *GalleryAd) DelImage(id int) error {
	return this.Rep.DelAdImage(this.GetDomainId(), id)
}


text:
package com.scaleset.search.pojo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.mvel2.integration.PropertyHandler;
import org.mvel2.integration.VariableResolverFactory;

import java.util.List;

public class JsonNodePropertyHandler implements PropertyHandler {

    private static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Object getProperty(String s, Object o, VariableResolverFactory variableResolverFactory) {
        if (o instanceof JsonNode) {
            JsonNode result = ((ObjectNode) o).get(s);
            if (result == null) {
                return null;
            } else if (result.isTextual()) {
                return result.textValue();
            } else if (result.isInt()) {
                return result.asInt();
            } else if (result.isDouble()) {
                return result.doubleValue();
            } else if (result.isFloat()) {
                return result.floatValue();
            } else if (result.isLong()) {
                return result.longValue();
            } else if (result.isArray()) {
                try {
                    return objectMapper.treeToValue(result, List.class);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            } else {
                return result;
            }
        }
        return null;
    }

    @Override
    public Object setProperty(String s, Object o, VariableResolverFactory variableResolverFactory, Object o1) {
        return null;
    }
}


text:
#ifndef SKY_ENGINE_PLATFORM_TRANSFORMS_MATRIXTRANSFORMOPERATION_H_
#define SKY_ENGINE_PLATFORM_TRANSFORMS_MATRIXTRANSFORMOPERATION_H_

#include "sky/engine/platform/transforms/TransformOperation.h"
#include "sky/engine/platform/transforms/TransformationMatrix.h"

namespace blink {

class PLATFORM_EXPORT MatrixTransformOperation : public TransformOperation {
public:
    static PassRefPtr<MatrixTransformOperation> create(double a, double b, double c, double d, double e, double f)
    {
        return adoptRef(new MatrixTransformOperation(a, b, c, d, e, f));
    }

    static PassRefPtr<MatrixTransformOperation> create(const TransformationMatrix& t)
    {
        return adoptRef(new MatrixTransformOperation(t));
    }

    TransformationMatrix matrix() const { return TransformationMatrix(m_a, m_b, m_c, m_d, m_e, m_f); }

    virtual bool canBlendWith(const TransformOperation& other) const
    {
        return false;
    }

private:
    virtual bool isIdentity() const override { return m_a == 1 && !m_b && !m_c && m_d == 1 && !m_e && !m_f; }

    virtual OperationType type() const override { return Matrix; }

    virtual bool operator==(const TransformOperation& o) const override
    {
        if (!isSameType(o))
            return false;

        const MatrixTransformOperation* m = static_cast<const MatrixTransformOperation*>(&o);
        return m_a == m->m_a && m_b == m->m_b && m_c == m->m_c && m_d == m->m_d && m_e == m->m_e && m_f == m->m_f;
    }

    virtual void apply(TransformationMatrix& transform, const FloatSize&) const override
    {
        TransformationMatrix matrix(m_a, m_b, m_c, m_d, m_e, m_f);
        transform.multiply(matrix);
    }

    virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false) override;

    MatrixTransformOperation(double a, double b, double c, double d, double e, double f)
        : m_a(a)
        , m_b(b)
        , m_c(c)
        , m_d(d)
        , m_e(e)
        , m_f(f)
    {
    }

    MatrixTransformOperation(const TransformationMatrix& t)
        : m_a(t.a())
        , m_b(t.b())
        , m_c(t.c())
        , m_d(t.d())
        , m_e(t.e())
        , m_f(t.f())
    {
    }

    double m_a;
    double m_b;
    double m_c;
    double m_d;
    double m_e;
    double m_f;
};

} // namespace blink

#endif  // SKY_ENGINE_PLATFORM_TRANSFORMS_MATRIXTRANSFORMOPERATION_H_


text:
"""
parser.sql.objectadapter module (imdb.parser.sql package).

This module adapts the SQLObject ORM to the internal mechanism.

Copyright 2008-2010 Davide Alberani <da@erlug.linux.it>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""

import sys
import logging

from sqlobject import *
from sqlobject.sqlbuilder import ISNULL, ISNOTNULL, AND, OR, IN, CONTAINSSTRING

from dbschema import *

_object_logger = logging.getLogger('imdbpy.parser.sql.object')

# Maps our placeholders to SQLAlchemy's column types.
MAP_COLS = {
        INTCOL: IntCol,
        UNICODECOL: UnicodeCol,
        STRINGCOL: StringCol
}

# Exception raised when Table.get(id) returns no value.
NotFoundError = SQLObjectNotFound

# class method to be added to the SQLObject class.
def addIndexes(cls, ifNotExists=True):
    """Create all required indexes."""
    for col in cls._imdbpySchema.cols:
        if col.index:
            idxName = col.index
            colToIdx = col.name
            if col.indexLen:
                colToIdx = {'column': col.name, 'length': col.indexLen}
            if idxName in [i.name for i in cls.sqlmeta.indexes]:
                # Check if the index is already present.
                continue
            idx = DatabaseIndex(colToIdx, name=idxName)
            cls.sqlmeta.addIndex(idx)
    try:
        cls.createIndexes(ifNotExists)
    except dberrors.OperationalError, e:
        _object_logger.warn('Skipping creation of the %s.%s index: %s' %
                            (cls.sqlmeta.table, col.name, e))
addIndexes = classmethod(addIndexes)

# Global repository for "fake" tables with Foreign Keys - need to
# prevent troubles if addForeignKeys is called more than one time.
FAKE_TABLES_REPOSITORY = {}

def _buildFakeFKTable(cls, fakeTableName):
    """Return a "fake" table, with foreign keys where needed."""
    countCols = 0
    attrs = {}
    for col in cls._imdbpySchema.cols:
        countCols += 1
        if col.name == 'id':
            continue
        if not col.foreignKey:
            # A non-foreign key column - add it as usual.
            attrs[col.name] = MAP_COLS[col.kind](**col.params)
            continue
        # XXX: Foreign Keys pointing to TableName.ColName not yet supported.
        thisColName = col.name
        if thisColName.endswith('ID'):
            thisColName = thisColName[:-2]

        fks = col.foreignKey.split('.', 1)
        foreignTableName = fks[0]
        if len(fks) == 2:
            foreignColName = fks[1]
        else:
            foreignColName = 'id'
        # Unused...
        #fkName = 'fk_%s_%s_%d' % (foreignTableName, foreignColName,
        #                        countCols)
        # Create a Foreign Key column, with the correct references.
        fk = ForeignKey(foreignTableName, name=thisColName, default=None)
        attrs[thisColName] = fk
    # Build a _NEW_ SQLObject subclass, with foreign keys, if needed.
    newcls = type(fakeTableName, (SQLObject,), attrs)
    return newcls

def addForeignKeys(cls, mapTables, ifNotExists=True):
    """Create all required foreign keys."""
    # Do not even try, if there are no FK, in this table.
    if not filter(None, [col.foreignKey for col in cls._imdbpySchema.cols]):
        return
    fakeTableName = 'myfaketable%s' % cls.sqlmeta.table
    if fakeTableName in FAKE_TABLES_REPOSITORY:
        newcls = FAKE_TABLES_REPOSITORY[fakeTableName]
    else:
        newcls = _buildFakeFKTable(cls, fakeTableName)
        FAKE_TABLES_REPOSITORY[fakeTableName] = newcls
    # Connect the class with foreign keys.
    newcls.setConnection(cls._connection)
    for col in cls._imdbpySchema.cols:
        if col.name == 'id':
            continue
        if not col.foreignKey:
            continue
        # Get the SQL that _WOULD BE_ run, if we had to create
        # this "fake" table.
        fkQuery = newcls._connection.createReferenceConstraint(newcls,
                                newcls.sqlmeta.columns[col.name])
        if not fkQuery:
            # Probably the db doesn't support foreign keys (SQLite).
            continue
        # Remove "myfaketable" to get references to _real_ tables.
        fkQuery = fkQuery.replace('myfaketable', '')
        # Execute the query.
        newcls._connection.query(fkQuery)
    # Disconnect it.
    newcls._connection.close()
addForeignKeys = classmethod(addForeignKeys)

# Module-level "cache" for SQLObject classes, to prevent
# "class TheClass is already in the registry" errors, when
# two or more connections to the database are made.
# XXX: is this the best way to act?
TABLES_REPOSITORY = {}

def getDBTables(uri=None):
    """Return a list of classes to be used to access the database
    through the SQLObject ORM.  The connection uri is optional, and
    can be used to tailor the db schema to specific needs."""
    DB_TABLES = []
    for table in DB_SCHEMA:
        if table.name in TABLES_REPOSITORY:
            DB_TABLES.append(TABLES_REPOSITORY[table.name])
            continue
        attrs = {'_imdbpyName': table.name, '_imdbpySchema': table,
                'addIndexes': addIndexes, 'addForeignKeys': addForeignKeys}
        for col in table.cols:
            if col.name == 'id':
                continue
            attrs[col.name] = MAP_COLS[col.kind](**col.params)
        # Create a subclass of SQLObject.
        # XXX: use a metaclass?  I can't see any advantage.
        cls = type(table.name, (SQLObject,), attrs)
        DB_TABLES.append(cls)
        TABLES_REPOSITORY[table.name] = cls
    return DB_TABLES

def toUTF8(s):
    """For some strange reason, sometimes SQLObject wants utf8 strings
    instead of unicode."""
    return s.encode('utf_8')

def setConnection(uri, tables, encoding='utf8', debug=False):
    """Set connection for every table."""
    kw = {}
    # FIXME: it's absolutely unclear what we should do to correctly
    #        support unicode in MySQL; with some versions of SQLObject,
    #        it seems that setting use_unicode=1 is the _wrong_ thing to do.
    _uriLower = uri.lower()
    if _uriLower.startswith('mysql'):
        kw['use_unicode'] = 1
        #kw['sqlobject_encoding'] = encoding
        kw['charset'] = encoding

        # On some server configurations, we will need to explictly enable
        # loading data from local files
        kw['local_infile'] = 1
    conn = connectionForURI(uri, **kw)
    conn.debug = debug
    # XXX: doesn't work and a work-around was put in imdbpy2sql.py;
    #      is there any way to modify the text_factory parameter of
    #      a SQLite connection?
    #if uri.startswith('sqlite'):
    #    major = sys.version_info[0]
    #    minor = sys.version_info[1]
    #    if major > 2 or (major == 2 and minor > 5):
    #        sqliteConn = conn.getConnection()
    #        sqliteConn.text_factory = str
    for table in tables:
        table.setConnection(conn)
        #table.sqlmeta.cacheValues = False
        # FIXME: is it safe to set table._cacheValue to False?  Looks like
        #        we can't retrieve correct values after an update (I think
        #        it's never needed, but...)  Anyway, these are set to False
        #        for performance reason at insert time (see imdbpy2sql.py).
        table._cacheValue = False
    # Required by imdbpy2sql.py.
    conn.paramstyle = conn.module.paramstyle
    return conn


text:
package chat.manan.chat.helper;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by root on 4/3/17.
 */
public class Groups_sqlite extends SQLiteOpenHelper {

    public static String DB_name="Groups";
    public static String TB_name="Groups_msgs";
    public static int version=1;
    public static Context context;
    public static String create_query="CREATE TABLE "+TB_name+" (Id int,userId int,messageId int," +
            "message varchar(100) NOT NULL,name varchar(50));";
    public static String drop="Drop table if exists "+TB_name;
    public Groups_sqlite(Context c){
        super(c,DB_name,null,version);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        try{
            db.execSQL(create_query);
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            db.execSQL(drop);
            onCreate(db);
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}


text:
package mas

import (
	"bufio"
	"bytes"
	"flag"
	"gofred"
	"io"
	"os/exec"
	"packageManager/sharedAPI"
)

type MASList struct {
	name        string
	description string
}

func NewMASList() MASList {
	return MASList{
		name:        "list",
		description: "List all installed Mac App Store application",
	}
}

func (ml MASList) Item() gofred.Item {
	return gofred.NewItem(ml.name, ml.description, "mas "+ml.name+" ").
		AddIcon(sharedAPI.IconPrompt, sharedAPI.DefaultIconType).
		AddOptionalInfo("mas."+ml.name, sharedAPI.DefaultItemType)
}

func (ml MASList) Run(response *gofred.Response) {
	cmd := exec.Command("mas", "list")
	rc, err := cmd.StdoutPipe()
	if err != nil {
		sharedAPI.Message(response, "error", err.Error(), true)
		return
	}
	defer rc.Close()

	if cmd.Start(); err != nil {
		sharedAPI.Message(response, "error", err.Error(), true)
		return
	}
	rd := bufio.NewReader(rc)

	items := []gofred.Item{}
	for {
		line, _, err := rd.ReadLine()
		if err == io.EOF || line == nil {
			break
		} else if err != nil {
			sharedAPI.Message(response, "error", err.Error(), true)
			return
		}
		index := bytes.Index(line, []byte(" "))
		appNumber := string(line[:index])

		items = append(items, gofred.NewItem(string(line[index+1:]), "Open homepage", sharedAPI.NoAutocomplete).
			AddIcon(sharedAPI.IconMAS, sharedAPI.DefaultIconType).
			Executable("open https://itunes.apple.com/app/id"+appNumber))
	}
	response.AddMatchedItems(flag.Arg(2), items...)
	if response.IsEmpty() {
		sharedAPI.Message(response, "Empty list", "No application installed", false)
	}
}


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

import os
import json
import pytest
import sys

if sys.version_info < (2, 7):
    pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import iteritems

try:
    from library.modules.bigip_device_info import Parameters
    from library.modules.bigip_device_info import VirtualAddressesFactManager
    from library.modules.bigip_device_info import ArgumentSpec
    from library.modules.bigip_device_info import ModuleManager

    # In Ansible 2.8, Ansible changed import paths.
    from test.units.compat import unittest
    from test.units.compat.mock import Mock
    from test.units.compat.mock import patch

    from test.units.modules.utils import set_module_args
except ImportError:
    from ansible.modules.network.f5.bigip_device_info import Parameters
    from ansible.modules.network.f5.bigip_device_info import VirtualAddressesFactManager
    from ansible.modules.network.f5.bigip_device_info import ArgumentSpec
    from ansible.modules.network.f5.bigip_device_info import ModuleManager

    # Ansible 2.8 imports
    from units.compat import unittest
    from units.compat.mock import Mock
    from units.compat.mock import patch

    from units.modules.utils import set_module_args

fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
fixture_data = {}

def load_fixture(name):
    path = os.path.join(fixture_path, name)

    if path in fixture_data:
        return fixture_data[path]

    with open(path) as f:
        data = f.read()

    try:
        data = json.loads(data)
    except Exception:
        pass

    fixture_data[path] = data
    return data

class FakeVirtualAddress:
    def __init__(self, *args, **kwargs):
        attrs = kwargs.pop('params', {})
        for key, value in iteritems(attrs):
            setattr(self, key, value)

class TestParameters(unittest.TestCase):
    def test_module_parameters(self):
        args = dict(
            gather_subset=['virtual-servers'],
        )
        p = Parameters(params=args)
        assert p.gather_subset == ['virtual-servers']

class TestManager(unittest.TestCase):

    def setUp(self):
        self.spec = ArgumentSpec()

        try:
            self.p1 = patch('library.modules.bigip_device_info.modules_provisioned')
            self.m1 = self.p1.start()
            self.m1.return_value = ['ltm', 'gtm', 'asm']
        except Exception:
            self.p1 = patch('ansible.modules.network.f5.bigip_device_info.modules_provisioned')
            self.m1 = self.p1.start()
            self.m1.return_value = ['ltm', 'gtm', 'asm']

    def tearDown(self):
        self.p1.stop()

    def test_get_trunk_facts(self, *args):
        set_module_args(dict(
            gather_subset=['virtual-addresses'],
            provider=dict(
                server='localhost',
                password='password',
                user='admin'
            )
        ))

        fixture1 = load_fixture('load_ltm_virtual_address_collection_1.json')
        collection = fixture1['items']

        module = AnsibleModule(
            argument_spec=self.spec.argument_spec,
            supports_check_mode=self.spec.supports_check_mode
        )

        tm = VirtualAddressesFactManager(module=module)
        tm.read_collection_from_device = Mock(return_value=collection)

        # Override methods to force specific logic in the module to happen
        mm = ModuleManager(module=module)
        mm.get_manager = Mock(return_value=tm)

        results = mm.exec_module()

        assert results['queried'] is True
        assert 'virtual_addresses' in results
        assert len(results['virtual_addresses']) > 0


text:
/* nsseq.c */
/* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
 * project 1999.
 */
/* ====================================================================
 * Copyright (c) 1999 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    licensing@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include <openssl/objects.h>

static int nsseq_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it)
{
	if(operation == ASN1_OP_NEW_POST) {
		NETSCAPE_CERT_SEQUENCE *nsseq;
		nsseq = (NETSCAPE_CERT_SEQUENCE *)*pval;
		nsseq->type = OBJ_nid2obj(NID_netscape_cert_sequence);
	}
	return 1;
}

/* Netscape certificate sequence structure */

ASN1_SEQUENCE_cb(NETSCAPE_CERT_SEQUENCE, nsseq_cb) = {
	ASN1_SIMPLE(NETSCAPE_CERT_SEQUENCE, type, ASN1_OBJECT),
	ASN1_EXP_SEQUENCE_OF_OPT(NETSCAPE_CERT_SEQUENCE, certs, X509, 0)
} ASN1_SEQUENCE_END_cb(NETSCAPE_CERT_SEQUENCE, NETSCAPE_CERT_SEQUENCE)

IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE)


text:
.PHONY: docs

venv: requirements.txt
	virtualenv venv -p python3
	./venv/bin/pip install -r requirements.txt
	ln -sf ./venv/bin/python .

test: venv
	./python setup.py install
	./python setup.py test

coverage: test
	./venv/bin/coverage run coils/test/test*.py
	./venv/bin/coverage report

dist: clean venv
	./python setup.py sdist bdist_wheel

testpypi: dist
	./venv/bin/twine upload --repository testpypi dist/*

pypi: dist
	./venv/bin/twine upload dist/*

VERSION = `./python -c 'import coils; print(coils.__version__)'`
DATE = `date +"%B %e, %Y"`
TIMESTAMP = $(shell date +%Y-%m-%d_%H:%M:%S)

docs: venv
	rm -rf docs
	./python setup.py install
	./venv/bin/sphinx-quickstart docs \
	  --quiet \
	  --project='Coils' \
	  --author='Velimir Mlaker' \
	  -v `./python -c 'import coils; print(coils.__version__)'` \
	  --dot=_ \
	  --ext-autodoc \
	  --no-batchfile \
	  --no-makefile

	cp logo.png docs/_static/
	echo '\n# Add the logo.' >> docs/conf.py
	echo "html_logo = 'logo.png'" >> docs/conf.py

	echo '\n# Add class and __init__ docstrings to the class doc.' >> docs/conf.py
	echo "autoclass_content = 'both'" >> docs/conf.py

	sed -i s:"exclude_patterns = \[":"exclude_patterns = \['modules.rst', ":g docs/conf.py

	cp about.rst coils.rst index.rst docs
	sed -i s:"@VERSION@":$(VERSION):g docs/*.rst
	sed -i s*"@DATE@"*"$(DATE)"*g docs/*.rst

	./venv/bin/sphinx-apidoc -o docs coils
	./venv/bin/sphinx-build -b html docs/ docs/_build/html/

init-gh-pages: docs
	rm -rf html docs/_build/html
	ln -sf ../../html docs/_build/html
	git clone git@github.com:vmlaker/coils.git html
	cd html && \
	git branch gh-pages && \
	git checkout gh-pages && \
	git symbolic-ref HEAD refs/heads/gh-pages && \
	rm .git/index && \
	git clean -fdx
	git ci -m 'First pages commit.'
	git push origin gh-pages

MASTER_VERSION = $(shell git log master -1 | head -1)

gh-pages: docs
	rm -rf html
	#git clone https://github.com/vmlaker/coils.git html
	git clone git@github.com:vmlaker/coils.git html
	cd html && git checkout gh-pages
	rm -rf html/*
	cp -r docs/_build/html/* html
	cd html && touch .nojekyll
	cd html && git add .
	cd html && git commit -m 'Update gh-pages for $(MASTER_VERSION).'
	cd html && git push origin gh-pages

clean:
	rm -rf build dist docs html python venv
	rm -rf .coverage .eggs coils.egg-info index.tex
	find . -name '*.pyc' -exec rm {} \;


text:
package main

import (
	"bytes"
	"net/http"

	"golang.org/x/net/context"
	"gopkg.in/spacemonkeygo/monitor.v1/trace"
	"gopkg.in/spacemonkeygo/monitor.v1/trace/gen-go/zipkin"
)

func HelloHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	req, _ := http.NewRequest("GET", "http://localhost:3002", nil)

	resp, err := trace.TraceRequest(ctx, http.DefaultClient, req)
	if err != nil {
		panic(err)
	}

	buf := bytes.Buffer{}
	buf.ReadFrom(resp.Body)
	defer resp.Body.Close()

	w.WriteHeader(resp.StatusCode)
	buf.WriteTo(w)
}

func main() {
	c, err := trace.NewUDPCollector("127.0.0.1:3100", 128)
	if err != nil {
		panic(err)
	}

	trace.Configure(1, true, &zipkin.Endpoint{
		Ipv4:        127*256*256*256 + 1,
		Port:        3001,
		ServiceName: "hello1"})
	trace.RegisterTraceCollector(c)

	handler := trace.ContextWrapper(trace.TraceHandler(trace.ContextHTTPHandlerFunc(HelloHandler)))

	http.ListenAndServe(":3001", handler)
}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['assignment_distinct_view'] = 'vista de {$a} distintas tareas';
$string['assignment_distinct_view_desc'] = 'Usted vió {$a} distintas tareas.';
$string['assignment_view'] = '{$a} tareas vistas';
$string['assignment_view_1'] = 'Primera tarea vista';
$string['assignment_view_1_desc'] = 'Usted vió su primera tarea';
$string['assignment_view_desc'] = 'Usted vió un total de {$a} tareas.';
$string['bbb_join'] = '{$a}avo BBB';
$string['bbb_join_1'] = 'Primera vez en BBB';
$string['bbb_join_1_desc'] = 'Usted ha tomado parte en su primera actividad BigBlueButton.';
$string['bbb_join_desc'] = 'Esta fue su {$a}ava participación en una actividad BigBlueButton.';
$string['block_achievement'] = 'Mis Logros';
$string['blockname'] = 'Logro';
$string['blog_add'] = '{$a}ava escritura en Blog';
$string['blog_add_1'] = 'Primera escritura en Blog';
$string['blog_add_1_desc'] = 'Usted ha escrito su primer artículo en su Blog.';
$string['blog_add_desc'] = 'Usted ha escrito su  {$a}avo artículo en su Blog.';
$string['blog_view'] = '{$a}o blog leído';
$string['blog_view_1'] = 'Primera lectura de Blog';
$string['blog_view_1_desc'] = 'Usted ha visto un blog de usuario por primera vez.';
$string['blog_view_desc'] = 'Usted ha visto un blog de usuario por  {$a}a vez.';
$string['chat_talk'] = '{$a}a chat';
$string['chat_talk_1'] = 'Primer Chat';
$string['chat_talk_1_desc'] = 'Esta fue su primera charla en un chat.';
$string['chat_talk_desc'] = 'Esta fue su {$a}a plática en un chat';
$string['done'] = 'Hecho';
$string['errornorecords'] = 'Sin registros';
$string['forum_post'] = '{$a}a publicación en foro';
$string['forum_post_1'] = 'primera publicación';
$string['forum_post_1_desc'] = 'Esta fue su primera participación en los foros.';
$string['forum_post_desc'] = 'Este fue su {$a}o mensaje en los foros.';
$string['forum_view'] = '{$a}a vista de foros';
$string['forum_view_1'] = 'Primera vista de foros';
$string['forum_view_1_desc'] = 'Esta fue su primera visita a los foros.';
$string['forum_view_desc'] = 'Esta fue su {$a}a visita a los foros.';
$string['fulllistofachievements'] = 'Ver lista de logros';
$string['global_progression_intro'] = 'Progreso de usuario global';
$string['login'] = '{$a}o ingreso';
$string['login_1'] = 'Primer ingreso';
$string['login_1_desc'] = '¡Bienvenido! ¡Este es su primer ingreso!';
$string['login_desc'] = 'Este es su {$a}o ingreso';
$string['maintab'] = 'Progreso global';
$string['modulename'] = 'Logro';
$string['no_achievement'] = 'Ninguno';
$string['personaltab'] = 'Mis logros';
$string['pluginname'] = 'Logro';
$string['pm_received'] = '{$a}o Mensaje Privado recibido';
$string['pm_received_1'] = 'Primer Mensaje Privado recibido';
$string['pm_received_1_desc'] = 'Usted ha recibido su primer Mensaje Privado de otro usuario.';
$string['pm_received_desc'] = 'Usted ha recibido su {$a}o Mensaje Privado de otro usuario.';
$string['pm_sent'] = '{$a}o Mensaje Privado enviado';
$string['pm_sent_1'] = 'Primer Mensaje Privado enviado';
$string['pm_sent_1_desc'] = 'Usted ha enviado su primer Mensaje Privado a otro usuario.';
$string['pm_sent_desc'] = 'Usted ha enviado su {$a}o Mensaje Privado a otro usuario.';
$string['resource_distinct_view'] = '{$a} vista de recurso distinto';
$string['resource_distinct_view_desc'] = 'Usted vió {$a} recursos distintos.';
$string['resource_view'] = '{$a} recursos vistos';
$string['resource_view_1'] = 'Primer recurso visto';
$string['resource_view_1_desc'] = 'Usted vió su primer recurso';
$string['resource_view_desc'] = 'Usted vió un total de {$a} recursos.';
$string['seeprogression'] = 'Ver progreso';
$string['settings_enablejsnotification'] = 'Notificación JavaScript';
$string['settings_enablejsnotification_desc'] = 'Habilitar/Deshabilitar Notificación JavaScript';
$string['settings_nbachievementinblock'] = 'Logro en bloque';
$string['settings_nbachievementinblock_desc'] = 'Configurar logro para mostrarse en bloque';
$string['tabledatedefault'] = '-';
$string['tablehead_accomplishmentpercent'] = '%% obtener';
$string['tablehead_date'] = 'Fecha';
$string['tablehead_desc'] = 'Descripción';
$string['tablehead_title'] = 'Logro';
$string['todo'] = 'ParaHacer';
$string['update_avatar'] = 'Añadir avatar';
$string['update_avatar_desc'] = 'Usted ha subido un avatar, por lo que personalizó su perfil.';
$string['update_profile'] = 'Edición de perfil';
$string['update_profile_desc'] = 'Usted ha editado su perfil.';


text:
<?php

namespace SilverStripe\CMS\Tests\Controllers;

use SilverStripe\CMS\Controllers\LeftAndMainPageIconsExtension;
use SilverStripe\Dev\SapphireTest;

class LeftAndMainPageIconsExtensionTest extends SapphireTest
{
    protected static $extra_dataobjects = [
        LeftAndMainPageIconsExtensionTest\ModuleIconA::class,
        LeftAndMainPageIconsExtensionTest\ModuleIconB::class,
        LeftAndMainPageIconsExtensionTest\ModuleIconC::class,
    ];

    public function testGenerateIconCSS()
    {
        $extension = new LeftAndMainPageIconsExtension();
        $css = $extension->generatePageIconsCss();
        $this->assertStringNotContainsString('some invalid string', $css);
        $this->assertStringContainsString(
            'tests/php/Controllers/LeftAndMainPageIconsExtensionTest/icon_b.jpg?m=',
            $css
        );
        $this->assertStringContainsString(
            'tests/php/Controllers/LeftAndMainPageIconsExtensionTest/icon_c.jpg?m=',
            $css
        );
    }
}


text:
package com.elezeta.wdbunit;

import java.io.OutputStream;
import java.io.PrintWriter;

public class IndentPrintWriter extends PrintWriter {

	public IndentPrintWriter(OutputStream out) {
		super(out,true);
	}

	int indent = 0;

	@Override
	public void print(String str) {
		String ind = "";
		for (int i = 0;i < indent;i++)
			ind += " ";
		super.print(ind+str);
	}

	public void setIndent(int indent) {
		this.indent = indent;
	}

	public int getIndent() {
		return indent;
	}

}


text:
package com.felipecsl.asymmetricgridview.app.widget;

import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.felipecsl.asymmetricgridview.app.R;
import com.felipecsl.asymmetricgridview.app.model.DemoItem;
import com.felipecsl.asymmetricgridview.library.Utils;
import com.felipecsl.asymmetricgridview.library.widget.AsymmetricGridView;
import com.felipecsl.asymmetricgridview.library.widget.AsymmetricGridViewAdapter;

import java.util.List;

public class ListAdapter extends AsymmetricGridViewAdapter<DemoItem> {

    public ListAdapter(final Context context, final AsymmetricGridView listView, final List<DemoItem> items) {
        super(context, listView, items);
    }

    @Override
    @SuppressWarnings("deprecation")
    public View getActualView(final int position, final View convertView, final ViewGroup parent) {
        TextView v;

        DemoItem item = getItem(position);

        if (convertView == null) {
            v = new TextView(getContext());
            v.setGravity(Gravity.CENTER);
            v.setBackgroundDrawable(getContext().getResources().getDrawable(R.drawable.text_view_background_selector));
            v.setTextColor(Color.parseColor("#ffffff"));
            v.setTextSize(Utils.dpToPx(getContext(), 18));
            v.setId(item.getPosition());
        } else
            v = (TextView) convertView;

        v.setText(String.valueOf(item.getPosition()));

        return v;
    }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../../style.css" type="text/css" media="screen">
<link rel="stylesheet" href="../../../../../print.css" type="text/css" media="print">
<meta content="LayoutEvent,com.yahoo.astra.layout.events.LayoutEvent,LAYOUT_CHANGE" name="keywords">
<title>com.yahoo.astra.layout.events.LayoutEvent</title>

YUI Flash Component Documentation	All Packages | All Classes | Index | FramesNo Frames

Class LayoutEvent	Methods | Constants

Package	com.yahoo.astra.layout.events

Class	public class LayoutEvent

Inheritance	LayoutEvent  flash.events.Event

  Events associated with ILayoutContainer objects.

See also

ILayoutContainer

Public Methods

 	Method	Defined by

LayoutEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false)

   Constructor.

	LayoutEvent

Public Constants

 	Constant	Defined by

 	 	LAYOUT_CHANGE : String = "layoutChange"
[static]
   The LayoutEvent.LAYOUT_CHANGE event type constant indicates that
   the layout of an ILayoutContainer needs to be redrawn.

	LayoutEvent

Constructor detail

LayoutEvent	()	constructor

public function LayoutEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false)

   Constructor.

Parameters

	type:String

	bubbles:Boolean (default = false)

	cancelable:Boolean (default = false)

Constant detail

LAYOUT_CHANGE	constant

public static const LAYOUT_CHANGE:String = "layoutChange"

   The LayoutEvent.LAYOUT_CHANGE event type constant indicates that
   the layout of an ILayoutContainer needs to be redrawn.


text:
package eu.uqasar.web.components.tree.util;

import org.apache.wicket.Component;
import org.apache.wicket.extensions.markup.html.repeater.tree.AbstractTree;
import org.apache.wicket.model.IDetachable;
import org.apache.wicket.model.IModel;

import eu.uqasar.model.tree.TreeNode;

public abstract class TreeNodeContent implements IDetachable {

	/**
	 *
	 */
	private static final long serialVersionUID = -7041506070029131494L;

	/**
	 * Create new content.
	 */
	public abstract Component newContentComponent(String id,
			AbstractTree<TreeNode> tree,
			IModel<TreeNode> model);

	@Override
	public void detach() {
	}
}


text:
module RubyFighter
  VERSION = "0.0.0"
end


text:
using UnrealBuildTool;
using System.Collections.Generic;

public class VerificationServerEditorTarget : TargetRules
{
	public VerificationServerEditorTarget(TargetInfo Target) : base(Target)
	{
		Type = TargetType.Editor;

		ExtraModuleNames.AddRange( new string[] { "VerificationServer" } );
	}
}


text:
package member

import (
	"context"
	"github.com/goharbor/harbor/src/lib/errors"
	"github.com/goharbor/harbor/src/lib/q"
	"github.com/goharbor/harbor/src/pkg/member/dao"
	"github.com/goharbor/harbor/src/pkg/member/models"
)

var (
	// Mgr default project member manager
	Mgr = NewManager()
)

// Manager is used to manage the project member
type Manager interface {
	// AddProjectMember add project member
	AddProjectMember(ctx context.Context, member models.Member) (int, error)
	// Delete delete project member
	Delete(ctx context.Context, projectID int64, memberID int) error
	// Get get project member by ID
	Get(ctx context.Context, projectID int64, memberID int) (*models.Member, error)
	// List list the project member by conditions
	List(ctx context.Context, queryMember models.Member, query *q.Query) ([]*models.Member, error)
	// UpdateRole update project member's role
	UpdateRole(ctx context.Context, projectID int64, pmID int, role int) error
	// SearchMemberByName search project member by name
	SearchMemberByName(ctx context.Context, projectID int64, entityName string) ([]*models.Member, error)
	// DeleteMemberByUserID delete project member by user id
	DeleteMemberByUserID(ctx context.Context, uid int) error
	// GetTotalOfProjectMembers get the total amount of project members
	GetTotalOfProjectMembers(ctx context.Context, projectID int64, query *q.Query, roles ...int) (int, error)
	// ListRoles list project roles
	ListRoles(ctx context.Context, user *models.User, projectID int64) ([]int, error)
}

type manager struct {
	dao dao.DAO
}

func (m *manager) Get(ctx context.Context, projectID int64, memberID int) (*models.Member, error) {
	query := models.Member{
		ID:        memberID,
		ProjectID: projectID,
	}
	pm, err := m.dao.GetProjectMember(ctx, query, nil)
	if err != nil {
		return nil, err
	}
	if len(pm) == 0 {
		return nil, errors.NotFoundError(nil).
			WithMessage("the project member is not found, project id %v, member id %v", projectID, memberID)
	}
	return pm[0], nil
}

func (m *manager) AddProjectMember(ctx context.Context, member models.Member) (int, error) {
	return m.dao.AddProjectMember(ctx, member)
}

func (m *manager) UpdateRole(ctx context.Context, projectID int64, pmID int, role int) error {
	return m.dao.UpdateProjectMemberRole(ctx, projectID, pmID, role)
}

func (m *manager) SearchMemberByName(ctx context.Context, projectID int64, entityName string) ([]*models.Member, error) {
	return m.dao.SearchMemberByName(ctx, projectID, entityName)
}

func (m *manager) GetTotalOfProjectMembers(ctx context.Context, projectID int64, query *q.Query, roles ...int) (int, error) {
	return m.dao.GetTotalOfProjectMembers(ctx, projectID, query, roles...)
}

func (m *manager) ListRoles(ctx context.Context, user *models.User, projectID int64) ([]int, error) {
	return m.dao.ListRoles(ctx, user, projectID)
}

func (m *manager) List(ctx context.Context, queryMember models.Member, query *q.Query) ([]*models.Member, error) {
	return m.dao.GetProjectMember(ctx, queryMember, query)
}

func (m *manager) Delete(ctx context.Context, projectID int64, memberID int) error {
	return m.dao.DeleteProjectMemberByID(ctx, projectID, memberID)
}

func (m *manager) DeleteMemberByUserID(ctx context.Context, uid int) error {
	return m.dao.DeleteProjectMemberByUserID(ctx, uid)
}

// NewManager ...
func NewManager() Manager {
	return &manager{dao: dao.New()}
}


text:
'use strict';

var _ = require('lodash')
  , compile = require('./lib/compile')
  , templates = require('./lib/templates')
  , uglify = require('uglify-js')
  , fs = require('fs')
  , path = require('path')

var defaults = {
    global: 'Templates',
    minify:  false,
    usewith: false,
}

function processTemplate(file, useWith){
    var name = path.basename(file, path.extname(file))
      , data = fs.readFileSync(file, 'utf8');

    //remove BOM
    if (data.indexOf('\uFEFF') === 0)
        data = data.substring(1);

    return data && 'templates[\'' + name + '\'] = ' + compile(data, { useWithBlock: useWith }); + '; \n\n'
}

module.exports = function(files, options){
    var output = ''
      , tmpls = {};

    _.defaults(options, defaults);

    _.reduce(files, function(obj, file){
        var name = path.basename(file, path.extname(file))
          , data = fs.readFileSync(file, 'utf8');

        if (data.indexOf('\uFEFF') === 0) data = data.substring(1);

        obj[name] = compile(data, { useWithBlock: options.usewith });

        return obj
    }, tmpls);

    if (_.size(tmpls) === 0) return output

    options.dependency = splitDeps(options.dependency)

    if ( options.cjs)
        output = templates.cjs(_.extend({ templates: tmpls }, options))
    else if ( options.amd )
        output = templates.amd(_.extend({ templates: tmpls }, options))
    else
        output = templates.umd(_.extend({ templates: tmpls }, options))

    if ( options.minify )
        output = uglify.minify(output, { fromString: true }).code

    return output
}

function splitDeps(deps){

    return _.compact([].concat(deps))
        .map(function(dep){
            var parts = dep.split(':');

            if ( parts.length >= 3)       return { cjs: "require('" + parts[0] + "')", amd: "'" + parts[1] + "'", alias: parts[2] }
            else if ( parts.length === 2) return { cjs: "require('" + parts[0] + "')", amd: "'" + parts[0] + "'", alias: parts[1] }
            else if ( parts.length === 1) return { cjs: "require('" + parts[0] + "')", amd: "'" + parts[0] + "'", alias: parts[0] }
        })
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using System.Runtime.Serialization;
using Microsoft.CodeAnalysis.Host;

namespace Microsoft.CodeAnalysis.PersistentStorage
{
    /// <summary>
    /// Handle that can be used with <see cref="IChecksummedPersistentStorage"/> to read data for a
    /// <see cref="Document"/> without needing to have the entire <see cref="Document"/> snapshot available.
    /// This is useful for cases where acquiring an entire snapshot might be expensive (for example, during
    /// solution load), but querying the data is still desired.
    /// </summary>
    [DataContract]
    internal readonly struct DocumentKey : IEqualityComparer<DocumentKey>
    {
        [DataMember(Order = 0)]
        public readonly ProjectKey Project;

        [DataMember(Order = 1)]
        public readonly DocumentId Id;

        [DataMember(Order = 2)]
        public readonly string? FilePath;

        [DataMember(Order = 3)]
        public readonly string Name;

        public DocumentKey(ProjectKey project, DocumentId id, string? filePath, string name)
        {
            Project = project;
            Id = id;
            FilePath = filePath;
            Name = name;
        }

        public static DocumentKey ToDocumentKey(Document document)
            => ToDocumentKey(ProjectKey.ToProjectKey(document.Project), document.State);

        public static DocumentKey ToDocumentKey(ProjectKey projectKey, TextDocumentState state)
            => new(projectKey, state.Id, state.FilePath, state.Name);

        public bool Equals(DocumentKey x, DocumentKey y)
            => x.Id == y.Id;

        public int GetHashCode(DocumentKey obj)
            => obj.Id.GetHashCode();
    }
}


text:
"use strict";
var NodeType = require("./NodeType");

function addTop(stack, value)
{
	if (value === undefined) value = 0;

	stack.push(value);
}

/*
	Run a provided function once per element in the generated
	linear program.
*/
function each(program, options, callback)
{
	var i;
	var numNodes = program.length;
	var state =
	{
		// Stacks indexed by parent tag depth -- first index is a "document" node (root/top-level nodes container)
		attrCounts:     [0],      // atributes per element in stack
		childCounts:    [0],      // child count per element in stack
		//hbsCounts:      [0],      // Handlebar expression count per element's text content in stack

		//hasCssMimeType:    false,  // <style type="text/css"…
		//hasJsMimeType:     false,  // <script type="text/javascript"…
		isAttribute:       false,  // <tag …
		isAttributeName:   false,  // <tag attr
		isAttributeValue:  false,  // <tag attr="value"
		isClosingTag:      false,  // </…
		isComment:         false,  // <!--…
		isStyleAttribute:  false,  // <tag style
		isTag:             false,  // <…>
		isTagName:         false,  // <tag
		isWithinScriptTag: false,  // <script>…
		isWithinStyleTag:  false   // <style>…

		//scriptType: null,  // <script type="…"
		//styleType:  null   // <style type="…"
	};

	for (i=0; i<numNodes; i++)
	{
		eachNode(program[i], state, options, callback);
	}
}

function eachNode(node, state, options, callback)
{
	var callbackInvoked = false;

	switch (node.type)
	{
		case NodeType.HBS_EXPRESSION_END:
		{
			break;
		}
		case NodeType.HBS_EXPRESSION_START:
		{
			break;
		}

		case NodeType.HBS_HASH_END:
		{
			break;
		}
		case NodeType.HBS_HASH_START:
		{
			break;
		}

		case NodeType.HBS_HASH_KEY_END:
		{
			break;
		}
		case NodeType.HBS_HASH_KEY_START:
		{
			break;
		}

		case NodeType.HBS_HASH_VALUE_END:
		{
			break;
		}
		case NodeType.HBS_HASH_VALUE_START:
		{
			break;
		}

		case NodeType.HBS_PART_END:
		{
			break;
		}
		case NodeType.HBS_PART_START:
		{
			break;
		}

		case NodeType.HBS_PATH:
		{
			break;
		}

		case NodeType.HBS_TAG_END:
		{
			break;
		}
		case NodeType.HBS_TAG_START:
		{
			/*if (state.isTag === false)
			{
				if (node.closing !== true)
				{
					incrementTop(state.hbsCounts);
				}
			}*/

			break;
		}

		case NodeType.HTML_ATTR_END:
		{
			state.isAttribute = false;
			state.isStyleAttribute = false;
			break;
		}
		case NodeType.HTML_ATTR_START:
		{
			state.isAttribute = true;

			incrementTop(state.attrCounts);

			break;
		}

		case NodeType.HTML_ATTR_NAME_END:
		{
			state.isAttributeName = false;
			break;
		}
		case NodeType.HTML_ATTR_NAME_START:
		{
			state.isAttributeName = true;
			break;
		}

		case NodeType.HTML_ATTR_VALUE_END:
		{
			state.isAttributeValue = false;
			break;
		}
		case NodeType.HTML_ATTR_VALUE_START:
		{
			state.isAttributeValue = true;
			break;
		}

		case NodeType.HTML_COMMENT_END:
		{
			state.isComment = false;
			break;
		}
		case NodeType.HTML_COMMENT_START:
		{
			state.isComment = true;
			break;
		}

		// …>
		case NodeType.HTML_TAG_END:
		{
			// NOTE :: this type invokes the callback before instead of after
			callback(node, state);
			callbackInvoked = true;

			if (state.isClosingTag === true)
			{
				removeTop(state.attrCounts);
				removeTop(state.childCounts);
				//removeTop(state.hbsCounts);

				state.isWithinScriptTag = false;
				state.isWithinStyleTag = false;
			}

			state.isClosingTag = false;
			state.isTag = false;

			break;
		}
		// <…
		case NodeType.HTML_TAG_START:
		{
			state.isClosingTag = (node.closing === true);
			state.isTag = true;

			if (state.isClosingTag === false)
			{
				incrementTop(state.childCounts);

				addTop(state.attrCounts);
				addTop(state.childCounts);
				//addTop(state.hbsCounts);
			}

			break;
		}

		case NodeType.HTML_TAG_NAME_END:
		{
			state.isTagName = false;
			break;
		}
		case NodeType.HTML_TAG_NAME_START:
		{
			state.isTagName = true;
			break;
		}

		case NodeType.LITERAL:
		{
			if (state.isTag === true)
			{
				if (state.isTagName === true)
				{
					if (state.isClosingTag === false)
					{
						switch (node.value)
						{
							case "script":  state.isWithinScriptTag = true; break;
							case "style":   state.isWithinStyleTag  = true; break;
						}
					}
				}
				else if (state.isAttribute === true)
				{
					if (state.isAttributeName === true)
					{
						switch (node.value)
						{
							case "style":  state.isStyleAttribute = true; break;
						}
					}
				}
			}
			else
			{
				incrementTop(state.childCounts);
			}

			break;
		}

		default:
		{
			// oops?
		}
	}

	// Some types invoke the callback at different times
	if (callbackInvoked === false)
	{
		callback(node, state);
	}
}

function incrementTop(stack)
{
	stack[stack.length - 1]++;
}

function removeTop(stack)
{
	stack.pop();
}

module.exports = each;


text:
import boto.exception
from boto.compat import json
import requests
import boto

class SearchServiceException(Exception):
    pass

class CommitMismatchError(Exception):
    pass

class EncodingError(Exception):
    """
    Content sent for Cloud Search indexing was incorrectly encoded.

    This usually happens when a document is marked as unicode but non-unicode
    characters are present.
    """
    pass

class ContentTooLongError(Exception):
    """
    Content sent for Cloud Search indexing was too long

    This will usually happen when documents queued for indexing add up to more
    than the limit allowed per upload batch (5MB)

    """
    pass

class DocumentServiceConnection(object):
    """
    A CloudSearch document service.

    The DocumentServiceConection is used to add, remove and update documents in
    CloudSearch. Commands are uploaded to CloudSearch in SDF (Search Document Format).

    To generate an appropriate SDF, use :func:`add` to add or update documents,
    as well as :func:`delete` to remove documents.

    Once the set of documents is ready to be index, use :func:`commit` to send the
    commands to CloudSearch.

    If there are a lot of documents to index, it may be preferable to split the
    generation of SDF data and the actual uploading into CloudSearch. Retrieve
    the current SDF with :func:`get_sdf`. If this file is the uploaded into S3,
    it can be retrieved back afterwards for upload into CloudSearch using
    :func:`add_sdf_from_s3`.

    The SDF is not cleared after a :func:`commit`. If you wish to continue
    using the DocumentServiceConnection for another batch upload of commands,
    you will need to :func:`clear_sdf` first to stop the previous batch of
    commands from being uploaded again.

    """

    def __init__(self, domain=None, endpoint=None):
        self.domain = domain
        self.endpoint = endpoint
        if not self.endpoint:
            self.endpoint = domain.doc_service_endpoint
        self.documents_batch = []
        self._sdf = None

    def add(self, _id, version, fields, lang='en'):
        """
        Add a document to be processed by the DocumentService

        The document will not actually be added until :func:`commit` is called

        :type _id: string
        :param _id: A unique ID used to refer to this document.

        :type version: int
        :param version: Version of the document being indexed. If a file is
            being reindexed, the version should be higher than the existing one
            in CloudSearch.

        :type fields: dict
        :param fields: A dictionary of key-value pairs to be uploaded .

        :type lang: string
        :param lang: The language code the data is in. Only 'en' is currently
            supported
        """

        d = {'type': 'add', 'id': _id, 'version': version, 'lang': lang,
            'fields': fields}
        self.documents_batch.append(d)

    def delete(self, _id, version):
        """
        Schedule a document to be removed from the CloudSearch service

        The document will not actually be scheduled for removal until :func:`commit` is called

        :type _id: string
        :param _id: The unique ID of this document.

        :type version: int
        :param version: Version of the document to remove. The delete will only
            occur if this version number is higher than the version currently
            in the index.
        """

        d = {'type': 'delete', 'id': _id, 'version': version}
        self.documents_batch.append(d)

    def get_sdf(self):
        """
        Generate the working set of documents in Search Data Format (SDF)

        :rtype: string
        :returns: JSON-formatted string of the documents in SDF
        """

        return self._sdf if self._sdf else json.dumps(self.documents_batch)

    def clear_sdf(self):
        """
        Clear the working documents from this DocumentServiceConnection

        This should be used after :func:`commit` if the connection will be reused
        for another set of documents.
        """

        self._sdf = None
        self.documents_batch = []

    def add_sdf_from_s3(self, key_obj):
        """
        Load an SDF from S3

        Using this method will result in documents added through
        :func:`add` and :func:`delete` being ignored.

        :type key_obj: :class:`boto.s3.key.Key`
        :param key_obj: An S3 key which contains an SDF
        """
        #@todo:: (lucas) would be nice if this could just take an s3://uri..."

        self._sdf = key_obj.get_contents_as_string()

    def commit(self):
        """
        Actually send an SDF to CloudSearch for processing

        If an SDF file has been explicitly loaded it will be used. Otherwise,
        documents added through :func:`add` and :func:`delete` will be used.

        :rtype: :class:`CommitResponse`
        :returns: A summary of documents added and deleted
        """

        sdf = self.get_sdf()

        if ': null' in sdf:
            boto.log.error('null value in sdf detected.  This will probably raise '
                '500 error.')
            index = sdf.index(': null')
            boto.log.error(sdf[index - 100:index + 100])

        url = "http://%s/2011-02-01/documents/batch" % (self.endpoint)

        # Keep-alive is automatic in a post-1.0 requests world.
        session = requests.Session()
        adapter = requests.adapters.HTTPAdapter(
            pool_connections=20,
            pool_maxsize=50,
            max_retries=5
        )
        session.mount('http://', adapter)
        session.mount('https://', adapter)
        r = session.post(url, data=sdf, headers={'Content-Type': 'application/json'})

        return CommitResponse(r, self, sdf)

class CommitResponse(object):
    """Wrapper for response to Cloudsearch document batch commit.

    :type response: :class:`requests.models.Response`
    :param response: Response from Cloudsearch /documents/batch API

    :type doc_service: :class:`boto.cloudsearch.document.DocumentServiceConnection`
    :param doc_service: Object containing the documents posted and methods to
        retry

    :raises: :class:`boto.exception.BotoServerError`
    :raises: :class:`boto.cloudsearch.document.SearchServiceException`
    :raises: :class:`boto.cloudsearch.document.EncodingError`
    :raises: :class:`boto.cloudsearch.document.ContentTooLongError`
    """
    def __init__(self, response, doc_service, sdf):
        self.response = response
        self.doc_service = doc_service
        self.sdf = sdf

        _body = response.content.decode('utf-8')

        try:
            self.content = json.loads(_body)
        except:
            boto.log.error('Error indexing documents.\nResponse Content:\n{0}\n\n'
                'SDF:\n{1}'.format(_body, self.sdf))
            raise boto.exception.BotoServerError(self.response.status_code, '',
                body=_body)

        self.status = self.content['status']
        if self.status == 'error':
            self.errors = [e.get('message') for e in self.content.get('errors',
                [])]
            for e in self.errors:
                if "Illegal Unicode character" in e:
                    raise EncodingError("Illegal Unicode character in document")
                elif e == "The Content-Length is too long":
                    raise ContentTooLongError("Content was too long")
            if 'adds' not in self.content or 'deletes' not in self.content:
                raise SearchServiceException("Error indexing documents"
                    " => %s" % self.content.get('message', ''))
        else:
            self.errors = []

        self.adds = self.content['adds']
        self.deletes = self.content['deletes']
        self._check_num_ops('add', self.adds)
        self._check_num_ops('delete', self.deletes)

    def _check_num_ops(self, type_, response_num):
        """Raise exception if number of ops in response doesn't match commit

        :type type_: str
        :param type_: Type of commit operation: 'add' or 'delete'

        :type response_num: int
        :param response_num: Number of adds or deletes in the response.

        :raises: :class:`boto.cloudsearch.document.CommitMismatchError`
        """
        commit_num = len([d for d in self.doc_service.documents_batch
            if d['type'] == type_])

        if response_num != commit_num:
            raise CommitMismatchError(
                'Incorrect number of {0}s returned. Commit: {1} Response: {2}'\
                .format(type_, commit_num, response_num))