text:
'use strict';

i18n.map('en', {
    anyJoin: {
        leave: 'Leave',
        join: 'Join',
        joined: 'Joined',
        joinSendRequest: 'Request membership',
        joinAcceptInvitation: 'Accept invitation',
        joinReject: 'Reject',
        joinCancel: 'Cancel',
        invitedSince: 'Invited since',
        invited: 'Invited',
        joinAcceptRequest: 'Accept request',
        joinInvite: 'Invite',
        noInvitations: 'There are no current invitations.',
        loading: 'Loading',
        searchUser: 'Search user',
        types: {
            join_request: 'Approving the requests',
            join_invitation: 'Only on invitation',
            join_open: 'Anyone can join with'

        },
        policyLabel: 'Policy of joining for {$1}',
        errors:{
            userAlreadyJoined: 'User already is joined to this entity',
            missingJoiningRequest: 'Joining request cannot be found',
            missingAcceptor: 'Missing Acceptor object',
            permissionDenied: 'Permission Denied',
            missingOriginator: 'Missing Originator object',
            userNotJoined: 'User not joined',
            noSubject: 'No subject'
        }
    }
});


text:
package com.mjiayou.trecore.ui.demo;

import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.mjiayou.trecore.TCActivity;
import com.mjiayou.trecore.bean.TCResponse;
import com.mjiayou.trecore.bean.entity.TCUMLogin;
import com.mjiayou.trecore.event.UserLoginStatusEvent;
import com.mjiayou.trecore.util.SharedUtil;
import com.mjiayou.trecore.util.ToastUtil;
import com.mjiayou.trecore.util.UserUtil;
import com.mjiayou.trecore.helper.Router;
import com.mjiayou.trebundle.R;
import com.umeng.socialize.bean.SHARE_MEDIA;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class TestUserLoginActivity extends TCActivity {

    @InjectView(R.id.et_phone)
    EditText mEtPhone;
    @InjectView(R.id.et_password)
    EditText mEtPassword;
    @InjectView(R.id.tv_forget_pwd)
    TextView mTvForgetPwd;
    @InjectView(R.id.tv_register)
    TextView mTvRegister;
    @InjectView(R.id.tv_login)
    TextView mTvLogin;
    @InjectView(R.id.iv_login_weibo)
    ImageView mIvLoginWeibo;
    @InjectView(R.id.iv_login_wechat)
    ImageView mIvLoginWechat;
    @InjectView(R.id.iv_login_qq)
    ImageView mIvLoginQQ;

    @OnClick({R.id.tv_forget_pwd, R.id.tv_register, R.id.tv_login})
    void onClicks(View view) {
        switch (view.getId()) {
            case R.id.tv_forget_pwd: {
                ToastUtil.show(mContext, "忘记密码");
                break;
            }
            case R.id.tv_register: {
                Router.openTestUserRegisterActivity(mContext);
                break;
            }
            case R.id.tv_login: {
                submitData();
                break;
            }
        }
    }

    @OnClick({R.id.iv_login_weibo, R.id.iv_login_wechat, R.id.iv_login_qq})
    void onClicksThirdLogin(View view) {
        switch (view.getId()) {
            case R.id.iv_login_weibo:
                mTCUMLogin.setPlatform(SHARE_MEDIA.SINA);
                break;
            case R.id.iv_login_wechat:
                mTCUMLogin.setPlatform(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.iv_login_qq:
                mTCUMLogin.setPlatform(SHARE_MEDIA.QQ);
                break;
        }
        loginByThird();
    }

    TCUMLogin mTCUMLogin = new TCUMLogin();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tc_activity_test_user_login);
        ButterKnife.inject(this);
        EventBus.getDefault().register(this);

        setTitle("登录");

        initView();
    }

    /**
     * EventBus处理登陆后更新用户信息
     */
    public void onEvent(UserLoginStatusEvent event) {
        // 针对注册成功直接跳转finish该页面的情况
        if (event.isLogin() && mActivity != null && !mActivity.isFinishing()) {
            try {
                mActivity.finish();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void initView() {
        super.initView();
        String phone = SharedUtil.get(mContext).getAccountUsername();
        if (!TextUtils.isEmpty(phone)) {
            mEtPhone.setText(phone);
        }
    }

    @Override
    public void submitData() {
        super.submitData();
        String phone = mEtPhone.getText().toString();
        String password = mEtPassword.getText().toString();

        if (TextUtils.isEmpty(phone)) {
            ToastUtil.show(mContext, "请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            ToastUtil.show(mContext, "请输入密码");
            return;
        }

        SharedUtil.get(mContext).setAccountUsername(phone);

        // 调用登录接口
        ToastUtil.show(mContext, "调用登录接口");
    }

    @Override
    public void callback(Message msg) {
        super.callback(msg);
    }

    public void refreshView(TCResponse response) {
        super.refreshView(response);
        ToastUtil.show(mContext, "登录成功");

        String tokenId = "123456";
        UserUtil.doLogin(tokenId);

        finish();
    }

    /**
     * 第三方登陆
     */
    private void loginByThird() {
        ToastUtil.show(mContext, "调用第三方登录");
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Kirby\Cms;

use Kirby\Exception\InvalidArgumentException;

class Permissions
{
	/**
	 * @var array
	 */
	public static $extendedActions = [];

	/**
	 * @var array
	 */
	protected $actions = [
		'access' => [
			'account'   => true,
			'languages' => true,
			'panel'     => true,
			'site'      => true,
			'system'    => true,
			'users'     => true,
		],
		'files' => [
			'changeName' => true,
			'create'     => true,
			'delete'     => true,
			'read'       => true,
			'replace'    => true,
			'update'     => true
		],
		'languages' => [
			'create' => true,
			'delete' => true
		],
		'pages' => [
			'changeSlug'     => true,
			'changeStatus'   => true,
			'changeTemplate' => true,
			'changeTitle'    => true,
			'create'         => true,
			'delete'         => true,
			'duplicate'      => true,
			'preview'        => true,
			'read'           => true,
			'sort'           => true,
			'update'         => true
		],
		'site' => [
			'changeTitle' => true,
			'update'      => true
		],
		'users' => [
			'changeEmail'    => true,
			'changeLanguage' => true,
			'changeName'     => true,
			'changePassword' => true,
			'changeRole'     => true,
			'create'         => true,
			'delete'         => true,
			'update'         => true
		],
		'user' => [
			'changeEmail'    => true,
			'changeLanguage' => true,
			'changeName'     => true,
			'changePassword' => true,
			'changeRole'     => true,
			'delete'         => true,
			'update'         => true
		]
	];

	/**
	 * Permissions constructor
	 *
	 * @param array $settings
	 * @throws \Kirby\Exception\InvalidArgumentException
	 */
	public function __construct($settings = [])
	{
		// dynamically register the extended actions
		foreach (static::$extendedActions as $key => $actions) {
			if (isset($this->actions[$key]) === true) {
				throw new InvalidArgumentException('The action ' . $key . ' is already a core action');
			}

			$this->actions[$key] = $actions;
		}

		if (is_array($settings) === true) {
			return $this->setCategories($settings);
		}

		if (is_bool($settings) === true) {
			return $this->setAll($settings);
		}
	}

	/**
	 * @param string|null $category
	 * @param string|null $action
	 * @return bool
	 */
	public function for(string $category = null, string $action = null): bool
	{
		if ($action === null) {
			if ($this->hasCategory($category) === false) {
				return false;
			}

			return $this->actions[$category];
		}

		if ($this->hasAction($category, $action) === false) {
			return false;
		}

		return $this->actions[$category][$action];
	}

	/**
	 * @param string $category
	 * @param string $action
	 * @return bool
	 */
	protected function hasAction(string $category, string $action): bool
	{
		return $this->hasCategory($category) === true && array_key_exists($action, $this->actions[$category]) === true;
	}

	/**
	 * @param string $category
	 * @return bool
	 */
	protected function hasCategory(string $category): bool
	{
		return array_key_exists($category, $this->actions) === true;
	}

	/**
	 * @param string $category
	 * @param string $action
	 * @param $setting
	 * @return $this
	 */
	protected function setAction(string $category, string $action, $setting)
	{
		// wildcard to overwrite the entire category
		if ($action === '*') {
			return $this->setCategory($category, $setting);
		}

		$this->actions[$category][$action] = $setting;

		return $this;
	}

	/**
	 * @param bool $setting
	 * @return $this
	 */
	protected function setAll(bool $setting)
	{
		foreach ($this->actions as $categoryName => $actions) {
			$this->setCategory($categoryName, $setting);
		}

		return $this;
	}

	/**
	 * @param array $settings
	 * @return $this
	 */
	protected function setCategories(array $settings)
	{
		foreach ($settings as $categoryName => $categoryActions) {
			if (is_bool($categoryActions) === true) {
				$this->setCategory($categoryName, $categoryActions);
			}

			if (is_array($categoryActions) === true) {
				foreach ($categoryActions as $actionName => $actionSetting) {
					$this->setAction($categoryName, $actionName, $actionSetting);
				}
			}
		}

		return $this;
	}

	/**
	 * @param string $category
	 * @param bool $setting
	 * @return $this
	 * @throws \Kirby\Exception\InvalidArgumentException
	 */
	protected function setCategory(string $category, bool $setting)
	{
		if ($this->hasCategory($category) === false) {
			throw new InvalidArgumentException('Invalid permissions category');
		}

		foreach ($this->actions[$category] as $actionName => $actionSetting) {
			$this->actions[$category][$actionName] = $setting;
		}

		return $this;
	}

	/**
	 * @return array
	 */
	public function toArray(): array
	{
		return $this->actions;
	}
}


text:
import { CHILDREN, TEXT, STRING } from 'substance'
import { RICH_TEXT_ANNOS } from './modelConstants'
import Reference from './Reference'

/*
  <element-citation publication-type="webpage">
    <day>10</day>
    <month>05</month>
    <uri>http://www.michaeleisen.org/blog/?p=1894</uri>
    <date-in-citation iso-8601-date="1995-09-10">1995-09-10</date-in-citation>
    <year>2016</year>
    <person-group person-group-type="author">
      <name>
        <surname>Eisen</surname>
        <given-names>M</given-names>
      </name>
    </person-group>
    <source>it is NOT junk</source>
    <article-title>The Imprinter of All Maladies</article-title>
  </element-citation>
*/
export default class WebpageRef extends Reference {}
WebpageRef.schema = {
  type: 'webpage-ref', // publication-type="webpage"
  title: TEXT(...RICH_TEXT_ANNOS), // <article-title>
  // E.g. website name, where the page appeared
  containerTitle: STRING, // <source>
  authors: CHILDREN('ref-contrib'), // <person-group person-group-type="author">
  year: STRING, // <year>
  month: STRING, // <month>
  day: STRING, // <day>
  accessedDate: STRING, // <date-in-citation iso-8601-date="1995-09-10">
  uri: STRING // <uri>
}


text:
require 'spec_helper'

describe Interwetten::LivescoreClient do
  before do
    stub_request(:any, /.*/).to_return(:body => mock_output("livescore.xml"))
    @livescore_client = Interwetten::LivescoreClient.new(666)
  end

  describe :methods do
    describe :get_events do
      before do
        @events = @livescore_client.get_events
      end

      it "should return an array with the events" do
        @events.should == [9759527, 9759529, 9759228]
      end
    end

    describe :get_score do
      before do
        @livescore = @livescore_client.get_score(9759527)
      end

      it "sends back the correct keys" do
        @livescore.keys.should == [:interwetten_id, :gametime, :status, :name, :sport_id, :start_time, :result]
      end
    end
  end
end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revis. gen. pl. (Leipzig) 3: 457 (1898)

#### Original name
Marasmius recubans Quél., 1873

### Remarks
null


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE127_Buffer_Underread__malloc_wchar_t_cpy_68a.c
Label Definition File: CWE127_Buffer_Underread__malloc.label.xml
Template File: sources-sink-68a.tmpl.c
*/
/*
 * @description
 * CWE: 127 Buffer Under-read
 * BadSource:  Set data pointer to before the allocated memory buffer
 * GoodSource: Set data pointer to the allocated memory buffer
 * Sink: cpy
 *    BadSink : Copy data to string using wcscpy
 * Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

wchar_t * CWE127_Buffer_Underread__malloc_wchar_t_cpy_68_badData;
wchar_t * CWE127_Buffer_Underread__malloc_wchar_t_cpy_68_goodG2BData;

#ifndef OMITBAD

/* bad function declaration */
void CWE127_Buffer_Underread__malloc_wchar_t_cpy_68b_badSink();

void CWE127_Buffer_Underread__malloc_wchar_t_cpy_68_bad()
{
    wchar_t * data;
    data = NULL;
    {
        wchar_t * dataBuffer = (wchar_t *)malloc(100*sizeof(wchar_t));
        wmemset(dataBuffer, L'A', 100-1);
        dataBuffer[100-1] = L'\0';
        /* FLAW: Set data pointer to before the allocated memory buffer */
        data = dataBuffer - 8;
    }
    CWE127_Buffer_Underread__malloc_wchar_t_cpy_68_badData = data;
    CWE127_Buffer_Underread__malloc_wchar_t_cpy_68b_badSink();
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good function declarations */
void CWE127_Buffer_Underread__malloc_wchar_t_cpy_68b_goodG2BSink();

/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
    wchar_t * data;
    data = NULL;
    {
        wchar_t * dataBuffer = (wchar_t *)malloc(100*sizeof(wchar_t));
        wmemset(dataBuffer, L'A', 100-1);
        dataBuffer[100-1] = L'\0';
        /* FIX: Set data pointer to the allocated memory buffer */
        data = dataBuffer;
    }
    CWE127_Buffer_Underread__malloc_wchar_t_cpy_68_goodG2BData = data;
    CWE127_Buffer_Underread__malloc_wchar_t_cpy_68b_goodG2BSink();
}

void CWE127_Buffer_Underread__malloc_wchar_t_cpy_68_good()
{
    goodG2B();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE127_Buffer_Underread__malloc_wchar_t_cpy_68_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE127_Buffer_Underread__malloc_wchar_t_cpy_68_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
package com.android.base.permission;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;

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

import timber.log.Timber;

/**
 * <pre>
 *   See:
 *          https://github.com/googlesamples/easypermissions
 *          http://droidyue.com/blog/2016/01/17/understanding-marshmallow-runtime-permission/index.html
 *          http://jijiaxin89.com/2015/08/30/Android-s-Runtime-Permission/
 *
 * Utility to request and check System permissions for apps targeting Android M (API >= 23).
 *
 * </pre>
 */
final class EasyPermissions {

    interface PermissionCaller {

        void onPortionPermissionsGranted(boolean allGranted, int requestCode, List<String> perms);

        void onPermissionsDenied(int requestCode, List<String> perms);

        /**
         * @return PermissionCaller must be Fragment(app and support) or Activity
         */
        Object getRequester();

        IPermissionUIProvider getPermissionUIProvider();
    }

    static private Context getContext(PermissionCaller permissionCaller) {
        Object object = permissionCaller.getRequester();
        if (object instanceof Activity) {
            return (Activity) object;
        } else if (object instanceof Fragment) {
            return ((Fragment) object).getActivity();
        } else if (object instanceof android.app.Fragment) {
            return ((android.app.Fragment) object).getActivity();
        } else {
            throw new RuntimeException("PermissionCaller getRequester mu");
        }
    }

    /**
     * 是否有权限
     */
    static boolean hasPermissions(Context context, String... perms) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            Timber.w("hasPermissions: API version < M, returning true by default");
            return true;
        }
        for (String perm : perms) {
            boolean hasPerm = (ContextCompat.checkSelfPermission(context, perm) ==
                    PackageManager.PERMISSION_GRANTED);
            if (!hasPerm) {
                return false;
            }
        }
        return true;
    }

    /**
     * 请求权限
     */
    static void requestPermissions(final PermissionCaller permissionCaller, final int requestCode, final String... perms) {

        if (hasPermissions(getContext(permissionCaller), perms)) {
            permissionCaller.onPortionPermissionsGranted(true, requestCode, Arrays.asList(perms));
            return;
        }

        final String[] filterPerms = filter(getContext(permissionCaller), perms);//过滤已有权限

        //判断是否有不再询问的复选框
        boolean shouldShowRationale = false;
        for (String filterPerm : filterPerms) {
            shouldShowRationale = shouldShowRationale || shouldShowRequestPermissionRationale(permissionCaller, filterPerm);
        }

        if (shouldShowRationale) {
            permissionCaller.getPermissionUIProvider().showPermissionRationaleDialog(
                    getContext(permissionCaller), filterPerms,
                    (dialog, which) -> executePermissionsRequest(permissionCaller, filterPerms, requestCode),
                    (dialog, which) -> permissionCaller.onPermissionsDenied(requestCode, Arrays.asList(filterPerms)));
            return;
        }
        //没有不再询问的复选框,直接申请
        executePermissionsRequest(permissionCaller, filterPerms, requestCode);
    }

    /**
     * 过滤掉已有的权限
     */
    @TargetApi(23)
    static String[] filter(Context context, String[] perms) {
        List<String> permList = new ArrayList<>();
        for (String perm : perms) {
            boolean hasPerm = (ContextCompat.checkSelfPermission(context, perm) == PackageManager.PERMISSION_GRANTED);
            if (!hasPerm) {
                permList.add(perm);
            }
        }
        return permList.toArray(new String[0]);
    }

    /**
     * 处理申请权限后的结果
     */
    static void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults, PermissionCaller permissionCaller) {
        // Make a collection of granted and denied permissions from the request.
        ArrayList<String> granted = new ArrayList<>();
        ArrayList<String> denied = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            String perm = permissions[i];
            if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                granted.add(perm);
            } else {
                denied.add(perm);
            }
        }
        // Report denied permissions, if any.
        if (!denied.isEmpty()) {
            permissionCaller.onPermissionsDenied(requestCode, denied);
        }
        // Report granted permissions, if any.
        if (!granted.isEmpty()) {
            boolean allGranted = denied.isEmpty();
            permissionCaller.onPortionPermissionsGranted(allGranted, requestCode, granted);
        }
    }

    /**
     * 这个方法需要在onPermissionDenial后调用,如果此时shouldShowRationale为false,表示用户已经选择了不再询问切拒绝了授予权限,需要到应用详情界面设置权限
     */
    static boolean checkDeniedPermissionsNeverAskAgain(final PermissionCaller permissionCaller, List<String> deniedPerms) {
        boolean shouldShowRationale = false;
        for (String perm : deniedPerms) {
            shouldShowRationale = shouldShowRequestPermissionRationale(permissionCaller, perm);
        }
        return !shouldShowRationale;
    }

    /**
     * 获取一个到详情界面的intent,去设置权限
     *
     * @param context 上下文
     * @return Intent
     */
    static Intent getIntentForPermission(Context context) {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
        intent.setData(uri);
        return intent;
    }

    /**
     * 帮我们判断接下来的对话框是否包含"不再询问"选择框。
     *
     * @return true表示有
     */
    @TargetApi(23)
    private static boolean shouldShowRequestPermissionRationale(PermissionCaller permissionCaller, String perm) {
        if (permissionCaller.getRequester() instanceof Activity) {
            return ActivityCompat.shouldShowRequestPermissionRationale((Activity) permissionCaller.getRequester(), perm);
        } else if (permissionCaller.getRequester() instanceof Fragment) {
            return ((Fragment) permissionCaller.getRequester()).shouldShowRequestPermissionRationale(perm);
        } else
            return permissionCaller.getRequester() instanceof android.app.Fragment && ((android.app.Fragment) permissionCaller.getRequester()).shouldShowRequestPermissionRationale(perm);
    }

    /**
     * 执行申请权限
     */
    @TargetApi(23)
    private static void executePermissionsRequest(PermissionCaller permissionCaller, String[] perms, int requestCode) {
        if (permissionCaller.getRequester() instanceof Activity) {
            ActivityCompat.requestPermissions((Activity) permissionCaller.getRequester(), perms, requestCode);
        } else if (permissionCaller.getRequester() instanceof Fragment) {
            ((Fragment) permissionCaller.getRequester()).requestPermissions(perms, requestCode);
        } else if (permissionCaller.getRequester() instanceof android.app.Fragment) {
            ((android.app.Fragment) permissionCaller.getRequester()).requestPermissions(perms, requestCode);
        }
    }

}


text:
package com.teleca.jamendo.db;

import com.teleca.jamendo.api.Album;

import android.content.ContentValues;
import android.database.Cursor;

/**
 * @author Lukasz Wisniewski
 */
public class AlbumDatabaseBuilder extends DatabaseBuilder<Album> {

	@Override
	public Album build(Cursor query) {
		int columnArtistName = query.getColumnIndex("artist_name");
		int columnName = query.getColumnIndex("album_name");
		int columnImage = query.getColumnIndex("album_image");
		int columnId = query.getColumnIndex("album_id");
		int columnRating = query.getColumnIndex("album_rating");

		Album album = new Album();
		album.setId(query.getInt(columnId));
		album.setArtistName(query.getString(columnArtistName));
		album.setName(query.getString(columnName));
		album.setRating(query.getDouble(columnRating));
		album.setImage(query.getString(columnImage));
		return album;
	}

	@Override
	public ContentValues deconstruct(Album album) {
		ContentValues values = new ContentValues();
		values.put("artist_name", album.getArtistName());
		values.put("album_image", album.getImage());
		values.put("album_name", album.getName());
		values.put("album_id", album.getId());
		values.put("album_rating", album.getRating());
		return values;
	}

}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Release Notes</title>
    <link rel="stylesheet" href="./css/screen.css" type="text/css" charset="utf-8" />
    <link rel="stylesheet" href="./css/gollum.css" type="text/css" charset="utf-8" />
    <link rel="stylesheet" href="./css/syntax.css" type="text/css" charset="utf-8" />

                  Aurelius Titan

Release Notes

Titan: Distributed Graph Database
http://titan.thinkaurelius.com

Titan 0.y.z

Version 0.3.2 (July 27, 2013)

<dependency>
   <groupId>com.thinkaurelius.titan</groupId>
   <artifactId>titan-core</artifactId>
   <version>0.3.2</version>
</dependency>

Tested Compatibility:

Cassandra 1.2.2

HBase 0.94.1

BerkeleyJE 5.0.73

Elasticsearch 0.90.0

Lucene 4.1.0

Java 1.6+

Features:

Support for multiple standard index conditions in queries

Bugfixes:

Fixed potential transaction leak when using thread-bound transactions

Let vertex.removeProperty(…) kill multivalued properties as the javadoc says

Avoided two spurious cases of "timestamp mismatch" exception

Removed unchecked cast in AbstractElement.equals(…)

Adjusted default Astyanax exponential backoff settings to avoid integer overflow against a dead peer

Fixed Astyanax config regression that caused node discovery and connection pool type to be ignored

Fixed double-checked locking on StandardVertex's added relations

Check the issue tracker for a full list of fixed issues.

Version 0.3.1 (May 14, 2013)

<dependency>
   <groupId>com.thinkaurelius.titan</groupId>
   <artifactId>titan-core</artifactId>
   <version>0.3.1</version>
</dependency>

Tested Compatibility:

Cassandra 1.2.2

HBase 0.94.1

BerkeleyJE 5.0.73

Elasticsearch 0.90.0

Lucene 4.1.0

Java 1.6+

Features:

Improved in-transaction index handling for equality matches

Support for Lucene 4 throughout

Storage backend compression enabled by default where applicable

Removed RexsterTitanClient since all the functionality has been rolled into RexsterClient

Automatic type-casting of most primitive types and Geoshape where possible

Refactored to using immutable data structures for storage backend communication

Re-implemented InMemory storage backend for better performance

Bugfixes:

Launching multiple Titan servers in one cluster with RF>1

Updated and improved the Astyanax adapter for Cassandra

Improved robustness of ID allocation

Vertex iteration in embedded Cassandra with BoP

Updated Titan server scripts and configuration files

Fixed issues around automatic transaction migration of vertices and edges

Fixed BerkeleyJE concurrency clean-up issue

Cleaned up and trimmed storage backend interfaces

Fixed ghost vertex issue when iterating over vertices

Fixed datatype conversion issues

Check the issue tracker for a full list of fixed issues.

Version 0.3.0 (March 29, 2013)

<dependency>
   <groupId>com.thinkaurelius.titan</groupId>
   <artifactId>titan-core</artifactId>
   <version>0.3.0</version>
</dependency>

Tested Compatibility:

Cassandra 1.2.2

HBase 0.94

BerkeleyJE 5.0.73

Features:

Geo, numeric range, and full-text indexing supporting multiple index backends

Edge Indexing

Refactoring of Titan-core for enhanced performance due to selective de-serialization

New query optimizer for vertex-centric and graph queries

Vertex centric query caching for selective queries

InMemoryGraph implementation

IdGraph support

Relaxed transactional scope requirement for vertices

Edge no longer extends Vertex

Updated to Kryo 2

Bugfixes:

Cassandra Thrift Max-Message-Size issue

JMX settings for Titan Server

Out-unique edges

Modified state in global graph operations

see issue tracker for a full list

Version 0.2.1 (March 22, 2013)

<dependency>
   <groupId>com.thinkaurelius.titan</groupId>
   <artifactId>titan-core</artifactId>
   <version>0.2.1</version>
</dependency>

Tested Compatibility:

Cassandra 1.2.0

HBase 0.94

BerkeleyJE 5.0.58

Features:

Refactored POM into multi-module project

Support for global vertex (g.V) and edge (g.E) iteration for cassandra and hbase backends

Compatible with Cassandra 1.2.0 for all three storage adapters: embedded, thrift, astyanax

Improved HBase adapter:

Automatic Master launch for testing

Refactored batch mutation and reading

Optimized HBase operations

Updated to Blueprints 2.3.0

Better integration with Rexster Rexpro

Automatic directory creation for local storage backends

Internal Titan version handling and compatibility checks

Added additional performance tests

Bugfixes:

Resolved issues around Java 1.7

Shutdown error in astyanax adapter

Made thrift frame and message size configurable for cassandra adapters

see issue tracker for a full list

Special Thanks to:

Pavel Yaskevich (xedin)

Version 0.2.0 (December 24, 2012)

<dependency>
   <groupId>com.thinkaurelius.titan</groupId>
   <artifactId>titan</artifactId>
   <version>0.2.0</version>
</dependency>

Tested Compatibility:

Cassandra 1.1.3 & 1.1.4

HBase 0.94.1

BerkeleyDB 5.0.58

TinkerPop (Blueprints, Gremlin, Rexster) 2.2.0

This version is incompatible with the previous version of Titan. Please follow the Upgrade Instructions to switch to the new version.

Features:

Embedded Cassandra: Titan can be embedded with Cassandra, that means, Titan starts a Cassandra node in the same JVM and uses efficient in process communication to store and retrieve data.

Titan Server: Titan comes with a light-weight Gremlin query server.

Streamlined configuration settings. Please review the new configuration options if you are upgrading from an older version of Titan.

Many small performance improvements throughout the code. Please review the issue tracker and the commit log for more details.

Bugfixes:

Fixed edge sorting bug which caused edges to be returned in a random order even when a vertex centric index was defined.

Fixed id allocation bug that causes Titan to read the entire row during id allocation which can lead to id allocation failures.

Completely refactored diskstorage package for better code quality and performance.

Fixed edge caching bug for composite primary keys on edges.

Fixed a number of smaller bugs. Please review the issue tracker and the commit log for more details.

Special Thanks to:

Zack Maril (zmaril)

Nicolas LaCasse (nlacasse)

Vadas Gintautas (vadasg)

Version 0.1.0 (September 7, 2012)

<dependency>
   <groupId>com.thinkaurelius.titan</groupId>
   <artifactId>titan</artifactId>
   <version>0.1.0</version>
</dependency>

Tested Compatibility:

Cassandra 1.1.3 & 1.1.4

HBase 0.94.1

BerkeleyDB 5.0.58

Features:

The focus of the initial Titan release was on building a stable and robust graph database as well as incorporating community feature suggestions and feedback from early adopters of Titan.

Bugfixes:

Fixed concurrency and synchronization issues

Special Thanks to:

Danny Thomas (BinaryRage)

jramsdale

Cristofer (crisweber)

tedoc2000

Dan Forest-Barbier (DPanth3r)

jncorpron

Marc Abramowitz (msabramo)

              Last edited by Dan LaRocque, 2013-07-28 06:49:42


text:
declare module A {}
declare module B {}


text:
package com.intellij.testFramework.utils.parameterInfo;

import com.intellij.lang.parameterInfo.ParameterInfoUIContext;
import com.intellij.psi.PsiElement;

import java.awt.*;

/**
 * @author Maxim.Mossienko
 */
public class MockParameterInfoUIContext<T extends PsiElement> implements ParameterInfoUIContext {
  private boolean enabled;
  private String text;
  private int highlightStart;
  private final T myFunction;
  private int parameterIndex;

  public MockParameterInfoUIContext(final T function) {
    myFunction = function;
  }

  @Override
  public void setupUIComponentPresentation(final String _text, final int highlightStartOffset, final int highlightEndOffset,
                                           final boolean isDisabled, final boolean strikeout, final boolean isDisabledBeforeHighlight,
                                           final Color background) {
    text = _text;
    highlightStart = highlightStartOffset;
  }

  @Override
  public boolean isUIComponentEnabled() {
    return enabled;
  }

  @Override
  public void setUIComponentEnabled(final boolean _enabled) {
    enabled = _enabled;
  }

  @Override
  public int getCurrentParameterIndex() {
    return parameterIndex;
  }

  public void setCurrentParameterIndex(final int parameterIndex) {
    this.parameterIndex = parameterIndex;
  }

  @Override
  public PsiElement getParameterOwner() {
    return myFunction;
  }

  @Override
  public Color getDefaultParameterColor() {
    return null;
  }

  public String getText() {
    return text;
  }

  public int getHighlightStart() {
    return highlightStart;
  }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>MOAL.data_structures.retroactive — MoAL  documentation</title>

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

    <link rel="top" title="MoAL  documentation" href="../../../index.html"/>
        <link rel="up" title="Module code" href="../../index.html"/>

             MoAL

  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

MOAL package

        MoAL

Docs »

Module code »

MOAL.data_structures.retroactive

Source code for MOAL.data_structures.retroactive

# -*- coding: utf-8 -*-

__author__ = """Chris Tabor (dxdstudio@gmail.com)"""

if __name__ == '__main__':
    from os import getcwd
    from os import sys
    sys.path.append(getcwd())

from MOAL.data_structures import persistent
from MOAL.helpers.display import Section
from MOAL.helpers.display import print_h2
from MOAL.helpers.display import print_simple

DEBUG = True if __name__ == '__main__' else False

[docs]class RetroactiveNode(persistent.FullyPersistentNode):
    """Piggybacking on the existing classes from previous examples,
    we just use the Partial/Full persistent classes for each of these.
    The only difference is the addition of temporal updates across all nodes."""

[docs]    def __setitem__(self, key, value):
        super(RetroactiveNode, self).__setitem__(key, value)
        # Apply the temporal updates
        self._update_retroactive(key)

[docs]    def _handlenode(self, nodeval):
        """Handle updating individual node values - throws in gibberish
        for each type, just for debugging/visualizing."""
        if isinstance(nodeval, dict):
            for key, val in nodeval.iteritems():
                nodeval[key] = '_{}'.format(val)
        elif isinstance(nodeval, list):
            for k, val in enumerate(nodeval):
                nodeval[k] = '>{}'.format(val)
        else:
            nodeval = '+{}'.format(nodeval)
        return nodeval

[docs]class PartiallyRetroactiveNode(RetroactiveNode):
    """From Wikipedia:

    "In computer science a retroactive data structure is data structure which
    supports efficient modifications to a sequence of operations that have been
    performed on the structure. These modifications can take the form of
    retroactive insertion, deletion or updating an operation that was
    performed at some time in the past."

    ----------------------------------------------------------------------------

    The notion of temporal updates is probably intuitive, especially the idea
    of cascading changes, but what is probably confusing (at least was for me)
    is how this translates into something real.

    For example, if one element changes, and the rest are also supposed to
    change as a result, what exactly should these other elements change to?
    It's one thing to say "update node X[0]'s value with y", but how does that
    translate for X[1], X[2], etc...? I think the point here is that it depends
    on your own personal use-case and context.

    For example, if you are using something like git, and you need to update
    the references when something changes, you can implement your own method
    of temporal updates on the data structure.

    Or, let's say you are maintaining some numerical values that have special
    properties, you can go back and recalculate each one.

    Or apply a hash function, or some other modifier for each element.
    Or just update the time-stamp.

    Hopefully that makes sense!
    """

[docs]    def _update_retroactive(self, key):
        for version in self.versions[key]:
            print('- (Partially) retroactively updating item')
            version = self._handlenode(self.versions[key][version])

[docs]class FullyRetroactiveNode(
        RetroactiveNode, persistent.ConfluentlyPersistentFatNode):

    def _update_retroactive(self, key):
        for version in self.versions[key]['versions']:
            print('- Retroactively updating item')
            version = self._handlenode(version['data'])

if DEBUG:
    with Section('Retroactive data structures'):
        print_h2('Partially retroactive node')
        partial = PartiallyRetroactiveNode()
        _example = {'foo': 'bam'}
        partial['foo'] = _example
        partial['bar'] = {'foo': 'bam'}
        # Do some updates to test.
        for x in range(4):
            partial['foo'] = {
                '{}{}'.format(x, k): v for k, v in _example.iteritems()}
        # Test plain values
        partial['foo'] = 133332
        print_simple('Partially retroactive data:', partial.versions)
        print_simple('All data for `foo`:', partial['foo'])

        print_h2('Fully retroactive node')
        full = FullyRetroactiveNode()
        # Values with the longest prefix also can be used to indicate
        # the number of updates done, if the token value is unique enough.
        # E.g. 'value': '_foo' => 'value': '___foo' indicates 'foo'
        # was updated three times.
        full['name'] = {'first': 'Chris', 'last': 'Tabor'}
        full['dob'] = {'month': 'Jan', 'day': '05', 'year': '1986'}
        full['name'] = {'first': 'Christopher', 'last': 'Tabor'}
        full['name'] = {'first': 'Christobot', 'last': 'Taborium'}
        full['name'] = {'first': 'Christobonicus', 'last': 'Taboriot'}
        print_simple('Fully retroactive data:', full.versions)

        © Copyright 2015, Chris Tabor.

  Built with Sphinx using a theme provided by Read the Docs.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

   <TextView
       android:id="@+id/name_token"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/token_background"
        android:textColor="@android:color/white"
        android:textSize="14sp"
        android:paddingLeft="3dp"
        android:paddingRight="3dp"
        android:paddingTop="2dp"
        android:paddingBottom="4dp"/>

   <ImageView
        android:id="@+id/icon_image_token"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:paddingLeft="5dp"
        android:scaleType="centerCrop" />

</LinearLayout>


text:
package org.databene.commons.log;

import org.databene.commons.ui.InfoPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * {@link InfoPrinter} implementation that writes text to a logger category.
 * Created: 01.08.2010 17:13:04
 * @since 0.5.3
 * @author Volker Bergmann
 */
public class LoggingInfoPrinter extends InfoPrinter {

    private final Logger logger;

	public LoggingInfoPrinter(Class<?> clazz) {
		this.logger = LoggerFactory.getLogger(clazz);
    }

	public LoggingInfoPrinter(String category) {
		this.logger = LoggerFactory.getLogger(category);
    }

	@Override
    public void printLines(Object owner, String... infoLines) {
        for (String info : infoLines)
        	logger.info(info);
    }

}


text:
{-# LANGUAGE ViewPatterns #-}

module Main where

import Gen2.Archive
import qualified Data.ByteString.Lazy as B
import System.FilePath
import qualified Data.Text as T
import System.Environment
import Control.Monad

import Module

main = do
  args <- getArgs
  case args of
   [archive] -> do
     meta <- readMeta archive
     putStrLn ("meta:\n" ++ show meta)
     index <- readIndex archive
     putStrLn "index:"
     mapM_ print index
     forM_ index $ extractIndexEntry archive
   _ -> putStrLn "usage: dumpArchive archiveFile"

extractIndexEntry :: FilePath -> IndexEntry -> IO ()
extractIndexEntry archive (ieEntry -> Object mod) = do
  let ms = T.unpack mod
      outFile = dropExtension archive ++ "_obj_" ++ ms <.> "js_o"
  putStrLn $ "extracing module object: " ++ ms ++ " ->\n  " ++ outFile
  bs <- readObject (mkModuleName ms) archive
  B.writeFile outFile bs
extractIndexEntry archive (ieEntry -> JsSource file) = do
  let outFile = dropExtension archive ++ "_src_" ++ map replaceChr file
      replaceChr c | c `elem` "\\/" = '_'
                   | otherwise      = c
  putStrLn $ "extracting js source: " ++ file ++ " ->\n  " ++ outFile
  bs <- readSource file archive
  B.writeFile outFile bs


text:
In this repository, various data mining algorithms are implemented while following the Course, Foundations of Data Mining at Eindhoven University of Technology (TU/e). Besides, hyper-parameter tuning techniques are experimented. The algorithms are as follows.
# Files and descriptions.
|File | Algorithm|
|-----|-------------|
|MPNN.py | Multiple processing nearest-neighbor based on Cosine similarity.|
|MTNN.py | Multiple threads nearest-neighbor based on Cosine similarity.|\
|NN.py | Nearest-neighbor based on Cosine similarity.|
|SGDDataset.py | Provides next_batch method, useful in Neural Network Mini-batch training.|
|ada_learning_rate_nn.py | One hidden layer and one Softmax output layer neural netwok based on Tensorflow.|
|challenge.py | Used to challenge the task 14951 in OpenML.|
|dataloader_1b.py | Used to load files in data1b/. Provided by Course Prof.|
|decision_tree.py | Experimented CART and randomized tree with a set of hyperparameter settings.|
|ensembles.py | Experimented with Random Forests.|
|evaluate_NN.py | Used to evaluate Nearest-neighbor algorithms with different distance functions, i.e., confusion matrix.|
|k_means.py | k-means with different initialization methods, inclu. first k points, uniformly sampled k points, kmeans++, gonzales algorithm.|
|k_medians.py | k-median clustering.|
|kernel_selection.py | Support Vector Machines (SVM) with different kernels, incl. linear, rbf and polynomial kernels.|
|kernel_selection2.py | Experimented parameters of SVM with rbf kernel, namely gamma and C.|
|kernel_selection3.py | Grid search of SVM with rbf kernel, using AUC as metric.|
|landscape_analysis.py | Grid search of SVM with rbf kernel. Plot the AUC = f(gamma, C) heat map.|
|max_margin_classifier.py | A simple example to explain support vectors and maximal margin linear classifier.|
|mnist_dataloader.py | To load the MNIST dataset (data1a/). Provided by Course Prof.|
|model_selection.py | Compute bias and variance using bootstraping of knearest-neighbor (different ks) or decision tree (different max_depth or max_leaf_nodes).|
|nn_mnist.py | Neural Network with sklearn.|
|nn_with_alpha.py | Neural Network with different alphas, i.e., l2-norm penalty implemented with Tensorflow.
|nn_with_learning_rate.py| Neural Network with different learning rates implemented with Tensorflow.|
|nn_with_momentum.py| Neural Network with different momentum implemented with Tensorflow.|
|nn_with_nodes.py | Neural Network with a hidden layer and a softmax output layer implemented in Tensorflow.|
|optimization.py | Experimented with different hyperparameter tuning techniques, incl. random search, grid search (with cross validation).|
|random_forests.py | Demonstrate how Random Forests reduce variance without increasing bias (much) so as to reduce the  classification error.|
|random_projection.py | Implement random projection, to do dimensionality reduction. The result is compared with MPNN.py.|
|roc_curves.py | Demonstrate the convex hull of many classifiers in ROC diagram.|
|tensor_flow_softmax_mnist.py | Softmax regression implemented in Tensorflow. This is used to practice with Tensorflow.|
|unit_circles.py | Demonstrate the unit ``circles`` of different norms, inclu. l1, l2, l10 and l-infinity.|


text:
using DotNetBlog.Core.Model.Widget;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DotNetBlog.Web.Widgets
{
    public class AdministrationWidget : ViewComponent
    {
        public IViewComponentResult Invoke(AdministrationWidgetConfigModel config)
        {
            ViewBag.Config = config;

            return View();
        }
    }
}


text:
namespace plat.routing {
    'use strict';

    /**
     * @name RouteRecognizer
     * @memberof plat.routing
     * @kind class
     *
     * @description
     * Assists in compiling and linking route strings. You can register route strings using
     * a defined scheme, and it will compile the routes. When you want to match a route, it will
     * find the associated compiled route and link it to the data given with the passed-in route.
     */
    export class RouteRecognizer {
        protected static _inject: any = {
            _BaseSegmentFactory: __BaseSegmentFactory,
            _State: __StateStatic,
            _rootState: __StateInstance,
        };

        /**
         * @name _BaseSegmentFactory
         * @memberof plat.routing.RouteRecognizer
         * @kind property
         * @access protected
         *
         * @type {plat.routing.BaseSegment}
         *
         * @description
         * Reference to the {@link plat.routing.BaseSegment|BaseSegment} injectable.
         */
        protected _BaseSegmentFactory: typeof BaseSegment;

        /**
         * @name _State
         * @memberof plat.routing.RouteRecognizer
         * @kind property
         * @access protected
         *
         * @type {plat.routing.State}
         *
         * @description
         * Reference to the {@link plat.routing.State|State} injectable.
         */
        protected _State: typeof State;

        /**
         * @name _rootState
         * @memberof plat.routing.RouteRecognizer
         * @kind property
         * @access protected
         *
         * @type {plat.routing.State}
         *
         * @description
         * A root state for the recognizer used to add next states.
         */
        protected _rootState: State;

        /**
         * @name _namedRoutes
         * @memberof plat.routing.RouteRecognizer
         * @kind property
         * @access protected
         *
         * @type {plat.IObject<plat.routing.INamedRoute>}
         *
         * @description
         * All the named routes for this recognizer.
         */
        protected _namedRoutes: IObject<INamedRoute> = {};

        /**
         * @name register
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access public
         *
         * @description
         * A method for registering routes to be identified later. Internally the
         * routes will be compiled into a series of {@link plat.routing.State|states}
         * which will be used to recognize the route later.
         *
         * @param {Array<plat.routing.IRouteDelegate>} routes The routes to register.
         * @param {plat.routing.IRegisterOptions} options? An object containing options for the
         * registered route.
         *
         * @returns {void}
         */
        public register(
            routes: IRouteDelegate[],
            options?: IRegisterOptions
        ): void {
            if (!isArray(routes)) {
                return;
            }

            let finalState = this._rootState;
            const length = routes.length;
            const regex: string[] = ['^'];
            const types: ISegmentTypeCount = {
                statics: 0,
                dynamics: 0,
                splats: 0,
            };
            const delegates: IDelegateParameterNames[] = [];
            let allSegments: BaseSegment[] = [];
            let segments: BaseSegment[];

            for (let i = 0; i < length; i += 1) {
                segments = this._parse(routes[i], delegates, types);
                allSegments = allSegments.concat(segments);
                finalState = this._compile(segments, finalState, regex);
            }

            finalState = this._finalize(finalState, regex);
            finalState.delegates = delegates;
            finalState.regex = new RegExp(`${regex.join('')}$`);
            finalState.types = types;

            if (isObject(options) && isString(options.name)) {
                this._namedRoutes[this._toLowerCase(options.name)] = {
                    segments: allSegments,
                    delegates: delegates,
                };
            }
        }

        /**
         * @name recognize
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access public
         *
         * @description
         * Searches for a match to the provided path. If a match is found, the path is deconstructed
         * to populate a parameters object (if the registered route was a dynamic/splat route).
         *
         * @param {string} path The path to recognize.
         *
         * @returns {plat.routing.IRecognizeResult} If the path is recognized, the linked delegates will be
         * returned.
         */
        public recognize(path: string): IRecognizeResult {
            let isTrailingSlashDropped: boolean = false;
            let solutions: State[] = [];

            path = this._addLeadingSlash(path);
            isTrailingSlashDropped = this._hasTrailingSlash(path);

            if (isTrailingSlashDropped) {
                path = path.substr(0, path.length - 1);
            }

            solutions = this._filter(this._findStates(path));

            return this._link(solutions[0], path, isTrailingSlashDropped);
        }

        /**
         * @name generate
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access public
         *
         * @description
         * Finds a {@link plat.routing.INamedRoute|INamedRoute} and generates a string
         * if it exists. Uses the parameters object to generate dynamic routes.
         *
         * @param {string} name The named route with which to generate the route string.
         * @param {plat.IObject<string>} parameters The route parameters, in the case that the
         * named route is dynamic.
         *
         * @returns {string} The generated route.
         */
        public generate(name: string, parameters?: IObject<string>): string {
            name = this._toLowerCase(name);
            const route = this._namedRoutes[name];
            let output = '';
            let segments: BaseSegment[];
            let length: number;

            if (!isObject(route)) {
                return;
            }

            segments = route.segments;
            length = segments.length;

            for (let i = 0; i < length; i += 1) {
                const segment = segments[i];

                if (segment.type === __BASE_SEGMENT_TYPE) {
                    continue;
                }

                output += '/';
                output += segment.generate(parameters);
            }

            output = this._addLeadingSlash(output);

            return output;
        }

        /**
         * @name delegatesFor
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access public
         *
         * @description
         * Finds the delegates for an {@link plat.routing.INamedRoute|INamedRoute}
         *
         * @param {string} name The named route from which to get the delegates.
         *
         * @returns {Array<IDelegateParameterNames>} The delegates for the named route.
         */
        public delegatesFor(name: string): IDelegateParameterNames[] {
            name = this._toLowerCase(name);
            const namedRoute = this._namedRoutes[name];
            let delegates: IDelegateParameterNames[];

            if (!isObject(namedRoute)) {
                return [];
            }

            delegates = namedRoute.delegates;

            if (!isArray(delegates)) {
                return [];
            }

            return delegates.slice(0);
        }

        /**
         * @name exists
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access public
         *
         * @description
         * Determines whether or not an {@link plat.routing.INamedRoute|INamedRoute} is registered.
         *
         * @param {string} name The named route to search for.
         *
         * @returns {boolean} Whether or not the named route exists.
         */
        public exists(name: string): boolean {
            return isObject(this._namedRoutes[this._toLowerCase(name)]);
        }

        /**
         * @name _toLowerCase
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access protected
         *
         * @description
         * Safely converts a string to lower case.
         *
         * @param {string} str The string to convert to lower case.
         *
         * @returns {plat.routing.State} The final state.
         */
        protected _toLowerCase(str: string): string {
            if (!isString(str)) {
                return str;
            }

            return str.toLowerCase();
        }

        /**
         * @name _finalize
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access protected
         *
         * @description
         * Finalizes a compiled route, adding a final state if necessary. If the state is equal to the
         * root state for the recognizer, a new state will be created. This is because the root state does not
         * represent any route.
         *
         * @param {plat.routing.State} state The state to finalize.
         * @param {string} regex The regular expression string built for the compiled routes. Used to recognize
         * routes and associate them with the compiled routes.
         *
         * @returns {plat.routing.State} The final state.
         */
        protected _finalize(state: State, regex: string[]): State {
            if (state === this._rootState) {
                state = state.add({
                    validCharacters: '/',
                });
                regex.push('/');
            }

            return state;
        }

        /**
         * @name _parse
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access protected
         *
         * @description
         * Parses a route into different {@link plat.routing.BaseSegment|segments};
         *
         * @param {plat.routing.IRouteDelegate} route The route options to be parsed.
         * @param {Array<plat.routing.IDelegateParameterNames>} delegates The delegates and associated names for mapping parameters.
         * @param {plat.routing.ISegmentTypeCount} types A count of all the segment types in the route.
         *
         * @returns {Array<plat.routing.BaseSegment>} The segments created for the route.
         */
        protected _parse(
            route: IRouteDelegate,
            delegates: IDelegateParameterNames[],
            types: ISegmentTypeCount
        ): BaseSegment[] {
            const names: string[] = [];

            delegates.push({
                delegate: route.delegate,
                names: names,
            });

            return this._BaseSegmentFactory.parse(route.pattern, names, types);
        }

        /**
         * @name _compile
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access protected
         *
         * @description
         * Compiles a list of segments into a series of {@link plat.routing.State|states}.
         *
         * @param {Array<plat.routing.BaseSegment>} segments The segments to compile.
         * @param {plat.routing.State} state The initial state used to compile.
         * @param {Array<string>} regex A regular expression string to build in order to match the segments.
         *
         * @returns {plat.routing.State} The final state obtained from compilation.
         */
        protected _compile(
            segments: BaseSegment[],
            state: State,
            regex: string[]
        ): State {
            const length = segments.length;
            const compile = this._State.compile;
            let segment: BaseSegment;

            for (let i = 0; i < length; i += 1) {
                segment = segments[i];

                if (segment.type === __BASE_SEGMENT_TYPE) {
                    continue;
                }

                state = state.add({ validCharacters: '/' });
                state = compile(segment, state);
                regex.push(`/${segment.regex}`);
            }

            return state;
        }

        /**
         * @name _addLeadingSlash
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access protected
         *
         * @description
         * Adds a leading slash to the passed-in string if necessary.
         *
         * @param {string} path The path to which to add the slash.
         *
         * @returns {string} The path, with leading slash added.
         */
        protected _addLeadingSlash(path: string): string {
            path = decodeURI(path);

            if (path[0] !== '/') {
                path = `/${path}`;
            }

            return path;
        }

        /**
         * @name _hasTrailingSlash
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access protected
         *
         * @description
         * Checks for a trailing slash on a given string.
         *
         * @param {string} path The path on which to look for a trailing slash.
         *
         * @returns {boolean} Whether or not the path has a trailing slash
         */
        protected _hasTrailingSlash(path: string): boolean {
            const length = path.length;

            return length > 1 && path[length - 1] === '/';
        }

        /**
         * @name _findStates
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access protected
         *
         * @description
         * Finds the compiled states for a given path.
         *
         * @param {string} path The path with which to look for compiled states.
         *
         * @returns {Array<plat.routing.State>} The states associated with the given path.
         */
        protected _findStates(path: string): State[] {
            let states: State[] = [this._rootState];
            const recognize = this._State.recognize;
            const length = path.length;

            for (let i = 0; i < length; i += 1) {
                states = recognize(path[i], states);

                if (states.length === 0) {
                    break;
                }
            }

            return states;
        }

        /**
         * @name _filter
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access protected
         *
         * @description
         * Filters out states with no delegates, and sorts the states.
         *
         * @param {Array<plat.routing.State>} states The states to filter.
         *
         * @returns {Array<plat.routing.State>} The filtered and sorted states
         */
        protected _filter(states: State[]): State[] {
            const length = states.length;
            const solutions: State[] = [];
            let state: State;

            for (let i = 0; i < length; i += 1) {
                state = states[i];
                if (isArray(state.delegates)) {
                    solutions.push(state);
                }
            }

            return this._State.sort(solutions);
        }

        /**
         * @name _link
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access protected
         *
         * @description
         * Links a state to a path, producing an {@link plat.routing.IRecognizeResult|IRecognizeResult}.
         *
         * @param {plat.routing.State} states The state to link.
         * @param {string} path The path to link.
         * @param {boolean} isTrailingSlashDropped Whether or not the trailing slash is dropped from the path.
         *
         * @returns {plat.routing.IRecognizeResult} The linked result.
         */
        protected _link(
            state: State,
            path: string,
            isTrailingSlashDropped: boolean
        ): IRecognizeResult {
            if (isObject(state) && isArray(state.delegates)) {
                if (isTrailingSlashDropped && this._isDynamic(state)) {
                    path = `${path}/`;
                }

                return this._State.link(state, path);
            }
        }

        /**
         * @name _isDynamic
         * @memberof plat.routing.RouteRecognizer
         * @kind function
         * @access protected
         *
         * @description
         * Determines whether or not the state is dynamic.
         *
         * @param {plat.routing.State} states The state used to determine if it is dynamic or not.
         *
         * @returns {boolean} Whether or not the state is dynamic.
         */
        protected _isDynamic(state: State): boolean {
            return state.regex.source.slice(-5) === '(.+)$';
        }
    }

    register.injectable(
        __RouteRecognizerInstance,
        RouteRecognizer,
        null,
        __INSTANCE
    );

    /**
     * @name IRecognizeResult
     * @memberof plat.routing
     * @kind interface
     *
     * @extends {Array<plat.routing.IDelegateInfo>}
     *
     * @description
     * An Array of delegate information for a recognized route.
     */
    export interface IRecognizeResult extends Array<IDelegateInfo> {}

    /**
     * @name IDelegateInfo
     * @memberof plat.routing
     * @kind interface
     *
     * @description
     * Information for a recognized route segment. Contains the registered
     * delegate, as well as a parameters object with key/value pairs for a
     * dynamic route segment.
     */
    export interface IDelegateInfo {
        /**
         * @name delegate
         * @memberof plat.routing.IDelegateInfo
         * @kind property
         *
         * @type {any}
         *
         * @description
         * A delegate can be anything. It is an object that will provide functionality
         * for a route segment.
         */
        delegate: any;

        /**
         * @name parameters
         * @memberof plat.routing.IDelegateInfo
         * @kind property
         *
         * @type {any}
         *
         * @description
         * The parameters for a route segment. If the segment is a dynamic or splat
         * segment, then the parameters will be a key/value pair object with the associated
         * variables.
         */
        parameters: any;

        /**
         * @name isDynamic
         * @memberof plat.routing.IDelegateInfo
         * @kind property
         *
         * @type {boolean}
         *
         * @description
         * States whether or not the register delegate is for a dynamic/splat route. If
         * this value is true, then the parameters object will be filled with key/value pairs
         * associated to the registered route parameters.
         */
        isDynamic: boolean;
    }

    /**
     * @name INamedRoute
     * @memberof plat.routing
     * @kind interface
     *
     * @description
     * Contains information about a named route. Created when you register a route with an associated
     * name.
     */
    export interface INamedRoute {
        /**
         * @name segments
         * @memberof plat.routing.INamedRoute
         * @kind property
         *
         * @type {Array<plat.routing.BaseSegment>}
         *
         * @description
         * All the segments for the named route.
         */
        segments: BaseSegment[];

        /**
         * @name delegates
         * @memberof plat.routing.INamedRoute
         * @kind property
         *
         * @type {Array<plat.routing.IDelegateParameterNames>}
         *
         * @description
         * All the delegates for the named route.
         */
        delegates: IDelegateParameterNames[];
    }

    /**
     * @name IRouteDelegate
     * @memberof plat.routing
     * @kind interface
     *
     * @description
     * Used during route registration to specify a delegate object to associate
     * with a route.
     */
    export interface IRouteDelegate {
        /**
         * @name pattern
         * @memberof plat.routing.IRouteDelegate
         * @kind property
         *
         * @type {string}
         *
         * @description
         * The pattern to match for the route, accepts dynamic routes as well as splat routes.
         *
         * @example
         * /posts/new
         *
         * @example
         * /posts/:id
         *
         * @example
         * /posts/*path
         */
        pattern: string;

        /**
         * @name delegate
         * @memberof plat.routing.IRouteDelegate
         * @kind property
         *
         * @type {any}
         *
         * @description
         * A delegate object which should provide functionality for the associated pattern. It can be anything,
         * it is up to the owner of the registered route to know what to do with the delegate.
         */
        delegate: any;
    }

    /**
     * @name IRegisterOptions
     * @memberof plat.routing
     * @kind interface
     *
     * @description
     * Options that you can pass in when registering routes.
     */
    export interface IRegisterOptions {
        /**
         * @name name
         * @memberof plat.routing.IRegisterOptions
         * @kind property
         *
         * @type {string}
         *
         * @description
         * Allows you to assign a name to a registered route.
         */
        name?: string;
    }
}


text:
class AcRxVariableCache : public AcRxVariableReactor
{
    /// <summary>
    /// Implemenation detail: handles updating the cache when variable changes.
    /// </summary>
  void changed(const AcRxVariable* sender, const AcRxVariableChangedEventArgs& args) override
  {
    const auto& rb = args.newValue();
    memcpy(&m_cache, &rb, sizeof(rb));
    if (rb.restype == RTSTR)
    {
      Acad::ErrorStatus es = acutUpdString(rb.resval.rstring, m_cache.resval.rstring);
      ASSERT(Acad::eOk == es);
    }
  }
  resbuf m_cache;
  AcString m_name;
public:
    /// <summary>
    /// Constructs a cache instance. The cache should be scoped long enough so that it is not
    /// created/destroyed for every access.
    /// </summary>
    /// <param name="name"/>Name of the AcRxVariable which the cache is to be constructed for.</param>
  AcRxVariableCache(const ACHAR* name)
    : m_name(name)
    , m_cache({0})
  {
    m_cache.restype = RTNONE;
    auto var = AcRxVariablesDictionary::get()->getVariable(name);
        //we will tolerate sysvars that are missing
    if (var == nullptr)
    {
      return ;
    }
    var->addReactor(this);
    Acad::ErrorStatus es = var->getValue(m_cache);
    ASSERT(Acad::eOk == es);
  }
    /// <summary>
    /// Destructs the cache.
    /// </summary>
  ~AcRxVariableCache()
  {
    auto var = AcRxVariablesDictionary::get()->getVariable(m_name.kwszPtr());
    if (var == nullptr)
    {
      return ;
    }
    var->removeReactor(this);
  }
    /// <summary>
    /// High performance accessor (boolean overload)
    /// </summary>
    /// <param name="def">default value that the function will return if
    /// the value of the variable is not available for any reason.
    /// </param>
  bool getBool(bool def)
  {
    return !!getInt16(def ? 1 : 0);
  }
    /// <summary>
    /// High performance accessor (int16 overload)
    /// </summary>
    /// <param name="def">default value that the function will return if
    /// the value of the variable is not available for any reason.
    /// </param>
  short getInt16(short def)
  {
    ASSERT(m_cache.restype == RTSHORT || m_cache.restype == RTNONE);
    if (m_cache.restype != RTSHORT)
    {
      return def;
    }
    return m_cache.resval.rint;
  }
    /// <summary>
    /// High performance accessor (double overload)
    /// </summary>
    /// <param name="def">default value that the function will return if
    /// the value of the variable is not available for any reason.
    /// </param>
  double getDouble(double def)
  {
    ASSERT(m_cache.restype == RTREAL || m_cache.restype == RTNONE);
    if (m_cache.restype != RTREAL)
    {
      return def;
    }
    return m_cache.resval.rreal;
  }
    /// <summary>
    /// High performance accessor (string overload)
    /// </summary>
  AcString getString()
  {
    AcString ret;
    ASSERT(m_cache.restype == RTSTR || m_cache.restype == RTNONE);
    if (m_cache.restype != RTSTR)
    {
      return ret;
    }
    return m_cache.resval.rstring;
  }
};


text:
package es.uniovi.reflection.weavej.test.aspects;

import java.lang.invoke.MethodHandle;

import es.uniovi.reflection.weavej.test.component.RationalNumber;

/**
 * Stateful aspect to weave Around pointcuts along with
 * {@link es.uniovi.reflection.weavej.test.component.RationalNumber RationalNumber}
 * methods.
 *
 * @author Oscar Rodriguez-Prieto Date: 2017/07/11
 *
 * @version 1.1.0
 *
 */
public class RationalValueAspect {

	private int limit;
	private boolean upLimit;

	public RationalValueAspect(int limit, boolean upLimit) {
		this.limit = limit;
		this.upLimit = upLimit;
	}

	public double getAcotedValue(MethodHandle mh, RationalNumber r) throws Throwable {
		double value = (double) mh.invoke(r);
		boolean control = upLimit ? (value > limit) : (value < limit);
		return control ? limit : value;

	}
}


text:
using Newtonsoft.Json;

namespace RiotWrapper.Static.Champions
{
    public class StaticSkin
    {
        [JsonProperty("num")]
        public int Num { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("id")]
        public int Id { get; set; }
    }
}


text:
class Recording < ActiveRecord::Base

  belongs_to :recordable, polymorphic: true
  validates_presence_of :recordable

end


text:
from django.contrib import admin
from haystack.admin import SearchModelAdmin
from .models import MockModel

class MockModelAdmin(SearchModelAdmin):
    haystack_connection = 'solr'
    date_hierarchy = 'pub_date'
    list_display = ('author', 'pub_date')

admin.site.register(MockModel, MockModelAdmin)


text:
package challenge48

import (
	"github.com/stripedpajamas/cryptopals/set5/challenge39"
	"github.com/stripedpajamas/cryptopals/set6/challenge47"
)

var rsa = challenge39.RSA{}

func init() {
	rsa.Initialize(1024)
}

// Oracle returns true if the decrypted ciphertext has valid padding
// valid meaning pt[0] = 0, pt[1] = 2 (at least for now)
func Oracle(ciphertext []byte) bool {
	challenge47.OracleCalls++
	pt := rsa.Decrypt(ciphertext)
	// append a 0 to account for the translation from numbers into bytes
	pt = append([]byte{0}, pt...)

	return pt[0] == 0 && pt[1] == 2
}


text:
<?php

/**
 * @file
 * Contains Commercie\CurrencyExchange\ExchangeRateInterface;
 */

namespace Commercie\CurrencyExchange;

/**
 * Defines an exchange rate.
 */
interface ExchangeRateInterface
{

    /**
     * Gets the code of the destination currency.
     *
     * @return string
     *   An ISO 4217 code.
     */
    public function getDestinationCurrencyCode();

    /**
     * Sets the code of the destination currency.
     *
     * @param string $currencyCode
     *   An ISO 4217 code.
     *
     * @return $this
     */
    public function setDestinationCurrencyCode($currencyCode);

    /**
     * Gets the code of the source currency.
     *
     * @return string
     *   An ISO 4217 code.
     */
    public function getSourceCurrencyCode();

    /**
     * Sets the code of the source currency.
     *
     * @param string $currencyCode
     *   An ISO 4217 code.
     *
     * @return $this
     */
    public function setSourceCurrencyCode($currencyCode);

    /**
     * Gets the exchange rate.
     *
     * @return string
     */
    public function getRate();

    /**
     * Sets the exchange rate.
     *
     * @param string $rate
     *
     * @return $this
     */
    public function setRate($rate);

    /**
     * Gets the timestamp of the moment this rate was obtained.
     *
     * @return int|null
     *   A Unix timestamp.
     */
    public function getTimestamp();

    /**
     * Sets the timestamp of the moment this rate was obtained.
     *
     * @param int $timestamp
     *   A Unix timestamp.
     *
     * @return $this
     */
    public function setTimestamp($timestamp);

}


text:
require 'tempfile'
require 'yaml'
require 'MrMurano/version'
require 'MrMurano/ProjectFile'
require 'MrMurano/Setting'
require 'MrMurano/SyncRoot'
require 'MrMurano/SyncUpDown'
require '_workspace'

# rubocop:disable Style/ClassAndModuleChildren
#   "Use nested module/class definitions instead of compact style."
module ::MrMurano
  module Testset
    class Settings
      def specific
      end

      def specific=(x)
      end
    end
  end
  module Testsettwo
  end
end

RSpec.describe MrMurano::Setting do
  include_context 'WORKSPACE'
  before(:example) do
    MrMurano::SyncRoot.instance.reset
    $cfg = MrMurano::Config.new
    $cfg.load
    $cfg['net.host'] = 'bizapi.hosted.exosite.io'
    $cfg['product.id'] = 'XYZ'

    @srv = MrMurano::Setting.new
  end

  context 'maps service name' do
    it 'device2 into Gateway' do
      ret = @srv.mapservice('device2')
      expect(ret).to eq('Gateway')
    end

    it 'gaTeWaY into Gateway' do
      ret = @srv.mapservice('gaTeWaY')
      expect(ret).to eq('Gateway')
    end

    it 'WeBServICe into Webservice' do
      ret = @srv.mapservice('WeBServICe')
      expect(ret).to eq('Webservice')
    end

    it 'bob into Bob' do
      ret = @srv.mapservice('bob')
      expect(ret).to eq('Bob')
    end
  end

  context 'read' do
    it "displays error when Service doesn't exist" do
      expect(@srv).to receive(:error).with('No Settings on "Fiddlingsticks"')
      ret = @srv.read('Fiddlingsticks', 'specific')
      expect(ret).to be_nil
    end

    it "displays error when Service doesn't have any Settings" do
      expect(@srv).to receive(:error).with('No Settings on "Testsettwo"')
      ret = @srv.read('Testsettwo', 'specific')
      expect(ret).to be_nil
    end

    it "displays error when Service doesn't have this Setting" do
      expect(@srv).to receive(:error).with("Unknown setting 'flipit' on 'Testset'")
      ret = @srv.read('Testset', 'flipit')
      expect(ret).to be_nil
    end

    it 'the settings' do
      expect_any_instance_of(MrMurano::Testset::Settings).to receive(:specific).and_return(4)
      ret = @srv.read('Testset', 'specific')
      expect(ret).to eq(4)
    end
  end

  context 'writes' do
    it "displays error when Service doesn't exist" do
      expect(@srv).to receive(:error).with('No Settings on "Fiddlingsticks"')
      ret = @srv.write('Fiddlingsticks', 'specific', 4)
      expect(ret).to be_nil
    end

    it "displays error when Service doesn't have any Settings" do
      expect(@srv).to receive(:error).with('No Settings on "Testsettwo"')
      ret = @srv.write('Testsettwo', 'specific', 4)
      expect(ret).to be_nil
    end

    it "displays error when Service doesn't have this Setting" do
      expect(@srv).to receive(:error).with("Unknown setting 'flipit' on 'Testset'")
      ret = @srv.write('Testset', 'flipit', 4)
      expect(ret).to be_nil
    end

    it 'the settings' do
      expect_any_instance_of(MrMurano::Testset::Settings).to receive(:specific=).with(4).and_return(4)
      ret = @srv.write('Testset', 'specific', 4)
      expect(ret).to eq(4)
    end
  end
end


text:
using Crosschat.Server.Domain.Seedwork.Specifications;

namespace Crosschat.Server.Domain.Entities
{
    public static class PublicMessageSpecification
    {
        public static Specification<PublicMessage> Author(User user)
        {
            return new DirectSpecification<PublicMessage>(m => m.Author == user);
        }
    }
}


text:
package aashrai.android.gettowork.di.component;

import aashrai.android.gettowork.di.SettingsScope;
import aashrai.android.gettowork.di.module.SettingsModule;
import aashrai.android.gettowork.view.activity.SettingsActivity;
import dagger.Subcomponent;

@Subcomponent(modules = SettingsModule.class) @SettingsScope public interface SettingsComponent {

  void inject(SettingsActivity settingsActivity);
}


text:
package com.jetbrains.python.formatter;

import com.intellij.application.options.TabbedLanguageCodeStylePanel;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.jetbrains.python.PythonLanguage;

/**
 * @author Rustam Vishnyakov
 */
public class PyCodeStyleMainPanel extends TabbedLanguageCodeStylePanel {
  protected PyCodeStyleMainPanel(CodeStyleSettings currentSettings, CodeStyleSettings settings) {
    super(PythonLanguage.getInstance(), currentSettings, settings);
  }

  @Override
  protected void initTabs(CodeStyleSettings settings) {
    super.initTabs(settings);
    addTab(new PyCodeStylePanel(settings));
  }
}


text:
<?xml version="1.0" encoding="utf-8"?><!--
  ~ Copyright (C) 2015 Actor LLC. <https://actor.im>
  -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <View
        android:id="@+id/background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerInside" />

    <com.droidkit.progress.CircularView
        android:id="@+id/progress"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_centerInParent="true"
        android:visibility="gone" />

    <RelativeLayout
        android:id="@+id/ownerContainer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#40000000">

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="24dp"
            android:layout_marginBottom="24dp"
            android:layout_marginTop="24dp"
            android:layout_toLeftOf="@+id/avatar"
            android:gravity="center_vertical"
            android:text="Name"
            android:textColor="#fff"
            android:textSize="16sp" />

        <im.actor.messenger.app.view.AvatarView
            android:id="@+id/avatar"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_alignParentRight="true"
            android:layout_margin="12dp" />
    </RelativeLayout>
</RelativeLayout>


text:
const { assert } = require('chai')
const sinon = require('sinon')
const walkers = require('../source/walkers.js')
const generators = require('../source/generators.js')
const allocator = require('../source/allocator.js')

describe('walkers', () => {
  beforeEach(() => {
    allocator.reset()
  })

  describe('AssignmentExpression', () => {
    let node
    let state
    let recursiveCall

    beforeEach(() => {
      node = {left: '', right: {type: 'MemberExpression'}}
      state = {}
      recursiveCall = sinon.spy()
    })

    it('walks `left`', () => {
      walkers.AssignmentExpression(node, state, recursiveCall)
      assert.isTrue(recursiveCall.called)
      assert.isTrue(recursiveCall.calledWith(node.left, state, 'Expression'))
    })

    it('walks `right`', () => {
      walkers.AssignmentExpression(node, state, recursiveCall)
      assert.isTrue(recursiveCall.calledTwice)
      assert.isTrue(recursiveCall.calledWith(node.right, state, 'Expression'))
    })

    describe('when `right` is a JSXElement', () => {
      it('walks the JSXElement with initialized state', () => {
        node.right = {type: 'JSXElement'}
        walkers.AssignmentExpression(node, state, recursiveCall)
        assert.isTrue(recursiveCall.calledTwice)
        assert.isTrue(
          recursiveCall.calledWith(
            node.right,
            {name: '$$a', parent: null}
          )
        )
      })
    })
  })

  describe('CallExpression', () => {
    let node
    let state
    let recursiveCall

    beforeEach(() => {
      node = {callee: 'callee'}
      state = {}
      recursiveCall = sinon.spy()
    })

    it('walks `callee`', () => {
      walkers.CallExpression(node, state, recursiveCall)
      assert.isTrue(recursiveCall.called)
      assert.isTrue(recursiveCall.calledWith(node.callee, state, 'Expression'))
    })

    it('walks `arguments`', () => {
      node.arguments = ['argument1']
      walkers.CallExpression(node, state, recursiveCall)
      assert.isTrue(recursiveCall.calledTwice)
      assert.isTrue(recursiveCall.calledWith(node.arguments[0], state, 'Expression'))
    })

    describe('when `arguments` has a JSXElement', () => {
      it('walks the JSXElement with initialized state', () => {
        node.arguments = [{type: 'JSXElement'}]
        walkers.CallExpression(node, state, recursiveCall)

        assert.isTrue(recursiveCall.calledTwice)
        assert.isTrue(
          recursiveCall.calledWith(
            node.arguments[0],
            {name: '$$a', parent: null}
          )
        )
      })
    })
  })

  describe('ConditionalExpression', () => {
    let node
    let state
    let recursiveCall

    beforeEach(() => {
      node = {consequent: 'consequent', alternate: 'alternate'}
      state = {}
      recursiveCall = sinon.spy()
    })

    it('walks `consequent` and `alternate', () => {
      walkers.ConditionalExpression(node, state, recursiveCall)

      assert.isTrue(recursiveCall.calledTwice)
      assert.isTrue(recursiveCall.calledWith(node.consequent, state, 'Expression'))
      assert.isTrue(recursiveCall.calledWith(node.alternate, state, 'Expression'))
    })

    describe('when `consequent` is a JSXElement', () => {
      it('walks `consequent` with initialized state', () => {
        node.consequent = {type: 'JSXElement'}
        walkers.ConditionalExpression(node, state, recursiveCall)
        assert.isTrue(recursiveCall.called)
        assert.isTrue(
          recursiveCall.calledWith(
            node.consequent,
            {name: '$$a', parent: null}
          )
        )
      })
    })

    describe('when `consequent` is a JSXElement', () => {
      it('walks `consequent` with initialized state', () => {
        node.alternate = {type: 'JSXElement'}
        walkers.ConditionalExpression(node, state, recursiveCall)
        assert.isTrue(recursiveCall.called)
        assert.isTrue(
          recursiveCall.calledWith(
            node.alternate,
            {name: '$$a', parent: null}
          )
        )
      })
    })
  })

  describe('LogicalExpression', () => {
    let node
    let state
    let recursiveCall

    beforeEach(() => {
      node = {left: 'left', right: 'right'}
      state = {}
      recursiveCall = sinon.spy()
    })

    it('walks `left` and `right`', () => {
      walkers.LogicalExpression(node, state, recursiveCall)
      assert.isTrue(recursiveCall.calledTwice)
      assert.isTrue(
        recursiveCall.calledWith(
          'left',
          state,
          'Expression'
        )
      )
      assert.isTrue(
        recursiveCall.calledWith(
          'right',
          state,
          'Expression'
        )
      )
    })

    describe('when `left` is a JSXElement', () => {
      it('walks `left` with initialized state', () => {
        node.left = {type: 'JSXElement'}
        walkers.LogicalExpression(node, state, recursiveCall)
        assert.isTrue(recursiveCall.called)
        assert.isTrue(
          recursiveCall.calledWith(
            node.left,
            {name: '$$a', parent: null}
          )
        )
      })
    })

    describe('when `right` is a JSXElement', () => {
      it('walks `right` with initialized state', () => {
        node.right = {type: 'JSXElement'}
        walkers.LogicalExpression(node, state, recursiveCall)
        assert.isTrue(recursiveCall.called)
        assert.isTrue(
          recursiveCall.calledWith(
            node.right,
            {name: '$$a', parent: null}
          )
        )
      })
    })
  })

  describe('ReturnStatement', () => {
    let node
    let state
    let recursiveCall

    beforeEach(() => {
      node = {}
      state = {}
      recursiveCall = sinon.spy()
    })

    it('walks `argument`', () => {
      node.argument = {}
      walkers.ReturnStatement(node, state, recursiveCall)
      assert.isTrue(recursiveCall.called)
      assert.isTrue(recursiveCall.calledWith(node.argument, state, 'Expression'))
    })

    describe('when `argument` is a JSXElement', () => {
      it('walks `argument` with initialized state', () => {
        node.argument = {type: 'JSXElement'}
        walkers.ReturnStatement(node, state, recursiveCall)
        assert.isTrue(recursiveCall.called)
        assert.isTrue(
          recursiveCall.calledWith(
            node.argument,
            {name: '$$a', parent: null}
          )
        )
      })
    })
  })

  describe('VariableDeclarator', () => {
    let node
    let state
    let recursiveCall

    beforeEach(() => {
      node = {id: 'id'}
      state = {}
      recursiveCall = sinon.spy()
    })

    it('walks `id`', () => {
      walkers.VariableDeclarator(node, state, recursiveCall)
      assert.isTrue(recursiveCall.called)
      assert.isTrue(recursiveCall.calledWith(node.id, state, 'Pattern'))
    })

    it('walks `init`', () => {
      node.init = 'init'
      walkers.VariableDeclarator(node, state, recursiveCall)
      assert.isTrue(recursiveCall.calledTwice)
      assert.isTrue(recursiveCall.calledWith(node.init, state, 'Expression'))
    })

    describe('when `init` is a JSXElement', () => {
      it('walks `init` with initialized state', () => {
        node.init = {type: 'JSXElement'}
        walkers.VariableDeclarator(node, state, recursiveCall)
        assert.isTrue(recursiveCall.calledTwice)
        assert.isTrue(
          recursiveCall.calledWith(
            node.init,
            {name: '$$a', parent: null}
          )
        )
      })
    })
  })

  describe('ArrowFunctionExpression', () => {
    let node
    let state
    let recursiveCall

    beforeEach(() => {
      node = {id: 'id'}
      state = {}
      recursiveCall = sinon.spy()
    })

    it('walks `id`', () => {
      walkers.ArrowFunctionExpression(node, state, recursiveCall)
      assert.isTrue(recursiveCall.called)
      assert.isTrue(recursiveCall.calledWith(node.id, state, 'Pattern'))
    })

    it('walks `body`', () => {
      node.body = 'body'
      walkers.ArrowFunctionExpression(node, state, recursiveCall)
      assert.isTrue(recursiveCall.calledTwice)
      assert.isTrue(recursiveCall.calledWith(node.body, state, 'Expression'))
    })

    describe('when `body` is a JSXElement', () => {
      it('walks `body` with initialized state', () => {
        node.body = {type: 'JSXElement'}
        walkers.ArrowFunctionExpression(node, state, recursiveCall)
        assert.isTrue(recursiveCall.calledTwice)
        assert.isTrue(
          recursiveCall.calledWith(
            node.body,
            {name: '$$a', parent: null}
          )
        )
      })
    })
  })

  describe('AssignmentPattern', () => {
    let node
    let state
    let recursiveCall

    beforeEach(() => {
      node = {left: 'left'}
      state = {}
      recursiveCall = sinon.spy()
    })

    it('walks `left`', () => {
      walkers.AssignmentPattern(node, state, recursiveCall)
      assert.isTrue(recursiveCall.called)
      assert.isTrue(recursiveCall.calledWith(node.left, state, 'Pattern'))
    })

    it('walks `right`', () => {
      node.right = 'right'
      walkers.AssignmentPattern(node, state, recursiveCall)
      assert.isTrue(recursiveCall.calledTwice)
      assert.isTrue(recursiveCall.calledWith(node.right, state, 'Pattern'))
    })

    describe('when `right` is a JSXElement', () => {
      it('walks `right` with initialized state', () => {
        node.right = {type: 'JSXElement'}
        walkers.AssignmentExpression(node, state, recursiveCall)
        assert.isTrue(recursiveCall.calledTwice)
        assert.isTrue(
          recursiveCall.calledWith(
            node.right,
            {name: '$$a', parent: null}
          )
        )
      })
    })
  })

  describe('Property', () => {
    let node
    let state
    let recursiveCall

    beforeEach(() => {
      node = {key: 'key'}
      state = {}
      recursiveCall = sinon.spy()
    })

    it('walks when `key` is a subscripts', () => {
      node.computed = true
      walkers.Property(node, state, recursiveCall)
      assert.isTrue(recursiveCall.called)
      assert.isTrue(recursiveCall.calledWith(node.key, state, 'Expression'))
    })

    it('walks `value`', () => {
      node.value = 'value'
      walkers.Property(node, state, recursiveCall)
      assert.isTrue(recursiveCall.called)
      assert.isTrue(recursiveCall.calledWith(node.value, state, 'Expression'))
    })

    describe('when `value` is a JSXElement', () => {
      it('walks `value` with initialized state', () => {
        node.value = {type: 'JSXElement'}
        walkers.Property(node, state, recursiveCall)
        assert.isTrue(recursiveCall.called)
        assert.isTrue(
          recursiveCall.calledWith(
            node.value,
            {name: '$$a', parent: null}
          )
        )
      })
    })
  })

  describe('JSXElement', () => {
    let node
    let state
    let recursiveCall

    beforeEach(() => {
      node = {openingElement: {attributes: []}, children: []}
      state = {name: 'name'}
      recursiveCall = sinon.spy()
    })

    it('walks `attributes`', () => {
      node.openingElement.attributes = ['attribute1', 'attribute2']
      walkers.JSXElement(node, state, recursiveCall)

      assert.isTrue(recursiveCall.calledTwice)
      assert.isTrue(
        recursiveCall.calledWith(
          node.openingElement.attributes[0],
          state
        )
      )
      assert.isTrue(
        recursiveCall.calledWith(
          node.openingElement.attributes[1],
          state
        )
      )
    })

    describe('walks `children`', () => {
      describe('child is a JSXElement or JSXExpressionContainer', () => {
        it('walks child with initialized state', () => {
          node.children = [{type: 'JSXElement'}, {type: 'JSXExpressionContainer'}]
          walkers.JSXElement(node, state, recursiveCall)

          assert.isTrue(recursiveCall.calledTwice)
          assert.isTrue(
            recursiveCall.calledWith(
              node.children[0],
              {name: '$$a', parent: 'name'}
            )
          )

          assert.isTrue(
            recursiveCall.calledWith(
              node.children[1],
              {name: '$$b', parent: 'name'}
            )
          )
        })
      })

      describe('child is a Literal', () => {
        describe('value is **only** a newline with/without whitespace', () => {
          it('does not walk the child', () => {
            node.children = [generators.literal('\n   ')]
            walkers.JSXElement(node, state, recursiveCall)
            assert.isFalse(recursiveCall.called)
          })
        })

        describe('value is anything else', () => {
          it('walks child with initialized state', () => {
            node.children = [generators.literal('hello, world')]
            walkers.JSXElement(node, state, recursiveCall)
            assert.isTrue(recursiveCall.called)
            assert.isTrue(
              recursiveCall.calledWith(
                node.children[0],
                {name: '$$a', parent: 'name'}
              )
            )
          })
        })
      })

      describe('child is anything else', () => {
        it('walks child', () => {
          node.children = [{type: 'nonsense'}]
          walkers.JSXElement(node, state, recursiveCall)
          assert.isTrue(recursiveCall.called)
          assert.isTrue(
            recursiveCall.calledWith(
              node.children[0],
              state
            )
          )
        })
      })
    })
  })

  describe('JSXExpressionContainer', () => {
    it('walks `expression`', () => {
      const node = {expression: 'expression'}
      const state = {}
      const recursiveCall = sinon.spy()

      walkers.JSXExpressionContainer(node, state, recursiveCall)
      assert.isTrue(recursiveCall.called)
      assert.isTrue(
        recursiveCall.calledWith(
          node.expression,
          state
        )
      )
    })
  })
})


text:
<!--
@license
Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

<link rel="import" href="polymer/polymer.html">

<style is="custom-style">

  :root {
    --tb-orange-weak: #ffa726;
    --tb-orange-strong: #f57c00;
    --tb-grey-darker: #e2e2e2;
    --tb-grey-lighter: #f3f3f3;
    --tb-ui-dark-accent: #757575;
    --tb-ui-light-accent: #e0e0e0;
    --tb-graph-faded: #e0d4b3;
  }

</style>


text:
import focusSource from './focus-source';
import focusWithin from './focus-within';
export default {
  focusSource,
  focusWithin,
};


text:
package com.wincom.mstar.domain;

import java.util.Date;

public class BUserLog {
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column nfjd502.dbo.BUserLog.UserID
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    private Integer userid;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column nfjd502.dbo.BUserLog.LoginTime
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    private Date logintime;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column nfjd502.dbo.BUserLog.LogoutTime
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    private Date logouttime;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column nfjd502.dbo.BUserLog.DutyLog
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    private String dutylog;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column nfjd502.dbo.BUserLog.UserID
     *
     * @return the value of nfjd502.dbo.BUserLog.UserID
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public Integer getUserid() {
        return userid;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column nfjd502.dbo.BUserLog.UserID
     *
     * @param userid the value for nfjd502.dbo.BUserLog.UserID
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column nfjd502.dbo.BUserLog.LoginTime
     *
     * @return the value of nfjd502.dbo.BUserLog.LoginTime
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public Date getLogintime() {
        return logintime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column nfjd502.dbo.BUserLog.LoginTime
     *
     * @param logintime the value for nfjd502.dbo.BUserLog.LoginTime
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public void setLogintime(Date logintime) {
        this.logintime = logintime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column nfjd502.dbo.BUserLog.LogoutTime
     *
     * @return the value of nfjd502.dbo.BUserLog.LogoutTime
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public Date getLogouttime() {
        return logouttime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column nfjd502.dbo.BUserLog.LogoutTime
     *
     * @param logouttime the value for nfjd502.dbo.BUserLog.LogoutTime
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public void setLogouttime(Date logouttime) {
        this.logouttime = logouttime;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column nfjd502.dbo.BUserLog.DutyLog
     *
     * @return the value of nfjd502.dbo.BUserLog.DutyLog
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public String getDutylog() {
        return dutylog;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column nfjd502.dbo.BUserLog.DutyLog
     *
     * @param dutylog the value for nfjd502.dbo.BUserLog.DutyLog
     *
     * @mbggenerated Thu Mar 02 11:23:21 CST 2017
     */
    public void setDutylog(String dutylog) {
        this.dutylog = dutylog == null ? null : dutylog.trim();
    }
}