text:
function norm_tr_a_theo = fct_norm_tr_a_theo_SelfSim_from_LS(...
    model,kappa1,kappa2)
% Compute the theoretical trace of the variance tensor a
%
error('This function should not be used');

alpha = ( 3 - model.sigma.slope_sigma )/2;

% %d_kappa = (2*pi) / sqrt(prod(model.grid.MX.*model.grid.dX));
% dkxdky = (2*pi)^2 / (prod(model.grid.MX.*model.grid.dX));

% Calcul of energy
% One has to divid by prod(model.grid.MX)^2 because of the 2 inverse
% Fourier transform.
% Moreover, one has to divide by d_kappa in order to transform the factor
% dk_x d_ky (necessary for the analitic integration) into d_kappa which
% appear in the definition of sigma_on_sq_dt

% % % %norm_a_theo = (pi/(4-2*alpha)) * ...
% % % %norm_a_theo = (1/(4-2*alpha)) * ...
% % % norm_tr_a_theo = (1/( prod(model.grid.MX) * d_kappa )) * ...
% % norm_tr_a_theo = (1/( prod(model.grid.MX)^2 * dkxdky )) * ...
% norm_tr_a_theo = (1/ dkxdky ) * ...
%     (2*pi/(4-2*alpha)) * ...
%     ( kappa2^(4-2*alpha) - kappa1^(4-2*alpha) );
norm_tr_a_theo = model.sigma.offset_spectrum_a_sigma * ...
    (1/(4-2*alpha)) * ...
    ( kappa2^(4-2*alpha) - kappa1^(4-2*alpha) );

% % Parseval ( * prod(model.grid.MX) )
% % and integrated over the space ( * prod(model.grid.MX) )
% norm_a_theo = prod(model.grid.MX)^2 * norm_a_theo;
%
% % Influence of discretisation
% norm_a_theo = norm_a_theo / ( prod(model.grid.MX.*model.grid.dX) /(2*pi) ) ;
%
%
% % % Influence of the complex brownian variance
% % norm_a_theo = 1/(prod(model.grid.MX))*norm_a_theo;
%
% % % Calcul of energy
% % % One has to divid by prod(model.grid.MX) because of the form of Parseval
% % % theorem for discrete Fourier transform
% % norm_a_theo = 1/prod(model.grid.MX) * norm_a_theo

end

redpajama_set_name: RedPajamaGithub


text:
@interface PodsDummy_Pods_KKAlertView : NSObject
@end
@implementation PodsDummy_Pods_KKAlertView
@end


text:
import pathlib
from time import sleep

import pytest

from pygls import IS_PYODIDE
from pygls.lsp.methods import (
    INITIALIZE,
    TEXT_DOCUMENT_DID_OPEN,
    WORKSPACE_EXECUTE_COMMAND,
)
from pygls.lsp.types import (
    ClientCapabilities,
    DidOpenTextDocumentParams,
    ExecuteCommandParams,
    InitializeParams,
    TextDocumentItem,
)
from pygls.protocol import LanguageServerProtocol
from pygls.server import LanguageServer
from . import CMD_ASYNC, CMD_SYNC, CMD_THREAD

def _initialize_server(server):
    server.lsp.lsp_initialize(
        InitializeParams(
            process_id=1234,
            root_uri=pathlib.Path(__file__).parent.as_uri(),
            capabilities=ClientCapabilities(),
        )
    )

def test_bf_initialize(client_server):
    client, server = client_server
    root_uri = pathlib.Path(__file__).parent.as_uri()
    process_id = 1234

    response = client.lsp.send_request(
        INITIALIZE,
        {
            "processId": process_id,
            "rootUri": root_uri,
            "capabilities": ClientCapabilities(),
        },
    ).result()

    assert server.process_id == process_id
    assert server.workspace.root_uri == root_uri
    assert "capabilities" in response

def test_bf_text_document_did_open(client_server):
    client, server = client_server

    _initialize_server(server)

    client.lsp.notify(
        TEXT_DOCUMENT_DID_OPEN,
        DidOpenTextDocumentParams(
            text_document=TextDocumentItem(
                uri=__file__, language_id="python", version=1, text="test"
            )
        ),
    )

    sleep(1)

    assert len(server.lsp.workspace.documents) == 1

    document = server.workspace.get_document(__file__)
    assert document.uri == __file__
    assert document.version == 1
    assert document.source == "test"
    assert document.language_id == "python"

@pytest.mark.skipif(IS_PYODIDE, reason='threads are not available in pyodide.')
def test_command_async(client_server):
    client, server = client_server

    is_called, thread_id = client.lsp.send_request(
        WORKSPACE_EXECUTE_COMMAND, ExecuteCommandParams(command=CMD_ASYNC)
    ).result()

    assert is_called
    assert thread_id == server.thread_id

@pytest.mark.skipif(IS_PYODIDE, reason='threads are not available in pyodide.')
def test_command_sync(client_server):
    client, server = client_server

    is_called, thread_id = client.lsp.send_request(
        WORKSPACE_EXECUTE_COMMAND, ExecuteCommandParams(command=CMD_SYNC)
    ).result()

    assert is_called
    assert thread_id == server.thread_id

@pytest.mark.skipif(IS_PYODIDE, reason='threads are not available in pyodide.')
def test_command_thread(client_server):
    client, server = client_server

    is_called, thread_id = client.lsp.send_request(
        WORKSPACE_EXECUTE_COMMAND, ExecuteCommandParams(command=CMD_THREAD)
    ).result()

    assert is_called
    assert thread_id != server.thread_id

def test_allow_custom_protocol_derived_from_lsp():
    class CustomProtocol(LanguageServerProtocol):
        pass

    server = LanguageServer('pygls-test', 'v1', protocol_cls=CustomProtocol)

    assert isinstance(server.lsp, CustomProtocol)

def test_forbid_custom_protocol_not_derived_from_lsp():
    class CustomProtocol:
        pass

    with pytest.raises(TypeError):
        LanguageServer('pygls-test', 'v1', protocol_cls=CustomProtocol)


text:
from __future__ import absolute_import

import os

__author__ = 'cenk'

BASE_DIR = os.path.dirname(__file__)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3.db'),
    }
}

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = ["*"]

# Application definition

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django.contrib.postgres',
    'translations',

)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'translations.urls'

STATIC_URL = '/static/'
SECRET_KEY = 'abcde12345'


text:
Sign Up Form

								<form method="post" action="insertion" class="col s12">

											<input name="fullname" type="text" id="full_name" class="validate" >
											Full Name

											<input name="username" type="text" id="user_name" class="validate" >
											User Name

											<input type="password" name="password1" id="password1" class="validate">
											Password

											<input type="password" name="password" id="passwd" class="validate">
											Confirm Password

											<input type="text" name="alamat" id="alamat" >
											Alamat

											<input type="text" name="kota" id="kota">
											Kota

											<input type="text" name = "no_telp">
											NO Telp

											<input type="email" id="email" name = "email" class="validate">
											Email

										<button class="waves-effect waves-light btn " type="submit" name="action">Submit</button>

								</form>

Log In

								<form class="col s12">

											<input name="username" type="text" id="username" name="username"class="validate" >
											User Name

											<input type="password" name="password" id="password1" class="validate">
											Password

										<button class="waves-effect waves-light btn " type="submit" name="action" value = 'login'>Submit</button>

								</form>

				<a href="<?php site_url('homepage/home') ?>" class="brand-logo left"><img src="<?php echo base_url("assets/image/Untitled-1.png") ?>" class="img-nav responsive-img">

Sign UP

					<?php echo validation_errors(); ?>
					<?php echo form_open('homepage/login'); ?>

								<input placeholder="username" name = "username" type="text" id="user" class="validate">

								<input placeholder="pass" name = "password" type="password" id="pass" class="validate">

								<button class="waves-effect waves-light btn-flat btn-small white-text" type="submit">Log In</button>

					</form>

Log In

Sign UP


text:
process.env.SELENIUM_PROMISE_MANAGER = '0';

import path from 'path';
import { inspect } from 'util';

import camelcaseKeys = require('camelcase-keys');
import createArgs = require('minimist');

import _ = require('lodash');

// const tiaDir = path.resolve(path.join(__dirname, '..'));

// Path relative to build/bin.
const tiaDir = path.resolve(path.join(__dirname, '..', '..'));

process.env.TS_NODE_PROJECT = path.join(tiaDir, 'tsconfig.json');

const transpileOnly = true;

process.env.TS_NODE_TRANSPILE_ONLY = `${transpileOnly}`;

require('ts-node').register({
  compilerOptions: {
    allowJs: false,
    baseUrl: tiaDir,
    moduleResolution: 'Node',
    resolveJsonModule: false,
    target: 'ES2018',
  },
  ignore: [],
  transpileOnly,
});

import nodeUtils = require('../utils/nodejs-utils');
import argConsts = require('../utils/arg-consts');
import helpUtils = require('../utils/help-utils');
import { runTestSuites } from '../engine/runner';
import tiaArgsUtils = require('../utils/tia-arguments-utils');

const { version } = require('../../package.json');

console.log(`TIA version: ${version}`);

nodeUtils.checkNodeJsVersion();

import '../engine/global-objects';

gT.tiaDir = tiaDir;

gT.version = version;

function unknownOption(option: string) {
  if (option && option.substr(0, 1) === '-') {
    gIn.cLogger.errln(`Unknown option: "${option}"\n`);
    helpUtils.usage();
    process.exit(1);
  }
  return true;
}

const opts = {
  // trace is number, numbers implied by default in minimist.
  boolean: [
    // 'logs-to-mail',
    'clear-profiles',
    'debug-avg',
    'debug-locale',
    'debug-max',
    'difs-to-slog',
    'dir',
    'ej-explore',
    'enable-email',
    'err-to-console',
    'force-log-actions',
    'ignore-skip-flag',
    'h',
    'headless',
    'help',
    'keep-browser-at-error',
    'log-to-console',
    'new',
    'print-proc-info',
    'run-self-tests',
    'share-browser',
    'show-empty-suites',
    'slog-dif-to-console',
    'stack-to-log',
    'stop-remote-driver',
    'suite',
    'use-remote-driver',
    'v',
    'version',
    'xvfb',
  ],
  default: {
    browser: gT.browsers[0],

    // l: false,
    'browser-log-level': gT.engineConsts.defaultBrowserLogLevel,
    'driver-log-level': gT.engineConsts.defaultDriverLogLevel,
    'hang-timeout': gT.engineConsts.hangTimeout,
    'sel-acts-delay': 0,
    'too-long-time': gT.engineConsts.tooLongTime,
    'trace-level': -1,

    // , 'ignore-skip-flag': false
  },
  string: [
    'browser',
    'browser-log-level',
    'check-logs',
    'def-host',
    'driver-log-level',

    'email-cfg-path',
    'ext-log',
    'hang-timeout',
    'pattern',
    'require-modules',
    'root-dir',
    'sel-acts-delay',
    'slog-subj',
    'too-long-time',
    'trace-level',
    'update-logs',
  ],
  unknown: unknownOption,
};

let args: any = createArgs(process.argv.slice(2), opts); // eslint-disable-line @typescript-eslint/no-explicit-any

args = camelcaseKeys(args);

if (args.h || args.help) {
  helpUtils.usage();
  process.exit(0);
}

if (args.v || args.version) {
  process.exit(0);
}

// args._ массив без -- или -.

if (args.checkLogs) {
  // TODO: Доделать.
  // const allowedArr = [
  //   'ignoreGood', // No difs, no fails, no empty.
  //   'expected',
  //
  //   // 'silent', // Do not ask for confirmation on dif applying.
  //
  // ];

  args.checkLogs = args.checkLogs.split(',');
}

if (args.runSelfTests) {
  // Tests for the engine.
  args.rootDir = tiaDir;
  args.extLog = gT.engineConsts.selfTestsExtLog;
  args.difsToSlog = true;
  args.slogDifToConsole = true;
}

if (args.debugAvg) {
  args.logToConsole = true;
  args.errToConsole = true;
  args.keepBrowserAtError = true;
  if (args.traceLevel === -1) {
    args.traceLevel = 2;
  }
}

if (args.debugMax) {
  args.logToConsole = true;
  args.errToConsole = true;
  args.keepBrowserAtError = true;
  args.forceLogActions = true;
  if (args.traceLevel === -1) {
    args.traceLevel = 3;
  }
}

const { browser } = args;
if (!gT.browsers.includes(browser)) {
  gIn.cLogger.errln(`Invalid browser: ${browser}`);
  gIn.cLogger.errln(`Supported browsers are: ${gT.browsers.join(', ')}`);
  process.exit(1);
}

gT.cLParams = args;

if (args._.includes('initRoot')) {
  tiaArgsUtils.initTiaRoot(args.rootDir); // function ends with process.exit().
}

if (args._.includes('initSuite')) {
  tiaArgsUtils.initTiaSuite(); // function ends with process.exit().
}

const rootDir = tiaArgsUtils.resolveRootDirEx(args.rootDir);
gT.cLParams.rootDir = rootDir;

if (!args.requireModules) {
  args.requireModules = process.env[gT.engineConsts.requireModulesEnvVarName];
}

gT.rootTestsDirPath = path.join(gT.cLParams.rootDir, gT.engineConsts.suiteDirName);

// =====================
gT.rootResultsDir = path.join(gT.rootTestsDirPath, gT.engineConsts.rootResDirName);

// =====================
const rootSuiteConfig = nodeUtils.requireIfExists(
  path.join(gT.rootResultsDir, gT.engineConsts.suiteRootConfigName)
);
gT.rootSuiteConfig = _.merge(_.cloneDeep(gT.suiteConfigDefault), rootSuiteConfig);

// =====================
const globalConfig = nodeUtils.requireIfExists(
  path.join(gT.rootResultsDir, gT.engineConsts.globalConfigName)
);
gT.globalConfig = _.merge(_.cloneDeep(gT.globalConfigDefault), globalConfig);

if (!gT.globalConfig.rootDirAlias) {
  gT.globalConfig.rootDirAlias = path.basename(gT.cLParams.rootDir);
}

// =====================

gT.defaultRootProfile = path.join(
  gT.rootResultsDir,
  gT.engineConsts.browserProfilesRootDirName,
  gT.engineConsts.defaultBrowserProfileName
);

// =====================

if (gT.cLParams.suite && gT.cLParams.dir) {
  console.error('You can not use --dir and --suite simultaneously');
  process.exit(1);
}

if (args.suite || args.dir) {
  gT.cLParams.suite = tiaArgsUtils.getTiaSuiteFromParents(process.cwd());
}

if (gT.cLParams.dir) {
  gT.cLParams.dir = process.cwd();
  gIn.dirArr = path.relative(gT.cLParams.suite, gT.cLParams.dir).split(path.sep);
}

// =====================
const rootDirConfig = nodeUtils.requireIfExists(
  path.join(gT.rootResultsDir, gT.engineConsts.dirRootConfigName)
);
gT.rootDirConfig = _.merge(_.cloneDeep(gT.dirConfigDefault), rootDirConfig);

// =====================
gT.rootLog = path.join(
  gT.rootResultsDir,
  gT.engineConsts.rootLogName + gT.engineConsts.logExtension
);

// =====================
gT.cLParams.emailCfgPath = tiaArgsUtils.resolvePathOptionRelativeToRootDir({
  cmdLineArgsPath: gT.cLParams.emailCfgPath,
  cutLastDirSep: false,
  description: 'EMail cfg path',
  envVarName: gT.engineConsts.emailCfgPathEnvVarName,
  mandatory: false,
});

if (gT.cLParams.emailCfgPath) {
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  gT.rootSuiteConfig = _.merge(_.cloneDeep(gT.rootSuiteConfig), require(gT.cLParams.emailCfgPath));
}

// =====================
if (!gT.cLParams.extLog) {
  gT.cLParams.extLog = process.env[gT.engineConsts.externalLogEnvVarName];
}

if (gT.cLParams.extLog) {
  gT.cLParams.extLog = path.resolve(gT.cLParams.extLog);
  gIn.tracer.msg3(`External log path: ${gT.cLParams.extLog}`);
} else {
  gIn.tracer.msg3('No external log path');
}

// =====================
if (args.slogSubj) {
  gT.cLParams.slogSubj = args.slogSubj.split(',');
  for (const subjItem of gT.cLParams.slogSubj!) {
    if (!argConsts.allowedSlogSubj.includes(subjItem)) {
      gIn.cLogger.errln(`Not supported subject item: ${subjItem}`);
      gIn.cLogger.errln(`Supported items: ${argConsts.allowedSlogSubj.join(',')}`);
      process.exit(1);
    }
  }
} else {
  gT.cLParams.slogSubj = [];
}

// =====================
gT.cLParams.testsParentDir = path.dirname(rootDir);

gIn.tracer.msg3(`Tests Parent Dir: ${gT.cLParams.testsParentDir}`);

// TODO: support several paths for pattern?

if (gT.cLParams.traceLevel > 3) {
  gT.cLParams.traceLevel = 3;
}

gIn.tracer.msg2(`chromedriver path: ${gIn.chromeDriverPath}`);

gT.cLParams.minPathSearchIndex = rootDir.length + 1; // Minimum index for path search.

if (args.requireModules) {
  const arr = args.requireModules.split(/\s*,\s*/);
  nodeUtils.requireArray(arr);
}

if (gT.cLParams.defHost) {
  gT.rootDirConfig.selHost = gT.cLParams.defHost;
}

// process.on('uncaughtException', (err) => {
//   gIn.logger.errorln('TIA: uncaughtException:');
//   gIn.logger.exception(err);
//   throw err;
// });

process.on('unhandledRejection', (reason: any, promise: Promise<any>) => {
  console.error(`Unhandled Rejection: reason: ${reason.toString()}`);
  console.error(`Unhandled Rejection: stack: ${reason.stack}`);
  process.exit(1);
});

if (gT.cLParams.ejExplore) {
  gT.cLParams.keepBrowserAtError = true;
}

gIn.tracer.msg3(`Parameters: ${inspect(gT.cLParams)}`);

runTestSuites()
  .then(() => {})
  .catch(e => {
    gIn.tracer.err(e);
    gIn.tracer.err(e.stack);
    throw e;
  });


text: export { FaceAdd32 as default } from "../../";


text:
package com.guojianyiliao.eryitianshi.View.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.guojianyiliao.eryitianshi.Data.Http_data;
import com.guojianyiliao.eryitianshi.Data.User_Http;
import com.guojianyiliao.eryitianshi.MyUtils.bean.UserInfoLogin;
import com.guojianyiliao.eryitianshi.MyUtils.utlis.SharedPreferencesTools;
import com.guojianyiliao.eryitianshi.MyUtils.utlis.SpUtils;
import com.guojianyiliao.eryitianshi.R;
import com.guojianyiliao.eryitianshi.Utils.MyBaseActivity;
import com.guojianyiliao.eryitianshi.Utils.SharedPsaveuser;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

/**
 *
 */
public class NamepageActivity extends MyBaseActivity {
    private EditText et_name_save;
    private TextView tv_pas;
    private LinearLayout ll_rutname;

    Gson gson;
    UserInfoLogin user ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_namepage);
        gson = new Gson();
        String s = SharedPreferencesTools.GetUsearInfo(this, "userSave", "userInfo");
        user = gson.fromJson(s, UserInfoLogin.class);
        try {
            findView();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void findView() {
        et_name_save = (EditText) findViewById(R.id.et_name_save);
        tv_pas = (TextView) findViewById(R.id.tv_pas);
        ll_rutname = (LinearLayout) findViewById(R.id.ll_rutname);

        et_name_save.addTextChangedListener(textListener);
        ll_rutname.setOnClickListener(listener);
    }

    private TextWatcher textListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (et_name_save.length() == 0) {
                tv_pas.setTextColor(android.graphics.Color.parseColor("#e0e0e0"));
                tv_pas.setOnClickListener(null);
            } else {
                tv_pas.setTextColor(android.graphics.Color.parseColor("#6fc9e6"));
                tv_pas.setOnClickListener(listener);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ll_rutname:
                    finish();
                    break;
                case R.id.tv_pas:

                    if (et_name_save.getText().toString().trim().equals("") || et_name_save.getText().toString() == null) {
                        Toast.makeText(NamepageActivity.this, "昵称不能为空", Toast.LENGTH_SHORT).show();
                    } else {
                        String userid = SharedPreferencesTools.GetUsearId(NamepageActivity.this,"userSave","userId");
                        OkHttpUtils
                                .post()
                                .url(Http_data.http_data + "user/updateUser")
                                .addParams("userid", userid)
                                .addParams("name", et_name_save.getText().toString())
                                .build()
                                .execute(new StringCallback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                        Toast.makeText(NamepageActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onResponse(String response, int id) {
                                        if (response.equals("true")) {
                                            user.setName(et_name_save.getText().toString());
                                            SharedPreferencesTools.SaveUserInfo(NamepageActivity.this, "userSave", "userInfo",gson.toJson(user));
                                            setResult(RESULT_OK);
                                            finish();
                                        } else {
                                            Toast.makeText(NamepageActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                    }

                    break;
            }
        }
    };
}


text:
import sys
import unittest

from alphatwirl.selection import build_selection
from alphatwirl.selection.modules import All
from alphatwirl.selection.modules import Any
from alphatwirl.selection.modules import Not
from alphatwirl.selection.modules.LambdaStr import LambdaStr

##__________________________________________________________________||
class MockFactoryDispatcher(object):
    def __call__(self, **kargs):
        return kargs

##__________________________________________________________________||
class Test_buildSelection(unittest.TestCase):

    def setUp(self):
        self.module = sys.modules['alphatwirl.selection.funcs']
        self._org_FactoryDispatcher = self.module.FactoryDispatcher
        self.module.FactoryDispatcher = MockFactoryDispatcher()

    def tearDown(self):
        self.module.FactoryDispatcher = self._org_FactoryDispatcher

    def test_call_kargs(self):

        kargs = dict(
            arg1 = 10,
            arg2 = 20,
            level = dict(factory = 'test_level1', arg2 = 2, arg3 = 3)
        )

        obj = build_selection(**kargs)

        self.assertIsNot(kargs, obj)
        obj.pop('AllClass')
        obj.pop('AnyClass')
        obj.pop('NotClass')
        obj.pop('LambdaStrClass')
        obj.pop('aliasDict')
        self.assertEqual(kargs, obj)

    def test_call_default_modules(self):

        obj = build_selection(
            arg1 = 10,
            arg2 = 20,
            level = dict(factory = 'test_level1', arg2 = 2, arg3 = 3)
            )

        self.assertIs(All, obj.pop('AllClass'))
        self.assertIs(Any, obj.pop('AnyClass'))
        self.assertIs(Not, obj.pop('NotClass'))
        self.assertIs(LambdaStr, obj.pop('LambdaStrClass'))
        obj.pop('aliasDict')

        expected = dict(
            arg1 = 10,
            arg2 = 20,
            level = dict(factory = 'test_level1', arg2 = 2, arg3 = 3)
        )
        self.assertEqual(expected, obj)

##__________________________________________________________________||


text:
package org.kuali.kra.irb.protocol.reference;

import org.kuali.kra.protocol.protocol.reference.ProtocolReferenceRuleBase;

/**
 * This class is implementation of AddProtocolReferenceRule interface. Impl makes sure necessary rules are satisfied
 * before object can be used.
 */
public class ProtocolReferenceRule extends ProtocolReferenceRuleBase {

}


text:
geostore
========

An abstraction over Google's Cloud Datastore API that enables efficient geo-spatial queries.

The geostore package implements a Store structure and Locatable interface that enable
you to store geospatially indexed objects in Google's App Engine Datastore.
By default (in mid 2014), Google has yet to implement a geospatial storage and search feature for Datastore
entities.  The geostore package therefore implements a simple scheme to tag your objects with geohashes, and
retrieve stored objects, using those geohash tags, based on location.

The basic storage scheme is inspired by the geohash method used by the Python Geomodel project for App Engine:
https://code.google.com/p/geomodel/
However Geostore is not a straight Go port of Geomodel. The implementation is different from the ground up
and as such, is not as robust, and most likely has corner case problems.
We exploit Datastore's efficient string list indexing and lookup as described in this talk by Brett Slatkin:
https://www.youtube.com/watch?v=AgaL6NGpkB8&list=PL15849162B82ABA20

The basic scheme works as follows.  The map of the world is recursively divided into 4 by 4 grids of 16 cells each.
For example, the top most grid (level 0) would look like this:

						----------------.Lat:90, Lng:180
					| C | D | E | F |
					-----------------
					| 8 | 9 | A | B |
					-----------------
					| 4 | 5 | 6 | 7 |
					-----------------
					| 0 | 1 | 2 | 3 |
				    .----------------
	Lat:-90, Lng:-180

Each of the grid squares in the grid above is then divided into 16 cells, and each of those into 16 more, down to
ten levels.  The full geocode for a lat/lng point in this scheme is a string that is 10 characters long, consisting of
symbols from 0-9 + A-F.
The full geocode for an object at location Lat:37.781, Lng:-122.4113 in this scheme, is the string 8E64BF8FAB, however, the
entity would be stored in the datastore with GeoBoxCodes consisting of every prefix substring, i.e. 8,8E, 8E6, ..., 8E64BF8FAB.

To find an entity within a region (viewbounds) we find an efficient subset of geoboxes (cells) that intersect with the viewbounds,
and then fetch all the objects in the datastore that are tagged with the geocodes for those cells.


text:
using extensions::PlatformAppBrowserTest;
using storage_monitor::StorageInfo;
using storage_monitor::StorageMonitor;

namespace {

// Dummy device properties.
const char kDeviceId[] = "testDeviceId";
const char kDeviceName[] = "foobar";
#if defined(FILE_PATH_USES_DRIVE_LETTERS)
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("C:\\qux");
#else
base::FilePath::CharType kDevicePath[] = FILE_PATH_LITERAL("/qux");
#endif

}  // namespace

class MediaGalleriesPlatformAppBrowserTest : public PlatformAppBrowserTest {
 protected:
  MediaGalleriesPlatformAppBrowserTest() : test_jpg_size_(0) {}
  ~MediaGalleriesPlatformAppBrowserTest() override {}

  void SetUpOnMainThread() override {
    PlatformAppBrowserTest::SetUpOnMainThread();
    ensure_media_directories_exists_.reset(new EnsureMediaDirectoriesExists);
    // Prevent the ProcessManager from suspending the chrome-test app. Needed
    // because the writer.onerror and writer.onwriteend events do not qualify as
    // pending callbacks, so the app looks dormant.
    extensions::ProcessManager::SetEventPageIdleTimeForTesting(
        TestTimeouts::action_max_timeout().InMilliseconds());

    int64_t file_size;
    ASSERT_TRUE(base::GetFileSize(GetCommonDataDir().AppendASCII("test.jpg"),
                                  &file_size));
    test_jpg_size_ = base::checked_cast<int>(file_size);
  }

  void TearDownOnMainThread() override {
    ensure_media_directories_exists_.reset();
    PlatformAppBrowserTest::TearDownOnMainThread();
  }

  bool RunMediaGalleriesTest(const std::string& extension_name) {
    base::ListValue empty_list_value;
    return RunMediaGalleriesTestWithArg(extension_name, empty_list_value);
  }

  bool RunMediaGalleriesTestWithArg(const std::string& extension_name,
                                    const base::ListValue& custom_arg_value) {
    // Copy the test data for this test into a temporary directory. Then add
    // a common_injected.js to the temporary copy and run it.
    const char kTestDir[] = "api_test/media_galleries/";
    base::FilePath from_dir =
        test_data_dir_.AppendASCII(kTestDir + extension_name);
    from_dir = from_dir.NormalizePathSeparators();

    base::ScopedAllowBlockingForTesting allow_blocking;
    base::ScopedTempDir temp_dir;
    if (!temp_dir.CreateUniqueTempDir())
      return false;

    if (!base::CopyDirectory(from_dir, temp_dir.GetPath(), true))
      return false;

    base::FilePath common_js_path(
        GetCommonDataDir().AppendASCII("common_injected.js"));
    base::FilePath inject_js_path(temp_dir.GetPath()
                                      .AppendASCII(extension_name)
                                      .AppendASCII("common_injected.js"));
    if (!base::CopyFile(common_js_path, inject_js_path))
      return false;

    const char* custom_arg = NULL;
    std::string json_string;
    if (!custom_arg_value.empty()) {
      base::JSONWriter::Write(custom_arg_value, &json_string);
      custom_arg = json_string.c_str();
    }

    base::AutoReset<base::FilePath> reset(&test_data_dir_, temp_dir.GetPath());
    bool result = RunPlatformAppTestWithArg(extension_name, custom_arg);
    content::RunAllPendingInMessageLoop();  // avoid race on exit in registry.
    return result;
  }

  void AttachFakeDevice() {
    device_id_ = StorageInfo::MakeDeviceId(
        StorageInfo::REMOVABLE_MASS_STORAGE_WITH_DCIM, kDeviceId);

    StorageMonitor::GetInstance()->receiver()->ProcessAttach(
        StorageInfo(device_id_, kDevicePath, base::ASCIIToUTF16(kDeviceName),
                    base::string16(), base::string16(), 0));
    content::RunAllPendingInMessageLoop();
  }

  void DetachFakeDevice() {
    StorageMonitor::GetInstance()->receiver()->ProcessDetach(device_id_);
    content::RunAllPendingInMessageLoop();
  }

  // Called if test only wants a single gallery it creates.
  void RemoveAllGalleries() {
    MediaGalleriesPreferences* preferences = GetAndInitializePreferences();

    // Make a copy, as the iterator would be invalidated otherwise.
    const MediaGalleriesPrefInfoMap galleries = preferences->known_galleries();
    for (auto it = galleries.begin(); it != galleries.end(); ++it) {
      preferences->ForgetGalleryById(it->first);
    }
  }

  // This function makes a single fake gallery. This is needed to test platforms
  // with no default media galleries, such as CHROMEOS. This fake gallery is
  // pre-populated with a test.jpg and test.txt.
  void MakeSingleFakeGallery(MediaGalleryPrefId* pref_id) {
    base::ScopedAllowBlockingForTesting allow_blocking;
    ASSERT_FALSE(fake_gallery_temp_dir_.IsValid());
    ASSERT_TRUE(fake_gallery_temp_dir_.CreateUniqueTempDir());

    MediaGalleriesPreferences* preferences = GetAndInitializePreferences();

    MediaGalleryPrefInfo gallery_info;
    ASSERT_FALSE(preferences->LookUpGalleryByPath(
        fake_gallery_temp_dir_.GetPath(), &gallery_info));
    MediaGalleryPrefId id = preferences->AddGallery(
        gallery_info.device_id, gallery_info.path,
        MediaGalleryPrefInfo::kAutoDetected, gallery_info.volume_label,
        gallery_info.vendor_name, gallery_info.model_name,
        gallery_info.total_size_in_bytes, gallery_info.last_attach_time, 0, 0,
        0);
    if (pref_id)
      *pref_id = id;

    content::RunAllPendingInMessageLoop();

    // Valid file, should show up in JS as a FileEntry.
    AddFileToSingleFakeGallery(GetCommonDataDir().AppendASCII("test.jpg"));

    // Invalid file, should not show up as a FileEntry in JS at all.
    AddFileToSingleFakeGallery(GetCommonDataDir().AppendASCII("test.txt"));
  }

  void AddFileToSingleFakeGallery(const base::FilePath& source_path) {
    base::ScopedAllowBlockingForTesting allow_blocking;
    ASSERT_TRUE(fake_gallery_temp_dir_.IsValid());

    ASSERT_TRUE(base::CopyFile(
        source_path,
        fake_gallery_temp_dir_.GetPath().Append(source_path.BaseName())));
  }

  base::FilePath GetCommonDataDir() const {
    return test_data_dir_.AppendASCII("api_test")
        .AppendASCII("media_galleries")
        .AppendASCII("common");
  }

  int num_galleries() const {
    return ensure_media_directories_exists_->num_galleries();
  }

  int test_jpg_size() const { return test_jpg_size_; }

  EnsureMediaDirectoriesExists* ensure_media_directories_exists() const {
    return ensure_media_directories_exists_.get();
  }

 private:
  MediaGalleriesPreferences* GetAndInitializePreferences() {
    MediaGalleriesPreferences* preferences =
        g_browser_process->media_file_system_registry()->GetPreferences(
            browser()->profile());
    base::RunLoop runloop;
    preferences->EnsureInitialized(runloop.QuitClosure());
    runloop.Run();
    return preferences;
  }

  std::string device_id_;
  base::ScopedTempDir fake_gallery_temp_dir_;
  int test_jpg_size_;
  std::unique_ptr<EnsureMediaDirectoriesExists>
      ensure_media_directories_exists_;
};

#if BUILDFLAG(ENABLE_NACL)
class MediaGalleriesPlatformAppPpapiTest
    : public MediaGalleriesPlatformAppBrowserTest {
 protected:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    MediaGalleriesPlatformAppBrowserTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnablePepperTesting);
  }

  void SetUpOnMainThread() override {
    MediaGalleriesPlatformAppBrowserTest::SetUpOnMainThread();

    ASSERT_TRUE(base::PathService::Get(chrome::DIR_GEN_TEST_DATA, &app_dir_));
    app_dir_ = app_dir_.AppendASCII("ppapi")
                   .AppendASCII("tests")
                   .AppendASCII("extensions")
                   .AppendASCII("media_galleries")
                   .AppendASCII("newlib");
  }

  const base::FilePath& app_dir() const { return app_dir_; }

 private:
  base::FilePath app_dir_;
};

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppPpapiTest, SendFilesystem) {
  RemoveAllGalleries();
  MakeSingleFakeGallery(NULL);

  const extensions::Extension* extension = LoadExtension(app_dir());
  ASSERT_TRUE(extension);

  extensions::ResultCatcher catcher;
  apps::AppLaunchParams params(
      extension->id(), apps::mojom::LaunchContainer::kLaunchContainerNone,
      WindowOpenDisposition::NEW_WINDOW,
      apps::mojom::AppLaunchSource::kSourceTest);
  params.command_line = *base::CommandLine::ForCurrentProcess();
  apps::AppServiceProxyFactory::GetForProfile(browser()->profile())
      ->BrowserAppLauncher()
      .LaunchAppWithParams(params);

  bool result = true;
  if (!catcher.GetNextResult()) {
    message_ = catcher.message();
    result = false;
  }
  content::RunAllPendingInMessageLoop();  // avoid race on exit in registry.
  ASSERT_TRUE(result) << message_;
}

#endif  // BUILDFLAG(ENABLE_NACL)

// Test is flaky, it fails on certain bots, namely WinXP Tests(1) and Linux
// (dbg)(1)(32).  See crbug.com/354425.
#if defined(OS_WIN) || defined(OS_LINUX)
#define MAYBE_MediaGalleriesNoAccess DISABLED_MediaGalleriesNoAccess
#else
#define MAYBE_MediaGalleriesNoAccess MediaGalleriesNoAccess
#endif
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MAYBE_MediaGalleriesNoAccess) {
  MakeSingleFakeGallery(NULL);

  base::ListValue custom_args;
  custom_args.AppendInteger(num_galleries() + 1);

  ASSERT_TRUE(RunMediaGalleriesTestWithArg("no_access", custom_args))
      << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, NoGalleriesRead) {
  ASSERT_TRUE(RunMediaGalleriesTest("no_galleries")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       NoGalleriesCopyTo) {
  ASSERT_TRUE(RunMediaGalleriesTest("no_galleries_copy_to")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesRead) {
  RemoveAllGalleries();
  MakeSingleFakeGallery(NULL);
  base::ListValue custom_args;
  custom_args.AppendInteger(test_jpg_size());

  ASSERT_TRUE(RunMediaGalleriesTestWithArg("read_access", custom_args))
      << message_;
}

// Test is flaky, it fails on certain bots, namely WinXP Tests(1) and Linux
// (dbg)(1)(32).  See crbug.com/354425.
#if defined(OS_WIN) || defined(OS_LINUX)
#define MAYBE_MediaGalleriesCopyTo DISABLED_MediaGalleriesCopyTo
#else
#define MAYBE_MediaGalleriesCopyTo MediaGalleriesCopyTo
#endif
IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MAYBE_MediaGalleriesCopyTo) {
  RemoveAllGalleries();
  MakeSingleFakeGallery(NULL);
  ASSERT_TRUE(RunMediaGalleriesTest("copy_to_access")) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesDelete) {
  MakeSingleFakeGallery(NULL);
  base::ListValue custom_args;
  custom_args.AppendInteger(num_galleries() + 1);
  ASSERT_TRUE(RunMediaGalleriesTestWithArg("delete_access", custom_args))
      << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest,
                       MediaGalleriesAccessAttached) {
  AttachFakeDevice();

  base::ListValue custom_args;
  custom_args.AppendInteger(num_galleries() + 1);
  custom_args.AppendString(kDeviceName);

  ASSERT_TRUE(RunMediaGalleriesTestWithArg("access_attached", custom_args))
      << message_;

  DetachFakeDevice();
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, ToURL) {
  RemoveAllGalleries();
  MediaGalleryPrefId pref_id;
  MakeSingleFakeGallery(&pref_id);

  base::ListValue custom_args;
  custom_args.AppendInteger(base::checked_cast<int>(pref_id));
  custom_args.AppendString(
      browser()->profile()->GetPath().BaseName().MaybeAsASCII());

  ASSERT_TRUE(RunMediaGalleriesTestWithArg("tourl", custom_args)) << message_;
}

IN_PROC_BROWSER_TEST_F(MediaGalleriesPlatformAppBrowserTest, GetMetadata) {
  RemoveAllGalleries();
  MakeSingleFakeGallery(NULL);

  AddFileToSingleFakeGallery(media::GetTestDataFilePath("90rotation.mp4"));
  AddFileToSingleFakeGallery(media::GetTestDataFilePath("id3_png_test.mp3"));

  base::ListValue custom_args;
#if BUILDFLAG(USE_PROPRIETARY_CODECS)
  custom_args.AppendBoolean(true);
#else
  custom_args.AppendBoolean(false);
#endif
  ASSERT_TRUE(RunMediaGalleriesTestWithArg("media_metadata", custom_args))
      << message_;
}


text:
package com.sequenceiq.flow.repository;

import java.util.List;
import java.util.Optional;
import java.util.Set;

import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import com.sequenceiq.flow.domain.ClassValue;
import com.sequenceiq.flow.domain.FlowLog;
import com.sequenceiq.flow.domain.FlowLogIdWithTypeAndTimestamp;
import com.sequenceiq.flow.domain.FlowLogWithoutPayload;
import com.sequenceiq.flow.domain.StateStatus;

@Transactional(TxType.REQUIRED)
public interface FlowLogRepository extends CrudRepository<FlowLog, Long> {

    Optional<FlowLog> findFirstByFlowIdOrderByCreatedDesc(String flowId);

    @Query("SELECT fl.flowId as flowId, " +
            "fl.resourceId as resourceId, " +
            "fl.created as created, " +
            "fl.flowChainId as flowChainId, " +
            "fl.nextEvent as nextEvent, " +
            "fl.payloadType as payloadType, " +
            "fl.flowType as flowType, " +
            "fl.currentState as currentState, " +
            "fl.finalized as finalized, " +
            "fl.cloudbreakNodeId as cloudbreakNodeId, " +
            "fl.stateStatus as stateStatus, " +
            "fl.version as version, " +
            "fl.resourceType as resourceType, " +
            "fl.flowTriggerUserCrn as flowTriggerUserCrn, " +
            "fl.operationType as operationType " +
            "FROM FlowLog fl " +
            "WHERE fl.flowId = :flowId " +
            "ORDER BY fl.created desc")
    Page<FlowLogWithoutPayload> findByFlowIdOrderByCreatedDesc(@Param("flowId") String flowId, Pageable page);

    @Query("SELECT fl.flowId as flowId, fl.flowType as flowType, fl.created as created FROM FlowLog fl "
            + "WHERE fl.stateStatus = 'PENDING' AND fl.resourceId = :resourceId")
    Set<FlowLogIdWithTypeAndTimestamp> findAllRunningFlowLogByResourceId(@Param("resourceId") Long resourceId);

    @Query("SELECT DISTINCT fl.flowId, fl.resourceId, fl.cloudbreakNodeId FROM FlowLog fl WHERE fl.stateStatus = 'PENDING'")
    List<Object[]> findAllPending();

    @Modifying
    @Query("UPDATE FlowLog fl SET fl.finalized = true WHERE fl.flowId = :flowId")
    void finalizeByFlowId(@Param("flowId") String flowId);

    @Query("SELECT fl FROM FlowLog fl WHERE fl.cloudbreakNodeId = :cloudbreakNodeId AND fl.stateStatus = 'PENDING'")
    Set<FlowLog> findAllByCloudbreakNodeId(@Param("cloudbreakNodeId") String cloudbreakNodeId);

    @Query("SELECT fl FROM FlowLog fl WHERE fl.cloudbreakNodeId IS NULL AND fl.stateStatus = 'PENDING'")
    Set<FlowLog> findAllUnassigned();

    @Query("SELECT fl FROM FlowLog fl WHERE fl.flowType = :flowType AND fl.resourceId = :resourceId ORDER BY fl.created DESC")
    List<FlowLog> findAllFlowByType(@Param("resourceId") Long resourceId, @Param("flowType") ClassValue classValue);

    @Query("SELECT fl FROM FlowLog fl WHERE fl.created IN " +
            "( SELECT max(fls.created) from FlowLog fls WHERE fls.flowType = :flowType and fls.resourceId = :resourceId " +
            "AND fls.currentState <> 'FINISHED' " +
            "GROUP BY (fls.flowId, fls.resourceId)) " +
            "ORDER BY fl.created DESC ")
    List<FlowLog> findLastNotFinishedFlowLogsByTypeAndResourceId(@Param("resourceId") Long resourceId, @Param("flowType") ClassValue classValue);

    @Query("SELECT fl.flowId FROM FlowLog fl WHERE fl.flowChainId IN (:chainIds)")
    Set<String> findAllFlowIdsByChainIds(@Param("chainIds") Set<String> chainIds);

    @Query("SELECT fl FROM FlowLog fl WHERE fl.flowId IN (:flowIds) ORDER BY fl.created DESC")
    List<FlowLog> findAllByFlowIdsCreatedDesc(@Param("flowIds") Set<String> flowIds);

    @Modifying
    @Query("UPDATE FlowLog fl SET fl.stateStatus = :stateStatus, fl.endTime = :endTime WHERE fl.id = :id")
    void updateLastLogStatusInFlow(@Param("id") Long id, @Param("stateStatus") StateStatus stateStatus, @Param("endTime") Long endTime);

    @Modifying
    @Query("DELETE FROM FlowLog fl WHERE fl.finalized = TRUE")
    int purgeFinalizedFlowLogs();

    List<FlowLog> findAllByResourceIdOrderByCreatedDesc(Long resourceId);

    Optional<FlowLog> findFirstByResourceIdOrderByCreatedDesc(@Param("resourceId") Long resourceId);

    List<FlowLog> findAllByResourceIdAndFinalizedIsFalseOrderByCreatedDesc(Long resourceId);

    List<FlowLog> findAllByFlowIdOrderByCreatedDesc(String flowId);

    List<FlowLog> findAllByFlowChainIdOrderByCreatedDesc(String flowChainId);

    List<FlowLog> findAllByResourceIdOrderByCreatedDesc(Long resourceId, Pageable page);

    @Query("SELECT COUNT(fl.id) > 0 FROM FlowLog fl WHERE fl.resourceId = :resourceId AND fl.stateStatus = :status")
    Boolean findAnyByStackIdAndStateStatus(@Param("resourceId") Long resourceId, @Param("status") StateStatus status);

    @Query("SELECT fl.flowId as flowId, " +
            "fl.resourceId as resourceId, " +
            "fl.created as created, " +
            "fl.flowChainId as flowChainId, " +
            "fl.nextEvent as nextEvent, " +
            "fl.payloadType as payloadType, " +
            "fl.flowType as flowType, " +
            "fl.currentState as currentState, " +
            "fl.finalized as finalized, " +
            "fl.cloudbreakNodeId as cloudbreakNodeId, " +
            "fl.stateStatus as stateStatus, " +
            "fl.version as version, " +
            "fl.resourceType as resourceType, " +
            "fl.flowTriggerUserCrn as flowTriggerUserCrn, " +
            "fl.operationType as operationType " +
            "FROM FlowLog fl " +
            "WHERE fl.flowId IN (:flowIds) " +
            "ORDER BY fl.created DESC")
    List<FlowLogWithoutPayload> findAllWithoutPayloadByFlowIdsCreatedDesc(@Param("flowIds") Set<String> flowIds);

    @Query("SELECT fl.flowId as flowId, " +
            "fl.resourceId as resourceId, " +
            "fl.created as created, " +
            "fl.flowChainId as flowChainId, " +
            "fl.nextEvent as nextEvent, " +
            "fl.payloadType as payloadType, " +
            "fl.flowType as flowType, " +
            "fl.currentState as currentState, " +
            "fl.finalized as finalized, " +
            "fl.cloudbreakNodeId as cloudbreakNodeId, " +
            "fl.stateStatus as stateStatus, " +
            "fl.version as version, " +
            "fl.resourceType as resourceType, " +
            "fl.flowTriggerUserCrn as flowTriggerUserCrn, " +
            "fl.operationType as operationType " +
            "FROM FlowLog fl " +
            "WHERE fl.flowId = :flowId " +
            "ORDER BY fl.created desc")
    List<FlowLogWithoutPayload> findAllWithoutPayloadByFlowIdOrderByCreatedDesc(@Param("flowId") String flowId);
}


text:
import * as dataSlots from './data-slots.js';
import { makePage } from './page.js';

export default Object.assign({
  makePage
}, dataSlots);


text:
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DataSetTools.DataReaderTools
{

    /// <summary>
    /// Maps values 1 to 1 from IDataReader to either struct with fields or class with properties.
    /// </summary>
    public class DataReaderToDTOMapper
    {
        /// <summary>
        /// Expects the IDataReader to have the exact same columns as T.
        /// Should not be used for massive amount of rows as reflection will cause performance issues.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        /// <remarks>Thank you! http://improve.dk/automatically-mapping-datatable-to-objects/</remarks>
        public static List<T> DataReaderToStruct<T>(IDataReader dr) where T : struct
        {
            var list = new List<T>();

            var fields = typeof(T).GetFields();
            if (fields.Length == 0)
            {
                throw new ArgumentException("T must have public fields, properties are not supported at this moment");
            }
            if (dr.FieldCount != fields.Length)
            {
                throw new ArgumentException("T and dr must have the same fields, 1to1");
            }

            var t = Activator.CreateInstance<T>();

            while (dr.Read())
            {
                foreach (FieldInfo fi in fields)
                    fi.SetValueDirect(__makeref(t), dr[fi.Name]);

                list.Add(t);
            }

            return list;
        }

        /// <summary>
        /// Expects the IDataReader to have the exact same columns as T.
        /// Should not be used for massive amount of rows as reflection will cause performance issues.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static List<T> DataReaderToObject<T>(IDataReader dr) where T : new()
        {
            var list = new List<T>();

            var properties = typeof(T).GetProperties();
            if (properties.Length == 0)
            {
                throw new ArgumentException("T must have public properties");
            }
            if (dr.FieldCount != properties.Length)
            {
                throw new ArgumentException("T and dr must have the same fields, 1to1");
            }

            while (dr.Read())
            {
                var t = Activator.CreateInstance<T>();
                foreach (PropertyInfo info in properties)
                {
                    info.SetValue(t, dr[info.Name]);
                }
                list.Add(t);
            }

            return list;
        }
    }
}


text:
package org.zaproxy.addon.commonlib;

import java.io.IOException;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.AbstractAppPlugin;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.core.scanner.Category;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpRequestHeader;
import org.parosproxy.paros.network.HttpStatusCode;

/**
 * An {@code AbstractAppPlugin} that checks for the presence of a file.
 *
 * @since 1.0.0
 */
public abstract class AbstractAppFilePlugin extends AbstractAppPlugin {

    private static final Logger LOG = Logger.getLogger(AbstractAppFilePlugin.class);
    private final String filename;
    private final String messagePrefix;

    /**
     * Constructs an {@code AbstractAppFilePlugin} with the given file name and messages prefix.
     *
     * <p>The message prefix is used to load the messages for the alert and scan rule, from the main
     * resource bundle ({@link Constant#messages}).
     *
     * @param filename the name of the file to check if it's present.
     * @param messagePrefix the messages prefix.
     */
    protected AbstractAppFilePlugin(String filename, String messagePrefix) {
        this.filename = filename;
        this.messagePrefix = messagePrefix;
    }

    @Override
    public String getName() {
        return Constant.messages.getString(messagePrefix + "name");
    }

    @Override
    public String getDescription() {
        return Constant.messages.getString(messagePrefix + "desc");
    }

    @Override
    public String getSolution() {
        return Constant.messages.getString(messagePrefix + "soln");
    }

    @Override
    public String getReference() {
        return Constant.messages.getString(messagePrefix + "refs");
    }

    @Override
    public int getCategory() {
        return Category.INFO_GATHER;
    }

    @Override
    public int getRisk() {
        return Alert.RISK_MEDIUM;
    }

    @Override
    public int getCweId() {
        return 215; // CWE-215: Information Exposure Through Debug Information
    }

    @Override
    public int getWascId() {
        return 13; // WASC-13: Information Leakage
    }

    private String getOtherInfo() {
        return Constant.messages.getString(messagePrefix + "otherinfo");
    }

    @Override
    public void scan() {
        // Check if the user stopped things. One request per URL so check before
        // sending the request
        if (isStop()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Scanner " + getName() + " Stopping.");
            }
            return;
        }

        HttpMessage newRequest = getNewMsg();
        newRequest.getRequestHeader().setMethod(HttpRequestHeader.GET);
        URI baseUri = getBaseMsg().getRequestHeader().getURI();
        URI newUri = null;
        try {
            String baseUriPath = baseUri.getPath() == null ? "" : baseUri.getPath();
            newUri =
                    new URI(
                            baseUri.getScheme(),
                            null,
                            baseUri.getHost(),
                            baseUri.getPort(),
                            createTestablePath(baseUriPath));
        } catch (URIException uEx) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(
                        "An error occurred creating a URI for the: "
                                + getName()
                                + " scanner. "
                                + uEx.getMessage(),
                        uEx);
            }
            return;
        }
        try {
            newRequest.getRequestHeader().setURI(newUri);
        } catch (URIException uEx) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(
                        "An error occurred setting the URI for a new request used by: "
                                + getName()
                                + " scanner. "
                                + uEx.getMessage(),
                        uEx);
            }
            return;
        }
        // Until https://github.com/zaproxy/zaproxy/issues/3563 is addressed
        // track completed in Kb
        // TODO change this when possible
        synchronized (getKb()) {
            if (getKb().getBoolean(newUri, messagePrefix)) {
                return;
            }
            getKb().add(newUri, messagePrefix, Boolean.TRUE);
        }
        try {
            sendAndReceive(newRequest, false);
        } catch (IOException e) {
            LOG.warn(
                    "An error occurred while checking ["
                            + newRequest.getRequestHeader().getMethod()
                            + "] ["
                            + newRequest.getRequestHeader().getURI()
                            + "] for "
                            + getName()
                            + " Caught "
                            + e.getClass().getName()
                            + " "
                            + e.getMessage());
            return;
        }
        if (isFalsePositive(newRequest)) {
            return;
        }
        int statusCode = newRequest.getResponseHeader().getStatusCode();
        if (statusCode == HttpStatusCode.OK) {
            raiseAlert(newRequest, getRisk(), Alert.CONFIDENCE_MEDIUM, "");
        } else if (this.getAlertThreshold().equals(AlertThreshold.LOW)
                && (statusCode == HttpStatusCode.UNAUTHORIZED
                        || statusCode == HttpStatusCode.FORBIDDEN)) {
            raiseAlert(newRequest, Alert.RISK_INFO, Alert.CONFIDENCE_LOW, getOtherInfo());
        }
    }

    /**
     * Always returns false - override to add functionality to detect FPs
     *
     * @param msg the message being scanned (after being sent).
     * @return true if its a false positive
     */
    public boolean isFalsePositive(HttpMessage msg) {
        return false;
    }

    private String createTestablePath(String baseUriPath) {
        String newPath = "";
        if (baseUriPath.contains("/")) {
            if (baseUriPath.endsWith("/")) {
                newPath = baseUriPath + filename;
            } else {
                newPath = baseUriPath.substring(0, baseUriPath.lastIndexOf('/')) + "/" + filename;
            }
        } else {
            newPath = baseUriPath + "/" + filename;
        }
        return newPath;
    }

    private void raiseAlert(HttpMessage msg, int risk, int confidence, String otherInfo) {
        newAlert()
                .setRisk(risk)
                .setConfidence(confidence)
                .setOtherInfo(otherInfo)
                .setEvidence(msg.getResponseHeader().getPrimeHeader())
                .setMessage(msg)
                .raise();
    }
}


text:
import omniORB
omniORB.updateModule("CosPropertyService__POA")

# ** 1. Stub files contributing to this module
import CosPropertyService_idl

# ** 2. Sub-modules

# ** 3. End


text:
using Microsoft.Azure.Devices;
using System;
using System.Windows.Forms;

namespace DeviceExplorer
{
    public partial class DeviceCreatedForm : Form
    {
        public DeviceCreatedForm(Device device)
        {
            InitializeComponent();
            if (device.Authentication.SymmetricKey != null)
            {
                richTextBox.Text = $"ID={device.Id}\nPrimaryKey={device.Authentication.SymmetricKey.PrimaryKey}\nSecondaryKey={device.Authentication.SymmetricKey.SecondaryKey}";
            }
            else if (device.Authentication.X509Thumbprint != null)
            {
                richTextBox.Text = $"ID={device.Id}\nPrimaryThumbPrint={device.Authentication.X509Thumbprint.PrimaryThumbprint}\nSecondaryThumbPrint={device.Authentication.X509Thumbprint.SecondaryThumbprint}";
            }
        }

        private void doneButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}


text:
import { Inject, Injectable } from '@angular/core';
import { BADGEUP_JS_CLIENT, BADGEUP_SETTINGS, BadgeUpSettings } from '../config';
import { BADGEUP_STORAGE, BadgeUpEarnedAchievement, BadgeUpNotificationType, BadgeUpPartialEvent, BadgeUpStorage } from '../declarations';

import { Achievement, BadgeUp as BadgeUpJSClient, EventProgress, EventRequest, EventResult, Award } from '@badgeup/badgeup-browser-client';
import { BadgeUpLogger } from './badgeUpLogger';
import { BadgeUpNotification } from './badgeUpNotification';
import { SubjectProvider } from './providers/subject';

@Injectable()
/**
 * The `BadgeUpClient` service is used to send events to BadgeUp. It also
 * allows you to subscribe to achievements earned.
 */
export class BadgeUpClient {

    /**
     * Notification callback used to receive BadgeUp notifications
     * about user achievements and awards.
     *
     * @callback notificationCallback
     * @param notificationType - The type of the notification.
     * @param data - Any data that type of notification has. This can be cast depending on the type of notification.
     */
    private notificationCallbacks: Array<(notificationType: BadgeUpNotificationType, data: any) => void> = [];

    /**
     * BadgeUp Ionic client constructor
     * @param badgeUpLogger - Internal logger.
     * @param badgeUpNotification - Provides toast notifications to users.
     * @param badgeUpSettings - Client settings.
     * @param badgeUpStorage - Storage engine for events.
     * @param browserClient - Underlying browser client that the ionic client relies on. https://github.com/BadgeUp/badgeup-browser-client
     */
    constructor(
        private subjectProvider: SubjectProvider,
        private badgeUpLogger: BadgeUpLogger,
        private badgeUpNotification: BadgeUpNotification,
        @Inject(BADGEUP_SETTINGS) private badgeUpSettings: BadgeUpSettings,
        @Inject(BADGEUP_STORAGE) private badgeUpStorage: BadgeUpStorage,
        @Inject(BADGEUP_JS_CLIENT) public badgeUpJSClient: BadgeUpJSClient) {
            this.init();
    }

    private init() {
        this.emit({
            key: 'badgeup:plugin:initialized'
        });
    }

    /**
     * Allows you to configure the default subject provider. If at any point the subject is undefined
     * for some events, this provider will be called.
     *
     * As an input, you get eventKey, which lets you return different subject values based on the event key.
     * For some event keys, you might want to use deviceId as a subject, for others, the user's email.
     * @param subjectProvider - The subject provider to use.
     */
    public setSubject(subject: string) {
        this.subjectProvider.setSubject(subject);
    }

    /**
     * Subscribe to BadgeUp notifications and receive new notifications about the state of system.
     *
     * For example, you can receive 'new achievement' notification that you can use to learn about
     * new achievements user has earned, and display some kind of congratulations modal.
     * @param notificationCallback - The callback to use when notification is received
     */
    public subscribe(notificationCallback: (notificationType: BadgeUpNotificationType, data: any) => void) {
        this.notificationCallbacks.push(notificationCallback);
    }

    /**
     * Unsubscribe from BadgeUp notifications.
     *
     * Unsubscribe if you're done, as failure to do so will lead to memory leaks.
     * @param notificationCallback - The callback to unsubscribe from.
     */
    public unsubscribe(notificationCallback: (notificationType: BadgeUpNotificationType, data: any) => void) {
        const filtredNotificationCallbacks: Array<(notificationType: BadgeUpNotificationType, data: any) => void> = [];
        for (const curNotificationCallback of this.notificationCallbacks) {
            if (curNotificationCallback !== notificationCallback) {
                filtredNotificationCallbacks.push(curNotificationCallback);
            }
        }

        this.notificationCallbacks = filtredNotificationCallbacks;
    }

    /**
     * Send a new BadgeUp event
     *
     * This method works without internet as well, using local storage to store the events.
     * Events will be synced to server once internet is available again.
     * @param badgeUpEvent - The event to send
     */
    public emit(e: BadgeUpPartialEvent) {

        if (!e.key) {
            throw new Error('[BadgeUp] Event key is required');
        } else if (typeof e.key !== 'string') {
            throw new TypeError('[BadgeUp] Event key has to be of type string');
        }

        const subject = e.subject || this.subjectProvider.currentSubject;

        const er = new EventRequest(
            subject,
            e.key,
            e.modifier
        );

        // set data
        if (e.data) {
            if (typeof e.data === 'string') {
                er.data = { value: e.data };
            } else {
                er.data = e.data;
            }
        }
        this.badgeUpStorage.storeEvent(er);
        this.flush();
    }

    private fire(eventType: BadgeUpNotificationType, data: any) {
        for (const handler of this.notificationCallbacks) {
            try {
                handler(eventType, data);
            } catch (e) {
                this.badgeUpLogger.error('Notification callback failure ' + e);
            }
        }
    }

    private progressHandler(progress: EventProgress[]): void {
        if (!Array.isArray(progress)) {
            return;
        }

        // get the progress record's related achievement records
        // new, complete achievements only
        const list = progress.filter((p) => (p.isNew && p.isComplete));

        const showAchievement = async (p: EventProgress) => {
            const p1 = this.badgeUpJSClient.achievements.getAchievementAwards(p.achievementId);
            const p2 = this.badgeUpJSClient.achievements.get(p.achievementId);

            const results = await Promise.all([p1, p2]);
            const earnedAwards: Award[] = results[0];
            const achievement: Achievement = results[1];

            const record: BadgeUpEarnedAchievement = {
                earnedAchievementId: p.earnedAchievementId,
                achievement
            };

            this.fire(BadgeUpNotificationType.NewAchievementEarned, record);

            if (!this.badgeUpSettings.disableAchievementPopups) {
                this.badgeUpNotification.showNewAchievementEarned(achievement, earnedAwards);
            }
        };

        for (const l of list) {
            try {
                showAchievement(l);
            } catch (err) {
                this.badgeUpLogger.error('Error presenting earned achievement notification', err);
            }
        }
    }

    /**
     * Sends all events in storage, clearing storage
     */
    private async flush() {

        const storedEvents = await this.badgeUpStorage.getEvents();
        for (const se of storedEvents) {
            try {
                const response = await this.badgeUpJSClient.events.create(se.badgeUpEvent);
                if (!response) {
                    continue;
                }

                // remove from storage
                this.badgeUpStorage.removeEvents([se]);

                const progress: EventProgress[] = response.results.reduce(function(p: EventProgress[], c: EventResult) {
                    p.push(...c.progress);
                    return p;
                }, []);

                // trigger actions to take based on progress
                this.progressHandler(progress);
            } catch (err) {
                this.badgeUpLogger.error(err);

                if (err.message === 'BAD REQUEST') {
                    // remove from storage
                    this.badgeUpStorage.removeEvents([se]);
                }
            }
        }
    }
}


text:
namespace __sanitizer {
  unsigned struct_utsname_sz = sizeof(struct utsname);
  unsigned struct_stat_sz = sizeof(struct stat);
  unsigned struct_stat64_sz = sizeof(struct stat64);
  unsigned struct_rusage_sz = sizeof(struct rusage);
  unsigned struct_tm_sz = sizeof(struct tm);
  unsigned struct_passwd_sz = sizeof(struct passwd);
  unsigned struct_group_sz = sizeof(struct group);
  unsigned siginfo_t_sz = sizeof(siginfo_t);
  unsigned struct_sigaction_sz = sizeof(struct sigaction);
  unsigned struct_itimerval_sz = sizeof(struct itimerval);
  unsigned pthread_t_sz = sizeof(pthread_t);
  unsigned pthread_mutex_t_sz = sizeof(pthread_mutex_t);
  unsigned pthread_cond_t_sz = sizeof(pthread_cond_t);
  unsigned pid_t_sz = sizeof(pid_t);
  unsigned timeval_sz = sizeof(timeval);
  unsigned uid_t_sz = sizeof(uid_t);
  unsigned gid_t_sz = sizeof(gid_t);
  unsigned mbstate_t_sz = sizeof(mbstate_t);
  unsigned sigset_t_sz = sizeof(sigset_t);
  unsigned struct_timezone_sz = sizeof(struct timezone);
  unsigned struct_tms_sz = sizeof(struct tms);
  unsigned struct_sigevent_sz = sizeof(struct sigevent);
  unsigned struct_sched_param_sz = sizeof(struct sched_param);
  unsigned struct_statfs_sz = sizeof(struct statfs);
  unsigned struct_sockaddr_sz = sizeof(struct sockaddr);
  unsigned ucontext_t_sz = sizeof(ucontext_t);
  unsigned struct_timespec_sz = sizeof(struct timespec);
#if SANITIZER_SOLARIS32
  unsigned struct_statvfs64_sz = sizeof(struct statvfs64);
#endif
  unsigned struct_statvfs_sz = sizeof(struct statvfs);

  const uptr sig_ign = (uptr)SIG_IGN;
  const uptr sig_dfl = (uptr)SIG_DFL;
  const uptr sig_err = (uptr)SIG_ERR;
  const uptr sa_siginfo = (uptr)SA_SIGINFO;

  int shmctl_ipc_stat = (int)IPC_STAT;

  unsigned struct_utmp_sz = sizeof(struct utmp);
  unsigned struct_utmpx_sz = sizeof(struct utmpx);

  int map_fixed = MAP_FIXED;

  int af_inet = (int)AF_INET;
  int af_inet6 = (int)AF_INET6;

  uptr __sanitizer_in_addr_sz(int af) {
    if (af == AF_INET)
      return sizeof(struct in_addr);
    else if (af == AF_INET6)
      return sizeof(struct in6_addr);
    else
      return 0;
  }

  unsigned struct_ElfW_Phdr_sz = sizeof(ElfW(Phdr));

  int glob_nomatch = GLOB_NOMATCH;

  unsigned path_max = PATH_MAX;

  // ioctl arguments
  unsigned struct_ifreq_sz = sizeof(struct ifreq);
  unsigned struct_termios_sz = sizeof(struct termios);
  unsigned struct_winsize_sz = sizeof(struct winsize);

  unsigned struct_sioc_sg_req_sz = sizeof(struct sioc_sg_req);
  unsigned struct_sioc_vif_req_sz = sizeof(struct sioc_vif_req);

  const unsigned IOCTL_NOT_PRESENT = 0;

  unsigned IOCTL_FIOASYNC = FIOASYNC;
  unsigned IOCTL_FIOCLEX = FIOCLEX;
  unsigned IOCTL_FIOGETOWN = FIOGETOWN;
  unsigned IOCTL_FIONBIO = FIONBIO;
  unsigned IOCTL_FIONCLEX = FIONCLEX;
  unsigned IOCTL_FIOSETOWN = FIOSETOWN;
  unsigned IOCTL_SIOCADDMULTI = SIOCADDMULTI;
  unsigned IOCTL_SIOCATMARK = SIOCATMARK;
  unsigned IOCTL_SIOCDELMULTI = SIOCDELMULTI;
  unsigned IOCTL_SIOCGIFADDR = SIOCGIFADDR;
  unsigned IOCTL_SIOCGIFBRDADDR = SIOCGIFBRDADDR;
  unsigned IOCTL_SIOCGIFCONF = SIOCGIFCONF;
  unsigned IOCTL_SIOCGIFDSTADDR = SIOCGIFDSTADDR;
  unsigned IOCTL_SIOCGIFFLAGS = SIOCGIFFLAGS;
  unsigned IOCTL_SIOCGIFMETRIC = SIOCGIFMETRIC;
  unsigned IOCTL_SIOCGIFMTU = SIOCGIFMTU;
  unsigned IOCTL_SIOCGIFNETMASK = SIOCGIFNETMASK;
  unsigned IOCTL_SIOCGPGRP = SIOCGPGRP;
  unsigned IOCTL_SIOCSIFADDR = SIOCSIFADDR;
  unsigned IOCTL_SIOCSIFBRDADDR = SIOCSIFBRDADDR;
  unsigned IOCTL_SIOCSIFDSTADDR = SIOCSIFDSTADDR;
  unsigned IOCTL_SIOCSIFFLAGS = SIOCSIFFLAGS;
  unsigned IOCTL_SIOCSIFMETRIC = SIOCSIFMETRIC;
  unsigned IOCTL_SIOCSIFMTU = SIOCSIFMTU;
  unsigned IOCTL_SIOCSIFNETMASK = SIOCSIFNETMASK;
  unsigned IOCTL_SIOCSPGRP = SIOCSPGRP;
  unsigned IOCTL_TIOCEXCL = TIOCEXCL;
  unsigned IOCTL_TIOCGETD = TIOCGETD;
  unsigned IOCTL_TIOCGPGRP = TIOCGPGRP;
  unsigned IOCTL_TIOCGWINSZ = TIOCGWINSZ;
  unsigned IOCTL_TIOCMBIC = TIOCMBIC;
  unsigned IOCTL_TIOCMBIS = TIOCMBIS;
  unsigned IOCTL_TIOCMGET = TIOCMGET;
  unsigned IOCTL_TIOCMSET = TIOCMSET;
  unsigned IOCTL_TIOCNOTTY = TIOCNOTTY;
  unsigned IOCTL_TIOCNXCL = TIOCNXCL;
  unsigned IOCTL_TIOCOUTQ = TIOCOUTQ;
  unsigned IOCTL_TIOCPKT = TIOCPKT;
  unsigned IOCTL_TIOCSCTTY = TIOCSCTTY;
  unsigned IOCTL_TIOCSETD = TIOCSETD;
  unsigned IOCTL_TIOCSPGRP = TIOCSPGRP;
  unsigned IOCTL_TIOCSTI = TIOCSTI;
  unsigned IOCTL_TIOCSWINSZ = TIOCSWINSZ;

  unsigned IOCTL_MTIOCGET = MTIOCGET;
  unsigned IOCTL_MTIOCTOP = MTIOCTOP;

  const int si_SEGV_MAPERR = SEGV_MAPERR;
  const int si_SEGV_ACCERR = SEGV_ACCERR;
} // namespace __sanitizer

using namespace __sanitizer;

COMPILER_CHECK(sizeof(__sanitizer_pthread_attr_t) >= sizeof(pthread_attr_t));

COMPILER_CHECK(sizeof(socklen_t) == sizeof(unsigned));
CHECK_TYPE_SIZE(pthread_key_t);

// There are more undocumented fields in dl_phdr_info that we are not interested
// in.
COMPILER_CHECK(sizeof(__sanitizer_dl_phdr_info) <= sizeof(dl_phdr_info));
CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_addr);
CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_name);
CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phdr);
CHECK_SIZE_AND_OFFSET(dl_phdr_info, dlpi_phnum);

CHECK_TYPE_SIZE(glob_t);
CHECK_SIZE_AND_OFFSET(glob_t, gl_pathc);
CHECK_SIZE_AND_OFFSET(glob_t, gl_pathv);
CHECK_SIZE_AND_OFFSET(glob_t, gl_offs);

CHECK_TYPE_SIZE(addrinfo);
CHECK_SIZE_AND_OFFSET(addrinfo, ai_flags);
CHECK_SIZE_AND_OFFSET(addrinfo, ai_family);
CHECK_SIZE_AND_OFFSET(addrinfo, ai_socktype);
CHECK_SIZE_AND_OFFSET(addrinfo, ai_protocol);
CHECK_SIZE_AND_OFFSET(addrinfo, ai_protocol);
CHECK_SIZE_AND_OFFSET(addrinfo, ai_addrlen);
CHECK_SIZE_AND_OFFSET(addrinfo, ai_canonname);
CHECK_SIZE_AND_OFFSET(addrinfo, ai_addr);

CHECK_TYPE_SIZE(hostent);
CHECK_SIZE_AND_OFFSET(hostent, h_name);
CHECK_SIZE_AND_OFFSET(hostent, h_aliases);
CHECK_SIZE_AND_OFFSET(hostent, h_addrtype);
CHECK_SIZE_AND_OFFSET(hostent, h_length);
CHECK_SIZE_AND_OFFSET(hostent, h_addr_list);

CHECK_TYPE_SIZE(iovec);
CHECK_SIZE_AND_OFFSET(iovec, iov_base);
CHECK_SIZE_AND_OFFSET(iovec, iov_len);

CHECK_TYPE_SIZE(msghdr);
CHECK_SIZE_AND_OFFSET(msghdr, msg_name);
CHECK_SIZE_AND_OFFSET(msghdr, msg_namelen);
CHECK_SIZE_AND_OFFSET(msghdr, msg_iov);
CHECK_SIZE_AND_OFFSET(msghdr, msg_iovlen);
CHECK_SIZE_AND_OFFSET(msghdr, msg_control);
CHECK_SIZE_AND_OFFSET(msghdr, msg_controllen);
CHECK_SIZE_AND_OFFSET(msghdr, msg_flags);

CHECK_TYPE_SIZE(cmsghdr);
CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_len);
CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_level);
CHECK_SIZE_AND_OFFSET(cmsghdr, cmsg_type);

COMPILER_CHECK(sizeof(__sanitizer_dirent) <= sizeof(dirent));
CHECK_SIZE_AND_OFFSET(dirent, d_ino);
CHECK_SIZE_AND_OFFSET(dirent, d_off);
CHECK_SIZE_AND_OFFSET(dirent, d_reclen);

#if SANITIZER_SOLARIS32
COMPILER_CHECK(sizeof(__sanitizer_dirent64) <= sizeof(dirent64));
CHECK_SIZE_AND_OFFSET(dirent64, d_ino);
CHECK_SIZE_AND_OFFSET(dirent64, d_off);
CHECK_SIZE_AND_OFFSET(dirent64, d_reclen);
#endif

CHECK_TYPE_SIZE(ifconf);
CHECK_SIZE_AND_OFFSET(ifconf, ifc_len);
CHECK_SIZE_AND_OFFSET(ifconf, ifc_ifcu);

CHECK_TYPE_SIZE(pollfd);
CHECK_SIZE_AND_OFFSET(pollfd, fd);
CHECK_SIZE_AND_OFFSET(pollfd, events);
CHECK_SIZE_AND_OFFSET(pollfd, revents);

CHECK_TYPE_SIZE(nfds_t);

CHECK_TYPE_SIZE(sigset_t);

COMPILER_CHECK(sizeof(__sanitizer_sigaction) == sizeof(struct sigaction));
// Can't write checks for sa_handler and sa_sigaction due to them being
// preprocessor macros.
CHECK_STRUCT_SIZE_AND_OFFSET(sigaction, sa_mask);
CHECK_STRUCT_SIZE_AND_OFFSET(sigaction, sa_flags);

CHECK_TYPE_SIZE(wordexp_t);
CHECK_SIZE_AND_OFFSET(wordexp_t, we_wordc);
CHECK_SIZE_AND_OFFSET(wordexp_t, we_wordv);
CHECK_SIZE_AND_OFFSET(wordexp_t, we_offs);

CHECK_TYPE_SIZE(tm);
CHECK_SIZE_AND_OFFSET(tm, tm_sec);
CHECK_SIZE_AND_OFFSET(tm, tm_min);
CHECK_SIZE_AND_OFFSET(tm, tm_hour);
CHECK_SIZE_AND_OFFSET(tm, tm_mday);
CHECK_SIZE_AND_OFFSET(tm, tm_mon);
CHECK_SIZE_AND_OFFSET(tm, tm_year);
CHECK_SIZE_AND_OFFSET(tm, tm_wday);
CHECK_SIZE_AND_OFFSET(tm, tm_yday);
CHECK_SIZE_AND_OFFSET(tm, tm_isdst);

CHECK_TYPE_SIZE(ether_addr);

CHECK_TYPE_SIZE(ipc_perm);
CHECK_SIZE_AND_OFFSET(ipc_perm, key);
CHECK_SIZE_AND_OFFSET(ipc_perm, seq);
CHECK_SIZE_AND_OFFSET(ipc_perm, uid);
CHECK_SIZE_AND_OFFSET(ipc_perm, gid);
CHECK_SIZE_AND_OFFSET(ipc_perm, cuid);
CHECK_SIZE_AND_OFFSET(ipc_perm, cgid);
CHECK_SIZE_AND_OFFSET(ipc_perm, mode);

CHECK_TYPE_SIZE(shmid_ds);
CHECK_SIZE_AND_OFFSET(shmid_ds, shm_perm);
CHECK_SIZE_AND_OFFSET(shmid_ds, shm_segsz);
CHECK_SIZE_AND_OFFSET(shmid_ds, shm_atime);
CHECK_SIZE_AND_OFFSET(shmid_ds, shm_dtime);
CHECK_SIZE_AND_OFFSET(shmid_ds, shm_ctime);
CHECK_SIZE_AND_OFFSET(shmid_ds, shm_cpid);
CHECK_SIZE_AND_OFFSET(shmid_ds, shm_lpid);
CHECK_SIZE_AND_OFFSET(shmid_ds, shm_nattch);

CHECK_TYPE_SIZE(clock_t);

CHECK_TYPE_SIZE(ifaddrs);
CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_next);
CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_name);
CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_addr);
CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_netmask);
// Compare against the union, because we can't reach into the union in a
// compliant way.
#ifdef ifa_dstaddr
#undef ifa_dstaddr
#endif
COMPILER_CHECK(sizeof(((__sanitizer_ifaddrs *)nullptr)->ifa_dstaddr) ==
               sizeof(((ifaddrs *)nullptr)->ifa_ifu));
COMPILER_CHECK(offsetof(__sanitizer_ifaddrs, ifa_dstaddr) ==
               offsetof(ifaddrs, ifa_ifu));
CHECK_SIZE_AND_OFFSET(ifaddrs, ifa_data);

CHECK_TYPE_SIZE(timeb);
CHECK_SIZE_AND_OFFSET(timeb, time);
CHECK_SIZE_AND_OFFSET(timeb, millitm);
CHECK_SIZE_AND_OFFSET(timeb, timezone);
CHECK_SIZE_AND_OFFSET(timeb, dstflag);

CHECK_TYPE_SIZE(passwd);
CHECK_SIZE_AND_OFFSET(passwd, pw_name);
CHECK_SIZE_AND_OFFSET(passwd, pw_passwd);
CHECK_SIZE_AND_OFFSET(passwd, pw_uid);
CHECK_SIZE_AND_OFFSET(passwd, pw_gid);
CHECK_SIZE_AND_OFFSET(passwd, pw_dir);
CHECK_SIZE_AND_OFFSET(passwd, pw_shell);

CHECK_SIZE_AND_OFFSET(passwd, pw_gecos);

CHECK_TYPE_SIZE(group);
CHECK_SIZE_AND_OFFSET(group, gr_name);
CHECK_SIZE_AND_OFFSET(group, gr_passwd);
CHECK_SIZE_AND_OFFSET(group, gr_gid);
CHECK_SIZE_AND_OFFSET(group, gr_mem);

CHECK_TYPE_SIZE(XDR);
CHECK_SIZE_AND_OFFSET(XDR, x_op);
CHECK_SIZE_AND_OFFSET(XDR, x_ops);
CHECK_SIZE_AND_OFFSET(XDR, x_public);
CHECK_SIZE_AND_OFFSET(XDR, x_private);
CHECK_SIZE_AND_OFFSET(XDR, x_base);
CHECK_SIZE_AND_OFFSET(XDR, x_handy);
COMPILER_CHECK(__sanitizer_XDR_ENCODE == XDR_ENCODE);
COMPILER_CHECK(__sanitizer_XDR_DECODE == XDR_DECODE);
COMPILER_CHECK(__sanitizer_XDR_FREE == XDR_FREE);

CHECK_TYPE_SIZE(sem_t);

#endif  // SANITIZER_SOLARIS


text:
<?php

namespace SumoCoders\FrameworkMultiUserBundle\Tests\Command;

use PHPUnit_Framework_TestCase;
use SumoCoders\FrameworkMultiUserBundle\Command\CreateUserHandler;
use SumoCoders\FrameworkMultiUserBundle\DataTransferObject\BaseUserDataTransferObject;
use SumoCoders\FrameworkMultiUserBundle\User\InMemoryBaseUserRepository;
use SumoCoders\FrameworkMultiUserBundle\User\Interfaces\UserRepository;
use SumoCoders\FrameworkMultiUserBundle\User\BaseUserRepositoryCollection;
use SumoCoders\FrameworkMultiUserBundle\Entity\BaseUser;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;

class CreateUserHandlerTest extends PHPUnit_Framework_TestCase
{
    /** @var UserRepository */
    private $userRepository;

    /** @var BaseUserRepositoryCollection */
    private $userRepositoryCollection;

    public function setUp(): void
    {
        $this->userRepository = new InMemoryBaseUserRepository(
            new EncoderFactory([BaseUser::class => new PlaintextPasswordEncoder()])
        );
        $this->userRepositoryCollection = new BaseUserRepositoryCollection([$this->userRepository]);
    }

    /**
     * Test if CreateUserHandler gets handled.
     */
    public function testCreateUserGetsHandled(): void
    {
        $handler = new CreateUserHandler(
            new EncoderFactory([BaseUser::class => new PlaintextPasswordEncoder()]),
            $this->userRepositoryCollection
        );

        $userDataTransferObject = new BaseUserDataTransferObject();
        $userDataTransferObject->userName = 'sumo';
        $userDataTransferObject->plainPassword = 'randomPassword';
        $userDataTransferObject->displayName = 'sumocoders';
        $userDataTransferObject->email = 'sumo@example.dev';

        $handler->handle($userDataTransferObject);

        $this->assertEquals(
            'sumo',
            $this->userRepository->findByUsername('sumo')->getUsername()
        );
        $this->assertEquals(
            'sumocoders',
            $this->userRepository->findByUsername('sumo')->getDisplayName()
        );
        $this->assertEquals(
            'randomPassword{' . $this->userRepository->findByUsername('sumo')->getSalt() . '}',
            $this->userRepository->findByUsername('sumo')->getPassword()
        );
        $this->assertEquals(
            'sumo@example.dev',
            $this->userRepository->findByUsername('sumo')->getEmail()
        );
    }
}


text:
layout: single
title: "Rev3: Montclair Sprint 2017 Race Report"
date: 2017-06-18T17:30:00-04:00
modified: 2017-06-20T13:00:00-04:00
description: "Rev3's Montclair; The only event in 2017 where I can compare how well I am improving year over year."
categories:
    - "Race Report"
tags:
    - Triathlon
    - Rev3
header:
    image: /assets/images/2017/06/18/Rev3-Montclair-Header.jpg            # Twitter (use 'overlay_image')
    overlay_image: /assets/images/2017/06/18/Rev3-Montclair-Header.jpg    # Article header at 2048x768
    overlay_filter: 0.15
    teaser: /assets/images/2017/06/18/Rev3-Montclair-Header-Twitter.jpg   # Shrink image to 575x216
    caption: "Photo credit: [**Justin Rummel**](https://www.justinrummel.com)"
---
Rev3's Montclair is the only race this year that I have previously participated in 2016, which make it a great opportunity to compare and see how I am improving.  Training has been going well for the past few months so I'm eager to see how my fitness is improving not only since January, but also when compared to last year.  This is not always safe as race conditions change due to weather or other circumstances... but both 2016 and 2017 conditions are very similar.

{% include toc icon="gears" title="Race Review ToC" %}

Race Breakdown
---

### Swim

Being so close to the race venue, I was able to squeeze in a quick swim warm-up just before the race director began the race announcements.  Earlier this week the water temperature for Lake Montclair was 84.6 degrees, which for a swimmer is very unappealing hot yucky mess.  Fortunately, the water "cooled down" to 80° for race morning.  With the water tempterature measuring at 80° raceing with a wetsuit is not possible.  Instead, I put on my [Roka Swim Skin][roka-ss] for a quick lap to the final orange buoy and back so I could experience the last 75m of the swim.

When you compare last year to this year I had great improvement in the swim, even though I needed a quick 10 second break just before the turn around point (I was having negative thoughts which was effecting my swim).  Also, not sure if it was me but trying to get to the first buoy was *really* difficult compared to the swim back.  It may because I finally got my 20ft diameter of personal space and was able to relax, but I couldn't get my swim rhythm in check until the 500m mark[^1].

- [Training Peaks Swim Data](https://home.trainingpeaks.com/athlete/workout/AMK43QJD3L22LTI4FEYTRMETSU)

### Bike

This course is a perfect representation of "Virginia Rollers".  It is a relentless pattern of three small rollers where total elevation climb is about 40ft, but then you get slapped with a 100ft climb over a mile long that tires you out quickly if you don't recognize what is in front of you.  Since this is a two loop oscillating course, we get that 100ft climb four times.

I remember having a great ride last year, so any chance of improving my time was going to be a difficult challenge.  I am no longer racing against other age groupers... I am racing myself.  Same plan as always for the bike segment, feel the first loop and then turn it up on the second loop.  Out of the 326 racers, I was the 20th fastest person on the bike.  However, to put into perspective how difficult the Male 40-44 Age Group bracket is, there were still four people in my AG that were faster out of that 19.

- [Training Peaks Bike Data](https://home.trainingpeaks.com/athlete/workout/5EQYGT7AELQMFTI4FEYTRMETSU)

###### Strava Ride Activity

### Run

This run is **hard** as you must climb the same road you left when you were on the bike, AND you get one of the fun 100' climbs immediately afterwards... meaning you really don't start going "downhill" till mile two of a 3.1 mile course.  Knowing this, I took it easy the first two miles... maybe a little too easy as the run was the only section where I didn't improve my time (Splits table is below).  It was fun reading the motivational chalk drawings while on the run course, as it was just enough distraction from the burning legs or lungs.

- [Training Peaks Run Data](https://home.trainingpeaks.com/athlete/workout/O7NJBW6HUQHQVTI4FEYTRMETSU)

###### Strava Run Activity

Post Race Thoughts
---

I'm beginning to really like this course.  Where else can you get a quick open water lake swim, rollers to attack on the uphill sections (and take advantage on the downhills, peaking at 38mph), and finish with a challenging run.  What makes this even better is since this is so close my family, and many [Speed Sherpa][ss] teammates register/race as well (plus always making new race friends before and after the event).

It really is a blast to hear people cheer you on from the crowed and from other racers on the course.  Someday I may even be able to climb onto the podium, but for now I will just enjoy the race.

Race Results
---

#### Rankings

- Overall: Placed 38th out of 326 (top 11%).
- Gender: Placed 30th out of 190 (top 15%).
- Male 40-44: Placed 7th out of 32

Among the Male 40-44 category there were 32 athletes.

- Swim: Ranked 13th
- Bike: Ranked 5th
- Run: Ranked 11th

#### Updated 2016-06-20 (Race Photos)

#### Splits

| Montclair Sprint   | 750m Swim    | T1   | 12.0 Mile Bike | T2   | 5k Run   | Total       |
|:-------------------|:------------:|:----:|:--------------:|:----:|:--------:|------------:|
| Goal Times[^2]     | 18:55        | 1:53 | 33:45          | 0:38 | 22:06    | 1:17:17     |
|=====
| Actual Times[^3]   | 16:57        | 2:07 | 33:30          | 0:45 | 23:37    | 1:16:54     |

Footnotes
---

[^1]: Pro tip. If the swim distance is 750m and you really did 920m... you're doing it wrong.
[^2]: Goal Times were based on beating [last year's race][mont-2016]
[^3]: Official Race Results available at [Rev3 Montclair Results page][mont-2017].

[roka-ss]: https://www.roka.com/collections/mens-viper-swimskins
[ss]: http://www.speedsherpa.com
[mont-2016]: http://timing.rev3tri.com/mobile/athlete-results/E62400DF-EED2-4370-8997-9FC458257203/1/270
[mont-2017]: http://timing.rev3tri.com/mobile/athlete-results/E35D1006-99F9-4670-B292-8538B7489651/1/62


text:
package com.yahala.android;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;

import com.yahala.messenger.FileLog;
import com.yahala.messenger.NotificationCenter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SmsListener extends BroadcastReceiver {

    private SharedPreferences preferences;

    @Override
    public void onReceive(Context context, Intent intent) {
        FileLog.e("yahala", "SmsListener " + intent.getAction());
        if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {

            if (!OSUtilities.isWaitingForSms()) {
                return;
            }
            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs;
            if (bundle != null) {
                try {
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    String wholeString = "";
                    for (int i = 0; i < msgs.length; i++) {
                        msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                        wholeString += msgs[i].getMessageBody();
                    }
                    try {
                        Pattern pattern = Pattern.compile("[0-9]+");
                        Matcher matcher = pattern.matcher(wholeString);
                        if (matcher.find()) {
                            String str = matcher.group(0);
                            if (str.length() >= 3) {
                                FileLog.e("yahala", "SmsListener code : " + str);
                                NotificationCenter.getInstance().postNotificationName(998, matcher.group(0));
                            }
                        }
                    } catch (Exception e) {
                        FileLog.e("yahala", e);
                    }

                } catch (Exception e) {
                    FileLog.e("yahala", e);
                }
            }
        }
    }
}


text:
Lists = new Meteor.Collection('lists');

// Calculate a default name for a list in the form of 'List A'
Lists.defaultName = function() {
  var nextLetter = 'A', nextName = 'List ' + nextLetter;
  while (Lists.findOne({name: nextName})) {
    // not going to be too smart here, can go past Z
    nextLetter = String.fromCharCode(nextLetter.charCodeAt(0) + 1);
    nextName = 'List ' + nextLetter;
  }

  return nextName;
};

Todos = new Meteor.Collection('todos');


text:
package main

import (
	"fmt"
	"strings"

	"github.com/spf13/cobra"
)

func printDNSSuffixList(cmd *cobra.Command, args []string) {
	dnsSuffixList := getDNSSuffixList()
	fmt.Println(strings.Join(dnsSuffixList, ","))
}


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Calculator */

#ifndef _Included_Calculator
#define _Included_Calculator
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Calculator
 * Method:    ADDNUMBERS
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_Calculator_ADDNUMBERS
  (JNIEnv *, jobject, jint, jint);

/*
 * Class:     Calculator
 * Method:    SUBNUMBERS
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_Calculator_SUBNUMBERS
  (JNIEnv *, jobject, jint, jint);

/*
 * Class:     Calculator
 * Method:    MULNUMBERS
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_Calculator_MULNUMBERS
  (JNIEnv *, jobject, jint, jint);

/*
 * Class:     Calculator
 * Method:    DIVNUMBERS
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_Calculator_DIVNUMBERS
  (JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif


text:
from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required

from musician.views import SongStateView, MusicianView

song_state_view = login_required(SongStateView.as_view())

urlpatterns = patterns('',
    url(r'(?P<state>(learn|learning|learned))/(?P<id>\d+)/$',
        song_state_view, name='musician_song_state'),
    url(r'user/(?P<user_name>(.*))/$', MusicianView.as_view(),
        name='musician_page'),
)


text:
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\UserProfilePhotos */

$this->title = 'Update User Profile Photos: ' . ' ' . $model->idUserProfilePhotos;
$this->params['breadcrumbs'][] = ['label' => 'User Profile Photos', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->idUserProfilePhotos, 'url' => ['view', 'id' => $model->idUserProfilePhotos]];
$this->params['breadcrumbs'][] = 'Update';
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>


text:
'use strict';

var Lib = require('../../lib');
var layoutAttributes = require('./layout_attributes');

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }
    coerce('treemapcolorway', layoutOut.colorway);
    coerce('extendtreemapcolors');
};


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

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="javax.sql.DataSource interface: JDBC 4.1 features" />
<meta content="DataSource interface" name="DC.subject" />
<meta content="DataSource interface" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc4_1summary.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc4_1connection.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefjdbc4_1datasource" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>javax.sql.DataSource interface: JDBC 4.1 features</title>

javax.sql.DataSource interface: JDBC 4.1 features

Derby has
the following JDBC 4.1-specific DataSource classes. Use these DataSource
classes if your application runs on JDK 6 or higher (except Java SE 8 Compact
Profiles) and calls methods specific to JDBC 4.1 or 4.2.

org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource40

org.apache.derby.jdbc.EmbeddedDataSource40

org.apache.derby.jdbc.EmbeddedXADataSource40

org.apache.derby.jdbc.ClientConnectionPoolDataSource40

org.apache.derby.jdbc.ClientDataSource40

org.apache.derby.jdbc.ClientXADataSource40

Derby supports additional
DataSource classes for applications that use JDK 8 Compact Profile 2 or 3. See
JDBC support for Java SE 8 Compact Profiles for
details.

Parent topic: Features supported on JDBC 4.1 and above

Related reference

java.sql.Connection interface: JDBC 4.1 features


text:
const authResponse = require('../../middleware/auth-response');

const {
  Friendship
} = require('../../database/models/friendship');

function deleteFriendship(req, res, next) {
  const friendshipId = req.params.friendshipId;
  const userId = req.user._id;

  Friendship.confirmUserOwnership(friendshipId, userId)
    .then((friendship) => friendship.remove())
    .then(() => {
      authResponse({
        data: {},
        message: 'Friendship successfully deleted.'
      })(req, res, next);
    })
    .catch(next);
}

module.exports = {
  deleteFriendship
};


text:
<?php

// This file was auto-generated from sdk-root/src/data/outposts/2019-12-03/paginators-1.json
return ['pagination' => ['ListOutposts' => ['input_token' => 'NextToken', 'output_token' => 'NextToken', 'limit_key' => 'MaxResults'], 'ListSites' => ['input_token' => 'NextToken', 'output_token' => 'NextToken', 'limit_key' => 'MaxResults']]];