text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ic_setting_pre" android:state_focused="true" android:state_pressed="true"/>
    <item android:drawable="@drawable/ic_setting_pre" android:state_focused="false" android:state_pressed="true"/>
    <item android:drawable="@drawable/ic_setting_pre" android:state_focused="true" android:state_selected="false"/>
    <item android:drawable="@drawable/ic_setting"/>
</selector>


text:
package com.powerblock.timesheets.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

import com.powerblock.timesheets.R;

public class MaterialsFragment extends Fragment {

	public MaterialsFragment(){
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
		setHasOptionsMenu(false);
		return inflater.inflate(R.layout.materials_fragment, container,false);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
		super.onCreateOptionsMenu(menu, inflater);
	}

}

redpajama_set_name: RedPajamaGithub


text:
# TileStrata
[![NPM version](http://img.shields.io/npm/v/tilestrata.svg?style=flat)](https://www.npmjs.org/package/tilestrata)
[![Build Status](http://img.shields.io/travis/naturalatlas/tilestrata/master.svg?style=flat)](https://travis-ci.org/naturalatlas/tilestrata)
[![Coverage Status](http://img.shields.io/coveralls/naturalatlas/tilestrata/master.svg?style=flat)](https://coveralls.io/r/naturalatlas/tilestrata)

TileStrata is a pluggable "slippy map" tile server that emphasizes code-as-configuration. It's clean, highly tested, and performant. After using [TileStache](http://tilestache.org/) (excellent) we decided we needed something that more-closely matched our stack: Node.js. The primary goal is painless extendability.

```sh
$ npm install tilestrata --save
```

### Introduction

TileStrata consists of three main actors, usually implemented as plugins:

- [*"provider"*](#writing-providers) – Generates a new tile (e.g mapnik)
- [*"cache"*](#writing-caches) – Persists a tile for later requests (e.g. filesystem)
- [*"transform"*](#writing-tranforms) – Takes a raw tile and transforms it (e.g. image scaling / compression)
- [*"request hook"*](#writing-request-hooks) – Called at the very beginning of a tile request.
- [*"response hook"*](#writing-response-hooks) – Called right before a tile is served to the client.

#### List of Plugins

- [tilestrata-mapnik](https://github.com/naturalatlas/tilestrata-mapnik) – Render tiles with [mapnik](http://mapnik.org/).
- [tilestrata-disk](https://github.com/naturalatlas/tilestrata-disk) – Cache map tiles to the filesystem.
- [tilestrata-dependency](https://github.com/naturalatlas/tilestrata-dependency) – Fetch tiles from other layers.
- [tilestrata-sharp](https://github.com/naturalatlas/tilestrata-sharp) – Compress, resize, transcode tiles (jpg, png, webp) using [libvips](https://www.npmjs.com/package/sharp).
- [tilestrata-gm](https://github.com/naturalatlas/tilestrata-gm) – Perform all sorts of image operations on tiles using [GraphicsMagick](https://www.npmjs.com/package/gm).
- [tilestrata-headers](https://github.com/naturalatlas/tilestrata-headers) – Set/override response headers.
- [tilestrata-blend](https://github.com/naturalatlas/tilestrata-blend) – Stack multiple layers together.
- [tilestrata-jsonp](https://github.com/naturalatlas/tilestrata-jsonp) – Serve utfgrids (and other JSON) as JSONP.
- [tilestrata-datadog](https://github.com/naturalatlas/tilestrata-datadog) – Send timing information to [Datadog](https://www.datadoghq.com/).
- [tilestrata-utfmerge](https://github.com/naturalatlas/tilestrata-utfmerge) – Merge UTF interactivity grids from mapnik.
- [tilestrata-vtile](https://github.com/naturalatlas/tilestrata-vtile) – Outputs mapnik vector tiles (protobufs).
- [tilestrata-vtile-raster](https://github.com/naturalatlas/tilestrata-vtile-raster) – Renders mapnik vector tiles into raster images.

## Configuration

```js
var tilestrata = require('tilestrata');
var disk = require('tilestrata-disk');
var sharp = require('tilestrata-sharp');
var mapnik = require('tilestrata-mapnik');
var dependency = require('tilestrata-dependency');
var strata = tilestrata.createServer();

// define layers
strata.layer('basemap')
    .route('tile@2x.png')
        .use(disk({dir: '/var/lib/tiles/basemap'}))
        .use(mapnik({
            xml: '/path/to/map.xml',
            tileSize: 512,
            scale: 2
        }))
    .route('tile.png')
        .use(disk({dir: '/var/lib/tiles/basemap'}))
        .use(dependency('basemap', 'tile@2x.png'))
        .use(sharp(function(image, sharp) {
            return image.resize(256);
        }));

// start accepting requests
strata.listen(8080);
```

Once configured and started, tiles can be accessed via:

```
/:layer/:z/:x:/:y/:filename
```

### Integrate with [Express.js](http://expressjs.com/) / [Connect](https://github.com/senchalabs/connect)

TileStrata comes with middleware for Express that makes serving tiles from an existing application really simple, eliminating the need to call `listen` on `strata`.

```js
var tilestrata = require('tilestrata');
var strata = tilestrata.createServer();
strata.layer('basemap') /* ... */
strata.layer('contours') /* ... */

app.use(tilestrata.middleware({
    server: strata,
    prefix: '/maps'
}));
```

## Usage Notes

### Rebuilding the Tile Cache

If you update your map styles or data, you'll probably want to update your tiles. Rather than dump of them at once and bring your tile server to a crawl, progressively rebuild the cache by requesting tiles with the `X-TileStrata-SkipCache` header. [TileMantle](https://github.com/naturalatlas/tilemantle) makes this process easy:

```
npm install -g tilemantle
tilemantle http://myhost.com/mylayer/{z}/{x}/{y}/t.png \
    -p 44.9457507,-109.5939822 -b 30mi -z 10-14 \
    -H "X-TileStrata-SkipCache:mylayer/t.png"
```

For the sake of the [tilestrata-dependency](https://github.com/naturalatlas/tilestrata-dependency) plugin, the value of the header is expected to be in the format:

```
X-TileStrata-SkipCache:*
X-TileStrata-SkipCache:[layer]/[file],[layer]/[file],...
```

In advanced use cases, it might be necessary for tiles to not be returned by the server until the cache is actually written (particularly when order matters due to dependencies). To achieve this, use:

```
X-TileStrata-CacheWait:1
```

## API Reference

#### [TileServer](#tileserver)

##### server.listen(port, [hostname], [callback])
Starts accepting requests on the specified port. The arguments to this method are exactly identical to node's http.Server [listen()](http://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback) method.

##### server.layer(name, [opts])
Registers a new layer with the given name and returns its [TileLayer](#tilelayer) instance. If the layer already exists, the existing instance will be returned. Whatever name is used will be the first part of the url that can be used to fetch tiles: `/:layer/...`. The following options can be provided:

  - **bbox**: A bounding box ([GeoJSON "bbox" format](http://geojson.org/geojson-spec.html#bounding-boxes)) that defines the valid extent of the layer. Any requests for tiles outside of this region will result in a 404 Not Found.
  - **minZoom**: The minimum `z` to return tiles for. Anything lesser will return a 404 Not Found.
  - **maxZoom**: The maximum `z` to return tiles for. Anything greater will return a 404 Not Found.

##### server.getTile(layer, filename, x, y, z, callback)
Attempts to retrieve a tile from the specified layer (string). The callback will be invoked with three arguments: `err`, `buffer`, and `headers`.

##### server.version
The version of TileStrata (useful to plugins, mainly).

#### [TileLayer](#tilelayer)

##### layer.route(filename, [options])

Registers a route. Returns a [TileRequestHandler](#tilerequesthandler) instance to be configured. The available options are:

  - **cacheFetchMode**: Defines how cache fetching happens when multiple caches are configured. The mode can be `"sequential"` or `"race"`. If set to `"race"`, TileStrata will fetch from all caches simultaneously and return the first that wins.

#### [TileRequestHandler](#tilerequesthandler)

##### handler.use(plugin)
Registers a plugin, which is either a provider, cache, transform, request hook, response hook, or combination of them. See the READMEs on the prebuilt plugins and/or the ["Writing TileStrata Plugins"](#writing-tilestrata-plugins) section below for more info.

#### [TileRequest](#tilerequest)

A request contains these properties: `x`, `y`, `z`, `layer` (string), `filename`, `method`, `headers`, and `qs`.

##### tile.clone()
Returns an identical copy of the tile request that's safe to mutate.

## Writing TileStrata Plugins

### Writing Request Hooks

A request hook implementation needs one method: `reqhook`. Optionally it can include an `init` method that gets called when the server is initializing. The hook's "req" will be a [http.IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage) and "res" will be the [http.ServerResponse](http://nodejs.org/api/http.html#http_class_http_serverresponse). This makes it possible to respond without even getting to the tile-serving logic (just don't call the callback).

```js
module.exports = function(options) {
    return {
        init: function(server, callback) {
            callback(err);
        },
        reqhook: function(server, tile, req, res, callback) {
            callback();
        }
    };
};
```

### Writing Caches

A cache implementation needs two methods: `get`, `set`. Optionally a cache can declare an `init` method that gets called when the server is initializing. If a cache fails (returns an error to the callback), the server will ignore the error and attempt to serve the tile from the registered provider.

```js
module.exports = function(options) {
    return {
        init: function(server, callback) {
            callback(err);
        },
        get: function(server, tile, callback) {
            callback(err, buffer, headers);
        },
        set: function(server, tile, buffer, headers, callback) {
            callback(err);
        }
    };
};
```

### Writing Providers

Providers are responsible for building tiles. A provider must define a `serve` method and optionally an `init` method that is called when the server starts.

```js
module.exports = function(options) {
    return {
        init: function(server, callback) {
            callback(err);
        },
        serve: function(server, tile, callback) {
            callback(err, buffer, headers);
        }
    };
};
```

### Writing Transforms

Transforms modify the result from a provider before it's served (and cached). A tranform must define a `transform` method and optionally an `init` method.

```js
module.exports = function(options) {
    return {
        init: function(server, callback) {
            callback(err);
        },
        transform: function(server, tile, buffer, headers, callback) {
            callback(err, buffer, headers);
        }
    };
};
```

### Writing Response Hooks

A response hook implementation needs one method: `reshook`. Optionally it can include an `init` method that gets called when the server is initializing. The hook's "req" will be a [http.IncomingMessage](http://nodejs.org/api/http.html#http_http_incomingmessage) and "res" will be the [http.ServerResponse](http://nodejs.org/api/http.html#http_class_http_serverresponse). The "result" argument contains three properties: `headers`, `buffer`, and `status` — each of which can be modified to affect the final response.

```js
module.exports = function(options) {
    return {
        init: function(server, callback) {
            callback(err);
        },
        reshook: function(server, tile, req, res, result, callback) {
            callback();
        }
    };
};
```

### Multi-Function Plugins

Sometimes a plugin must consist of multiple parts. For instance, a plugin tracking response times must register a request hook and response hook. To accomodate this, TileStrata supports arrays:
```js
module.exports = function() {
    return [
        {reqhook: function(...) { /* ... */ }},
        {reshook: function(...) { /* ... */ }}
    ];
};
```

## Contributing

Before submitting pull requests, please update the [tests](test) and make sure they all pass.

```sh
$ npm test
```

## License

Copyright © 2014–2015 [Natural Atlas, Inc.](https://github.com/naturalatlas) & [Contributors](https://github.com/naturalatlas/tilestrata/graphs/contributors)

Licensed 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.


text:
from typing import Optional

from appium.options.common.supports_capabilities import SupportsCapabilities

WDA_BASE_URL = 'wdaBaseUrl'

class WdaBaseUrlOption(SupportsCapabilities):
    @property
    def wda_base_url(self) -> Optional[str]:
        """
        Prefix to build a custom WebDriverAgent URL.
        """
        return self.get_capability(WDA_BASE_URL)

    @wda_base_url.setter
    def wda_base_url(self, value: str) -> None:
        """
        This value, if specified, will be used as a prefix to build a custom
        WebDriverAgent url. It is different from webDriverAgentUrl, because
        if the latter is set then it expects WebDriverAgent to be already
        listening and skips the building phase. Defaults to http://localhost.
        """
        self.set_capability(WDA_BASE_URL, value)


text:
class BashPreexec < Formula
  desc "preexec and precmd functions for Bash just like Zsh."
  homepage "https://github.com/rcaloras/bash-preexec"
  url "https://github.com/rcaloras/bash-preexec/archive/0.3.0.tar.gz"
  sha256 "0b75f66dc956cd205d9f0259fff23839d704699f5679ae37d0e43e8cf50b3b18"

  head "https://github.com/rcaloras/bash-preexec.git"

  bottle :unneeded

  def install
    (prefix/"etc/profile.d").install "bash-preexec.sh"
  end

  def caveats; <<-EOS.undent
    Add the following line to your bash profile (e.g. ~/.bashrc, ~/.profile, or ~/.bash_profile)

      [[ -f $(brew --prefix)/etc/profile.d/bash-preexec.sh ]] && . $(brew --prefix)/etc/profile.d/bash-preexec.sh

    EOS
  end

  test do
    # Just testing that the file is installed
    assert File.exist?("#{prefix}/etc/profile.d/bash-preexec.sh")
  end
end


text:
package cc.dividebyzero.swearspear.gui;

import java.util.Locale;

import cc.dividebyzero.swearspear.R;
import cc.dividebyzero.swearspear.R.layout;
import cc.dividebyzero.swearspear.gui.fragments.ControlPanelFragment;
import cc.dividebyzero.swearspear.gui.fragments.StringGallerySelectorFragment;
import cc.dividebyzero.swearspear.gui.fragments.ControlPanelFragment.CPFCallback;
import cc.dividebyzero.swearspear.gui.fragments.StringSelectorFragment;
import cc.dividebyzero.swearspear.gui.fragments.StringSelectorFragment.StringEventListener;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

public class SwearSpearActivity extends FragmentActivity implements CPFCallback, OnInitListener, StringEventListener {

    private static final String    LOG_TAG          = SwearSpearActivity.class.getSimpleName();

    private static final int       MSG_DO_RANDOMIZE = 10;
    private static final int       MSG_DO_SPEAK     = 20;

    private Handler                mHandler         = new Handler() {

                                                        @Override
                                                        public void handleMessage(Message msg) {
                                                            super.handleMessage(msg);
                                                            final int what = msg.what;

                                                            if (what == MSG_DO_RANDOMIZE)
                                                          {
                                                              randomizeInsult();
                                                          } else if (what == MSG_DO_SPEAK)
                                                    {
                                                        speakInsult();
                                                    }
                                                }

                                                    };

    private ControlPanelFragment   mControlPanel    = null;

    private StringSelectorFragment mRow1Selector    = null;
    private StringSelectorFragment mRow2Selector    = null;
    private StringSelectorFragment mRow3Selector    = null;

    private TextToSpeech           mTts;

    private StringBuffer buffy=new StringBuffer();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.swearspear_acv);

        mTts = new TextToSpeech(
                        getApplicationContext(),
                        this // TextToSpeech.OnInitListener
        );

        mControlPanel = new ControlPanelFragment();
        mControlPanel.setCallback(this);

        // Execute a transaction, replacing any existing fragment
        // with this one inside the frame.
        android.support.v4.app.FragmentTransaction ft;
        ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.secondary_container, mControlPanel, "cfp1");
        ft.commit();

        initSelectorFragments();

    }

    private void initSelectorFragments() {

        android.support.v4.app.FragmentTransaction ft;

        //TODO: depending on orientation && ft tyype
        mRow1Selector=new StringGallerySelectorFragment();
        mRow1Selector.setEventListener(this);

        ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.first_sel_container, mRow1Selector, "row1");
        ft.commit();

        mRow2Selector=new StringGallerySelectorFragment();
        mRow2Selector.setEventListener(this);

        ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.second_sel_container, mRow2Selector, "row2");
        ft.commit();

        mRow3Selector=new StringGallerySelectorFragment();
        mRow3Selector.setEventListener(this);

        ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.third_sel_container, mRow3Selector, "row3");
        ft.commit();

        mRow1Selector.setArrayResourceId(R.array.row1);
        mRow2Selector.setArrayResourceId(R.array.row2);
        mRow3Selector.setArrayResourceId(R.array.row3);
    }

    public void onRandomizePressed() {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_DO_RANDOMIZE));

    }

    public void onSpeakPressed() {
        mHandler.sendMessage(mHandler.obtainMessage(MSG_DO_SPEAK));

    }

    protected void randomizeInsult() {
        if(mRow1Selector!=null)
        {
            mRow1Selector.makeRandomSelection();
        }
        if(mRow2Selector!=null)
        {
            mRow2Selector.makeRandomSelection();
        }
        if(mRow3Selector!=null)
        {
            mRow3Selector.makeRandomSelection();
        }
    }

    private void speakInsult() {
        if (mControlPanel != null)
        {
            final String text = mControlPanel.getCurrentText();

            speechOutput(text);
        }

    }

    private void speechOutput(final String text) {
        if (mTts == null) return;
        mTts.speak(text,
                        TextToSpeech.QUEUE_FLUSH, // Drop all pending entries in the playback queue.
                        null
                        );
    }

    public void onInit(int status) {
        // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
        if (status == TextToSpeech.SUCCESS)
        {
            // Set preferred language to US english.
            // Note that a language may not be available, and the result will indicate this.
            int result = mTts.setLanguage(Locale.US);
            // Try this someday for some interesting results.
            // int result mTts.setLanguage(Locale.FRANCE);
            if (result == TextToSpeech.LANG_MISSING_DATA ||
                            result == TextToSpeech.LANG_NOT_SUPPORTED)
            {
                // Lanuage data is missing or the language is not supported.
                Log.e(LOG_TAG, "Language is not available.");
            } else
            {
                // Check the documentation for other possible result codes.
                // For example, the language may be available for the locale,
                // but not for the specified country and variant.

            }
        } else
        {
            // Initialization failed.
            Log.e(LOG_TAG, "Could not initialize TextToSpeech.");
            Toast.makeText(getApplicationContext(), R.string.tts_error, Toast.LENGTH_LONG).show();
            if (mControlPanel != null)
            {
                mControlPanel.disableSpeak();
            }

        }

    }

    public void onItemSelected(final int selectorId,String item) {
        buffy.setLength(0);

        if(selectorId==R.array.row1)
        {
            setCurrentDisplayedText(item);
        }else if(selectorId==R.array.row2 || selectorId==R.array.row3)
        {

             buffy.append(getCurrentDisplayedText());
             buffy.append(" ");
             buffy.append(item);
             setCurrentDisplayedText(buffy.toString());

        }

    }

    private String getCurrentDisplayedText(){
        if(mControlPanel!=null)
        {
            return mControlPanel.getCurrentText();
        }
        return "";
    }

    private void setCurrentDisplayedText(final String text){
        if(mControlPanel!=null)
        {
            mControlPanel.setCurrentText(text);
        }
    }

}


text:
package main

import (
	"bytes"
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/log/level"
	"gopkg.in/alecthomas/kingpin.v2"
	"gopkg.in/yaml.v2"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/prometheus/common/expfmt"
	"github.com/prometheus/common/promlog"
	"github.com/prometheus/common/promlog/flag"
	"github.com/prometheus/common/version"

	"github.com/prometheus/blackbox_exporter/config"
	"github.com/prometheus/blackbox_exporter/prober"
)

var (
	sc = &config.SafeConfig{
		C: &config.Config{},
	}

	configFile    = kingpin.Flag("config.file", "Blackbox exporter configuration file.").Default("blackbox.yml").String()
	listenAddress = kingpin.Flag("web.listen-address", "The address to listen on for HTTP requests.").Default(":9115").String()
	timeoutOffset = kingpin.Flag("timeout-offset", "Offset to subtract from timeout in seconds.").Default("0.5").Float64()

	Probers = map[string]prober.ProbeFn{
		"http": prober.ProbeHTTP,
		"tcp":  prober.ProbeTCP,
		"icmp": prober.ProbeICMP,
		"dns":  prober.ProbeDNS,
	}
)

func probeHandler(w http.ResponseWriter, r *http.Request, c *config.Config, logger log.Logger) {
	moduleName := r.URL.Query().Get("module")
	if moduleName == "" {
		moduleName = "http_2xx"
	}
	module, ok := c.Modules[moduleName]
	if !ok {
		http.Error(w, fmt.Sprintf("Unknown module %q", moduleName), 400)
		return
	}

	// If a timeout is configured via the Prometheus header, add it to the request.
	var timeoutSeconds float64
	if v := r.Header.Get("X-Prometheus-Scrape-Timeout-Seconds"); v != "" {
		var err error
		timeoutSeconds, err = strconv.ParseFloat(v, 64)
		if err != nil {
			http.Error(w, fmt.Sprintf("Failed to parse timeout from Prometheus header: %s", err), http.StatusInternalServerError)
			return
		}
	}
	if timeoutSeconds == 0 {
		timeoutSeconds = 10
	}

	if module.Timeout.Seconds() < timeoutSeconds && module.Timeout.Seconds() > 0 {
		timeoutSeconds = module.Timeout.Seconds()
	}
	timeoutSeconds -= *timeoutOffset
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutSeconds*1e9))
	defer cancel()
	r = r.WithContext(ctx)

	probeSuccessGauge := prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "probe_success",
		Help: "Displays whether or not the probe was a success",
	})
	probeDurationGauge := prometheus.NewGauge(prometheus.GaugeOpts{
		Name: "probe_duration_seconds",
		Help: "Returns how long the probe took to complete in seconds",
	})
	params := r.URL.Query()
	target := params.Get("target")
	if target == "" {
		http.Error(w, "Target parameter is missing", 400)
		return
	}

	prober, ok := Probers[module.Prober]
	if !ok {
		http.Error(w, fmt.Sprintf("Unknown prober %q", module.Prober), 400)
		return
	}

	sl := newScrapeLogger(logger, moduleName, target)
	level.Info(sl).Log("msg", "Beginning probe", "probe", module.Prober, "timeout_seconds", timeoutSeconds)

	start := time.Now()
	registry := prometheus.NewRegistry()
	registry.MustRegister(probeSuccessGauge)
	registry.MustRegister(probeDurationGauge)
	success := prober(ctx, target, module, registry, sl)
	duration := time.Since(start).Seconds()
	probeDurationGauge.Set(duration)
	if success {
		probeSuccessGauge.Set(1)
		level.Info(sl).Log("msg", "Probe succeeded", "duration_seconds", duration)
	} else {
		level.Error(sl).Log("msg", "Probe failed", "duration_seconds", duration)
	}

	debug := false
	if r.URL.Query().Get("debug") == "true" {
		debug = true
	}

	if debug {
		w.Header().Set("Content-Type", "text/plain")
		fmt.Fprintf(w, "Logs for the probe:\n")
		sl.buffer.WriteTo(w)
		fmt.Fprintf(w, "\n\n\nMetrics that would have been returned:\n")
		mfs, err := registry.Gather()
		if err != nil {
			fmt.Fprintf(w, "Error gathering metrics: %s\n", err)
		}
		for _, mf := range mfs {
			expfmt.MetricFamilyToText(w, mf)
		}
		fmt.Fprintf(w, "\n\n\nModule configuration:\n")
		c, err := yaml.Marshal(module)
		if err != nil {
			fmt.Fprintf(w, "Error marshalling config: %s\n", err)
		}
		w.Write(c)
		return
	}

	h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
	h.ServeHTTP(w, r)
}

type scrapeLogger struct {
	next         log.Logger
	module       string
	target       string
	buffer       bytes.Buffer
	bufferLogger log.Logger
}

func newScrapeLogger(logger log.Logger, module string, target string) *scrapeLogger {
	logger = log.With(logger, "module", module, "target", target)
	sl := &scrapeLogger{
		next:   logger,
		buffer: bytes.Buffer{},
	}
	bl := log.NewLogfmtLogger(&sl.buffer)
	sl.bufferLogger = log.With(bl, "ts", log.DefaultTimestampUTC, "caller", log.Caller(6), "module", module, "target", target)
	return sl
}

func (sl scrapeLogger) Log(keyvals ...interface{}) error {
	sl.bufferLogger.Log(keyvals...)
	kvs := make([]interface{}, len(keyvals))
	copy(kvs, keyvals)
	// Switch level to debug for application output.
	for i := 0; i < len(kvs); i += 2 {
		if kvs[i] == level.Key() {
			kvs[i+1] = level.DebugValue()
		}
	}
	return sl.next.Log(kvs...)
}

func init() {
	prometheus.MustRegister(version.NewCollector("blackbox_exporter"))
}

func main() {
	allowedLevel := promlog.AllowedLevel{}
	flag.AddFlags(kingpin.CommandLine, &allowedLevel)
	kingpin.Version(version.Print("blackbox_exporter"))
	kingpin.HelpFlag.Short('h')
	kingpin.Parse()
	logger := promlog.New(allowedLevel)

	level.Info(logger).Log("msg", "Starting blackbox_exporter", "version", version.Info())
	level.Info(logger).Log("msg", "Build context", version.BuildContext())

	if err := sc.ReloadConfig(*configFile); err != nil {
		level.Error(logger).Log("msg", "Error loading config", "err", err)
		os.Exit(1)
	}
	level.Info(logger).Log("msg", "Loaded config file")

	hup := make(chan os.Signal)
	reloadCh := make(chan chan error)
	signal.Notify(hup, syscall.SIGHUP)
	go func() {
		for {
			select {
			case <-hup:
				if err := sc.ReloadConfig(*configFile); err != nil {
					level.Error(logger).Log("msg", "Error reloading config", "err", err)
					continue
				}
				level.Info(logger).Log("msg", "Reloaded config file")
			case rc := <-reloadCh:
				if err := sc.ReloadConfig(*configFile); err != nil {
					level.Error(logger).Log("msg", "Error reloading config", "err", err)
					rc <- err
				} else {
					level.Info(logger).Log("msg", "Reloaded config file")
					rc <- nil
				}
			}
		}
	}()

	http.HandleFunc("/-/reload",
		func(w http.ResponseWriter, r *http.Request) {
			if r.Method != "POST" {
				w.WriteHeader(http.StatusMethodNotAllowed)
				fmt.Fprintf(w, "This endpoint requires a POST request.\n")
				return
			}

			rc := make(chan error)
			reloadCh <- rc
			if err := <-rc; err != nil {
				http.Error(w, fmt.Sprintf("failed to reload config: %s", err), http.StatusInternalServerError)
			}
		})
	http.Handle("/metrics", promhttp.Handler())
	http.HandleFunc("/probe", func(w http.ResponseWriter, r *http.Request) {
		sc.Lock()
		conf := sc.C
		sc.Unlock()
		probeHandler(w, r, conf, logger)
	})
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`
    <title>Blackbox Exporter</title>

Blackbox Exporter

Probe prometheus.io for http_2xx

Debug probe prometheus.io for http_2xx

Metrics

Configuration

    `))
	})

	http.HandleFunc("/config", func(w http.ResponseWriter, r *http.Request) {
		sc.RLock()
		c, err := yaml.Marshal(sc.C)
		sc.RUnlock()
		if err != nil {
			level.Warn(logger).Log("msg", "Error marshalling configuration", "err", err)
			http.Error(w, err.Error(), 500)
			return
		}
		w.Write(c)
	})

	level.Info(logger).Log("msg", "Listening on address", "address", *listenAddress)
	if err := http.ListenAndServe(*listenAddress, nil); err != nil {
		level.Error(logger).Log("msg", "Error starting HTTP server", "err", err)
		os.Exit(1)
	}
}


text:
<?php namespace Hive\Locator;

class Object extends Library implements Contract\Object
{

    /**
     * Default configuration settings.
     *
     * @var array config default object configuration for the library.
     * @var array ['legend'] : array : Legend used to create the map, ie. what to call each of the array keys (in order)
     * @var array ['aliases'] : array : Alias to the legend as methods $environment->in('staging'); $environment->is('domain.com.au');
     * @var array ['driver'] : string|object : The driver which will compare our value to see if it is a match
     * @var array ['current'] : array : Allow access to the current result from these names;
     * @var array ['access'] : array : Whether to allow access to the result through method calls, property calls or a 'current'.
     * @var array ['current'] : array : Any names which to allow access to the current result.
     */
    protected $config = [
        'legend'    => ['server', 'type', 'domain'],
        'aliases'   => ['in' => 'server', 'as' => 'type', 'is' => 'domain'],
        'driver'    => 'Hive\Locator\Driver\Simple',
        'access'    => ['method' => true, 'property' => true, 'current' => true],
        'current'   => ['current']
    ];

    /**
     * Object constructor.
     *
     * Merge the object config with the libraries
     *
     * @param array $map
     * @param array $config
     */
    public function __construct(array $map, array $config = [])
    {

        // Merge the received config with the defaults
        $config = array_merge($this->config, $config);

        parent::__construct($map, $config);
    }

    /**
     * Will allow access to the result through properties.
     *
     * Allows access to the result, through property calls on the object,
     * depending on config, it can allow access via the legend, current or alias.
     * @param $name
     *
     * @return bool|object
     * @throws Exception\UndefinedProperty
     */
    public function __get($name)
    {
        // If magic properties are turned on
        if ($this->config['access']['property'])
        {
            // If we have a value, return it
            if ($value = $this->magic($name)) {
                return $value;
            }
        }

        // Throw a Bad Method call as the method wasn't found.
        throw new Exception\UndefinedProperty(__CLASS__, $name);
    }

    /**
     * Will allow access to the result through a method call.
     *
     * Allows access to the result through a method call on the object, depending on the config.
     * It can allow access via the legend, current or alias. To enable, ensure that 'method is with in Config['access'].
     *
     * If an argument is sent to, it will compare the argument with the result and return a true/false boolean.
     *
     * @param $name
     * @param $arguments
     *
     * @return bool|object
     * @throws Exception\BadMethodCall
     * @throws Exception\UnresolvedLegend
     */
    public function __call($name, $arguments)
    {

        // If magic methods are turned on
        if ($this->config['access']['method'])
        {
            // If we have a value
            if ($value = $this->magic($name))
            {
                // If there was an argument sent in, compare the values.
                if (isset($arguments[0]))
                {
                    $value = ($value == $arguments[0]);
                }

                return $value;
            }
        }

        // Throw a Bad Method call as the method wasn't found.
        throw new Exception\BadMethodCall(__CLASS__, $name);
    }

    /**
     * Method used to find items from their legend, alias or current.
     *
     * @param $name
     *
     * @return bool|object
     * @throws Exception\UnresolvedLegend
     */
    private function magic($name)
    {
        // Make sure we have a result
        if ($this->status)
        {
            // If the current property is set and the called property, return the current result.
            if (in_array($name, $this->config['current']))
            {
                return (object) $this->result;
            }

            // Return the current item directly by a call to its legend property
            if (in_array($name, $this->config['legend']))
            {
                return $this->result[$name];
            }

            // Return the current item directly by a call to its alias
            if (in_array($name, array_keys($this->config['aliases'])))
            {
                // Find what legend we are looking for from the alias
                $legend = $this->config['aliases'][$name];
                return $this->result[$legend];
            }

            return false; #:(
        }
        else
        {
            // You can not us ean alias with an unresolved legend.
            throw new Exception\UnresolvedLegend();
        }
    }

    /**
     * Will get the value of items other then the current.
     *
     * Does a fuzzy search, based upon the parameters, any which are sent in as config['current'] it will use the current result.
     *
     * @return \stdClass
     * @throws Exception\UndefinedMapping
     * @throws Exception\UnresolvedLegend
     */
    public function get()
    {
        // Make sure we have a result
        if ($this->status)
        {
            $args = func_get_args();

            $result = $this->map;

            $legends = $this->config['legend'];

            // We don't need the last item, which is the 'result', we add it at the end.
            array_pop($legends);

            // loop through all of the legends and assign them based of the args
            for ($i=0; $i<count($legends); $i++)
            {
                if (isset($args[$i]) && !in_array($args[$i], $this->config['current']))
                {
                    // If the item exists with in our result, use it otherwise throw an exception
                    if (isset($result[$args[$i]]))
                    {
                        $result = $result[$args[$i]];
                        //$map[$legends[$i]] = $args[$i];
                    }
                    else
                    {
                        // There is no mapping of that name, throw an exception.
                        throw new Exception\UndefinedMapping($legends[$i], $args[$i]);
                    }
                }
                else
                {
                    $result = $result[$this->result[$legends[$i]]];
                    $map[$legends[$i]] = $this->result[$legends[$i]];
                }
            }

            $map[end($this->config['legend'])] = $result;

            return (object) $map;
        }
        else
        {
            // You can not us ean alias with an unresolved legend.
            throw new Exception\UnresolvedLegend();
        }
    }
}


text:
package gov.va.vba.persistence.entity;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.hibernate.envers.NotAudited;

import javax.persistence.*;
import java.io.*;
import java.util.UUID;

/**
 * Created by Pete Grazaitis on 4/2/2015.
 */
@MappedSuperclass
public abstract class AbstractEntity implements Serializable {

    private Long id;

    private Integer version;

    private UUID objectId = UUID.randomUUID();

    /**
     * get the ID for the master record
     * @return master record ID
     */
    /**record ID. */
    @Id
//    @GeneratedValue(strategy= GenerationType.AUTO)
    @SequenceGenerator(name = "SEQUENCE_GEN", sequenceName = "BCDS.BCDS_HIBERNATE_SEQUENCE", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCE_GEN")
    public Long getId(){
        return id;
    }

    /**
     * set the ID for the master record
     * @param id ID for the master record
     */
    public void setId(Long id){
        this.id = id;
    }

    /**
     * @return the version
     */
    @Version
    public Integer getVersion() {
        return version;
    }

    /**
     * @param version the version to set
     */
    public void setVersion(Integer version) {
        this.version = version;
    }

    @Column(name="OBJECT_ID")
    @NotAudited
    public UUID getObjectId() {
        if(objectId == null) {
            objectId = UUID.randomUUID();
        }

        return  objectId;
    }

    public void setObjectId(UUID objectId) {
        this.objectId = objectId;
    }

    protected void clearIdentity() {
        setObjectId(UUID.randomUUID()); //Grab unique identifer to leverage. Business logic assumes this will never be null.
        setId(null); //Persistence id is generated upon flush, clearing will allow generation mechanism to create a new one.
        //setLogicalId(null); //TODO: Leverage a generation technique similar to current model of -1,-2, etc for BGS
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if(o == null || !(o instanceof AbstractEntity)) return false;

        AbstractEntity other = (AbstractEntity)o;
        if (this.getObjectId() == null) return false;
        else if (this.getObjectId() == other.getObjectId()) return true;

        return this.getObjectId().equals(other.getObjectId());
    }

    @Override
    public int hashCode() {
        if (this.getObjectId() != null) {
            return this.getObjectId().hashCode();
        } else {
            return super.hashCode(); //This should never fire.
        }
    }

    @Override
    public String toString()
    {
        return ToStringBuilder.reflectionToString(this);
    }

}


text:
 #!/usr/bin/python:
# -*- coding: utf-8 -*-
from sys import argv
import tweepy
import facebook
script, first = argv

def get_api_tweet(cfg):
  auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
  auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
  return tweepy.API(auth)
def main_tweet():
  cfg = {
    "consumer_key"        : " ",
    "consumer_secret"     : " ",
    "access_token"        : " - ",
    "access_token_secret" : " "
    }
  api = get_api_tweet(cfg)
  tweet = "இன்ரைய நாள் காட்டி  #tamilcalender (©belongs to watermarked party),"
 #tweet = 'test'
  image_path = "%s"%first
  status = api.update_with_media(image_path,tweet)
if __name__ == "__main__":
 main_tweet()

def main():
  cfg = {
    "page_id"      : " ",
    "access_token" : " &"
    }
  api = get_api(cfg)
def get_api(cfg):
  graph = facebook.GraphAPI(cfg['access_token'])
  resp = graph.get_object('me/accounts')
  page_access_token = None
  for page in resp['data']:
    if page['id'] == cfg['page_id']:
      page_access_token = page['access_token']
  graph = facebook.GraphAPI(page_access_token)
  #caption = ''
  caption = "இன்ரைய நாள் காட்டி  #tamilcalender (©belongs to watermarked party)"
  albumid = ''
  with open(first,"rb") as image:
          posted_image_id = graph.put_photo(image, caption, albumid)
  return graph
if __name__ == "__main__":
  main()


text:
require 'coveralls'
Coveralls.wear!

require 'calculator'

RSpec.configure do |config|
  config.color = true
end


text:
#include "gtest/gtest.h"

#include "facekit/core/status.hpp"

TEST(Status, DefaultCtor) {
  namespace FK = FaceKit;
  FK::Status s;
  EXPECT_EQ(s.Code(), FK::Status::Type::kOk);
  EXPECT_EQ(s.Message(), "");
}

TEST(Status, SpecificCtor) {
  namespace FK = FaceKit;
  using Type = FK::Status::Type;
  FK::Status s(Type::kInternalError, "Internal Error");
  EXPECT_EQ(s.Code(), Type::kInternalError);
  EXPECT_EQ(s.Message(), "Internal Error");
}

TEST(Status, CopyCtor) {
  namespace FK = FaceKit;
  using Type = FK::Status::Type;
  FK::Status s1(Type::kUnknown, "Unknown");
  FK::Status s2(s1);
  EXPECT_EQ(s1.Code(), s2.Code());
  EXPECT_EQ(s1.Message(), s2.Message());
}

TEST(Status, Assignment) {
  namespace FK = FaceKit;
  using Type = FK::Status::Type;
  FK::Status s1(Type::kInvalidArgument, "Invalid Arg");
  FK::Status s2;
  s2 = s1;
  EXPECT_EQ(s1.Code(), s2.Code());
  EXPECT_EQ(s1.Message(), s2.Message());
}

TEST(Status, Equals) {
  namespace FK = FaceKit;
  using Type = FK::Status::Type;
  FK::Status s1(Type::kInvalidArgument, "Invalid Arg");
  FK::Status s2(Type::kInvalidArgument, "Invalid Arg");
  ASSERT_EQ(s1, s2);
}

TEST(Status, EqualsCopy) {
  namespace FK = FaceKit;
  using Type = FK::Status::Type;
  FK::Status s1(Type::kNotFound, "Not Found");
  FK::Status s2(s1);
  ASSERT_EQ(s1, s2);
}

TEST(Status, EqualsAssignment) {
  namespace FK = FaceKit;
  using Type = FK::Status::Type;
  FK::Status s1(Type::kAlreadyExists, "Exists");
  FK::Status s2 = s1;
  ASSERT_EQ(s1, s2);
}

TEST(Status, DiffCode) {
  namespace FK = FaceKit;
  using Type = FK::Status::Type;
  FK::Status s1(Type::kOutOfRange, "Out");
  FK::Status s2(Type::kInvalidArgument, "Out");
  ASSERT_NE(s1, s2);
}

TEST(Status, DiffMessage) {
  namespace FK = FaceKit;
  using Type = FK::Status::Type;
  FK::Status s1(Type::kOutOfRange, "Out");
  FK::Status s2(Type::kOutOfRange, "Out range");
  ASSERT_NE(s1, s2);
}

TEST(Status, ToString) {
  namespace FK = FaceKit;
  using Type = FK::Status::Type;

  FK::Status s1;
  EXPECT_EQ(s1.ToString(), "Ok");
  FK::Status s2(Type::kUnknown, "message");
  EXPECT_EQ(s2.ToString(), "Unknown: message");
  FK::Status s3(Type::kInvalidArgument, "message");
  EXPECT_EQ(s3.ToString(), "Invalid argument: message");
  FK::Status s4(Type::kNotFound, "message");
  EXPECT_EQ(s4.ToString(), "Not found: message");
  FK::Status s5(Type::kAlreadyExists, "message");
  EXPECT_EQ(s5.ToString(), "Already exists: message");
  FK::Status s6(Type::kOutOfRange, "message");
  EXPECT_EQ(s6.ToString(), "Out of range: message");
  FK::Status s7(Type::kUnimplemented, "message");
  EXPECT_EQ(s7.ToString(), "Unimplemented: message");
  FK::Status s8(Type::kInternalError, "message");
  EXPECT_EQ(s8.ToString(), "Internal error: message");
  FK::Status s9((Type)-10, "message");
  EXPECT_EQ(s9.ToString(), "Unknown code (-10): message");
}

int main(int argc, char* argv[]) {
  // Init gtest framework
  ::testing::InitGoogleTest(&argc, argv);
  // Run unit test
  return RUN_ALL_TESTS();
}


text:
package cc.factorie.app.nlp.phrase

import cc.factorie._
import cc.factorie.app.nlp._
import cc.factorie.app.nlp.pos._
import cc.factorie.app.nlp.coref.WithinDocCoref
import cc.factorie.app.nlp.morph.BasicMorphologicalAnalyzer
import cc.factorie.variable.{EnumDomain, CategoricalVariable}
import scala.reflect.ClassTag

object NumberDomain extends EnumDomain {
  val UNKNOWN,     // uncertain
  SINGULAR,        // one of something
  PLURAL = Value   // multiple of something
  freeze()
}

class Number extends CategoricalVariable[String] {
  def this(value:String) = { this(); _initialize(domain.index(value)) }
  def this(value:Int) = { this(); _initialize(value) }
  def domain = NumberDomain
}
class PhraseNumber(val phrase:Phrase, value:Int) extends Number(value) {
  def this(phrase:Phrase, value:String) = this(phrase, NumberDomain.index(value))
}

/** Cheap number predictor based on rules and lexicons.  Really this should use a real morphological analyzer. */
class NounPhraseNumberLabeler[A<:AnyRef](documentAttrToPhrases:(A)=>Iterable[Phrase])(implicit docAttrClass:ClassTag[A]) extends DocumentAnnotator {
  val singularPronoun = Set("i", "me", "my", "mine", "myself", "he", "she", "it", "him", "her", "his", "hers", "its", "one", "ones", "oneself", "this", "that")
  val pluralPronoun = Set("we", "us", "our", "ours", "ourselves", "ourself", "they", "them", "their", "theirs", "themselves", "themself", "these", "those")
  val singularDeterminer = Set("a", "an", "this")
  val pluralDeterminer = Set("those", "these", "some", "both")
  def isProper(pos:String): Boolean = pos.startsWith("NNP")
  def isNoun(pos:String): Boolean = pos(0) == 'N'
  def isPossessive(pos:String): Boolean = pos == "POS"
  def process(document:Document): Document = {
    for (phrase <- documentAttrToPhrases(document.attr[A])) process(phrase)
    document
  }
  def process(phrase:Phrase): Unit = {
    import NumberDomain._
    val number = new PhraseNumber(phrase, UNKNOWN)
    phrase.attr += number
    if (phrase.length > 0) {
      val firstWord = phrase(0).string.toLowerCase
      val headPos = phrase.headToken.attr[PennPosTag].categoryValue
      if (singularPronoun.contains(firstWord) || singularDeterminer.contains(firstWord)) number := SINGULAR
      else if (pluralPronoun.contains(firstWord) || pluralDeterminer.contains(firstWord)) number := PLURAL
      else if (isProper(headPos) && phrase.exists(token => token.string.toLowerCase == "and")) number := PLURAL
      else if (isNoun(headPos) || isPossessive(headPos)) {
        val headWord = phrase.headToken.string.toLowerCase
        if (BasicMorphologicalAnalyzer.isPlural(headWord)) number := PLURAL
        else if (headPos.startsWith("N")) { if (headPos.endsWith("S")) number := PLURAL else number := SINGULAR }
        else number := SINGULAR
      }
    }
  }
  override def tokenAnnotationString(token:Token): String = { val phrases = documentAttrToPhrases(token.document.attr[A]).filter(_.contains(token)); phrases.map(_.attr[Number].categoryValue).mkString(",") }
  override def phraseAnnotationString(phrase:Phrase): String = { val t = phrase.attr[Number]; if (t ne null) t.categoryValue else "_" }
  def prereqAttrs: Iterable[Class[_]] = List(classOf[PennPosTag], classOf[NounPhraseList])
  def postAttrs: Iterable[Class[_]] = List(classOf[PhraseNumber])
}

//class NounPhraseNumberLabeler extends PhraseNumberLabeler[NounPhraseList](phrases => phrases)
object NounPhraseNumberLabeler extends NounPhraseNumberLabeler[NounPhraseList](phrases => phrases)

//class MentionPhraseNumberLabeler extends PhraseNumberLabeler[WithinDocCoref](_.mentions.map(_.phrase))
object MentionPhraseNumberLabeler extends NounPhraseNumberLabeler[WithinDocCoref](_.mentions.map(_.phrase))

// No reason to have this.   Label should always go on Phrase, not mention. -akm
//object MentionNumberLabeler extends NumberLabeler[Mention,MentionList]


text:
package com.geccocrawler.gecco.spider.render.json;

import net.sf.cglib.beans.BeanMap;

import com.geccocrawler.gecco.request.HttpRequest;
import com.geccocrawler.gecco.response.HttpResponse;
import com.geccocrawler.gecco.spider.SpiderBean;
import com.geccocrawler.gecco.spider.render.AbstractRender;

/**
 * 将下载下来的json映射到bean中
 *
 * @author huchengyi
 *
 */
public class JsonRender extends AbstractRender {

	private JsonFieldRender jsonFieldRender;

	public JsonRender() {
		super();
		this.jsonFieldRender = new JsonFieldRender();
	}

	@Override
	public void fieldRender(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) {
		jsonFieldRender.render(request, response, beanMap, bean);
	}

}


text:
class Performance < ApplicationRecord
    belongs_to :discography
    belongs_to :actor
    belongs_to :character
    belongs_to :cast
    belongs_to :school
end


text:
<!--
@license
Copyright (c) 2016 The Jviz Project Authors. All rights reserved.
The Jviz Project is under the MIT License. See https://github.com/jviz/jviz/blob/dev/LICENSE
-->
<script>
  //Initialize the biojviz object
  var jviz_bio = {};
</script>


text:
using System;
using System.Reflection;
using System.Diagnostics;
using System.Resources;
using System.Threading;
using System.Globalization;
using Xamarin.Forms;

namespace Todo
{
	public class L10n
	{
		/// <remarks>
		/// Maybe we can cache this info rather than querying every time
		/// </remarks>
		public static string Locale ()
		{
			return DependencyService.Get<ILocale>().GetCurrent();
		}

		public static string Localize(string key, string comment) {

			// FOR DEBUGGING
			var assembly = typeof(L10n).GetTypeInfo().Assembly;
			foreach (var res in assembly.GetManifestResourceNames())
				System.Diagnostics.Debug.WriteLine("found resource: " + res);

			var netLanguage = Locale ();

			ResourceManager temp = new ResourceManager("Todo.AppResources", typeof(L10n).GetTypeInfo().Assembly);
			//ResourceManager temp = new ResourceManager("Todo.Resx.AppResources", typeof(L10n).GetTypeInfo().Assembly);

			string result = temp.GetString (key, new CultureInfo (netLanguage));

			return result;
		}
	}
}


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class frmDetectRSS
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmDetectRSS))
        Me.ListBox1 = New System.Windows.Forms.ListBox()
        Me.btnAdd = New System.Windows.Forms.Button()
        Me.btnClose = New System.Windows.Forms.Button()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.SuspendLayout()
        '
        'ListBox1
        '
        Me.ListBox1.FormattingEnabled = True
        Me.ListBox1.Location = New System.Drawing.Point(12, 35)
        Me.ListBox1.Name = "ListBox1"
        Me.ListBox1.Size = New System.Drawing.Size(372, 134)
        Me.ListBox1.TabIndex = 0
        '
        'btnAdd
        '
        Me.btnAdd.Location = New System.Drawing.Point(302, 175)
        Me.btnAdd.Name = "btnAdd"
        Me.btnAdd.Size = New System.Drawing.Size(82, 23)
        Me.btnAdd.TabIndex = 1
        Me.btnAdd.Text = "Add Selected"
        Me.btnAdd.UseVisualStyleBackColor = True
        '
        'btnClose
        '
        Me.btnClose.Location = New System.Drawing.Point(12, 175)
        Me.btnClose.Name = "btnClose"
        Me.btnClose.Size = New System.Drawing.Size(81, 23)
        Me.btnClose.TabIndex = 2
        Me.btnClose.Text = "Close"
        Me.btnClose.UseVisualStyleBackColor = True
        '
        'Label1
        '
        Me.Label1.AutoSize = True
        Me.Label1.Font = New System.Drawing.Font("Segoe UI", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.ForeColor = System.Drawing.Color.DimGray
        Me.Label1.Location = New System.Drawing.Point(12, 9)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(81, 13)
        Me.Label1.TabIndex = 3
        Me.Label1.Text = "Detected Feed"
        '
        'frmDetectRSS
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackColor = System.Drawing.Color.WhiteSmoke
        Me.ClientSize = New System.Drawing.Size(396, 208)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.btnClose)
        Me.Controls.Add(Me.btnAdd)
        Me.Controls.Add(Me.ListBox1)
        Me.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.MinimizeBox = False
        Me.Name = "frmDetectRSS"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Detected Feeds"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents ListBox1 As System.Windows.Forms.ListBox
    Friend WithEvents btnAdd As System.Windows.Forms.Button
    Friend WithEvents btnClose As System.Windows.Forms.Button
    Friend WithEvents Label1 As System.Windows.Forms.Label
End Class


text:
package com.navercorp.pinpoint.plugin.rabbitmq.spring;

import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier;
import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifierHolder;
import com.navercorp.pinpoint.plugin.rabbitmq.util.RabbitMQTestConstants;
import com.navercorp.test.pinpoint.plugin.rabbitmq.MessageConverter;
import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.TestMessageHolder;
import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.service.TestReceiverService;
import com.navercorp.test.pinpoint.plugin.rabbitmq.spring.service.TestSenderService;
import org.junit.Assert;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;

import java.util.concurrent.TimeUnit;

/**
 * @author HyunGil Jeong
 */
public class SpringAmqpRabbitTestRunner {

    private static final long TRACE_WAIT_TIME_MS = 3000L;

    private final TestSenderService testSenderService;
    private final TestReceiverService testReceiverService;
    private final TestMessageHolder testMessageHolder;
    private final ConnectionFactory connectionFactory;
    private final String remoteAddress;

    public SpringAmqpRabbitTestRunner(TestApplicationContext context) {
        if (context == null) {
            throw new NullPointerException("context");
        }
        this.testSenderService = context.getTestSenderService();
        this.testMessageHolder = context.getTestMessageHolder();
        this.testReceiverService = context.getTestReceiverService();
        this.connectionFactory = context.getConnectionFactory();
        this.remoteAddress = connectionFactory.getHost() + ":" + connectionFactory.getPort();
    }

    public String getRemoteAddress() {
        return remoteAddress;
    }

    public PluginTestVerifier runPush(int expectedTraceCount) throws InterruptedException {
        final String message = "hello rabbit mq";

        testSenderService.sendMessage(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PUSH, message);
        Assert.assertEquals(message, testMessageHolder.getMessage(10, TimeUnit.SECONDS));

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        // Wait till all traces are recorded (consumer traces are recorded from another thread)
        awaitAndVerifyTraceCount(verifier, expectedTraceCount, TRACE_WAIT_TIME_MS);
        return verifier;
    }

    public PluginTestVerifier runPull(int expectedTraceCount) throws InterruptedException {
        final String message = "hello rabbit mq!";

        testSenderService.sendMessage(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL, message);
        Assert.assertEquals(message, testReceiverService.receiveMessage(MessageConverter.FOR_TEST));

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        // Wait till all traces are recorded (consumer traces are recorded from another thread)
        awaitAndVerifyTraceCount(verifier, expectedTraceCount, TRACE_WAIT_TIME_MS);
        return verifier;
    }

    public PluginTestVerifier runPull(int expectedTraceCount, long timeoutMs) throws InterruptedException {
        final String message = "hello rabbit mq!";

        testSenderService.sendMessage(RabbitMQTestConstants.EXCHANGE, RabbitMQTestConstants.ROUTING_KEY_PULL, message);
        Assert.assertEquals(message, testReceiverService.receiveMessage(MessageConverter.FOR_TEST, timeoutMs));

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
        // Wait till all traces are recorded (consumer traces are recorded from another thread)
        awaitAndVerifyTraceCount(verifier, expectedTraceCount, TRACE_WAIT_TIME_MS);
        return verifier;
    }

    private static void awaitAndVerifyTraceCount(PluginTestVerifier verifier, int expectedTraceCount, long maxWaitMs) throws InterruptedException {
        final long waitIntervalMs = 100L;
        long maxWaitTime = maxWaitMs;
        if (maxWaitMs < waitIntervalMs) {
            maxWaitTime = waitIntervalMs;
        }
        long startTime = System.currentTimeMillis();
        try {
            while (System.currentTimeMillis() - startTime < maxWaitTime) {
                try {
                    verifier.verifyTraceCount(expectedTraceCount);
                    return;
                } catch (AssertionError e) {
                    // ignore and retry
                    Thread.sleep(waitIntervalMs);
                }
            }
            verifier.verifyTraceCount(expectedTraceCount);
        } finally {
            verifier.printCache();
        }
    }
}


text:
waxClass{"SimpleAnnotation", NSObject, protocols={"MKAnnotation"}}

function initWithLatLong(self, lat, long)
  self.super:init()
  self.lat = lat
  self.long = long

  -- These variables have underscores because they would have conflicted with
  -- method names required by the MKAnnotation protocol.
  self._title = 'Untitled'
  self._subtitle = ''
end

function coordinate(self)
  return CLLocationCoordinate2D(self.lat, self.long)
end

function title(self)
  return self._title
end

function setTitle(self, title)
  self._title = title
  return nil
end

function subtitle(self)
  return self._subtitle
end

function setSubtitle(self, subtitle)
  self._subtitle = subtitle
  return nil
end


text:
package net.sourceforge.myvd.inserts.jdbc;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.sql.DataSource;

import org.apache.logging.log4j.Logger;

import net.sourceforge.myvd.chain.AddInterceptorChain;
import net.sourceforge.myvd.chain.BindInterceptorChain;
import net.sourceforge.myvd.chain.CompareInterceptorChain;
import net.sourceforge.myvd.chain.DeleteInterceptorChain;
import net.sourceforge.myvd.chain.ExetendedOperationInterceptorChain;
import net.sourceforge.myvd.chain.InterceptorChain;
import net.sourceforge.myvd.chain.ModifyInterceptorChain;
import net.sourceforge.myvd.chain.PostSearchCompleteInterceptorChain;
import net.sourceforge.myvd.chain.PostSearchEntryInterceptorChain;
import net.sourceforge.myvd.chain.RenameInterceptorChain;
import net.sourceforge.myvd.chain.SearchInterceptorChain;
import net.sourceforge.myvd.core.NameSpace;
import net.sourceforge.myvd.inserts.Insert;
import net.sourceforge.myvd.types.Attribute;
import net.sourceforge.myvd.types.Bool;
import net.sourceforge.myvd.types.DistinguishedName;
import net.sourceforge.myvd.types.Entry;
import net.sourceforge.myvd.types.ExtendedOperation;
import net.sourceforge.myvd.types.Filter;
import net.sourceforge.myvd.types.FilterNode;
import net.sourceforge.myvd.types.FilterType;
import net.sourceforge.myvd.types.Int;
import net.sourceforge.myvd.types.Password;
import net.sourceforge.myvd.types.Results;
import net.sourceforge.myvd.util.EntryUtil;
import net.sourceforge.myvd.util.IteratorEntrySet;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.novell.ldap.LDAPConstraints;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPMessage;
import com.novell.ldap.LDAPModification;
import com.novell.ldap.LDAPSearchConstraints;
import com.novell.ldap.LDAPSearchRequest;
import com.novell.ldap.util.DN;
import com.novell.ldap.util.RDN;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.sql.DataSource;

import org.apache.logging.log4j.Logger;

import net.sourceforge.myvd.chain.AddInterceptorChain;
import net.sourceforge.myvd.chain.BindInterceptorChain;
import net.sourceforge.myvd.chain.CompareInterceptorChain;
import net.sourceforge.myvd.chain.DeleteInterceptorChain;
import net.sourceforge.myvd.chain.ExetendedOperationInterceptorChain;
import net.sourceforge.myvd.chain.InterceptorChain;
import net.sourceforge.myvd.chain.ModifyInterceptorChain;
import net.sourceforge.myvd.chain.PostSearchCompleteInterceptorChain;
import net.sourceforge.myvd.chain.PostSearchEntryInterceptorChain;
import net.sourceforge.myvd.chain.RenameInterceptorChain;
import net.sourceforge.myvd.chain.SearchInterceptorChain;
import net.sourceforge.myvd.core.NameSpace;
import net.sourceforge.myvd.inserts.Insert;
import net.sourceforge.myvd.types.Attribute;
import net.sourceforge.myvd.types.Bool;
import net.sourceforge.myvd.types.DistinguishedName;
import net.sourceforge.myvd.types.Entry;
import net.sourceforge.myvd.types.ExtendedOperation;
import net.sourceforge.myvd.types.Filter;
import net.sourceforge.myvd.types.FilterNode;
import net.sourceforge.myvd.types.FilterType;
import net.sourceforge.myvd.types.Int;
import net.sourceforge.myvd.types.Password;
import net.sourceforge.myvd.types.Results;
import net.sourceforge.myvd.util.EntryUtil;
import net.sourceforge.myvd.util.IteratorEntrySet;

import com.novell.ldap.LDAPConstraints;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPModification;
import com.novell.ldap.LDAPSearchConstraints;
import com.novell.ldap.LDAPSearchRequest;
import com.novell.ldap.util.DN;
import com.novell.ldap.util.RDN;

public class JdbcInsert implements Insert,JdbcPool {

	static Logger logger = org.apache.logging.log4j.LogManager.getLogger(JdbcInsert.class);

	public static final String MYVD_DB_CON = "MYVD_DB_CON_";
	public static final String MYVD_DB_LDAP2DB = "MYVD_DB_LDAP2DB_";
	public static final String MYVD_DB_DB2LDAP = "MYVD_DB_DB2LDAP_";

	public static final String MYVD_DID_BIND = "MYVD_DB_DID_BIND_";
	String driver;
	String url;
	String user;
	String pwd;
	boolean useSimple;

	int maxCons;
	//int maxIdleCons;

	DataSource ds;

	String base;
	String SQL;
	String searchSQL;
	String rdn;
	String dbRdn;

	String objectClass;

	DN baseDN;

	boolean addBaseToFilter;

	static HashMap<String,JdbcPoolHolder> poolCache = new HashMap<String,JdbcPoolHolder>();

	HashMap<String,String> ldap2db,db2ldap;
	private String name;
	private boolean hasWhere;
	private String whereClause;
	private boolean hasPostWhere;
	private Object postWhere;

	NameSpace ns;

	private String valQuery;

	private Properties props;

	private JdbcPoolHolder jdbcPoolHolder;

	public static HashMap<String,JdbcPoolHolder> getPoolCache() {
		return poolCache;
	}

	public void configure(String name, Properties props, NameSpace nameSpace)
			throws LDAPException {

		this.name = name;
		this.props = props;

		driver = props.getProperty("driver");
		logger.info("Driver : " + driver);
		url = props.getProperty("url");
		logger.info("URL : " + url);
		user = props.getProperty("user");
		logger.info("User : " + user);
		pwd = props.getProperty("password");
		logger.info("Password : **********");

		this.valQuery = props.getProperty("validationQuery");
		if (valQuery == null) {
			logger.warn("No validation query specified, defaulting to 'SELECT 1'");
			valQuery = "SELECT 1";
		}
		logger.info("Validation Query : '" + this.valQuery + "'");

		this.maxCons = Integer.parseInt(props.getProperty("maxCons","5"));
		logger.info("Max Cons : " + this.maxCons);
		//this.maxIdleCons = Integer.parseInt(props.getProperty("maxIdleCons","5"));
		//logger.info("maxIdleCons : " + this.maxIdleCons);

		generatePool(props);
		base = nameSpace.getBase().toString();

		rdn = props.getProperty("rdn");
		logger.info("RDN : " + rdn);

		String mapping = props.getProperty("mapping");
		logger.info("Mapping : " + mapping);
		StringTokenizer toker = new StringTokenizer(mapping,",");

		this.ldap2db = new HashMap<String,String>();
		this.db2ldap = new HashMap<String,String>();

		while (toker.hasMoreTokens()) {
			String token = toker.nextToken();
			String ldap = token.substring(0,token.indexOf('='));
			String db = token.substring(token.indexOf('=') + 1);

			ldap2db.put(ldap.toLowerCase(),db.toLowerCase());
			db2ldap.put(db.toLowerCase(),ldap.toLowerCase());

		}

		this.objectClass = props.getProperty("objectClass");
		logger.info("objectClass : " + objectClass);
		this.rdn = props.getProperty("rdn");
		this.dbRdn = ldap2db.get(rdn);

		this.useSimple = props.getProperty("useSimple","false").equalsIgnoreCase("true");
		logger.info("Use Simple : " + useSimple);
		this.SQL = props.getProperty("sql");
		logger.info("SQL : " + this.SQL);
		int whereEnd;

		String fields = this.SQL.substring(this.SQL.toLowerCase().indexOf("select") + "select".length() + 1,this.SQL.toLowerCase().indexOf("from"));
		logger.info("fields : " + fields);
		int where = this.SQL.toLowerCase().indexOf("where");
		String table = "";
		if (where == -1) {
			table = this.SQL.substring(this.SQL.toLowerCase().indexOf("from") + "from".length() + 1).trim();
		} else {
			table = this.SQL.substring(this.SQL.toLowerCase().indexOf("from") + "from".length() + 1,where).trim();
		}

		logger.info("table - " + table);

		if (this.useSimple) {
			this.searchSQL = this.SQL.substring(this.SQL.toLowerCase().indexOf(" from "));

			int whereBegin = this.searchSQL.toLowerCase().indexOf(" where ");

			whereEnd = this.searchSQL.toLowerCase().indexOf(" order ");
			this.hasPostWhere = true;

			if (whereEnd == -1) {
				whereEnd = this.searchSQL.toLowerCase().indexOf(" group ");
			}

			if (whereEnd == -1) {
				this.hasPostWhere = false;
				whereEnd = this.searchSQL.length();
			}

			if (this.hasPostWhere) {
				this.postWhere = this.searchSQL.substring(whereEnd);
			}

			if (whereBegin != -1) {
				this.hasWhere = true;

				this.whereClause = "(" + this.searchSQL.substring(whereBegin + " where ".length(),whereEnd) + ") ";

				this.searchSQL = this.searchSQL.substring(0,whereBegin);
			} else {
				if (this.hasPostWhere) {
					this.searchSQL = this.searchSQL.substring(0,whereEnd);
				}
				this.hasWhere = false;
			}

		} else {
			this.searchSQL = "SELECT " + ldap2db.get(this.rdn.toLowerCase()) + " " + SQL.substring(SQL.indexOf(" FROM "));
		}

		this.baseDN = new DN(base);

		this.addBaseToFilter = Boolean.parseBoolean(props.getProperty("addBaseToFilter","true"));
		logger.info("Add Base To Filter : " + this.addBaseToFilter);

		this.ns = nameSpace;

	}

	private void generatePool(Properties props) throws LDAPException {
		String poolKey = (url+user).toLowerCase();

		synchronized(poolCache) {
			if (poolCache.get(poolKey) != null ) {
				logger.info(this.name + " - using existing connection pool");
				this.jdbcPoolHolder = poolCache.get(poolKey);
				jdbcPoolHolder.upCount();
				this.ds = jdbcPoolHolder.getDs();
			} else {
				logger.info(this.name + " - creating connection pool");
				ComboPooledDataSource cpds = new ComboPooledDataSource();
				try {
					cpds.setDriverClass(driver);
				} catch (PropertyVetoException e1) {
					throw new LDAPException(LDAPException.resultCodeToString(LDAPException.OPERATIONS_ERROR), LDAPException.OPERATIONS_ERROR, "Could not load driver",e1);
				}
				cpds.setJdbcUrl(url);
				cpds.setUser(user);
				cpds.setPassword(pwd);
				cpds.setMaxPoolSize(this.maxCons);
				//cpds.setma(this.maxIdleCons);
				cpds.setPreferredTestQuery(this.valQuery);
				cpds.setTestConnectionOnCheckin(true);
				int testPeriod = Integer.parseInt(props.getProperty("idleConnectionTestPeriod","30"));
				cpds.setIdleConnectionTestPeriod(testPeriod);
				int unreturnedConnectionTimeout = Integer.parseInt(props.getProperty("unreturnedConnectionTimeout","30"));
				cpds.setUnreturnedConnectionTimeout(unreturnedConnectionTimeout);
				cpds.setDebugUnreturnedConnectionStackTraces(true);

				int checkoutTimeout = Integer.parseInt(props.getProperty("checkoutTimeout","30000"));
				cpds.setCheckoutTimeout(checkoutTimeout);

				this.ds = cpds;
				this.jdbcPoolHolder = new JdbcPoolHolder(poolKey);
				jdbcPoolHolder.upCount();
				jdbcPoolHolder.setDs(cpds);
				poolCache.put(poolKey, jdbcPoolHolder);
			}

		}
	}

	public void add(AddInterceptorChain chain, Entry entry,
			LDAPConstraints constraints) throws LDAPException {
		Connection con = null;

		try {
			con = this.getCon();
			loadRequest(chain, con);
			chain.nextAdd(entry, constraints);
		} catch (Throwable t) {
			if (t instanceof LDAPException) {
				throw (LDAPException) t;
			} else {
				throw new LDAPException("Error",LDAPException.OPERATIONS_ERROR,"Error",t);
			}

		} finally {
			unloadRequest(chain, con);
			returnCon(con);
		}

	}

	private void loadRequest(InterceptorChain chain, Connection con) {
		chain.getRequest().put(JdbcInsert.MYVD_DB_CON + this.name, con);
		chain.getRequest().put(JdbcInsert.MYVD_DB_DB2LDAP + this.name, this.db2ldap.clone());

		chain.getRequest().put(JdbcInsert.MYVD_DB_LDAP2DB + this.name, this.ldap2db.clone());
	}

	public void returnCon(Connection con) {
		try {
			con.close();
		} catch (SQLException e) {

		}

	}

	public void bind(BindInterceptorChain chain, DistinguishedName dn,
			Password pwd, LDAPConstraints constraints) throws LDAPException {
		Connection con = null;

		chain.getRequest().put(JdbcInsert.MYVD_DID_BIND + this.name, false);

		try {
			con = this.getCon();
			chain.getRequest().put(JdbcInsert.MYVD_DB_CON + this.name, con);
			chain.nextBind(dn, pwd, constraints);
		} catch (Throwable t) {
			if (t instanceof LDAPException) {
				throw (LDAPException) t;
			} else {
				throw new LDAPException("Error",LDAPException.OPERATIONS_ERROR,"Error",t);
			}

		} finally {
			unloadRequest(chain, con);
			if (! ((Boolean) chain.getRequest().get(MYVD_DID_BIND + this.name))) {
				throw new LDAPException(LDAPException.resultCodeToString(LDAPException.INVALID_CREDENTIALS),LDAPException.INVALID_CREDENTIALS,"No authentication occurred");
			}
		}

	}

	private void unloadRequest(InterceptorChain chain, Connection con) {
		chain.getRequest().remove(JdbcInsert.MYVD_DB_CON + this.name);
		returnCon(con);
		chain.getRequest().remove(JdbcInsert.MYVD_DB_DB2LDAP + this.name);
		chain.getRequest().remove(JdbcInsert.MYVD_DB_LDAP2DB + this.name);
	}

	public void compare(CompareInterceptorChain chain, DistinguishedName dn,
			Attribute attrib, LDAPConstraints constraints) throws LDAPException {
		// TODO Auto-generated method stub

	}

	public void delete(DeleteInterceptorChain chain, DistinguishedName dn,
			LDAPConstraints constraints) throws LDAPException {
		Connection con = null;

		try {
			con = this.getCon();
			chain.getRequest().put(JdbcInsert.MYVD_DB_CON + this.name, con);
			chain.nextDelete(dn, constraints);
		} catch (Throwable t) {
			if (t instanceof LDAPException) {
				throw (LDAPException) t;
			} else {
				throw new LDAPException("Error",LDAPException.OPERATIONS_ERROR,"Error",t);
			}

		} finally {
			unloadRequest(chain, con);
		}

	}

	public void extendedOperation(ExetendedOperationInterceptorChain chain,
			ExtendedOperation op, LDAPConstraints constraints)
			throws LDAPException {
		Connection con = null;

		try {
			con = this.getCon();
			chain.getRequest().put(JdbcInsert.MYVD_DB_CON + this.name, con);
			chain.nextExtendedOperations(op, constraints);
		} catch (Throwable t) {
			if (t instanceof LDAPException) {
				throw (LDAPException) t;
			} else {
				throw new LDAPException("Error",LDAPException.OPERATIONS_ERROR,"Error",t);
			}

		} finally {
			unloadRequest(chain, con);
		}

	}

	public void modify(ModifyInterceptorChain chain, DistinguishedName dn,
			ArrayList<LDAPModification> mods, LDAPConstraints constraints)
			throws LDAPException {
		Connection con = null;

		try {
			con = this.getCon();
			this.loadRequest(chain, con);
			chain.nextModify(dn, mods, constraints);
		} catch (Throwable t) {
			if (t instanceof LDAPException) {
				throw (LDAPException) t;
			} else {
				throw new LDAPException("Error",LDAPException.OPERATIONS_ERROR,"Error",t);
			}

		} finally {
			unloadRequest(chain, con);
		}

	}

	public void search(SearchInterceptorChain chain, DistinguishedName base,
			Int scope, Filter filter, ArrayList<Attribute> attributes,
			Bool typesOnly, Results results, LDAPSearchConstraints constraints)
			throws LDAPException {

		if (scope.getValue() == 0) {

			if (base.getDN().toString().equals(this.base)) {
				ArrayList<Entry> entries = new ArrayList<Entry>();

				entries.add(new Entry(EntryUtil.createBaseEntry(new DN(this.base))));

				chain.addResult(results,new IteratorEntrySet(entries.iterator()),base,scope,filter,attributes,typesOnly,constraints);
				return;
			} else {
				filter = addBaseToFilter(base, filter);
			}

		} else if (this.addBaseToFilter && scope.getValue() == 2 && ! base.getDN().equals(this.baseDN)) {
			filter = addBaseToFilter(base, filter);
		}

		Connection con = null;

		try {
			con = getCon();

		String mappedSearch;
		String querySQL = "";
		ArrayList<Object> vals = new ArrayList<Object>();

		if (this.useSimple) {
			StringBuffer buf = new StringBuffer();
			if (filter.getRoot().getType() == FilterType.PRESENCE && filter.getRoot().getName().equalsIgnoreCase("objectClass")) {
				buf.append("SELECT ");

				createSELECT(attributes, buf);

				buf.append(this.searchSQL);

				if (this.hasWhere) {
					buf.append(" WHERE ").append(this.whereClause);
				}

				if (this.hasPostWhere) {
					buf.append(this.postWhere);
				}

				querySQL = buf.toString();
			} else {
				StringBuffer filterString = new StringBuffer();
				this.stringFilter(filter.getRoot(),filterString,vals);
				buf.append("SELECT ");

				createSELECT(attributes, buf);

				buf.append(this.searchSQL).append(' ');

				if (this.hasWhere) {
					buf.append(" WHERE ").append(this.whereClause).append(" AND (").append(filterString.toString()).append(") ");
				} else {
					buf.append(" WHERE ").append(filterString.toString()).append(" ");
				}

				if (this.hasPostWhere) {
					buf.append(this.postWhere);
				}

				querySQL = buf.toString();

			}

		} else {
			if (filter.getRoot().getType() == FilterType.PRESENCE && filter.getRoot().getName().equalsIgnoreCase("objectClass")) {
				mappedSearch = this.searchSQL;
			} else {
				StringBuffer filterString = new StringBuffer();
				this.stringFilter(filter.getRoot(),filterString,vals);
				mappedSearch = this.searchSQL + " WHERE " + filterString.toString();
			}

			querySQL = "SELECT * FROM (" + SQL + ") X WHERE " + this.dbRdn + " IN (" + mappedSearch + ") ORDER BY " + this.dbRdn;
		}
		////System.out.println(querySQL);
		//System.err.println(querySQL);

			if (logger.isDebugEnabled()) {
				logger.debug("Search SQL : \"" + querySQL + "\"");
			}

			PreparedStatement ps = con.prepareStatement(querySQL);

			for (int i=0,m=vals.size();i<m;i++) {
				if (logger.isDebugEnabled()) {
					logger.debug("Adding parameter '" + (i + 1) + "'='" + vals.get(i));
				}
				ps.setObject(i + 1, vals.get(i));
			}

			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				chain.addResult(results,new JdbcEntrySet(con,ps,rs,this,filter,scope.getValue(),base.getDN()),base,scope,filter,attributes,typesOnly,constraints);
			} else {
				con.close();
			}
		} catch (Exception e) {
			logger.error("Failed search",e);

			try {
				if (con != null && ! con.isClosed()) {
					con.close();
				}
			} catch (SQLException e1) {
				logger.warn("Error closing connection",e1);
			}

			throw new LDAPException(e.toString(),LDAPException.OPERATIONS_ERROR,e.toString());
		} finally {

		}

	}

	private void createSELECT(ArrayList<Attribute> attributes, StringBuffer buf) {
		Iterator<Attribute> it = attributes.iterator();

		boolean foundRDN = false;
		boolean foundAttrib = false;
		if (attributes.size() == 0) {
			buf.append(" * ");
			return;
		}

		while (it.hasNext()) {
			foundAttrib = false;
			String attrib = it.next().getAttribute().getName();

			if (attrib.equalsIgnoreCase(this.rdn)) {
				foundRDN = true;
			}

			if (attrib.equalsIgnoreCase("*")) {
				buf.append("* ");
			} else {

				String ldap2dbVal = ldap2db.get(attrib.toLowerCase());
				if (ldap2dbVal != null) {
					buf.append(ldap2dbVal).append(' ');
					foundAttrib = true;
				} else {
					continue;
				}
			}

			if ((it.hasNext()  || ! foundRDN) && foundAttrib) {
				buf.append(',');
			}
		}

		if (! foundRDN) {
			buf.append(this.ldap2db.get(this.rdn.toLowerCase())).append(" ,");
		}

		if (! foundAttrib) {
			buf.setLength(buf.lastIndexOf(",") - 1);
		}

		if (buf.charAt(buf.length() - 1) == ',') {
			buf.setLength(buf.length() - 1);
		}

	}

	private Filter addBaseToFilter(DistinguishedName base, Filter filter) {
		String rdnName,rdnVal;

		RDN rdn = (RDN) base.getDN().getRDNs().get(0);
		rdnName = rdn.getType();
		rdnVal = rdn.getValue();

		ArrayList<FilterNode> ands = new ArrayList<FilterNode>();
		ands.add(new FilterNode(FilterType.EQUALS,rdnName, rdnVal));
		try {
			ands.add((FilterNode) filter.getRoot().clone());
		} catch (CloneNotSupportedException e) {

		}
		FilterNode newroot = new FilterNode(FilterType.AND,ands);
		filter = new Filter(newroot);
		////System.out.println("filter : " + filter.getRoot().toString());
		return filter;
	}

	public Connection getCon() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		try {
			return this.ds.getConnection();
		} catch (SQLException e) {
			if (e.getMessage().contains("has been closed")) {
				logger.warn("Pool is closed, recreating");
				try {
					generatePool(props);
				} catch (LDAPException e1) {
					throw new SQLException("Could not recreate pool",e1);
				}
				return this.ds.getConnection();

			} else {
				throw e;
			}
		}

	}

	public void rename(RenameInterceptorChain chain, DistinguishedName dn,
			DistinguishedName newRdn, Bool deleteOldRdn,
			LDAPConstraints constraints) throws LDAPException {
		Connection con = null;

		try {
			con = this.getCon();
			chain.getRequest().put(JdbcInsert.MYVD_DB_CON + this.name, con);
			chain.nextRename(dn, newRdn, deleteOldRdn, constraints);
		} catch (Throwable t) {
			if (t instanceof LDAPException) {
				throw (LDAPException) t;
			} else {
				throw new LDAPException("Error",LDAPException.OPERATIONS_ERROR,"Error",t);
			}

		} finally {
			unloadRequest(chain, con);

		}

	}

	public void rename(RenameInterceptorChain chain, DistinguishedName dn,
			DistinguishedName newRdn, DistinguishedName newParentDN,
			Bool deleteOldRdn, LDAPConstraints constraints)
			throws LDAPException {
		Connection con = null;

		try {
			con = this.getCon();
			chain.getRequest().put(JdbcInsert.MYVD_DB_CON + this.name, con);
			chain.nextRename(dn, newRdn, newParentDN, deleteOldRdn, constraints);
		} catch (Throwable t) {
			if (t instanceof LDAPException) {
				throw (LDAPException) t;
			} else {
				throw new LDAPException("Error",LDAPException.OPERATIONS_ERROR,"Error",t);
			}

		} finally {
			unloadRequest(chain, con);

		}

	}

	public void postSearchEntry(PostSearchEntryInterceptorChain chain,
			Entry entry, DistinguishedName base, Int scope, Filter filter,
			ArrayList<Attribute> attributes, Bool typesOnly,
			LDAPSearchConstraints constraints) throws LDAPException {
		//no need for post search entry code

	}

	public void postSearchComplete(PostSearchCompleteInterceptorChain chain,
			DistinguishedName base, Int scope, Filter filter,
			ArrayList<Attribute> attributes, Bool typesOnly,
			LDAPSearchConstraints constraints) throws LDAPException {
		//no need for post search complete code

	}

	private String stringFilter(FilterNode root, StringBuffer filter,ArrayList<Object> vals) {
        FilterType op;
        //filter.append('(');
        String comp = null;
        ArrayList<FilterNode> children;
        Iterator<FilterNode> filterIt;
        String attribName = null;

        boolean isFirst = true;

                op = root.getType();
                switch (op){
                    case AND:

                    		HashMap<String,ArrayList<FilterNode>> attribs = new HashMap<String,ArrayList<FilterNode>>();
                    		//first sort the nodes into "buckets"
                    		children = root.getChildren();
                        filterIt = children.iterator();
                        while (filterIt.hasNext()) {
                        		FilterNode node = filterIt.next();
                        		if (node.getType() == FilterType.AND) {
                        			ArrayList<FilterNode> ands = attribs.get("&");
                        			if (ands == null) {
                        				ands = new ArrayList<FilterNode>();
                        				attribs.put("&",ands);
                        			}
                        			ands.add(node);
                        		} else if (node.getType() == FilterType.OR) {
                        			ArrayList<FilterNode> ors = attribs.get("|");
                        			if (ors == null) {
                        				ors = new ArrayList<FilterNode>();
                        				attribs.put("|",ors);
                        			}
                        			ors.add(node);
                        		} else if (node.getType() == FilterType.NOT) {
                        			ArrayList<FilterNode> nots = attribs.get("!");
                        			if (nots == null) {
                        				nots = new ArrayList<FilterNode>();
                        				attribs.put("!",nots);
                        			}
                        			nots.add(node);
                        		} else {

                        			ArrayList<FilterNode> attribNodes = attribs.get(node.getName().toLowerCase());
                        			if (attribNodes == null) {
                        				attribNodes = new ArrayList<FilterNode>();
                        				attribs.put(node.getName(),attribNodes);
                        			}
                        			attribNodes.add(node);
                        		}
                        }

                        filter.append(" ( ");

                        Iterator<String> itBuckets = attribs.keySet().iterator();
                        while (itBuckets.hasNext()) {
                        		String attrib = itBuckets.next();
                        		ArrayList<FilterNode> nodes = attribs.get(attrib);
                        		if (attrib.equals("&")) {
                        			Iterator<FilterNode> itNodes = nodes.iterator();
                        			filter.append(" ( ");
                        			while (itNodes.hasNext()) {
                        				stringFilter(itNodes.next(),filter,vals);
                        				if (itNodes.hasNext()) {
                        					filter.append(" AND ");
                        				}
                        			}

                        			filter.append(" ) ");

                        			if (itBuckets.hasNext()) {
                        				filter.append(" AND ");
                        			}
                        		} else if (attrib.equals("|")) {
                        			Iterator<FilterNode> itNodes = nodes.iterator();
                        			filter.append(" ( ");
                        			while (itNodes.hasNext()) {
                        				stringFilter(itNodes.next(),filter,vals);
                        				if (itNodes.hasNext()) {
                        					filter.append(" AND ");
                        				}
                        			}
                        			filter.append(" ) ");

                        			if (itBuckets.hasNext()) {
                        				filter.append(" AND ");
                        			}
                        		} else if (attrib.equals("!")) {
                        			Iterator<FilterNode> itNodes = nodes.iterator();
                        			filter.append(" ( ");
                        			while (itNodes.hasNext()) {
                        				stringFilter(itNodes.next(),filter,vals);
                        				if (itNodes.hasNext()) {
                        					filter.append(" AND ");
                        				}
                        			}
                        			filter.append(" ) ");

                        			if (itBuckets.hasNext()) {
                        				filter.append(" AND ");
                        			}
                        		} else {
                        			Iterator<FilterNode> itNodes = nodes.iterator();
                        			filter.append(" ( ");
                        			while (itNodes.hasNext()) {
                        				stringFilter(itNodes.next(),filter,vals);
                        				if (itNodes.hasNext()) {
                        					filter.append(" OR ");
                        				}
                        			}
                        			filter.append(" ) ");

                        			if (itBuckets.hasNext()) {
                        				filter.append(" AND ");
                        			}
                        		}
                        }

                        filter.append(" ) ");

                        break;
                    case OR:
                    		filter.append(" ( ");

                        children = root.getChildren();
                        filterIt = children.iterator();
                        while (filterIt.hasNext()) {
                        		stringFilter(filterIt.next(),filter,vals);
                        		if (filterIt.hasNext()) {
                        			filter.append(" OR ");
                        		}
                        }
                        filter.append(" ) ");
                        break;

                    case NOT:
                        filter.append(" NOT ( ");
                        stringFilter(root.getNot(),filter,vals);
                        filter.append(" ) ");

                        break;
                    case EQUALS:{
                    		if (root.getName().equalsIgnoreCase("objectclass")) {
                    			filter.append(" 1=1 ");
                    		} else {
		                        attribName = this.ldap2db.get(root.getName().toLowerCase());

		                        if (attribName == null) {
		                        	filter.append(" 1 = 0 ");
		                        } else {

		                    		filter.append(attribName);
		                    		filter.append("=?");

		                    		vals.add(root.getValue());
		                        }
                    		}

                        break;
                    }
                    case GREATER_THEN:{
                    		attribName = this.ldap2db.get(root.getName().toLowerCase());
                    		filter.append(attribName);
                        filter.append(">=?");
                        vals.add(root.getValue());
                        break;
                    }
                    case LESS_THEN:{
                    		attribName = this.ldap2db.get(root.getName().toLowerCase());
                    		filter.append(attribName);
                        filter.append("<=?");
                        vals.add(root.getValue());
                        break;

                    }
                    case PRESENCE:
                    		if (root.getName().equalsIgnoreCase("objectclass")) {
                    			filter.append(" 1=1 ");
                    		} else {
	                    		filter.append(this.ldap2db.get(root.getName().toLowerCase()));
	                        filter.append(" IS NOT NULL ");
                    		}
                        break;
                    /*case APPROX_MATCH:
                        filter.append((String)itr.next());
                        filter.append("~=");
                        byte[] value = (byte[])itr.next();
                        filter.append(byteString(value));

                        if (comp != null && itr.hasNext()) {
                        	filter.append(comp);
                        }

                        break;
                    case LDAPSearchRequest.EXTENSIBLE_MATCH:
                        String oid = (String)itr.next();

                        filter.append((String)itr.next());
                        filter.append(':');
                        filter.append(oid);
                        filter.append(":=");
                        filter.append((String)itr.next());

                        if (comp != null && itr.hasNext()) {
                        	filter.append(comp);
                        }

                        break;*/
                    case SUBSTR:{
                    		attribName = this.ldap2db.get(root.getName().toLowerCase());
                    		filter.append(attribName);
                        filter.append(" LIKE '");
                        boolean noStarLast = false;

                        filter.append(root.getValue().replace('*','%')).append('\'');

                        break;
                    }
                }

        if (comp != null) {
        	filter.append(')');
        }

        return attribName;
    }

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

	public HashMap<String, String> getDB2LDAPMap() {
		return this.db2ldap;
	}

	public String getRDNField() {
		return this.rdn;
	}

	public HashMap<String, String> getLDAP2DBMap() {
		return this.ldap2db;
	}

	public void shutdown() {
		synchronized(poolCache) {
			if (this.jdbcPoolHolder.downCount()) {
				poolCache.remove(this.jdbcPoolHolder.getKey());
			}
		}

	}

	public String getObjectClass() {
		return this.objectClass;
	}
}


text:
Orange3-Spark
=============

A set of widgets for Orange data mining suite to work with Apache Spark ML API.

Requirements
------------

 - Python >= 3.4
 - Pandas
 - Orange 3

Please follow the instruction to install Orange 3 first.

The main Orange project is hosted at: https://github.com/biolab/orange3
Download from: http://orange.biolab.si

Features
--------

  * A Spark Context.
  * A Hive Table.
  * A Dataframe from an SQL Query.
  * A Dataset Builder, basically a call to VectorAssembler, this is usefull before sending data to Estimators.
  * Transformers from the feature module.
  * Estimators from classification module.
  * Estimators from regression module.
  * Estimators from clustering module.
  * Evaluation from evaluator module.
  * A PySpark script executor + PySpark console.
  * DataFrame transformes for Pandas and Orangle Tables

... more coming soon!

Installing
----------

First, you need to have Apache Spark installed. Follow the instructions here:
http://spark.apache.org/docs/latest/

Then you can do:

    pip install Orange3-spark

or install the add-on from the Orange's Options | Add-ons menu. Note, if
installing from Add-ons menu, the installation may fail if not all requirements
are satisfiable.

If you require ODBC connectivity, you need to install `pyodbc`
(which requires `sql.h` available if built with `pip` –
that's `unixodbc-dev` package on Linux).

If install is ok, you should see a new section in Orange containing a series of widgets from Spark ML API.


text:
<?php

/**
 * This file is part of the Aggregator library.
 *
 * @author Łukasz Makuch <kontakt@lukaszmakuch.pl>
 * @license MIT http://opensource.org/licenses/MIT
 */

namespace lukaszmakuch\Aggregator\SubjectProjector;

use lukaszmakuch\Aggregator\SubjectProjector\Exception\UnableToProject;

/**
 * Gets a different represenation of the given subject.
 *
 * @author Łukasz Makuch <kontakt@lukaszmakuch.pl>
 */
interface SubjectProjector
{
    /**
     * @param mixed $subject any possible subject
     * @return mixed different representation of the given subject
     * @throws UnableToProject
     */
    public function getDifferentRepresentationOf($subject);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/sinch-rtc-sample-messaging.iml" filepath="$PROJECT_DIR$/sinch-rtc-sample-messaging.iml" />
    </modules>
  </component>
</project>


text:
namespace System.ComponentModel
{

#if CONFIG_COMPONENT_MODEL

[AttributeUsage(AttributeTargets.All)]
public class ToolboxItemAttribute : Attribute
{
	// Internal state.
	private Type toolboxItemType;
	private String toolboxItemTypeName;

	// Pre-defined attribute values.
	public static readonly ToolboxItemAttribute Default
			= new ToolboxItemAttribute(true);
	public static readonly ToolboxItemAttribute None
			= new ToolboxItemAttribute(false);

	// Constructors.
	public ToolboxItemAttribute(bool defaultType)
			{
				if(defaultType)
				{
					toolboxItemTypeName =
						"System.Drawing.Design.ToolboxItem,System.Drawing";
				}
			}
	public ToolboxItemAttribute(String toolboxItemName)
			{
				this.toolboxItemTypeName = toolboxItemName;
			}
	public ToolboxItemAttribute(Type toolboxItemType)
			{
				this.toolboxItemType = toolboxItemType;
			}

	// Get the attribute's value.
	public Type ToolboxItemType
			{
				get
				{
					if(toolboxItemType != null)
					{
						return toolboxItemType;
					}
					else
					{
						toolboxItemType = Type.GetType(toolboxItemTypeName);
						return toolboxItemType;
					}
				}
			}
	public String ToolboxItemTypeName
			{
				get
				{
					if(toolboxItemTypeName != null)
					{
						return toolboxItemTypeName;
					}
					else if(toolboxItemType != null)
					{
						toolboxItemTypeName =
							toolboxItemType.AssemblyQualifiedName;
						return toolboxItemTypeName;
					}
					else
					{
						return String.Empty;
					}
				}
			}

	// Determine if two attribute values are equal.
	public override bool Equals(Object obj)
			{
				ToolboxItemAttribute other = (obj as ToolboxItemAttribute);
				if(other != null)
				{
					return (ToolboxItemTypeName == other.ToolboxItemTypeName);
				}
				else
				{
					return false;
				}
			}

	// Get the hash code for this value.
	public override int GetHashCode()
			{
				return ToolboxItemTypeName.GetHashCode();
			}

	// Determine if this is a default attribute value.
	public override bool IsDefaultAttribute()
			{
				return (ToolboxItemTypeName ==
						  "System.Drawing.Design.ToolboxItem,System.Drawing");
			}

}; // class ToolboxItemAttribute

#endif // CONFIG_COMPONENT_MODEL

}; // namespace System.ComponentModel


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='RegistrationProfile',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('activation_key', models.CharField(max_length=40, verbose_name='activation key')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, unique=True, verbose_name='user')),
            ],
            options={
                'verbose_name': 'registration profile',
                'verbose_name_plural': 'registration profiles',
            },
        ),
    ]