text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements.  See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership.  The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License.  You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
-->

<metadata xmlns="http://maven.apache.org/METADATA/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/METADATA/1.1.0 http://maven.apache.org/xsd/metadata-1.1.0.xsd"
  modelVersion="1.1.0">
  <groupId>org.apache.maven.its</groupId>
  <artifactId>dep-mng5324</artifactId>
  <version>07.20.3-SNAPSHOT</version><!-- metadata for artifact snapshot -->
  <versioning>
    <snapshot>
      <timestamp>20120809.112920</timestamp>
      <buildNumber>97</buildNumber>
    </snapshot>
    <lastUpdated>20120809112920</lastUpdated>
    <snapshotVersions>
      <snapshotVersion>
        <classifier>classifierA</classifier>
        <extension>jar</extension>
        <value>07.20.3-20120809.112124-88</value>
        <updated>20120809112124</updated>
      </snapshotVersion>
      <snapshotVersion>
        <classifier>classifierB</classifier>
        <extension>jar</extension>
        <value>07.20.3-20120809.112920-97</value>
        <updated>20120809112920</updated>
      </snapshotVersion>
    </snapshotVersions>
  </versioning>
</metadata>


text:
import test from 'ava'
import promisify from '../promisify'

function asyncFunc(hasError, b, cb) {
  setTimeout(() => {
    const err = hasError ? new Error('err1') : null
    cb(err, b)
  }, 10)
}

const obj = {
  prop: 'test',
  asyncMethod(hasError, cb) {
    setTimeout(() => {
      const err = hasError ? new Error('err1') : null
      cb(err, this.prop)
    })
  },
}

const piAsyncFunc = promisify(asyncFunc)
const piAsyncMethod = promisify(obj.asyncMethod, obj)

test('promisify', async function(t) {
  const b = await piAsyncFunc(false, 15)
  t.is(b, 15)
  t.throws(piAsyncFunc(true, 16))

  const methodRet = await piAsyncMethod(false)
  t.is(methodRet, obj.prop)

  t.throws(piAsyncMethod(true))
})

redpajama_set_name: RedPajamaGithub


text:
export const DEVICE_PIXEL_RATIO: number;
export const FIREFOX: boolean;
export const IMAGE_DECODE: boolean;
export const MAC: boolean;
export const PASSIVE_EVENT_LISTENERS: boolean;
export const SAFARI: boolean;
export const WEBKIT: boolean;
export const WORKER_OFFSCREEN_CANVAS: boolean;


text:
using Xamarin.Forms;

namespace ${Namespace}.Views
{
	public partial class ${Name} : NavigationPage
	{
		public ${Name} ()
		{
			InitializeComponent ();
		}
	}
}


text:
title: "The Test Pyramid and Availability Bias"
description: "The Test Pyramid is over referenced and over simplified."
date: "2015-12-21"
categories:
    - "tech"
    - "testing"
    - "development"
    - "engineering"
    - "quality"
---

[The test pyramid](https://www.mountaingoatsoftware.com/blog/the-forgotten-layer-of-the-test-automation-pyramid) has its place - it gets across a simple idea, but it has been taken too literally, and applied innapropriately.

<!--more-->

The Pyramid and Dificult Compromises
-------------

My understanding of Cohns original article was that people too often downplay the service or integration tests, and I think discussions of the pyramid miss this emphasis, and have focused too much on the Pyramid itself.

Unit vs X Tests (where X = any name for anything other than Unit)  must be the most tiresome debate ever in the history of software development. Over the years I have often found myself encouraging and sometimes justifying my compromises. My arguments have never been devastatingly good, because like any engineering there are often many good enough ways to achieve the desired outcome.

'Good enough' is at the heart of all engineering. Good enough to manage the risks with just enough confidence. From past experience I have, in general, found that developers from a computer science background sometimes struggle with 'engineering compromise' more than those from an engineering background.

Judging good enough and risk is hard and takes confidence and experience to get the balance right in the many different projects and products we work within. A set of tried and tested prescriptions is always more straight forward.

The Base of the Pyramid Problem
-------------------------------

It is way too prescriptive:

* It oversimplifies the situation, so it is used as a crutch to avoid critical thinking (notice I avoided the phrase containing the word 'cargo'). How often would 70:20:10 be perfect for your situation.
* The top of the pyramid refers explicitly to GUI based tests, often irrelevant, often the people who mention it forget this. (However, even a testing trapezoid would still be wrong)
* True user testing is completely ignored - experience - emotion - engagement (Dare I say quality as [Persig](https://en.wikipedia.org/wiki/Zen_and_the_Art_of_Motorcycle_Maintenance) defines it "Quality is the knife-edge of experience, found only in the present, known or at least potentially accessible to all of us")
* It is based on the false assumption that integration tests are slow and flaky, they can be as fast and robust as unit tests.
* It is 4 years old - the world has turned. Modern GUI's (think Mobile and [SPA](https://en.wikipedia.org/wiki/Single-page_application)) are almost always cleanly divided by a well defined API. (if not then it's not a testing problem, but a design problem)
* It downplays the relevance of boundary interactions, particularly during concurrency.
* Unit tests are subject to availability bias - and take on an inflated importance because of it.
* Unit tests themselves are a kind of availability bias - because they are easy to write and run they are used in the place of a more difficult, more complex, more valuable strategy, one that only becomes clear when you critically assess the real risks affecting quality.

An Illustration of Broken Thinking
----------------------------------
The article most cited to me is the well read [Test Pyramid](http://martinfowler.com/bliki/TestPyramid.html) by Martin Fowler which references the original Mike Cohn article, [The Forgotten Layer of the Test Automation Pyramid](https://www.mountaingoatsoftware.com/blog/the-forgotten-layer-of-the-test-automation-pyramid)

Martins post links to another well known supporting article from the Google Testing Blog with the deliberately captivating title...

[Just Say No to More End-to-End Tests](http://googletesting.blogspot.ch/2015/04/just-say-no-to-more-end-to-end-tests.html)

Which captures the narrow experiences and environment of one setup with some fundamental problems. Some parts of that Google testing blog post I simply did not fully understand until a few re-reads, and even then I was left questioning the validity of what I read. I felt it sounded outdated, and was based on some strange assumptions, it appears I am not alone.

A counterpoint is posted on Martin's post, which is also worth reading: [Making End-to-End Tests Work](https://www.symphonious.net/2015/04/30/making-end-to-end-tests-work/) which succinctly points out some limitation of the test system mentioned in the Google testing blog post above...

> "If your idea of fantastic test infrastructure starts with the words "every night" and ends with an email being sent you're doomed"

The Google post is further analytically [dismembered here](http://bryanpendleton.blogspot.com.au/2015/04/on-testing-strategies-and-end-to-end.html?m=1), and this article captures my own confusion well...

> "Whatever went wrong with this project, though, one thing is very clear to me:
>
> The testing strategy is not the problem here."

Detail of Availability Bias
---------------------------------
(my own pseudo science - feel free to skip to next section (but there is mention of interesting work in any case))

Recently I have been reading a fascinating book that has long been on my to-read list: [Kahneman's Thinking Fast and Slow](http://www.amazon.co.uk/Thinking-Fast-Slow-Daniel-Kahneman/dp/0141033576). Fortuitously Kahneman has gifted me another tool in my arsenal against the over valuing of unit tests. Availability bias.

The over importance of unit testing may just be down to availability bias.

When I analyse the past encounters over the issue of unit testing vs other types of testing, I suspect this bias (or availability heuristic as it is also known) may be the main factor that tips the balance in favour of unit tests and has resulted in them appearing to be so important.

Whilst I can't do the book justice here, I'll try and capture the salient points. Availability bias is an example of many evolutionary shortcuts in the human mind that can substitute a simple emotional decision for an otherwise difficult complex one, and has been demonstrated in many, brilliant, simple psychological experiments.

In particular, according to Kahneman, Norbert Schwarz showed the paradox that we are less confident in our decision when asked to come up with more reasons why it is a good decision. Our brains make an overconfident emotional decision when we can immediately produce a few supporting reasons, and a less confident decision, when forced to think harder. This is one of those paradoxes which are obvious when pointed out.

The book goes onto describe some related effects, regarding risk, which triggered my connection with testing, because I think much more in terms of risk than of test type, or test metric. Research by Paul Slovic, Sarah Lichtenstein and Baruch Fischhoff Showed that scientists opinions on the benefits of a particular technology could be increased by downplaying the risks, and similarly that the perception of the risks of a technology would be decreased, just by describing the benefits.

It is clear how this emotional bias can be applied to software testing:

1. A lack of unit tests most often described as (and can be) a risk - therefore the benefits of unit tests are exaggerated in our minds.
2. We can quickly recall a few examples of people who repeat the advantages of unit tests, and quickly recall a few personal experiences that support their advantage so the risks of focussing on them are downplayed.

This is all based in normal animal survival laziness - it takes energy for our deep thinking brain to engage.

A more direct consequence of our natural laziness also has a different type of biasing effect on the increased value attributed to unit testing.

It is hard for anyone deeply embedded in a development team to truly know how valuable the team is, or, where necessary, how valuable individual members of the team are, or even how good the product is. The situation has developed where the very people responsible for the success of a development team are some of the least likely to be able to make an objective decision. Under these conditions it is easy to see how 'measurement' is needed, it is this natural laziness that allows easy measurements to become so influential.

Unit tests are easy, and the quick visibility they afford in the form of the second most harmfull metric in development - coverage, creates something measurable. This is an easy metric, and when coupled with the biases of 1 and 2 above it is easy to see how unit testing and test coverage take on a an overly exaggerated value. Perhaps most often outside of the team who writes the tests.

I also think it is likely that we are still suffering the rebound from 10 years ago when test automation and unit testing were much less an integral part of the development cycle. The easiest goto tool in the interim has been the unit test.

The Smart Way
-------------

Whilst this post actually started out as a document of my linking availability bias with the over emphasis on unit testing and was not meant to be about the value of various tests in practice, it is probably clear that I encourage a more individually considered approach, than a set of prescribed rules.

I want to make it clear that I totally understand that there are loads of cases, particularly on the computer science focussed side of development where unit tests are essentially the only sensible test strategy. But they are only one part of the package, and often a small part.

In this article: [Why the Testing Pyramid is Misleading](http://www.joecolantonio.com/2015/12/09/why-the-testing-pyramid-is-misleading-think-scales/) the author discusses Todd Gardners (TrackJs) views which could be concieved to be indirectly addressing availability bias of unit tests, by making the point that we tend to not think in terms of risk. This article resonates strongly with my own approach to quality (again where quality is typically a bigger thing than that which we normally test for)

That article references the video offering very sensible advice from Todd Gardner, Software Engineer and Entrepreneur at TrackJS, namely think critically...

[Case Studies in Terrible Testing](https://vimeo.com/144684986)
(slide deck [here](http://www.slideshare.net/todd3091/case-studies-in-terrible-testing))

Especially salient is the advice from 25 minutes on, though this picture of the relative importance of different testing to mitigate the scale of the risks to the success of one particular project should illustrate the main thrust of the presentation...

![testing scales](https://lh3.googleusercontent.com/-uyf9z1SiSgw/Vnft1EYuFaI/AAAAAAAAMlQ/j_PQhbHL-jI/w1167-d-h870-p-rw "Testing Scales")
_Figure 1. A custom set of sliding scales of differing test strategies_

When we truly think about how we can best reduce the risk to success, and use alternative appropriate tools to manage that risk we start to focus more on delivering real value.

Monitoring, CD, and a real understanding of the users perceived value or quality through canary code, A/B testing and the like will have a much bigger impact than 70% coverage.

> "Fast to fix is almost as good as never broken (and sometimes better)"

_(from Todd's slides above)_

The 'scales of risk' metaphor is much more intelligent and appropriate than the pyramid. The pyramid is one combination of the risk scales which may well align with a correct assignment of risk in a minority of real world cases (as would the ice cream cone). Though as far as I remember, not on any projects I have worked on.


text:
<?xml version="1.0" encoding="utf-8"?>
<transitionSet xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:targetApi="lollipop"
    android:duration="1000"
    android:transitionOrdering="together">

    <targets>
        <!-- don't animate the status bar and navigation bar to avoid flickering due to different windowBackgrounds across activities -->
        <target android:excludeId="@android:id/statusBarBackground" />
        <target android:excludeId="@android:id/navigationBarBackground"/>
        <target android:excludeId="@id/action_bar_container" />
    </targets>

    <fade android:fadingMode="fade_out" />

    <slide android:slideEdge="top" />

</transitionSet>


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Miscellaneous — WinSys v0.5beta documentation</title>
    <link rel="stylesheet" href="_static/winsys.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="author" title="About these documents" href="about.html" />
    <link rel="top" title="WinSys v0.5beta documentation" href="index.html" />
    <link rel="next" title="logging_handlers – Additional Logging Handlers" href="logging_handlers.html" />
    <link rel="prev" title="security" href="security.html" />

Navigation

          index

          modules |

          next |

          previous |

WinSys v0.5beta documentation »

Miscellaneous¶

Introduction¶

Various of the modules offered by winsys don’t fit neatly into
any one area. These include the <tt class="xref py py-mod docutils literal">logging_handlers</tt>, based on the
<tt class="xref py py-class docutils literal">Mailslot</tt> class.

Sections¶

<tt class="docutils literal">logging_handlers</tt> – Additional Logging Handlers

Introduction

Classes

<tt class="docutils literal">environment</tt> – Environment Block

Functions

Classes

References

Table Of Contents

Miscellaneous

Introduction

Sections

Previous topic

<tt class="docutils literal">security</tt>

Next topic

<tt class="docutils literal docutils literal docutils literal">logging_handlers</tt> – Additional Logging Handlers

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

WinSys v0.5beta documentation »

        © Copyright 2011, Tim Golden.
      Created using Sphinx 1.0.7.


text:
package readinglist;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private ReaderRepository readerRepository;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/").access("hasRole('READER')")
				.antMatchers("/**").permitAll().and().formLogin()
				.loginPage("/login").failureUrl("/login?error=true");
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth)
			throws Exception {
		auth.userDetailsService(new UserDetailsService() {
			@Override
			public UserDetails loadUserByUsername(String username)
					throws UsernameNotFoundException {
				Reader reader = readerRepository.findOne(username);
				if (reader != null) {
					return reader;
				} else {
					throw new UsernameNotFoundException(
							"Could not find user: " + username);
				}
			}
		});
	}
}


text:
#include <QtGui/qdialog.h>

class Type;
class TileSet;
class PreviewBox;
class QLineEdit;
class QComboBox;
class QSpinBox;
class QDoubleSpinBox;

class NewTypeDialog : public QDialog {
    Q_OBJECT

public:
    NewTypeDialog(QWidget* parent = 0, Qt::WindowFlags flags = 0);

    Type* createType(TileSet* tileSet);

private:
    PreviewBox* mPreview;
    QComboBox* mMesh;

    QSpinBox* mX;
    QSpinBox* mY;

    private slots:
        void changeSize();
};


text:
import tornado.escape
import tornado.web
import tornado.websocket
import motor
import logging
import ast
import bcrypt

from interface import *
from choices import *
from decorators import *

__all__ = [
    "LoginHandler", "LogoutHandler",
    "DeviceListHandler", "DeviceCreateHandler", "DeviceUpdateHandler",
    "UserListHandler", "UserCreateHandler", "UserUpdateHandler",
    "DeviceSocketHandler", "TrebolSocketHandler",
]

class BaseHandler(tornado.web.RequestHandler):
    def set_current_user(self, user):
        if user:
            self.set_secure_cookie("user", tornado.escape.json_encode(user))
        else:
            self.clear_cookie("user")

    def get_current_user(self):
        user_json = self.get_secure_cookie("user")
        if user_json:
            return tornado.escape.json_decode(user_json)
        else:
            return None

    def set_message(self, kind, text):
        msg = {"type": kind, "text": text}
        self.set_secure_cookie("message", str(msg))

    def get_message(self):
        message = self.get_secure_cookie("message")
        self.clear_cookie("message")
        if message:
            message = ast.literal_eval(message)
        return message

class LoginHandler(BaseHandler):
    def get(self):
        self.render("login.html", message=self.get_message())

    @tornado.gen.coroutine
    def post(self):
        users = self.settings["db"].users
        email = self.get_argument("email", "")
        password = self.get_argument("password", "").encode()
        user = yield users.find_one({"email": email})

        if user and user['hash'] and \
           bcrypt.hashpw(password, user["hash"].encode()) == user["hash"]:
            user.pop("hash")
            self.set_current_user(user)
            self.redirect(self.get_argument("next", u"/device/list/"))
        else:
            self.set_message("danger", "Authorization Failure.")
            self.redirect(self.settings["login_url"])

class LogoutHandler(BaseHandler):
    def get(self):
        self.clear_cookie("user")
        self.redirect(self.get_argument("next", "/"))

class DeviceListHandler(BaseHandler):
    @tornado.web.authenticated
    @tornado.gen.coroutine
    def get(self):
        db = self.settings["db"]
        cursor = db.devices.find().sort('name', 1)
        count = yield cursor.count()
        devices = yield cursor.to_list(count)

        self.render(
            "device_list.html",
            username=self.get_current_user(),
            devices=devices,
            message=self.get_message()
        )

class DeviceCreateHandler(BaseHandler):
    @tornado.web.authenticated
    @is_admin
    def get(self):
        self.render("device_create.html", message=self.get_message())

    @tornado.gen.coroutine
    def post(self):
        db = self.settings["db"]
        name = self.get_argument("name", "")
        key = self.get_argument("key", "")
        device = yield db.devices.find_one({"name": name})

        if device is not None:
            kind = "danger"
            text = "Device already exists."
        elif name and key:
            yield db.devices.insert({
                "name": name,
                "key": key,
                "address": None,
            })
            kind = "success"
            text = "Device {} added succesfully".format(name)
        else:
            kind = "danger"
            text = "Please enter a valid device."

        self.set_message(kind, text)
        self.redirect('/device/create/')

class DeviceUpdateHandler(BaseHandler):
    @tornado.web.authenticated
    @is_admin
    @tornado.gen.coroutine
    def get(self, slug):
        db = self.settings["db"]
        name = slug.rstrip("/")
        device = yield db.devices.find_one({"name": name})

        if device is None:
            raise tornado.web.HTTPError(404)

        message = self.get_secure_cookie("message", "")
        self.render(
            "device_update.html", device=device, message=message)

    @tornado.gen.coroutine
    def post(self, slug):
        db = self.settings["db"]
        name = slug.rstrip("/")
        device = yield db.devices.find_one({"name": name})
        action = self.get_argument("action", "")

        if action not in ("update", "delete") or device is None:
            raise tornado.web.HTTPError(404)

        if action == "delete":
            response = yield db.devices.remove({"name": name})
            if response["err"] is None:
                kind = "success"
                text = "Device {} deleted.".format(name)
            else:
                kind = "danger"
                text = "Device {} could not be deleted: {}".format(
                    name, response["err"])
            redirect = "/device/list/"
        elif action == "update":
            new_name = self.get_argument("name", None)
            new_key = self.get_argument("key", None)

            if new_name is None:
                kind = "danger"
                text = "Please enter a device name."
                redirect = "/device/{}/update/".format(name)
            elif new_key is None:
                kind = "danger"
                text = "Please enter a key for device."
                redirect = "/device/{}/update/".format(name)
            else:
                update = {"name": new_name, "key": new_key}
                response = yield db.devices.update(
                    {"name": name}, {"$set": update})

                if response["err"] is None:
                    kind = "success"
                    text = "Device updated succesfully."
                else:
                    kind = "alert"
                    text = "Device update failure: {}".format(response["err"])
                redirect = "/device/{}/update/".format(name)

        self.set_message(kind, text)
        self.redirect(redirect)

class UserListHandler(BaseHandler):
    @tornado.web.authenticated
    @is_admin
    @tornado.gen.coroutine
    def get(self):
        cursor = self.settings["db"].users.find().sort('_id', 1)
        count = yield cursor.count()
        users = yield cursor.to_list(count)
        self.render("user_list.html", users=users, message=self.get_message())

class UserCreateHandler(BaseHandler):
    @tornado.web.authenticated
    @is_admin
    def get(self):
        self.render(
            "user_create.html", message=self.get_message(), groups=USER_GROUPS)

    @tornado.gen.coroutine
    def post(self):
        db = self.settings["db"]
        email = self.get_argument("email", "")
        password = self.get_argument("password", "")
        group = self.get_argument("group", "")
        user = yield db.users.find_one({"email": email})

        if user is not None:
            kind = "danger"
            text = "User already exists."
        elif email and password and group in USER_GROUPS:
            yield create_new_user(db, email, password, group)
            kind = "success"
            text = "User {} added succesfully.".format(email)
        else:
            kind = "danger"
            text = "Please enter a valid user."

        self.set_message(kind, text)
        self.redirect("/user/create/")

class UserUpdateHandler(BaseHandler):
    @tornado.web.authenticated
    @is_admin
    @tornado.gen.coroutine
    def get(self, uid):
        user = yield self.settings["db"].users.find_one({"_id": int(uid)})
        if user is None:
            raise tornado.web.HTTPError(404)

        self.render("user_update.html", user=user, message=self.get_message(),
                    groups=USER_GROUPS)

    @tornado.gen.coroutine
    def post(self, uid):
        db = self.settings["db"]
        uid = int(uid)
        user = yield db.users.find_one({"_id": uid})
        action = self.get_argument("action", "")

        if action not in ("update", "delete") or user is None:
            raise tornado.web.HTTPError(404)

        if action == "delete":
            response = yield db.users.remove({"_id": uid})
            if response["err"] is None:
                kind = "success"
                text = "User {} deleted.".format(user["email"])
            else:
                kind = "danger"
                text = "User {} could not be deleted: {}".format(
                    user["email"], response["err"])
            redirect = "/device/list/"
        elif action == "update":
            new_email = self.get_argument("email", None)
            new_group = self.get_argument("group", None)
            new_pass = self.get_argument("password", None)

            if new_email == "" or new_group not in USER_GROUPS:
                kind = "danger"
                text = "Please enter a valid user."
                redirect = "/user/{}/update/".format(name)
            else:
                update = {"email": new_email, "group": new_group}
                if new_pass != "":
                    update.update({"hash": bcrypt.hashpw(
                        new_pass.encode(), bcrypt.gensalt(8))})
                response = yield db.users.update(
                    {"_id": uid}, {"$set": update})
                redirect = "/user/{}/update".format(str(uid))

                if response["err"] is None:
                    kind = "success"
                    text = "User updated successfully."

                    if user["email"] == self.get_current_user()["email"]:
                        if update.has_key("hash"):
                            update.pop("hash")
                        self.set_current_user(update)
                else:
                    kind = "danger"
                    text = "User update failure: {}".format(response["err"])

        self.set_message(kind, text)
        self.redirect(redirect)

class DeviceSocketHandler(tornado.websocket.WebSocketHandler):
    devices = set()

    @tornado.gen.coroutine
    def open(self):
        if not self.request.headers.has_key("X-Device-Name"):
            self.write_message("missing-device-name")
            self.close()
            self.finish()

        if not self.request.headers.has_key("X-Device-Key"):
            self.write_message("missing-device-key")
            self.close()
            self.finish()

        if self.request.headers.has_key("X-Real-Ip"):
            self.request.remote_ip = self.request.headers.get("X-Real-Ip")

        name = self.request.headers["X-Device-Name"]
        key = self.request.headers["X-Device-Key"]
        device = yield self.settings["db"].devices.find_and_modify(
            {"name": name, "key": key},
            {"$set": {"address": self.request.remote_ip}},
            new=True)

        if device is None:
            self.write_message("device-does-not-exist")
            self.close()

        DeviceSocketHandler.devices.add(self)
        logging.info("A device connected.")
        TrebolSocketHandler.device_action(self, "connect")

    def on_close(self):
        DeviceSocketHandler.devices.remove(self)
        logging.info("A device disconnected.")
        TrebolSocketHandler.device_action(self, "disconnect")

class TrebolSocketHandler(tornado.websocket.WebSocketHandler):
    clients = set()

    def open(self):
        TrebolSocketHandler.clients.add(self)
        logging.info("A Trebol client connected.")

        for device in DeviceSocketHandler.devices:
            TrebolSocketHandler.device_action(device, "connect")

    @classmethod
    def device_action(cls, device, action):
        msg = {
            "action": action,
            "device": device.request.headers["X-Device-Name"],
            "address": device.request.remote_ip,
        }

        for client in cls.clients:
            client.write_message(msg)

    def on_close(self):
        TrebolSocketHandler.clients.remove(self)
        logging.info("A Trebol client disconnected.")


text:
aacgmv2._aacgmv2
================

This submodule contains the interface to the AACGM-v2 C library. For the user-friendly wrapper, see the functions in :py:mod:`aacgmv2.wrapper`.

.. automodule:: aacgmv2._aacgmv2
    :members:


text:
package org.apache.commons.codec;

/**
 * Defines common encoding methods for String encoders.
 *
 * @version $Id$
 */
public interface StringEncoder extends Encoder {

    /**
     * Encodes a String and returns a String.
     *
     * @param source
     *            the String to encode
     * @return the encoded String
     * @throws EncoderException
     *             thrown if there is an error condition during the encoding process.
     */
    String encode(String source) throws EncoderException;
}


text:
import constants from '../constants';

export const isLoggedIn = () => {
  return typeof window !=='undefined' && !!window.localStorage[ constants.jwt_token.TOKEN_NAME ];
};

export const requireAuth = (nextState, replaceState) => {
  // console.log({ nextState, replaceState });
  // console.log("nextState.location.pathname.indexOf('p-admin')!==-1",nextState.location.pathname.indexOf('p-admin')!==-1)
  if (!isLoggedIn()) {
    replaceState({
      pathname: (nextState.location.pathname.indexOf('p-admin')!==-1)?`/p-admin/login?return_url=${nextState.location.pathname}`:`/login?return_url=${nextState.location.pathname}`,
      state: {
        nextPathname: nextState.location.pathname,
      },
    });
  }
};

export const getMFAPath = (state) => {
  let mfapath = (state.manifest.containers[ `${state.settings.adminPath}/mfa` ])
    ? `${state.settings.adminPath}/mfa`
    : '/mfa';
  // console.log({ mfapath });
  return mfapath;
};

export const getMFASetupPath = (state) => {
  let mfasetuppath = (state.manifest.containers[ `${state.settings.adminPath}/auth/login-otp-setup` ])
    ? `${state.settings.adminPath}/auth/login-otp-setup`
    : '/auth/login-otp-setup';
  // console.log({ mfasetuppath });
  return mfasetuppath;
};


text:
<?php namespace Bluematt\Litcode\Block\Element;

use League\CommonMark\ContextInterface;
use League\CommonMark\Util\ArrayCollection;
use League\CommonMark\Util\RegexHelper;
use Bluematt\Litcode\Util\FileCommand;

class FencedCode
  extends \League\CommonMark\Block\Element\FencedCode {
    use ExportableTrait;

    public function finalize(ContextInterface $context)
    {
        parent::finalize($context);

        // Create an empty file/command
        $this->fileCommand = new FileCommand('');

        // Remove empty lines from the end of the code
        $reversed = array_reverse($this->getStrings(), true);
        foreach ($reversed as $index => $line) {
            if ($line == '' || $line === "\n" || preg_match('/^(\n *)$/', $line)) {
                unset($reversed[$index]);
            } else {
                break;
            }
        }

        // Handle the info string (e.g. "``` php")
        $this->info = RegexHelper::unescape(trim($this->strings->first()));

        if ($this->strings->count() == 1) {
            $this->finalStringContents = '';
        } else {
            // Remove the first line (the ```)
            $strings       = array_values($this->strings->slice(1));
            $this->strings = new ArrayCollection($strings);
            // If there's any content left, this is the code
            if ($this->strings->count()) {
                // If the first line is a file/command, remove the line
                if (FileCommand::isFileCommand($this->strings->get(0))) {
                    $this->fileCommand = new FileCommand($this->strings->get(0));
                    $this->strings->remove(0);
                }
            }
            $this->finalStringContents = implode("\n", $this->strings->toArray());
        }
    }

    //    public function getFileCommand()
    //    {
    //        // TODO: Implement getFileCommand() method.
    //    }

    //    public function setFileCommand(FileCommand $fileCommand)
    //    {
    //        // TODO: Implement setFileCommand() method.
    //    }
}


text:
import {
  is,
  any,
  start,
  end,
  progress,
  percent,
  endProgress,
  nodeIsDebug
} from './utils';

// Import to export
import { mapWaitingActions, mapWaitingGetters, waitFor } from './helpers';

import vuexStore from './vuex/store';
import vWaitComponent from './components/v-wait.vue';
import vWaitDirective from './directives/wait.js';

export default class VueWait {
  constructor(options = {}) {
    const defaults = {
      accessorName: '$wait',
      // Vuex Options
      useVuex: false,
      vuexModuleName: 'wait',
      // Components
      registerComponent: true,
      componentName: 'v-wait',
      // Directives
      registerDirective: true,
      directiveName: 'wait'
    };
    this.options = {
      ...defaults,
      ...options
    };
    this.initialized = false;
  }

  init(App, store) {
    if (nodeIsDebug() && !install.installed && VueWait.getVueVersion(App) < 3) {
      console.warn(
        `[vue-wait] not installed. Make sure to call \`Vue.use(VueWait)\` before init root instance.`
      );
    }

    if (this.initialized) {
      return;
    }

    if (this.options.registerComponent) {
      App.component(this.options.componentName, vWaitComponent);
    }

    if (this.options.registerDirective) {
      App.directive(this.options.directiveName, vWaitDirective);
    }

    if (this.options.useVuex) {
      const { vuexModuleName } = this.options;
      if (!store) {
        throw new Error('[vue-wait] Vuex not initialized.');
      }
      this.store = store;

      if (!store._modules.get([vuexModuleName])) {
        store.registerModule(vuexModuleName, vuexStore);
      }

      const config = {
        computed: {
          is: () => waiter => store.getters[`${vuexModuleName}/is`](waiter),
          any: () => store.getters[`${vuexModuleName}/any`],
          percent: () => waiter =>
            store.getters[`${vuexModuleName}/percent`](waiter)
        }
      };

      if (VueWait.getVueVersion(App) > 2) {
        const { createApp } = require('vue');
        this.stateHandler = createApp(config).mount(
          document.createElement('div')
        );
      } else {
        this.stateHandler = new App(config);
      }
    } else {
      const config = {
        data() {
          return {
            waitingFor: [],
            progresses: {}
          };
        },
        computed: {
          is() {
            return waiter => is(this.waitingFor, waiter);
          },
          any() {
            return any(this.waitingFor);
          },
          percent() {
            return waiter => percent(this.progresses, waiter);
          }
        },
        methods: {
          start(waiter) {
            this.waitingFor = start(this.waitingFor, waiter);
          },
          end(waiter) {
            this.waitingFor = end(this.waitingFor, waiter);
            this.progresses = endProgress(this.progresses, waiter);
          },
          progress({ waiter, current, total }) {
            this.progresses = progress(this.progresses, waiter, current, total);
          }
        }
      };

      if (VueWait.getVueVersion(App) > 2) {
        const { createApp } = require('vue');
        this.stateHandler = createApp(config).mount(
          document.createElement('div')
        );
      } else {
        this.stateHandler = new App(config);
      }
    }

    this.initialized = true;
  }

  get any() {
    return this.stateHandler.any;
  }

  static getVueVersion(app) {
    return parseFloat((app.version || '').split('.')[0] || 0);
  }

  is(waiter) {
    return this.stateHandler.is(waiter);
  }

  // alias for `is`
  waiting(waiter) {
    return this.is(waiter);
  }

  percent(waiter) {
    return this.stateHandler.percent(waiter);
  }

  dispatchWaitingAction(action, waiter) {
    const { vuexModuleName } = this.options;
    this.store.dispatch(`${vuexModuleName}/${action}`, waiter, {
      root: true
    });
  }

  start(waiter) {
    if (this.options.useVuex) {
      this.dispatchWaitingAction('start', waiter);
      return;
    }
    this.stateHandler.start(waiter);
  }

  end(waiter) {
    if (this.options.useVuex) {
      this.dispatchWaitingAction('end', waiter);
      return;
    }
    this.stateHandler.end(waiter);
  }

  progress(waiter, current, total = 100) {
    if (!this.is(waiter)) {
      this.start(waiter);
    }

    if (current > total) {
      this.end(waiter);
      return;
    }

    if (this.options.useVuex) {
      this.dispatchWaitingAction('progress', { waiter, current, total });
      return;
    }
    this.stateHandler.progress({ waiter, current, total });
  }
}

export function install(App) {
  if (install.installed && App) {
    if (nodeIsDebug()) {
      console.warn(
        '[vue-wait] already installed. Vue.use(VueWait) should be called only once.'
      );
    }
    return;
  }

  App.mixin({
    /**
     * VueWait init hook, injected into each instances init hooks list.
     */
    beforeCreate() {
      const { wait, store, parent } = this.$options;

      let instance = null;
      if (wait) {
        instance = typeof wait === 'function' ? new wait() : wait;
        // Inject store
        instance.init(App, store);
      } else if (parent && parent.__$waitInstance) {
        instance = parent.__$waitInstance;
        instance.init(App, parent.$store);
      }

      if (instance) {
        // Store helper for internal use
        this.__$waitInstance = instance;
        this[instance.options.accessorName] = instance;
      }
    }
  });

  install.installed = true;
}

function createVueWait(options) {
  const Wait = {
    instance: null,
    async install(app) {
      if (this.installed && app) {
        if (nodeIsDebug()) {
          console.warn('[vue-wait] already installed');
        }
        return this.instance;
      }

      const instance = new VueWait(options);
      instance.init(app, app.config.globalProperties.$store);
      app.config.globalProperties[instance.options.accessorName] = instance;

      app.mixin({
        beforeCreate() {
          this.__$waitInstance = instance;
        }
      });

      this.instance = instance;
      this.installed = true;
      return instance;
    }
  };

  return Wait;
}

// Export which are imported to export
export { mapWaitingActions, mapWaitingGetters, waitFor, createVueWait };

VueWait.install = install;


text:
if exists (select * from sysobjects where id = object_id(N'[dbo].[NoVisReport]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[NoVisReport]
GO

CREATE PROCEDURE [dbo].[NoVisReport]
									@Param1		INT,
									@Param2		DATETIME=NULL
AS

SELECT @Param1 Col1, @Param2 Col2


text:
FROM phusion/baseimage:latest
MAINTAINER Mike Petersen <mike@odania-it.de>

ENV HOME /root
ADD . /srv
RUN /srv/install.sh
CMD ["/sbin/my_init"]

EXPOSE 80


text:
package scala.meta.tests.parsers

import scala.compat.Platform.EOL
import scala.meta._

import munit._

import scala.meta.tests.TreeSuiteBase

class ToplevelTermSuite extends TreeSuiteBase {
  implicit val dialect: Dialect = dialects.Scala3.withAllowToplevelTerms(true)
  test("allowToplevelTerms simple") {

    val sourceString = """def foo(x: Int): Int = x
                          |foo(x)
                          |""".trim.stripMargin

    val tree = sourceString.parse[Source].get

    assertEquals(tree.syntax, sourceString)
    val expected =
      Source(
        List(
          Defn.Def(
            Nil,
            Term.Name("foo"),
            Nil,
            List(List(Term.Param(Nil, Term.Name("x"), Some(Type.Name("Int")), None))),
            Some(Type.Name("Int")),
            Term.Name("x")
          ),
          Term.Apply(Term.Name("foo"), List(Term.Name("x")))
        )
      )
    assertTree(tree)(expected)
  }

  test("allowToplevelTerms and allowPackageStatementsWithToplevelTerms with package") {

    val sourceString = """package bar
                         |def foo(x: Int): Int = x
                         |foo(x)
                         |""".trim.stripMargin

    val tree = sourceString.parse[Source].get

    assertEquals(tree.syntax, sourceString)
    val expected =
      Source(
        List(
          Pkg(
            Term.Name("bar"),
            List(
              Defn.Def(
                Nil,
                Term.Name("foo"),
                Nil,
                List(List(Term.Param(Nil, Term.Name("x"), Some(Type.Name("Int")), None))),
                Some(Type.Name("Int")),
                Term.Name("x")
              ),
              Term.Apply(Term.Name("foo"), List(Term.Name("x")))
            )
          )
        )
      )
    assertTree(tree)(expected)
  }

  test("allowToplevelTerms and allowPackageStatementsWithToplevelTerms no package") {
    val sourceString = """def foo(x: Int): Int = x
                         |foo(x)
                         |""".trim.stripMargin

    val tree = sourceString.parse[Source].get

    assertEquals(tree.syntax, sourceString)
    val expected = Source(
      List(
        Defn.Def(
          Nil,
          Term.Name("foo"),
          Nil,
          List(List(Term.Param(Nil, Term.Name("x"), Some(Type.Name("Int")), None))),
          Some(Type.Name("Int")),
          Term.Name("x")
        ),
        Term.Apply(Term.Name("foo"), List(Term.Name("x")))
      )
    )
    assertTree(tree)(expected)
  }

}


text:
<readable><title>293881927_ac62900fd4</title><content>
a dog jumps over a fence , while two other dogs watch .
One dog , apparently standing on the edge of a fence , confronts three others in a backyard setting .
The dog is on the fence
Three dogs are in a fenced yard and one is jumping off the fence .
Two pitbulls fighting , one standing on top of a fence .
</content></readable>


text:
const INITIAL_STATE = {
  items: null,
  open: false
}

const open = (state, action) => ({
  ...state,
  items: action.items,
  open: true
})

const close = (state, action) => ({
  ...state,
  open: false
})

const clear = (state, action) => INITIAL_STATE

const reducer = (state = INITIAL_STATE, action) => {

  switch (action.type) {

  case 'OPEN':
    return open(state, action)

  case 'CLOSE':
    return close(state, action)

  case 'CLEAR':
    return clear(state, action)

  default:
    return state
  }

}

export default reducer


text:
package net.ssehub.kernel_haven.util.logic;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static net.ssehub.kernel_haven.util.logic.FormulaBuilder.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import net.ssehub.kernel_haven.util.null_checks.NonNull;

/**
 * Tests for VariableValueReplacer.
 *
 * @author bargfeldt
 *
 */
@RunWith(Parameterized.class)
public class VariableValueReplacerTest {

    private @NonNull Formula formula;
    private @NonNull String variable;
    private boolean value;
    private boolean exactMatch;

    private @NonNull Formula expected;

    /**
     * Constructor for VariableValueReplacerTest.
     *
     * @param formula Input formula
     * @param variable Input variable
     * @param value Input value
     * @param exactMatch Input exactMatch
     * @param expected Expected output
     */
    public VariableValueReplacerTest(@NonNull Formula formula, @NonNull String variable, boolean value,
        boolean exactMatch, @NonNull Formula expected) {
        this.formula = formula;
        this.variable = variable;
        this.value = value;
        this.exactMatch = exactMatch;
        this.expected = expected;
    }

    /**
     * Test parameters.
     *
     * @return Collection of parameters
     */
    @Parameters(name = "{0} -> {4}")
    public static Collection<Object[]> getParameters() {
        return Arrays.asList(new Object[][] {
            {True.INSTANCE, "A", false, true, True.INSTANCE},
            {False.INSTANCE, "A", true, true, False.INSTANCE},

            {new Variable("A"), "A", false, true, False.INSTANCE},
            {new Variable("A"), "A", true, true, True.INSTANCE},
            {new Variable("X"), "A", true, true, new Variable("X")},
            {new Variable("Foo"), "F", false, false, False.INSTANCE},
            {new Variable("Foo"), "X", false, false, new Variable("Foo")},

            {not(new Variable("Foo")), "F", false, false, not(False.INSTANCE)},
            {not(not(new Variable("Bar"))), "Bar", true, true, not(not(True.INSTANCE))},

            {or("Foo", False.INSTANCE), "Foo", true, true, or(True.INSTANCE, False.INSTANCE)},
            {or(True.INSTANCE, "Bar"), "B", false, false, or(True.INSTANCE, False.INSTANCE)},
            {or(True.INSTANCE, "Bar"), "B", false, true, or(True.INSTANCE, "Bar")},

            {and("Foo", False.INSTANCE), "Foo", true, true, and(True.INSTANCE, False.INSTANCE)},
            {and(True.INSTANCE, "Bar"), "B", false, false, and(True.INSTANCE, False.INSTANCE)},
            {and(True.INSTANCE, "Bar"), "B", false, true, and(True.INSTANCE, "Bar")},

            {or(and("A", not("B")), not(or(True.INSTANCE, and("C", "B")))), "B", false, true,
                or(and("A", not(False.INSTANCE)), not(or(True.INSTANCE, and("C", False.INSTANCE))))},
        });
    }

    /**
     * Run the tests.
     */
    @Test
    public void test() {
        assertThat(new VariableValueReplacer(variable, value, exactMatch).visit(formula), is(expected));
    }

}


text:
const createService = require('feathers-mongoose');
const createModel = require('../../models/cities.model');
const hooks = require('./cities.hooks');
const filters = require('./cities.filters');

module.exports = function () {
  const app = this;
  const Model = createModel(app);
  const paginate = app.get('paginate');

  const options = {
    name: 'cities',
    Model,
    paginate
  };

  // Initialize our service with any options it requires
  app.use('/cities', createService(options));

  // Get our initialized service so that we can register hooks and filters
  const service = app.service('cities');

  service.hooks(hooks);

  if (service.filter) {
    service.filter(filters);
  }
};


text:
package com.intellij.codeInspection.deadCode;

import com.intellij.analysis.AnalysisScope;
import com.intellij.codeInsight.daemon.impl.quickfix.SafeDeleteFix;
import com.intellij.codeInspection.*;
import com.intellij.codeInspection.ex.EntryPointsManagerImpl;
import com.intellij.codeInspection.ex.GlobalInspectionContextImpl;
import com.intellij.codeInspection.ex.InspectionToolWrapper;
import com.intellij.codeInspection.ex.Tools;
import com.intellij.codeInspection.reference.*;
import com.intellij.codeInspection.ui.InspectionToolPresentation;
import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection;
import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspectionBase;
import com.intellij.java.JavaBundle;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.DefUseUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.TitledSeparator;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBRadioButton;
import com.intellij.ui.components.JBTabbedPane;
import com.intellij.util.ObjectUtils;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.uast.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public final class UnusedDeclarationInspection extends UnusedDeclarationInspectionBase {
  private final UnusedParametersInspection myUnusedParameters = new UnusedParametersInspection();

  public UnusedDeclarationInspection() { }

  @TestOnly
  public UnusedDeclarationInspection(boolean enabledInEditor) {
    super(enabledInEditor);
  }

  @Override
  public String getAlternativeID() {
    return UnusedSymbolLocalInspectionBase.UNUSED_PARAMETERS_SHORT_NAME;
  }

  @Override
  public void runInspection(@NotNull AnalysisScope scope,
                            @NotNull InspectionManager manager,
                            @NotNull GlobalInspectionContext globalContext,
                            @NotNull ProblemDescriptionsProcessor problemDescriptionsProcessor) {
    if (myLocalInspectionBase.PARAMETER) {
      globalContext.getRefManager().iterate(new RefVisitor() {
        @Override public void visitElement(@NotNull RefEntity refEntity) {
          try {
            if (!(refEntity instanceof RefMethod) ||
                !globalContext.shouldCheck(refEntity, UnusedDeclarationInspection.this) ||
                !UnusedDeclarationPresentation.compareVisibilities((RefMethod)refEntity, myLocalInspectionBase.getParameterVisibility())) {
              return;
            }
            CommonProblemDescriptor[] descriptors = myUnusedParameters.checkElement(refEntity, scope, manager, globalContext, problemDescriptionsProcessor);
            if (descriptors != null) {
              problemDescriptionsProcessor.addProblemElement(refEntity, descriptors);
            }
          }
          catch (ProcessCanceledException | IndexNotReadyException e) {
            throw e;
          }
          catch (Throwable e) {
            LOG.error("Exception on '" + refEntity.getExternalName() + "'", e);
          }
        }
      });
    }
    super.runInspection(scope, manager, globalContext, problemDescriptionsProcessor);
  }

  @Override
  public RefGraphAnnotator getAnnotator(@NotNull RefManager refManager) {
    return new UnusedVariablesGraphAnnotator(InspectionManager.getInstance(refManager.getProject()), refManager);
  }

  @Override
  public boolean queryExternalUsagesRequests(@NotNull InspectionManager manager,
                                             @NotNull GlobalInspectionContext globalContext,
                                             @NotNull ProblemDescriptionsProcessor problemDescriptionsProcessor) {
    final boolean requests = super.queryExternalUsagesRequests(manager, globalContext, problemDescriptionsProcessor);
    if (!requests && myLocalInspectionBase.PARAMETER) {
      myUnusedParameters.queryExternalUsagesRequests(manager, globalContext, problemDescriptionsProcessor);
    }
    return requests;
  }

  @Nullable
  @Override
  public String getHint(@NotNull QuickFix fix) {
    return myUnusedParameters.getHint(fix);
  }

  @Nullable
  @Override
  public LocalQuickFix getQuickFix(String hint) {
    return myUnusedParameters.getQuickFix(hint);
  }

  @Override
  protected UnusedSymbolLocalInspectionBase createUnusedSymbolLocalInspection() {
    //noinspection deprecation
    return new UnusedSymbolLocalInspection();
  }

  @Override
  public JComponent createOptionsPanel() {
    JTabbedPane tabs = new JBTabbedPane(SwingConstants.TOP);
    tabs.add(JavaBundle.message("tab.title.members.to.report"), ScrollPaneFactory.createScrollPane(myLocalInspectionBase.createOptionsPanel(), true));
    tabs.add(JavaBundle.message("tab.title.entry.points"), ScrollPaneFactory.createScrollPane(new OptionsPanel(), true));
    return tabs;
  }

  private final class OptionsPanel extends JPanel {
    private final JCheckBox myMainsCheckbox;
    private final JCheckBox myAppletToEntries;
    private final JCheckBox myServletToEntries;
    private final JCheckBox myNonJavaCheckbox;

    private OptionsPanel() {
      super(new GridBagLayout());
      GridBagConstraints gc = new GridBagConstraints();
      gc.weightx = 1;
      gc.weighty = 0;

      gc.fill = GridBagConstraints.HORIZONTAL;
      gc.anchor = GridBagConstraints.NORTHWEST;
      gc.gridx = 0;
      gc.gridy = 0;
      gc.gridwidth = 2;
      add(new JBLabel(JavaBundle.message("label.unused.declaration.reachable.from.tests.option")), gc);
      gc.gridy++;

      final JBRadioButton asEntryPoint = new JBRadioButton(JavaBundle.message("radio.button.unused.declaration.used.option"), isTestEntryPoints());
      final JBRadioButton asUnused = new JBRadioButton(JavaBundle.message("radio.button.unused.declaration.unused.option"), !isTestEntryPoints());
      final ButtonGroup group = new ButtonGroup();
      group.add(asEntryPoint);
      group.add(asUnused);
      final ActionListener listener = e -> setTestEntryPoints(asEntryPoint.isSelected());
      asEntryPoint.addActionListener(listener);
      asUnused.addActionListener(listener);

      gc.gridwidth = 1;
      gc.weightx = 0;
      add(asEntryPoint, gc);
      gc.gridx = 1;
      gc.weightx = 1;
      add(asUnused, gc);

      gc.gridx = 0;
      gc.gridy++;

      gc.gridwidth = 2;
      add(new TitledSeparator(), gc);
      gc.gridy++;
      add(new JBLabel(JavaBundle.message("label.entry.points")), gc);
      gc.insets = JBUI.insets(5, 0, 0, 0);
      gc.gridy++;

      add(createBtnPanel(), gc);
      gc.gridy++;
      gc.insets = JBUI.insets(0, 5, 2, 0);

      myMainsCheckbox = new JCheckBox(JavaBundle.message("inspection.dead.code.option.main"));
      myMainsCheckbox.setSelected(ADD_MAINS_TO_ENTRIES);
      myMainsCheckbox.addActionListener(e -> ADD_MAINS_TO_ENTRIES = myMainsCheckbox.isSelected());

      add(myMainsCheckbox, gc);
      gc.gridy++;

      myAppletToEntries = new JCheckBox(JavaBundle.message("inspection.dead.code.option.applet"));
      myAppletToEntries.setSelected(ADD_APPLET_TO_ENTRIES);
      myAppletToEntries.addActionListener(e -> ADD_APPLET_TO_ENTRIES = myAppletToEntries.isSelected());
      add(myAppletToEntries, gc);
      gc.gridy++;

      myServletToEntries = new JCheckBox(JavaBundle.message("inspection.dead.code.option.servlet"));
      myServletToEntries.setSelected(ADD_SERVLET_TO_ENTRIES);
      myServletToEntries.addActionListener(e -> ADD_SERVLET_TO_ENTRIES = myServletToEntries.isSelected());
      add(myServletToEntries, gc);
      gc.gridy++;

      for (final EntryPoint extension : getExtensions()) {
        if (extension.showUI()) {
          final JCheckBox extCheckbox = new JCheckBox(extension.getDisplayName());
          extCheckbox.setSelected(extension.isSelected());
          extCheckbox.addActionListener(e -> {
            extension.setSelected(extCheckbox.isSelected());
            saveEntryPointElement(extension);
          });
          add(extCheckbox, gc);
          gc.gridy++;
        }
      }

      myNonJavaCheckbox =
      new JCheckBox(JavaBundle.message("inspection.dead.code.option.external"));
      myNonJavaCheckbox.setSelected(ADD_NONJAVA_TO_ENTRIES);
      myNonJavaCheckbox.addActionListener(e -> ADD_NONJAVA_TO_ENTRIES = myNonJavaCheckbox.isSelected());

      gc.weighty = 1;
      add(myNonJavaCheckbox, gc);
    }

    private JPanel createBtnPanel() {
      final JPanel btnPanel = new JPanel(new GridBagLayout());
      GridBagConstraints constraints = new GridBagConstraints();
      constraints.anchor = GridBagConstraints.NORTHWEST;
      constraints.fill = GridBagConstraints.NONE;
      constraints.weightx = 0;
      btnPanel.add(EntryPointsManagerImpl.createConfigureClassPatternsButton(), constraints);
      constraints.gridx = 1;
      btnPanel.add(EntryPointsManagerImpl.createConfigureAnnotationsButton(), constraints);
      constraints.fill = GridBagConstraints.HORIZONTAL;
      constraints.weightx = 1;
      btnPanel.add(Box.createHorizontalBox(), constraints);
      return btnPanel;
    }
  }

  private class UnusedVariablesGraphAnnotator extends RefGraphAnnotator {
    private final InspectionManager myInspectionManager;
    private final GlobalInspectionContextImpl myContext;
    private final Tools myTools;

    UnusedVariablesGraphAnnotator(InspectionManager inspectionManager, RefManager refManager) {
      myInspectionManager = inspectionManager;
      myContext = (GlobalInspectionContextImpl)((RefManagerImpl)refManager).getContext();
      myTools = myContext.getTools().get(getShortName());
    }

    @Override
    public void onReferencesBuild(RefElement refElement) {
      if (refElement instanceof RefClass) {
        UClass uClass = ((RefClass)refElement).getUastElement();
        if (uClass != null) {
          for (UClassInitializer initializer : uClass.getInitializers()) {
            findUnusedLocalVariables(initializer.getUastBody(), refElement);
          }
        }
      }
      else if (refElement instanceof RefMethod) {
        UDeclaration element = ((RefMethod)refElement).getUastElement();
        if (element instanceof UMethod) {
          UExpression body = ((UMethod)element).getUastBody();
          if (body != null) {
            findUnusedLocalVariables(body, refElement);
          }
        }
      }
      else if (refElement instanceof RefField) {
        UField field = ((RefField)refElement).getUastElement();
        if (field != null) {
          UExpression initializer = field.getUastInitializer();
          findUnusedLocalVariables(initializer, refElement);
        }
      }
    }

    private void findUnusedLocalVariables(UExpression body, RefElement refElement) {
      if (body == null) return;
      PsiElement psiBody = body.getSourcePsi();
      if (psiBody == null) return;
      if (!myTools.isEnabled(psiBody)) return;
      InspectionToolWrapper toolWrapper = myTools.getInspectionTool(psiBody);
      InspectionToolPresentation presentation = myContext.getPresentation(toolWrapper);
      if (((UnusedDeclarationInspection)toolWrapper.getTool()).getSharedLocalInspectionTool().LOCAL_VARIABLE) {
        List<CommonProblemDescriptor> descriptors = new ArrayList<>();
        findUnusedLocalVariablesInElement(psiBody, descriptors);
        if (!descriptors.isEmpty()) {
          presentation.addProblemElement(refElement, descriptors.toArray(CommonProblemDescriptor.EMPTY_ARRAY));
        }
      }
    }

    private void findUnusedLocalVariablesInElement(@NotNull PsiElement element, @NotNull List<CommonProblemDescriptor> descriptors) {
      Set<PsiVariable> usedVariables = new HashSet<>();
      List<DefUseUtil.Info> unusedDefs = DefUseUtil.getUnusedDefs(element, usedVariables);
      if (unusedDefs != null && !unusedDefs.isEmpty()) {
        for (DefUseUtil.Info varDefInfo : unusedDefs) {
          PsiElement parent = varDefInfo.getContext();
          PsiVariable variable = varDefInfo.getVariable();
          if (PsiUtil.isIgnoredName(variable.getName())) continue;
          if (parent instanceof PsiDeclarationStatement || parent instanceof PsiForeachStatement ||
              variable instanceof PsiResourceVariable || variable instanceof PsiPatternVariable) {
            if (!varDefInfo.isRead() && !SuppressionUtil.inspectionResultSuppressed(variable, UnusedDeclarationInspection.this)) {
              descriptors.add(createProblemDescriptor(variable));
            }
          }
        }
      }
      element.accept(new JavaRecursiveElementWalkingVisitor() {
        @Override
        public void visitClass(@NotNull PsiClass aClass) {
          // prevent going to local classes
        }

        @Override
        public void visitLambdaExpression(@NotNull PsiLambdaExpression lambdaExpr) {
          final PsiElement body = lambdaExpr.getBody();
          if (body == null) return;
          findUnusedLocalVariablesInElement(body, descriptors);
        }

        @Override
        public void visitLocalVariable(@NotNull PsiLocalVariable variable) {
          super.visitLocalVariable(variable);
          if (!usedVariables.contains(variable) && variable.getInitializer() == null &&
              !SuppressionUtil.inspectionResultSuppressed(variable, UnusedDeclarationInspection.this)) {
            descriptors.add(createProblemDescriptor(variable));
          }
        }
      });
    }

    private ProblemDescriptor createProblemDescriptor(PsiVariable psiVariable) {
      PsiElement toHighlight = ObjectUtils.notNull(psiVariable.getNameIdentifier(), psiVariable);
      return myInspectionManager.createProblemDescriptor(
        toHighlight, JavaBundle.message("inspection.unused.assignment.problem.descriptor1"), new SafeDeleteFix(psiVariable),
        ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false);
    }
  }

  @Override
  public boolean isReadActionNeeded() {
    return true;
  }
}


text:
using System;
using System.Globalization;
using System.Security;
using System.Security.Authentication;
using System.Threading;
using System.Web;

using ASC.ActiveDirectory;
using ASC.ActiveDirectory.Base.Settings;
using ASC.ActiveDirectory.ComplexOperations;
using ASC.Api.Attributes;
using ASC.Api.Interfaces;
using ASC.Api.Utils;
using ASC.Common.Caching;
using ASC.Common.Data;
using ASC.Common.Data.Sql;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.FederatedLogin.Helpers;
using ASC.FederatedLogin.LoginProviders;
using ASC.IPSecurity;
using ASC.MessagingSystem;
using ASC.Security.Cryptography;
using ASC.Web.Core;
using ASC.Web.Core.Sms;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.Core.Notify;
using ASC.Web.Studio.Core.SMS;
using ASC.Web.Studio.Core.TFA;
using ASC.Web.Studio.Core.Users;
using ASC.Web.Studio.PublicResources;
using ASC.Web.Studio.UserControls.Common;
using ASC.Web.Studio.Utility;

using Constants = ASC.Core.Configuration.Constants;
using SecurityContext = ASC.Core.SecurityContext;

namespace ASC.Specific.AuthorizationApi
{
    /// <summary>
    /// Authorization for api.
    /// </summary>
    public class AuthenticationEntryPoint : IApiEntryPoint
    {
        private static readonly ICache Cache = AscCache.Memory;
        private ILog Log = LogManager.GetLogger("ASC.Web");

        /// <summary>
        /// Entry point name.
        /// </summary>
        public string Name
        {
            get { return "authentication"; }
        }

        private static HttpRequest Request
        {
            get { return HttpContext.Current.Request; }
        }

        /// <summary>
        /// Returns the authentication token for use in api authorization.
        /// </summary>
        /// <short>
        /// Get the authentication token
        /// </short>
        /// <param name="userName">User name or email</param>
        /// <param name="password">Password</param>
        /// <param name="provider">Social media provider type</param>
        /// <param name="accessToken">Provider token</param>
        /// <param name="codeOAuth">Code for take token</param>
        /// <returns>Authentication token to use in the 'Authorization' header when calling API methods</returns>
        /// <exception cref="AuthenticationException">Thrown when not authenticated.</exception>
        [Create(@"", false, false)] //NOTE: This method doesn't require auth!!!  //NOTE: This method doesn't check payment!!!
        public AuthenticationTokenData AuthenticateMe(string userName, string password, string provider, string accessToken, string codeOAuth)
        {
            bool viaEmail;
            var user = GetUser(userName, password, provider, accessToken, out viaEmail, codeOAuth);

            if (StudioSmsNotificationSettings.IsVisibleAndAvailableSettings && StudioSmsNotificationSettings.Enable)
            {
                if (string.IsNullOrEmpty(user.MobilePhone) || user.MobilePhoneActivationStatus == MobilePhoneActivationStatus.NotActivated)
                    return new AuthenticationTokenData
                    {
                        Sms = true
                    };

                SmsManager.PutAuthCode(user, false);

                return new AuthenticationTokenData
                {
                    Sms = true,
                    PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
                    Expires = new ApiDateTime(DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval))
                };
            }

            if (TfaAppAuthSettings.IsVisibleSettings && TfaAppAuthSettings.Enable)
            {
                if (!TfaAppUserSettings.EnableForUser(user.ID))
                    return new AuthenticationTokenData
                    {
                        Tfa = true,
                        TfaKey = user.GenerateSetupCode().ManualEntryKey
                    };

                return new AuthenticationTokenData
                {
                    Tfa = true
                };
            }

            try
            {
                var action = viaEmail ? MessageAction.LoginSuccessViaApi : MessageAction.LoginSuccessViaApiSocialAccount;
                var token = CookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.ID, action);

                var tenant = CoreContext.TenantManager.GetCurrentTenant().TenantId;
                var expires = TenantCookieSettings.GetExpiresTime(tenant);

                return new AuthenticationTokenData
                {
                    Token = token,
                    Expires = new ApiDateTime(expires)
                };
            }
            catch
            {
                MessageService.Send(Request, user.DisplayUserName(false), viaEmail ? MessageAction.LoginFailViaApi : MessageAction.LoginFailViaApiSocialAccount);
                throw new AuthenticationException("User authentication failed");
            }
            finally
            {
                SecurityContext.Logout();
            }
        }

        /// <summary>
        /// Sets a mobile phone for the user with the name specified in the request.
        /// </summary>
        /// <short>Set a mobile phone</short>
        /// <param name="userName">User name or email</param>
        /// <param name="password">Password</param>
        /// <param name="provider">Social media provider type</param>
        /// <param name="accessToken">Provider token</param>
        /// <param name="mobilePhone">New mobile phone</param>
        /// <returns>Mobile phone</returns>
        [Create(@"setphone", false, false)] //NOTE: This method doesn't require auth!!!  //NOTE: This method doesn't check payment!!!
        public AuthenticationTokenData SaveMobilePhone(string userName, string password, string provider, string accessToken, string mobilePhone)
        {
            bool viaEmail;
            var user = GetUser(userName, password, provider, accessToken, out viaEmail);
            mobilePhone = SmsManager.SaveMobilePhone(user, mobilePhone);
            MessageService.Send(HttpContext.Current.Request, MessageAction.UserUpdatedMobileNumber, MessageTarget.Create(user.ID), user.DisplayUserName(false), mobilePhone);

            return new AuthenticationTokenData
            {
                Sms = true,
                PhoneNoise = SmsSender.BuildPhoneNoise(mobilePhone),
                Expires = new ApiDateTime(DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval))
            };
        }

        /// <summary>
        /// Sends sms with the authentication code.
        /// </summary>
        /// <short>Send sms code</short>
        /// <param name="userName">User name or email</param>
        /// <param name="password">Password</param>
        /// <param name="provider">Social media provider type</param>
        /// <param name="accessToken">Provider token</param>
        /// <returns>Mobile phone</returns>
        [Create(@"sendsms", false, false)] //NOTE: This method doesn't require auth!!!  //NOTE: This method doesn't check payment!!!
        public AuthenticationTokenData SendSmsCode(string userName, string password, string provider, string accessToken)
        {
            bool viaEmail;
            var user = GetUser(userName, password, provider, accessToken, out viaEmail);
            SmsManager.PutAuthCode(user, true);

            return new AuthenticationTokenData
            {
                Sms = true,
                PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone),
                Expires = new ApiDateTime(DateTime.UtcNow.Add(SmsKeyStorage.StoreInterval))
            };
        }

        /// <summary>
        /// Returns the two-factor authentication token for use in api authorization.
        /// </summary>
        /// <short>
        /// Get the two-factor authentication token
        /// </short>
        /// <param name="userName">User name or email</param>
        /// <param name="password">Password</param>
        /// <param name="provider">Social media provider type</param>
        /// <param name="accessToken">Provider token</param>
        /// <param name="code">Two-factor authentication code</param>
        /// <param name="codeOAuth">Code for take token</param>
        /// <returns>Two-factor authentication token to use in 'Authorization' header when calling API methods</returns>
        [Create(@"{code}", false, false)] //NOTE: This method doesn't require auth!!!  //NOTE: This method doesn't check payment!!!
        public AuthenticationTokenData AuthenticateMe(string userName, string password, string provider, string accessToken, string code, string codeOAuth)
        {
            bool viaEmail;
            var user = GetUser(userName, password, provider, accessToken, out viaEmail, codeOAuth);

            var sms = false;
            try
            {
                if (StudioSmsNotificationSettings.IsVisibleAndAvailableSettings && StudioSmsNotificationSettings.Enable)
                {
                    sms = true;
                    SmsManager.ValidateSmsCode(user, code, true);
                }
                else if (TfaAppAuthSettings.IsVisibleSettings && TfaAppAuthSettings.Enable)
                {
                    if (user.ValidateAuthCode(code, true, true))
                    {
                        MessageService.Send(Request, MessageAction.UserConnectedTfaApp, MessageTarget.Create(user.ID));
                    }
                }
                else
                {
                    throw new SecurityException("Auth code is not available");
                }

                var token = CookiesManager.AuthenticateMeAndSetCookies(user.Tenant, user.ID, MessageAction.LoginSuccess);
                var tenant = CoreContext.TenantManager.GetCurrentTenant().TenantId;
                var expires = TenantCookieSettings.GetExpiresTime(tenant);

                var result = new AuthenticationTokenData
                {
                    Token = token,
                    Expires = new ApiDateTime(expires)
                };

                if (sms)
                {
                    result.Sms = true;
                    result.PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone);
                }
                else
                {
                    result.Tfa = true;
                }

                return result;
            }
            catch
            {
                MessageService.Send(Request, user.DisplayUserName(false), sms
                                                                              ? MessageAction.LoginFailViaApiSms
                                                                              : MessageAction.LoginFailViaApiTfa,
                                    MessageTarget.Create(user.ID));
                throw new AuthenticationException("User authentication failed");
            }
            finally
            {
                SecurityContext.Logout();
            }
        }

        /// <summary>
        /// Requests an invitation by email on personal.onlyoffice.com.
        /// </summary>
        /// <short>Register a user on the Personal portal</short>
        /// <param name="email">Email address</param>
        /// <param name="lang">Culture</param>
        /// <param name="spam">User consent to subscribe to the ONLYOFFICE newsletter</param>
        /// <param name="recaptchaResponse">ReCAPTCHA token</param>
        /// <visible>false</visible>
        [Create(@"register", false)] //NOTE: This method doesn't require auth!!!
        public string RegisterUserOnPersonal(string email, string lang, bool spam, string recaptchaResponse)
        {
            if (!CoreContext.Configuration.Personal) throw new MethodAccessException("Method is only available on personal.onlyoffice.com");

            try
            {
                if (CoreContext.Configuration.CustomMode) lang = "ru-RU";

                var cultureInfo = SetupInfo.GetPersonalCulture(lang).Value;

                if (cultureInfo != null)
                {
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;
                }

                email.ThrowIfNull(new ArgumentException(Resource.ErrorEmailEmpty, "email"));

                if (!email.TestEmailRegex()) throw new ArgumentException(Resource.ErrorNotCorrectEmail, "email");

                if (!SetupInfo.IsSecretEmail(email)
                    && !string.IsNullOrEmpty(SetupInfo.RecaptchaPublicKey) && !string.IsNullOrEmpty(SetupInfo.RecaptchaPrivateKey))
                {
                    var ip = Request.Headers["X-Forwarded-For"] ?? Request.UserHostAddress;

                    if (String.IsNullOrEmpty(recaptchaResponse)
                        || !Authorize.ValidateRecaptcha(recaptchaResponse, ip))
                    {
                        throw new Authorize.RecaptchaException(Resource.RecaptchaInvalid);
                    }
                }

                var newUserInfo = CoreContext.UserManager.GetUserByEmail(email);

                if (CoreContext.UserManager.UserExists(newUserInfo.ID))
                {
                    if (!SetupInfo.IsSecretEmail(email) || SecurityContext.IsAuthenticated)
                    {
                        throw new Exception(CustomNamingPeople.Substitute<Resource>("ErrorEmailAlreadyExists"));
                    }

                    try
                    {
                        SecurityContext.CurrentAccount = Constants.CoreSystem;
                        CoreContext.UserManager.DeleteUser(newUserInfo.ID);
                    }
                    finally
                    {
                        SecurityContext.Logout();
                    }
                }
                if (!spam)
                {
                    try
                    {
                        const string _databaseID = "com";
                        using (var db = DbManager.FromHttpContext(_databaseID))
                        {
                            db.ExecuteNonQuery(new SqlInsert("template_unsubscribe", false)
                                                   .InColumnValue("email", email.ToLowerInvariant())
                                                   .InColumnValue("reason", "personal")
                                );
                            Log.Debug(String.Format("Write to template_unsubscribe {0}", email.ToLowerInvariant()));
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Debug(String.Format("ERROR write to template_unsubscribe {0}, email:{1}", ex.Message, email.ToLowerInvariant()));
                    }
                }
                StudioNotifyService.Instance.SendInvitePersonal(email);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return string.Empty;
        }

        /// <summary>
        /// Checks user name and password when logging.
        /// </summary>
        /// <short>Log in</short>
        /// <param name="userName">User name or email</param>
        /// <param name="password">Password</param>
        /// <param name="key">Email key</param>
        /// <exception cref="AuthenticationException">Thrown when not authenticated.</exception>
        /// <visible>false</visible>
        [Create(@"login", false, false)] //NOTE: This method doesn't require auth!!!  //NOTE: This method doesn't check payment!!!
        public bool AuthenticateMe(string userName, string password, string key)
        {
            var authInterval = TimeSpan.FromMinutes(5);
            var checkKeyResult = EmailValidationKeyProvider.ValidateEmailKey(userName + password + ConfirmType.Auth, key, authInterval);
            if (checkKeyResult != EmailValidationKeyProvider.ValidationResult.Ok) throw new SecurityException("Access Denied.");

            bool viaEmail;
            var user = GetUser(userName, password, null, null, out viaEmail);
            return user != null;
        }

        private static UserInfo GetUser(string userName, string password, string provider, string accessToken, out bool viaEmail, string codeOAuth = null)
        {
            viaEmail = true;
            var action = MessageAction.LoginFailViaApi;
            UserInfo user = null;
            try
            {
                if (string.IsNullOrEmpty(provider) || provider == "email")
                {
                    userName.ThrowIfNull(new ArgumentException(@"userName empty", "userName"));
                    password.ThrowIfNull(new ArgumentException(@"password empty", "password"));

                    int counter;
                    int.TryParse(Cache.Get<String>("loginsec/" + userName), out counter);
                    if (++counter > SetupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(userName))
                    {
                        throw new Authorize.BruteForceCredentialException();
                    }
                    Cache.Insert("loginsec/" + userName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

                    if (EnableLdap)
                    {
                        var localization = new LdapLocalization(Resource.ResourceManager);
                        var ldapUserManager = new LdapUserManager(localization);

                        ldapUserManager.TryGetAndSyncLdapUserInfo(userName, password, out user);
                    }

                    if (user == null || !CoreContext.UserManager.UserExists(user.ID))
                    {
                        var passwordHash = PasswordHasher.GetClientPassword(password);
                        user = CoreContext.UserManager.GetUsersByPasswordHash(
                            CoreContext.TenantManager.GetCurrentTenant().TenantId,
                            userName,
                            passwordHash);
                    }

                    if (user == null || !CoreContext.UserManager.UserExists(user.ID))
                    {
                        throw new Exception("user not found");
                    }

                    Cache.Insert("loginsec/" + userName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }
                else
                {
                    if (!(CoreContext.Configuration.Standalone || CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Oauth))
                    {
                        throw new Exception(Resource.ErrorNotAllowedOption);
                    }
                    viaEmail = false;

                    action = MessageAction.LoginFailViaApiSocialAccount;

                    var thirdPartyProfile = ProviderManager.GetLoginProfile(provider, accessToken, codeOAuth);
                    userName = thirdPartyProfile.EMail;

                    user = LoginWithThirdParty.GetUserByThirdParty(thirdPartyProfile);
                }
            }
            catch (Authorize.BruteForceCredentialException)
            {
                MessageService.Send(Request, !string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce);
                throw new AuthenticationException("Login Fail. Too many attempts");
            }
            catch
            {
                MessageService.Send(Request, !string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, action);
                throw new AuthenticationException("User authentication failed");
            }

            var tenant = CoreContext.TenantManager.GetCurrentTenant();
            var settings = IPRestrictionsSettings.Load();
            if (settings.Enable && user.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant))
            {
                throw new IPSecurityException();
            }

            return user;
        }

        protected static bool EnableLdap
        {
            get
            {
                if (!CoreContext.Configuration.Standalone
                    && (!SetupInfo.IsVisibleSettings(ManagementType.LdapSettings.ToString())
                        || !CoreContext.TenantManager.GetTenantQuota(TenantProvider.CurrentTenantID).Ldap))
                {
                    return false;
                }

                var enabled = LdapSettings.Load().EnableLdapAuthentication;

                return enabled;
            }
        }
    }
}


text:
/*
 * Board.h
 * input file   : Board.idl
 * generated at : Tue May 22 11:39:20 +0900 2012
 */

#ifndef _BOARD_H_
#define _BOARD_H_
#include "CORBA_Object.h"

typedef CORBA_Object Board;
extern void Board_initialize(Board o, CORBA_Environment * ev);
extern CORBA_octet Board_getStone(Board o, CORBA_octet x, CORBA_octet y,
				  CORBA_Environment * ev);
extern void Board_putStone(Board o, CORBA_octet x, CORBA_octet y,
			   CORBA_octet stoneType, CORBA_Environment * ev);
extern CORBA_octet Board_checkConnect6(Board o, CORBA_Environment * ev);
extern CORBA_octet Board_checkPattern6(Board o, CORBA_octet pattern,
				       CORBA_Environment * ev);
extern void Board_popLastPosition(Board o, CORBA_octet * x,
				  CORBA_octet * y, CORBA_octet * direction,
				  CORBA_Environment * ev);

extern void dispatch(Req * request, Reply * reply, Giop_Hdr * header);

#endif				/* _BOARD_H_ */


text:
<?xml version="1.0" encoding="UTF-8" ?>
<phpdoc>
    <title>BBYOpen PHP wrapper</title>
    <parser>
        <target>build/phpdoc</target>
    </parser>
    <transformer>
        <target>build/phpdoc</target>
    </transformer>
    <transformations>
        <template name="responsive" />
    </transformations>
    <files>
        <directory>./src</directory>
    </files>
</phpdoc>


text:
package com.kk.taurus.xfolder.adapter;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.jiajunhui.xapp.medialoader.bean.PhotoItem;
import com.kk.taurus.xfolder.R;
import com.kk.taurus.xfolder.engine.ImageDisplayEngine;

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

/**
 * Created by Taurus on 2017/5/21.
 */

public class ScanImagePagerAdapter extends PagerAdapter {

    private Context mContext;
    private List<PhotoItem> mItems = new ArrayList<>();

    public ScanImagePagerAdapter(Context context, List<PhotoItem> photoItems){
        this.mContext = context;
        this.mItems = photoItems;
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        PhotoItem item = mItems.get(position);
        View itemView = View.inflate(mContext, R.layout.item_scan_image,null);
        ImageView image = (ImageView) itemView.findViewById(R.id.iv_image);
        ImageDisplayEngine.display(mContext,image,item.getPath(),R.mipmap.icon_image);
        container.addView(itemView);
        return itemView;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
}


text:
package net.violet.platform.dataobjects;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.violet.platform.datamodel.Notification;
import net.violet.platform.datamodel.Notification.NOTIFICATION_STATUS;
import net.violet.platform.datamodel.factories.Factories;

import org.apache.log4j.Logger;

public class NotificationData extends APIData<Notification> {

	private static final Logger LOGGER = Logger.getLogger(NotificationData.class);

	protected NotificationData(Notification inNotification) {
		super(inNotification);
	}

	public static NotificationData getData(Notification inNotification) {
		try {
			return RecordData.getData(inNotification, NotificationData.class, Notification.class);
		} catch (final InstantiationException e) {
			NotificationData.LOGGER.fatal(e, e);
		} catch (final IllegalAccessException e) {
			NotificationData.LOGGER.fatal(e, e);
		} catch (final InvocationTargetException e) {
			NotificationData.LOGGER.fatal(e, e);
		} catch (final NoSuchMethodException e) {
			NotificationData.LOGGER.fatal(e, e);
		}

		return null;
	}

	public static NotificationData findByAPIId(String inAPIId, String inAPIKey) {

		NotificationData theResult = null;
		final long theID = APIData.fromObjectID(inAPIId, ObjectClass.NOTIFICATION, inAPIKey);

		if (theID != 0) {
			final Notification notification = Factories.NOTIFICATION.find(theID);

			if (notification != null) {
				theResult = NotificationData.getData(notification);
			}
		}

		return theResult;
	}

	/**
	 * @return the attribute id
	 */
	public long getId() {
		final Notification theRecord = getRecord();
		if (theRecord != null) {
			return theRecord.getId();
		}

		return 0;
	}

	public static List<NotificationData> getReceived(VObjectData inRecipient, int inSkip, int inGetCount) {
		final List<NotificationData> theResult = new ArrayList<NotificationData>();
		for (final Notification theNotification : Factories.NOTIFICATION.findAllReceived(inRecipient.getRecord(), inSkip, inGetCount)) {
			theResult.add(NotificationData.getData(theNotification));
		}

		return theResult;
	}

	public static long getCountReceived(VObjectData inRecipient) {
		return Factories.NOTIFICATION.countReceived(inRecipient.getRecord());
	}

	public static List<NotificationData> getSent(VObjectData inSender, int inSkip, int inGetCount) {
		final List<NotificationData> theResult = new ArrayList<NotificationData>();
		for (final Notification theNotification : Factories.NOTIFICATION.findAllSent(inSender.getRecord(), inSkip, inGetCount)) {
			theResult.add(NotificationData.getData(theNotification));
		}

		return theResult;
	}

	public static long getCountSent(VObjectData inSender) {
		return Factories.NOTIFICATION.countSent(inSender.getRecord());
	}

	@Override
	protected ObjectClass getObjectClass() {
		return ObjectClass.NOTIFICATION;
	}

	private static NotificationData create(VObjectData inSender, VObjectData inRecipient, ApplicationData inApplication, NOTIFICATION_STATUS inStatus) {
		return NotificationData.getData(Factories.NOTIFICATION.create(inSender.getRecord(), inRecipient.getRecord(), inApplication.getRecord(), inStatus));
	}

	public static NotificationData findPending(VObjectData inSender, ApplicationData inApplication) {
		return NotificationData.getData(Factories.NOTIFICATION.findPending(inSender.getRecord(), inApplication.getRecord()));
	}

	public VObjectData getSender() {
		final Notification theRecord = getRecord();
		if (theRecord != null) {
			return VObjectData.getData(theRecord.getSender());
		}

		return VObjectData.getData(null);
	}

	public VObjectData getRecipient() {
		final Notification theRecord = getRecord();
		if (theRecord != null) {
			return VObjectData.getData(theRecord.getRecipient());
		}

		return VObjectData.getData(null);
	}

	public ApplicationData getApplication() {
		final Notification theRecord = getRecord();
		if (theRecord != null) {
			return ApplicationData.getData(theRecord.getApplication());
		}

		return ApplicationData.getData(null);
	}

	public String getStatus() {
		final Notification theRecord = getRecord();
		if (theRecord != null) {
			return theRecord.getStatus();
		}
		return net.violet.common.StringShop.EMPTY_STRING;
	}

	public Date getNotificationDate() {
		final Notification theRecord = getRecord();
		if (theRecord != null) {
			return theRecord.getNotificationDate();
		}
		return null;
	}

	public static void sendPendingNotification(VObjectData inSender, VObjectData inRecipient, ApplicationData inApplication) {
		NotificationData.create(inSender, inRecipient, inApplication, NOTIFICATION_STATUS.PENDING);
	}

	public static void sendFinishNotification(VObjectData inSender, VObjectData inRecipient, ApplicationData inApplication) {
		NotificationData.create(inSender, inRecipient, inApplication, NOTIFICATION_STATUS.FINISHED);
	}

	public static void sendCancelNotification(VObjectData inSender, ApplicationData inApplication) {
		final NotificationData theNotificationData = NotificationData.findPending(inSender, inApplication);
		if (theNotificationData.isValid()) {
			final VObjectData theRecipient = theNotificationData.getRecipient();
			theNotificationData.delete(); //delete pending notification
			NotificationData.create(inSender, theRecipient, inApplication, NOTIFICATION_STATUS.CANCELLED);
		}
	}

	public static void sendAcceptNotification(VObjectData inSender, ApplicationData inApplication) {
		final NotificationData theNotificationData = NotificationData.findPending(inSender, inApplication);
		if (theNotificationData.isValid()) {
			final VObjectData theRecipient = theNotificationData.getRecipient();
			theNotificationData.delete(); //delete pending notification
			NotificationData.create(theRecipient, inSender, inApplication, NOTIFICATION_STATUS.ACCEPTED);
		}
	}

	public static void sendRejectNotification(VObjectData inSender, ApplicationData inApplication) {
		final NotificationData theNotificationData = NotificationData.findPending(inSender, inApplication);
		if (theNotificationData.isValid()) {
			final VObjectData theRecipient = theNotificationData.getRecipient();
			theNotificationData.delete(); //delete pending notification
			NotificationData.create(theRecipient, inSender, inApplication, NOTIFICATION_STATUS.REJECTED);
		}
	}
}