text:
package cn.com.oceancode.service;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import com.sun.jersey.spi.resource.Singleton;

import cn.com.oceancode.utils.LogUtils;
import cn.com.oceancode.utils.SqlInjectUtils;

@Singleton
@Component
@Path("/admin")
public class AdminService extends OCService {

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(AdminService.class);

	static final String SERVICE_NAME = "admin";

	public static Map<String, Object> init_index(HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("init_index(HttpServletRequest) - start"); //$NON-NLS-1$
		}

		Map<String, Object> root = new HashMap<String, Object>();
		try {
			Map<String, Object> user = initMe(request);
			root.put("user", user);
			// root.put("nav", nav);
		} catch (Exception e) {
			logger.error("init_index(HttpServletRequest)", e); //$NON-NLS-1$

			if (logger.isDebugEnabled()) {
				logger.debug("init_index(HttpServletRequest) - end"); //$NON-NLS-1$
			}
			return root;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("init_index(HttpServletRequest) - end"); //$NON-NLS-1$
		}
		return root;
	}

	public static Map<String, Object> init_cache(HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("init_cache(HttpServletRequest) - start"); //$NON-NLS-1$
		}

		Map<String, Object> root = new HashMap<String, Object>();
		try {
			Map<String, Object> user = initMe(request);
			root.put("user", user);
			// root.put("nav", nav);
		} catch (Exception e) {
			logger.error("init_cache(HttpServletRequest)", e); //$NON-NLS-1$

			if (logger.isDebugEnabled()) {
				logger.debug("init_cache(HttpServletRequest) - end"); //$NON-NLS-1$
			}
			return root;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("init_cache(HttpServletRequest) - end"); //$NON-NLS-1$
		}
		return root;
	}

	public static Map<String, Object> init_code(HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("init_code(HttpServletRequest) - start"); //$NON-NLS-1$
		}

		Map<String, Object> root = new HashMap<String, Object>();
		try {
			Map<String, Object> user = initMe(request);
			root.put("user", user);
			// root.put("nav", nav);
		} catch (Exception e) {
			logger.error("init_code(HttpServletRequest)", e); //$NON-NLS-1$

			if (logger.isDebugEnabled()) {
				logger.debug("init_code(HttpServletRequest) - end"); //$NON-NLS-1$
			}
			return root;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("init_code(HttpServletRequest) - end"); //$NON-NLS-1$
		}
		return root;
	}

	public static Map<String, Object> init_menu(HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("init_menu(HttpServletRequest) - start"); //$NON-NLS-1$
		}
		Map<String, Object> root = new HashMap<String, Object>();
		try {
			NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(jdbcTemplate);
			Map<String, Object> args = new HashMap<String, Object>();
			List<Map<String, Object>> queryForList = template.queryForList("select * from t_menu where status = '1'",
					args);
			// for (Map<String, Object> map : queryForList) {
			// String string = map.get("cjsj").toString();
			// map.put("cjsj", sjFormate19(string));
			// }
			root.put("list", queryForList);
			Map<String, Object> user = initMe(request);
			root.put("user", user);
			// root.put("nav", nav);
		} catch (Exception e) {
			logger.error("init_menu(HttpServletRequest)", e); //$NON-NLS-1$

			if (logger.isDebugEnabled()) {
				logger.debug("init_menu(HttpServletRequest) - end"); //$NON-NLS-1$
			}
			return root;
		}

		if (logger.isDebugEnabled()) {
			logger.debug("init_menu(HttpServletRequest) - end"); //$NON-NLS-1$
		}
		return root;
	}

	public static Map<String, Object> init_menu_add(HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("init_menu_add(HttpServletRequest) - start"); //$NON-NLS-1$
		}

		Map<String, Object> root = new HashMap<String, Object>();
		root.put("id", "");
		root.put("text", "");
		root.put("pid", "");
		root.put("nav", "");
		root.put("note", "");
		root.put("url", "");
		String id = request.getParameter("id");
		if (id != null && !id.equals("")) {
			NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(jdbcTemplate);
			Map<String, Object> args = new HashMap<String, Object>();
			args.put("id", new Integer(id));
			List<Map<String, Object>> queryForList = template
					.queryForList("select * from t_menu where id = :id and status = '1'", args);
			if (queryForList.size() > 0) {
				Map<String, Object> obj = queryForList.get(0);
				root.put("id", obj.get("id"));
				root.put("text", obj.get("text"));
				if ("1".equals(request.getParameter("d"))) {//非复制
					root.put("id", "");
					root.put("text", obj.get("text")+"_复制");
				}
				root.put("pid", obj.get("pid"));
				root.put("nav", obj.get("nav"));
				root.put("note", obj.get("note"));
				root.put("url", obj.get("url"));
			}
		}

		if (logger.isDebugEnabled()) {
			logger.debug("init_menu_add(HttpServletRequest) - end"); //$NON-NLS-1$
		}
		return root;
	}

	@POST
	@Path("delMenu")
	public String delMenu(@FormParam("id") String id, @Context HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("delMenu(String, HttpServletRequest) - start " + id); //$NON-NLS-1$
		}

		String msg = "";
		long logId = LogUtils.getLogId();
		String startTime = LogUtils.getNowTime();
		NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(jdbcTemplate);
		try {
			Map<String, Object> args = new HashMap<String, Object>();
			String sql = "update t_menu set status = '0' where id in (" + SqlInjectUtils.cleanSQLInject(id) + ")";
			int i = template.update(sql, args);
			LogUtils.writeLogDetail(logId, "删除菜单", "", "", "", "", LogUtils.getNowTime(), args.toString());
			LogUtils.writeLogS(logId, SERVICE_NAME, Thread.currentThread().getStackTrace()[1].getMethodName(),
					startTime, LogUtils.getNowTime(), msg, LogUtils.getUserId(request));
			String returnString = "alert('删除" + i + "条数据');load('admin.menu.html');";
			if (logger.isDebugEnabled()) {
				logger.debug("delMenu(String, HttpServletRequest) - end"); //$NON-NLS-1$
			}
			return returnString;
		} catch (Exception e) {
			logger.error("delMenu(String, HttpServletRequest)", e); //$NON-NLS-1$

			LogUtils.writeLogE(logId, SERVICE_NAME, Thread.currentThread().getStackTrace()[1].getMethodName(),
					startTime, LogUtils.getNowTime(), e.getMessage(), LogUtils.getStackTrace(e),
					LogUtils.getUserId(request));

			if (logger.isDebugEnabled()) {
				logger.debug("delMenu(String, HttpServletRequest) - end"); //$NON-NLS-1$
			}
			return "alert('操作失败');cancelLoading();";
		}
	}

	@POST
	@Path("addMenu")
	public String addMenu(@FormParam("menuText") String menuText, @FormParam("menuNav") String menuNav,
			@FormParam("menuNote") String menuNote, @FormParam("menuUrl") String menuUrl,
			@FormParam("menuPid") String menuPid, @Context HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("addMenu(String, String, String, String, HttpServletRequest) - start"); //$NON-NLS-1$
		}

		String msg = "";
		long logId = LogUtils.getLogId();
		String startTime = LogUtils.getNowTime();
		NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(jdbcTemplate);
		try {
			Map<String, Object> args = new HashMap<String, Object>();
			args.put("menuText", menuText);
			args.put("menuNav", menuNav);
			args.put("menuNote", menuNote);
			args.put("menuUrl", menuUrl);
			args.put("menuPid", menuPid.replaceAll(",", ""));
			String sql = "insert into t_menu(text,nav,note,url,pid) values (:menuText, :menuNav, :menuNote, :menuUrl, :menuPid)";
			int i = template.update(sql, args);
			if (i == 1) {
				LogUtils.writeLogDetail(logId, "添加菜单", "", "", "", "", LogUtils.getNowTime(), args.toString());
				LogUtils.writeLogS(logId, SERVICE_NAME, Thread.currentThread().getStackTrace()[1].getMethodName(),
						startTime, LogUtils.getNowTime(), msg, LogUtils.getUserId(request));
				String returnString = "alert('操作成功');load('admin.menu.html');";

				if (logger.isDebugEnabled()) {
					logger.debug("addMenu(String, String, String, String, HttpServletRequest) - end"); //$NON-NLS-1$
				}
				return returnString;
			} else {
				throw new Exception("添加数据条数为" + i);
			}
		} catch (Exception e) {
			logger.error("addMenu(String, String, String, String, HttpServletRequest)", e); //$NON-NLS-1$

			LogUtils.writeLogE(logId, SERVICE_NAME, Thread.currentThread().getStackTrace()[1].getMethodName(),
					startTime, LogUtils.getNowTime(), e.getMessage(), LogUtils.getStackTrace(e),
					LogUtils.getUserId(request));

			if (logger.isDebugEnabled()) {
				logger.debug("addMenu(String, String, String, String, HttpServletRequest) - end"); //$NON-NLS-1$
			}
			return "alert('操作失败, " + URLEncoder.encode(e.getMessage()) + "');cancelLoading();";
		}
	}

	@POST
	@Path("saveMenu")
	public String addMenu(@FormParam("menuId") String menuId, @FormParam("menuText") String menuText,
			@FormParam("menuNav") String menuNav, @FormParam("menuNote") String menuNote,
			@FormParam("menuUrl") String menuUrl, @FormParam("menuPid") String menuPid,
			@Context HttpServletRequest request) {
		if (logger.isDebugEnabled()) {
			logger.debug("addMenu(String, String, String, String, String, String, HttpServletRequest) - start"); //$NON-NLS-1$
		}

		String msg = "";
		long logId = LogUtils.getLogId();
		String startTime = LogUtils.getNowTime();
		NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(jdbcTemplate);
		try {
			Map<String, Object> args = new HashMap<String, Object>();
			args.put("id", new Integer(menuId));
			args.put("text", menuText);
			args.put("nav", menuNav);
			args.put("note", menuNote);
			args.put("url", menuUrl);
			args.put("pid", new Integer(menuPid.replaceAll(",", "")));
			String sql = "update t_menu set text=:text,nav=:nav,note=note,url=:url,pid=:pid where id=:id";
			int i = template.update(sql, args);
			if (i == 1) {
				LogUtils.writeLogDetail(logId, "修改菜单", "", "", "", "", LogUtils.getNowTime(), args.toString());
				LogUtils.writeLogS(logId, SERVICE_NAME, Thread.currentThread().getStackTrace()[1].getMethodName(),
						startTime, LogUtils.getNowTime(), msg, LogUtils.getUserId(request));
				String returnString = "alert('操作成功');load('admin.menu.html');";

				if (logger.isDebugEnabled()) {
					logger.debug("addMenu(String, String, String, String, String, String, HttpServletRequest) - end"); //$NON-NLS-1$
				}
				return returnString;
			} else {
				throw new Exception("保存数据条数为" + i);
			}
		} catch (Exception e) {
			logger.error("addMenu(String, String, String, String, String, String, HttpServletRequest)", e); //$NON-NLS-1$

			LogUtils.writeLogE(logId, SERVICE_NAME, Thread.currentThread().getStackTrace()[1].getMethodName(),
					startTime, LogUtils.getNowTime(), e.getMessage(), LogUtils.getStackTrace(e),
					LogUtils.getUserId(request));

			String returnString = "alert('操作失败, " + URLEncoder.encode(e.getMessage()) + "');cancelLoading();";
			if (logger.isDebugEnabled()) {
				logger.debug("addMenu(String, String, String, String, String, String, HttpServletRequest) - end"); //$NON-NLS-1$
			}
			return returnString;
		}
	}

}


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

/*============================================================================
**
** Source:  test2.c
**
** Purpose: Calls fgets to read a full line from a file.  A maximum length
**          parameter greater than the length of the line is passed.
**
**
**==========================================================================*/

#include <palsuite.h>

int __cdecl main(int argc, char **argv)
{
    const char outBuf1[] = "This is a test.\n";
    const char outBuf2[] = "This is too.";

    char inBuf[sizeof(outBuf1) + sizeof(outBuf2)];
    const char filename[] = "testfile.tmp";
    const int offset = 5;  /*value chosen arbitrarily*/
    int expectedLen;
    int actualLen;

    FILE * fp;

    if (PAL_Initialize(argc, argv))
    {
        return FAIL;
    }

    /*write the file that we will use to test */
    fp = fopen(filename, "w");
    if (fp == NULL)
    {
        Fail("Unable to open file for write.\n");
    }

    fwrite(outBuf1, sizeof(outBuf1[0]), sizeof(outBuf1), fp);
    fwrite(outBuf2, sizeof(outBuf2[0]), sizeof(outBuf2), fp);

    if (fclose(fp) != 0)
    {
        Fail("error closing stream opened for write.\n");
    }

    /*Read until the first linebreak*/
    fp = fopen(filename, "r");
    if (fp == NULL)
    {
        Fail("Unable to open file for read.\n");
    }

    if (fgets(inBuf, sizeof(outBuf1) + offset , fp) != inBuf)
    {
        Fail("Error reading from file using fgets.\n");
    }

    /*note: -1 because strlen returns the length of a string _not_
      including the NULL, while fgets returns a string of specified
      maximum length _including_ the NULL.*/
    expectedLen = strlen(outBuf1);
    actualLen = strlen(inBuf);
    if (actualLen > expectedLen)
    {
        Fail("fgets() was asked to read the first line of a file, but did "
             "not stop at the end of the line.\n");
    }
    else if (actualLen < expectedLen)
    {
        Fail("fgets() was asked to read the first line of a file, but did "
             "not read the entire line.\n");
    }
    else if (memcmp(inBuf, outBuf1, actualLen) != 0)
    {
        /*We didn't read back exactly outBuf1*/
        Fail("fgets() was asked to read the first line of a file.  It "
             "has read back a string of the correct length, but the"
             " contents are not correct.\n");
    }

    if (fclose(fp) != 0)
    {
        Fail("Error closing file after using fgets().\n");
    }

    PAL_Terminate();
    return PASS;

}

redpajama_set_name: RedPajamaGithub


text:
package com.jjoe64.graphview_demos.categories;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview_demos.FullscreenExample;
import com.jjoe64.graphview_demos.ItemDetailFragment;
import com.jjoe64.graphview_demos.R;
import com.jjoe64.graphview_demos.examples.AdvancedBarGraph;
import com.jjoe64.graphview_demos.examples.MultipleBarGraph;
import com.jjoe64.graphview_demos.examples.SimpleBarGraph;
import com.jjoe64.graphview_demos.examples.SimplePointsGraph;

/**
 * Created by jonas on 07.09.16.
 */
public class PointsGraphFragment extends ItemDetailFragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.points_graph_content, container, false);

        GraphView graph = (GraphView) rootView.findViewById(R.id.graph);
        new SimplePointsGraph().initGraph(graph);
        rootView.findViewById(R.id.cardSimplePointsGraph).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openFullscreen(FullscreenExample.SIMPLE_POINTS_GRAPH);
            }
        });
        rootView.findViewById(R.id.imgFullscreen).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openFullscreen(FullscreenExample.SIMPLE_POINTS_GRAPH);
            }
        });
        rootView.findViewById(R.id.imgSource).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openSource(FullscreenExample.SIMPLE_POINTS_GRAPH);
            }
        });

        return rootView;
    }
}


text:
package me.ztiany.android.database.origin;

import android.database.sqlite.SQLiteDatabase;

import me.ztiany.android.database.App;

public class DatabaseManager {

    private int mOpenCounter = 0;
    private volatile static DatabaseManager instance;
    private static DBHelper mDatabaseHelper;
    private SQLiteDatabase mDatabase;

    private DatabaseManager() {
        mDatabaseHelper = new DBHelper(App.getApp());
    }

    public static DatabaseManager getInstance() {
        if (instance == null) {
            synchronized (DatabaseManager.class) {
                if (instance == null) {
                    instance = new DatabaseManager();
                }
            }
        }
        return instance;
    }

    public synchronized SQLiteDatabase openDatabase() {
        if (mOpenCounter == 0) {
            // Opening new database
            mDatabase = mDatabaseHelper.getWritableDatabase();
        }
        mOpenCounter++;//引用加1
        return mDatabase;
    }

    public synchronized void closeDatabase() {
        mOpenCounter--;
        if (mOpenCounter == 0) {
            // Closing database
            mDatabase.close();
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Threading;
using FluentAssertions;

namespace Light.DependencyInjection.Tests
{
    public class ClassWithoutDependencies : IAbstractionA { }

    public class ClassWithDependency
    {
        public readonly ClassWithoutDependencies A;

        public ClassWithDependency(ClassWithoutDependencies a)
        {
            A = a;
        }
    }

    public class ClassWithTwoDependencies
    {
        public readonly ClassWithoutDependencies A;
        public readonly ClassWithDependency B;

        public ClassWithTwoDependencies(ClassWithoutDependencies a, ClassWithDependency b)
        {
            A = a;
            B = b;
        }
    }

    public interface IAbstractionA { }

    public class DisposableSpy : IDisposable
    {
        private int _disposeCallCount;

        public int DisposeCallCount => _disposeCallCount;

        public void Dispose()
        {
            _disposeCallCount++;
        }

        public void DisposeMustHaveBeenCalledExactlyOnce()
        {
            _disposeCallCount.Should().Be(1);
        }
    }

    public class ServiceLocatorClient
    {
        public readonly DependencyInjectionContainer Container;

        public ServiceLocatorClient(DependencyInjectionContainer container)
        {
            Container = container;
        }
    }

    public class ClassWithProperty : IEmptyInterface
    {
        public ClassWithoutDependencies InstanceWithoutDependencies { get; set; }
    }

    public interface IEmptyInterface { }

    public class ClassWithPropertyInjectionDependency
    {
        public readonly IEmptyInterface InstanceWithProperty;

        public ClassWithPropertyInjectionDependency(IEmptyInterface instanceWithProperty)
        {
            InstanceWithProperty = instanceWithProperty;
        }
    }

    public class ClassWithPublicField
    {
        public bool PublicField;
    }

    public class ThreadSaveClass
    {
        private static int _numberOfInstancesCreated;

        public ThreadSaveClass()
        {
            Interlocked.Increment(ref _numberOfInstancesCreated);
        }

        public static int NumberOfInstancesCreated => _numberOfInstancesCreated;
    }

    public class GenericClassWithGenericProperty<T>
    {
        public T Property { get; set; }
    }

    public class GenericClassWithGenericField<T>
    {
        public T Field;
    }

    public class Implementation1 : IAbstractionA { }

    public class Implementation2 : IAbstractionA { }

    public class Implementation3 : IAbstractionA { }

    public class ClassWithCollectionDependency
    {
        public readonly IReadOnlyList<IAbstractionA> Instances;

        public ClassWithCollectionDependency(IReadOnlyList<IAbstractionA> instances)
        {
            Instances = instances;
        }
    }

    public class ClassWithCollectionDependencyOnProperty
    {
        public List<IAbstractionA> Instances { get; set; }
    }

    public class ClassWithCollectionDependencyOnField
    {
        public IEnumerable<IAbstractionA> Instances;
    }
}


text:
package de.matthiasmann.twl.model;

import de.matthiasmann.twl.EditField;

/**
 * An abstract container for auto completion results.
 *
 * @author Matthias Mann
 */
public abstract class AutoCompletionResult {

    /**
     * Return value for {@link #getCursorPosForResult} to use EditField's
     * default cursor position for {@link EditField#setText(java.lang.String)}
     */
    public static final int DEFAULT_CURSOR_POS = -1;

    protected final String text;
    protected final int prefixLength;

    public AutoCompletionResult(String text, int prefixLength) {
        this.text = text;
        this.prefixLength = prefixLength;
    }

    /**
     * The prefix length is the length of prefix which was used to collect the data.
     * The remaining part of the text is used for high lighting the results.
     * This is used for things like tree completion.
     *
     * @return the prefix length
     */
    public int getPrefixLength() {
        return prefixLength;
    }

    /**
     * Returns the text which was used for this auto completion
     * @return the text which was used for this auto completion
     */
    public String getText() {
        return text;
    }

    /**
     * Returns the number of results
     * @return the number of results
     */
    public abstract int getNumResults();

    /**
     * Returns a selected result entry
     * @param idx the index of the desired result entry
     * @return the result entry
     * @see #getNumResults()
     */
    public abstract String getResult(int idx);

    /**
     * Returns the desired cursor position for the given result entry.
     *
     * The default implementation returns {@link #DEFAULT_CURSOR_POS}
     *
     * @param idx the index of the desired result entry
     * @return the cursor position
     * @see #getNumResults()
     * @see #getResult(int)
     * @see #DEFAULT_CURSOR_POS
     */
    public int getCursorPosForResult(int idx) {
        return DEFAULT_CURSOR_POS;
    }

    /**
     * Tries to refine the results. Refining can result in a different order
     * of results then a new query but is faster.
     *
     * If refining resulted in no results then an empty AutoCompletionResult
     * is returned.
     *
     * @param text The new text
     * @param cursorPos The new cursor position
     * @return the new refined AutoCompletionResult or null if refining was not possible
     */
    public AutoCompletionResult refine(String text, int cursorPos) {
        return null;
    }
}


text:
from typing import Any, Generic, TypeVar

T = TypeVar("T")

class Context(Generic[T]):
    body: T

    def __init__(self, body: T, **kwargs: Any) -> None:
        self.body = body
        self.metadata = kwargs.copy()

    def add_metadata(self, **kwargs: Any) -> None:
        self.metadata.update(kwargs)


text:
//
//  NSMutableDictionary+Store.h
//  SmartDeviceLink-iOS
//
//  Created by Muller, Alexander (A.) on 11/7/16.
//  Copyright © 2016 smartdevicelink. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "SDLLogMacros.h"

NS_ASSUME_NONNULL_BEGIN

typedef NSString* SDLRPCParameterName NS_TYPED_ENUM;
typedef NSString* SDLEnum NS_TYPED_ENUM;

@interface NSDictionary (Store)

- (void)sdl_setObject:(nullable NSObject *)object forName:(SDLRPCParameterName)name;

- (nullable SDLEnum)sdl_enumForName:(SDLRPCParameterName)name error:(NSError * _Nullable *)error;
- (nullable NSArray<SDLEnum> *)sdl_enumsForName:(SDLRPCParameterName)name error:(NSError * _Nullable *)error;

/**
 *  @param classType expected class of returned object
 *  @param error if stored value isn't classType
 *  @return object of classType or nil
*/
- (nullable id)sdl_objectForName:(SDLRPCParameterName)name ofClass:(Class)classType error:(NSError * _Nullable *)error;

/**
 *  @param classType expected class of array objects
 *  @param error if array objects value isn't classType or stored objects aren't array
 *  @return return array of classType or nil
*/
- (nullable NSArray *)sdl_objectsForName:(SDLRPCParameterName)name ofClass:(Class)classType error:(NSError * _Nullable *)error;

@end

NS_ASSUME_NONNULL_END


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.lorislab.tower</groupId>
		<artifactId>tower-base</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath>../</relativePath>
	</parent>

	<name>tower-base-api</name>
	<artifactId>tower-base-api</artifactId>
	<packaging>jar</packaging>

</project>


text:
"""
Sets up the terminal color scheme.
"""

from django.core.management import color
from django.utils import termcolors

def color_style():
    style = color.color_style()
    if color.supports_color():
        style.INFO = termcolors.make_style(fg='green')
        style.WARN = termcolors.make_style(fg='yellow')
        style.BOLD = termcolors.make_style(opts=('bold',))
        style.URL = termcolors.make_style(fg='green', opts=('bold',))
        style.MODULE = termcolors.make_style(fg='yellow')
        style.MODULE_NAME = termcolors.make_style(opts=('bold',))
        style.URL_NAME = termcolors.make_style(fg='red')
    return style


text:
int recv_sideband(const char *me, int in_stream, int out);
void send_sideband(int fd, int band, const char *data, ssize_t sz, int packet_max);

#endif


text:
 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         ndnboost/regex/config/borland.hpp
  *   VERSION      see <ndnboost/version.hpp>
  *   DESCRIPTION: regex borland-specific config setup.
  */

#if defined(__BORLANDC__)
#  if (__BORLANDC__ == 0x550) || (__BORLANDC__ == 0x551)
      // problems with std::basic_string and dll RTL:
#     if defined(_RTLDLL) && defined(_RWSTD_COMPILE_INSTANTIATE)
#        ifdef NDNBOOST_REGEX_BUILD_DLL
#           error _RWSTD_COMPILE_INSTANTIATE must not be defined when building regex++ as a DLL
#        else
#           pragma message("Defining _RWSTD_COMPILE_INSTANTIATE when linking to the DLL version of the RTL may produce memory corruption problems in std::basic_string, as a result of separate versions of basic_string's static data in the RTL and you're exe/dll: be warned!!")
#        endif
#     endif
#     ifndef _RTLDLL
         // this is harmless for a staic link:
#        define _RWSTD_COMPILE_INSTANTIATE
#     endif
      // external templates cause problems for some reason:
#     define NDNBOOST_REGEX_NO_EXTERNAL_TEMPLATES
#  endif
#  if (__BORLANDC__ <= 0x540) && !defined(NDNBOOST_REGEX_NO_LIB) && !defined(_NO_VCL)
      // C++ Builder 4 and earlier, we can't tell whether we should be using
      // the VCL runtime or not, do a static link instead:
#     define NDNBOOST_REGEX_STATIC_LINK
#  endif
   //
   // VCL support:
   // if we're building a console app then there can't be any VCL (can there?)
#  if !defined(__CONSOLE__) && !defined(_NO_VCL)
#     define NDNBOOST_REGEX_USE_VCL
#  endif
   //
   // if this isn't Win32 then don't automatically select link
   // libraries:
   //
#  ifndef _Windows
#     ifndef NDNBOOST_REGEX_NO_LIB
#        define NDNBOOST_REGEX_NO_LIB
#     endif
#     ifndef NDNBOOST_REGEX_STATIC_LINK
#        define NDNBOOST_REGEX_STATIC_LINK
#     endif
#  endif

#if __BORLANDC__ < 0x600
//
// string workarounds:
//
#include <cstring>
#undef strcmp
#undef strcpy
#endif

#endif


text:
package com.amazonaws.services.simpleworkflow.flow.generic;

import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;

public interface GenericWorkflowClientExternal {

    public WorkflowExecution startWorkflow(StartWorkflowExecutionParameters startParameters);

    public void signalWorkflowExecution(SignalExternalWorkflowParameters signalParameters);

    public void requestCancelWorkflowExecution(WorkflowExecution execution);

    public String getWorkflowState(WorkflowExecution execution);

    public void terminateWorkflowExecution(TerminateWorkflowExecutionParameters terminateParameters);

    public String generateUniqueId();

}


text:
namespace base {
struct Feature;
}  // namespace base

namespace ash {

struct HatsConfig {
  HatsConfig(const base::Feature& feature,
             const char* const histogram_name,
             const base::TimeDelta& new_device_threshold,
             const char* const is_selected_pref_name,
             const char* const cycle_end_timestamp_pref_name);
  HatsConfig(const HatsConfig&) = delete;
  HatsConfig& operator=(const HatsConfig&) = delete;

  // Chrome OS-level feature (switch) we use to retrieve whether this HaTS
  // survey is enabled or not, and its parameters.
  const base::Feature& feature;

  // Histogram name. New entries should be added to
  // tools/metrics/histograms/metadata/browser/histograms.xml, as a variant of
  // Browser.ChromeOS.HatsSatisfaction.
  const char* const histogram_name;

  // Minimum amount of time after initial login or oobe after which we can show
  // the HaTS notification.
  const base::TimeDelta new_device_threshold;

  // Preference name for a boolean that stores whether we were selected for the
  // current survey cycle.
  const char* const is_selected_pref_name;

  // Preference name for an int64 that stores the current survey cycle end.
  const char* const cycle_end_timestamp_pref_name;
};

// CrOS HaTS configs are declared here and defined in hats_config.cc
extern const HatsConfig kHatsGeneralSurvey;
extern const HatsConfig kHatsEntSurvey;
extern const HatsConfig kHatsStabilitySurvey;
extern const HatsConfig kHatsPerformanceSurvey;
extern const HatsConfig kHatsOnboardingSurvey;
extern const HatsConfig kHatsSmartLockSurvey;
extern const HatsConfig kHatsUnlockSurvey;
extern const HatsConfig kHatsArcGamesSurvey;
extern const HatsConfig kHatsAudioSurvey;

}  // namespace ash

// TODO(https://crbug.com/1164001): remove when ChromeOS code migration is done.
namespace chromeos {
using ::ash::kHatsGeneralSurvey;
}  // namespace chromeos

#endif  // CHROME_BROWSER_ASH_HATS_HATS_CONFIG_H_


text:
import numpy as np
from op_test import OpTest
from testsuite import append_loss_ops, create_op, set_input
from white_list import no_grad_set_white_list, op_threshold_white_list
from xpu.get_test_cover_info import (
    get_xpu_op_support_types,
    is_empty_grad_op_type,
    type_dict_str_to_numpy,
)

import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core
from paddle.fluid.backward import append_backward
from paddle.fluid.framework import Program, convert_np_dtype_to_dtype_

class XPUOpTest(OpTest):
    @classmethod
    def setUpClass(cls):
        '''Fix random seeds to remove randomness from tests'''
        cls.use_xpu = True
        cls.use_mkldnn = False
        super().setUpClass()

    @classmethod
    def tearDownClass(cls):
        """Restore random seeds"""

        def is_empty_grad_op(op_type):
            grad_op = op_type + '_grad'
            xpu_version = core.get_xpu_device_version(0)
            xpu_op_list = core.get_xpu_device_op_list(xpu_version)
            if grad_op in xpu_op_list.keys():
                return False
            return True

        if cls.dtype == np.float16:
            place = paddle.XPUPlace(0)
            if not core.is_float16_supported(place):
                return

        if cls.dtype == np.float64:
            return

        super().tearDownClass()

    def _get_places(self):
        places = [paddle.XPUPlace(0)]
        return places

    def check_output(
        self,
        atol=0.001,
        no_check_set=None,
        equal_nan=False,
        check_dygraph=True,
        inplace_atol=None,
        check_eager=False,
    ):
        place = paddle.XPUPlace(0)
        self.check_output_with_place(
            place,
            atol,
            no_check_set,
            equal_nan,
            check_dygraph,
            inplace_atol,
            check_eager,
        )

    def check_output_with_place(
        self,
        place,
        atol=0.001,
        no_check_set=None,
        equal_nan=False,
        check_dygraph=True,
        inplace_atol=None,
        check_eager=False,
    ):
        self.infer_dtype_from_inputs_outputs(self.inputs, self.outputs)
        if self.dtype == np.float64:
            return

        if self.dtype == np.float16:
            if not core.is_float16_supported(place):
                return

        if self.dtype == np.float16:
            atol = 0.1
        return super().check_output_with_place(
            place, atol, no_check_set, equal_nan, check_dygraph, inplace_atol
        )

    def check_grad(
        self,
        inputs_to_check,
        output_names,
        no_grad_set=None,
        numeric_grad_delta=0.005,
        in_place=False,
        max_relative_error=0.005,
        user_defined_grads=None,
        user_defined_grad_outputs=None,
        check_dygraph=True,
        numeric_place=None,
        check_eager=False,
    ):
        place = paddle.XPUPlace(0)
        self.check_grad_with_place(
            place,
            inputs_to_check,
            output_names,
            no_grad_set,
            numeric_grad_delta,
            in_place,
            max_relative_error,
            user_defined_grads,
            user_defined_grad_outputs,
            check_dygraph,
            numeric_place,
            check_eager,
        )

    def check_grad_with_place(
        self,
        place,
        inputs_to_check,
        output_names,
        no_grad_set=None,
        numeric_grad_delta=0.005,
        in_place=False,
        max_relative_error=0.005,
        user_defined_grads=None,
        user_defined_grad_outputs=None,
        check_dygraph=True,
        numeric_place=None,
        check_eager=False,
    ):
        if hasattr(self, 'op_type_need_check_grad'):
            xpu_version = core.get_xpu_device_version(0)
            if is_empty_grad_op_type(
                xpu_version, self.op_type, self.in_type_str
            ):
                self._check_grad_helper()
                return

        cast_grad_op_types = get_xpu_op_support_types('cast')
        cast_grad_op_types_np = []
        for ctype in cast_grad_op_types:
            cast_grad_op_types_np.append(type_dict_str_to_numpy[ctype])

        if self.dtype not in cast_grad_op_types_np:
            return

        if self.dtype == np.float64:
            return

        if self.dtype == np.float16:
            if not core.is_float16_supported(place):
                return

        if self.dtype == np.float16:
            max_relative_error = 1.0
            return super().check_grad_with_place(
                place,
                inputs_to_check,
                output_names,
                no_grad_set,
                numeric_grad_delta,
                in_place,
                max_relative_error,
                user_defined_grads,
                user_defined_grad_outputs,
                check_dygraph,
            )

        a1 = self.get_grad_with_place(
            place,
            inputs_to_check,
            output_names,
            no_grad_set=no_grad_set,
            user_defined_grad_outputs=user_defined_grad_outputs,
        )
        a2 = self.get_grad_with_place(
            place,
            inputs_to_check,
            output_names,
            no_grad_set=no_grad_set,
            user_defined_grad_outputs=user_defined_grad_outputs,
        )
        a3 = self.get_grad_with_place(
            paddle.CPUPlace(),
            inputs_to_check,
            output_names,
            no_grad_set=no_grad_set,
            user_defined_grad_outputs=user_defined_grad_outputs,
        )
        self._assert_is_close(
            a1, a2, inputs_to_check, 0.00000001, "Gradient Check On two xpu"
        )
        self._assert_is_close(
            a1,
            a3,
            inputs_to_check,
            max_relative_error,
            "Gradient Check On cpu & xpu",
        )

    def get_grad_with_place(
        self,
        place,
        inputs_to_check,
        output_names,
        no_grad_set=None,
        numeric_grad_delta=0.005,
        in_place=False,
        max_relative_error=0.005,
        user_defined_grad_outputs=None,
        check_dygraph=True,
    ):
        self.scope = core.Scope()
        op_inputs = self.inputs if hasattr(self, "inputs") else dict()
        op_outputs = self.outputs if hasattr(self, "outputs") else dict()
        op_attrs = self.attrs if hasattr(self, "attrs") else dict()

        self._check_grad_helper()
        if (
            self.dtype == np.float64
            and self.op_type
            not in op_threshold_white_list.NEED_FIX_FP64_CHECK_GRAD_THRESHOLD_OP_LIST
        ):
            numeric_grad_delta = 1e-5
            max_relative_error = 1e-7

        cache_list = None
        if hasattr(self, "cache_name_list"):
            cache_list = self.cache_name_list

        # oneDNN numeric gradient should use CPU kernel
        use_onednn = False
        if "use_mkldnn" in op_attrs and op_attrs["use_mkldnn"]:
            op_attrs["use_mkldnn"] = False
            use_onednn = True

        mean_grad_op_types = get_xpu_op_support_types('mean')
        mean_grad_op_types_np = []
        for mtype in mean_grad_op_types:
            mean_grad_op_types_np.append(type_dict_str_to_numpy[mtype])

        self.op = create_op(
            self.scope,
            self.op_type,
            op_inputs,
            op_outputs,
            op_attrs,
            cache_list=cache_list,
        )

        if use_onednn:
            op_attrs["use_mkldnn"] = True

        if no_grad_set is None:
            no_grad_set = set()
        else:
            if (
                (self.op_type not in no_grad_set_white_list.NEED_TO_FIX_OP_LIST)
                and (
                    self.op_type not in no_grad_set_white_list.NOT_CHECK_OP_LIST
                )
                and (not self.is_bfloat16_op())
            ):
                raise AssertionError(
                    "no_grad_set must be None, op_type is "
                    + self.op_type
                    + " Op."
                )

        for input_to_check in inputs_to_check:
            set_input(self.scope, self.op, self.inputs, place)

        if not type(output_names) is list:
            output_names = [output_names]

        if self.dtype not in mean_grad_op_types_np:

            prog = Program()
            block = prog.global_block()
            scope = core.Scope()
            self._append_ops(block)

            inputs = self._get_inputs(block)
            outputs = self._get_outputs(block)
            feed_dict = self.feed_var(inputs, place)
            cast_inputs = list(map(block.var, output_names))
            cast_outputs = block.create_var(
                dtype="float32", shape=cast_inputs[0].shape
            )
            cast_op = block.append_op(
                type="cast",
                inputs={"X": cast_inputs},
                outputs={"Out": cast_outputs},
                attrs={
                    "in_dtype": convert_np_dtype_to_dtype_(self.dtype),
                    "out_dtype": core.VarDesc.VarType.FP32,
                },
            )
            cast_op.desc.infer_var_type(block.desc)
            cast_op.desc.infer_shape(block.desc)

            output_names = [cast_outputs.name]

            loss = append_loss_ops(block, output_names)
            loss_names = [loss.name]
            recast_inputs = list(map(block.var, loss_names))
            recast_loss = block.create_var(
                dtype=self.dtype, shape=recast_inputs[0].shape
            )

            recast_op = block.append_op(
                type="cast",
                inputs={"X": recast_inputs},
                outputs={"Out": recast_loss},
                attrs={
                    "in_dtype": core.VarDesc.VarType.FP32,
                    "out_dtype": convert_np_dtype_to_dtype_(self.dtype),
                },
            )
            recast_op.desc.infer_var_type(block.desc)
            recast_op.desc.infer_shape(block.desc)

            param_grad_list = append_backward(
                loss=recast_loss,
                parameter_list=[input_to_check],
                no_grad_set=no_grad_set,
            )
            fetch_list = [g for p, g in param_grad_list]

            executor = fluid.Executor(place)
            return list(
                map(
                    np.array,
                    executor.run(
                        prog,
                        feed_dict,
                        fetch_list,
                        scope=scope,
                        return_numpy=False,
                    ),
                )
            )

        analytic_grads = self._get_gradient(
            inputs_to_check,
            place,
            output_names,
            no_grad_set,
            user_defined_grad_outputs=user_defined_grad_outputs,
        )
        return analytic_grads


text:
<ResultadoCAN>
<ResultadoSolicitacaoCancelamento>
Cancelado%2073263500055432
</ResultadoSolicitacaoCancelamento>
<NSUCancelamento>
123456
</NSUCancelamento>
</ResultadoCAN>


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

#ifndef __se3_python_model_hpp__
#define __se3_python_model_hpp__

#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <eigenpy/exception.hpp>
#include <eigenpy/eigenpy.hpp>

#include "pinocchio/multibody/model.hpp"
#include "pinocchio/multibody/parser/sample-models.hpp"
#include "pinocchio/python/se3.hpp"
#include "pinocchio/python/eigen_container.hpp"
#include "pinocchio/python/handler.hpp"

namespace se3
{
  namespace python
  {
    namespace bp = boost::python;

    typedef Handler<Model> ModelHandler;

    struct ModelPythonVisitor
      : public boost::python::def_visitor< ModelPythonVisitor >
    {
    public:
      typedef Model::Index Index;
      typedef eigenpy::UnalignedEquivalent<Motion>::type Motion_fx;
      typedef eigenpy::UnalignedEquivalent<SE3>::type SE3_fx;
      typedef eigenpy::UnalignedEquivalent<Inertia>::type Inertia_fx;

      struct add_body_visitor : public boost::static_visitor<Model::Index>
      {
        ModelHandler & _model;
        Model::Index & _index;
        const SE3_fx & _placement;
        const Inertia_fx & _inertia;
        const std::string & _jName;
        const std::string & _bName;
        bool _visual;

        add_body_visitor( ModelHandler & model,
                          Model::Index & idx, const SE3_fx & placement,
                          const Inertia_fx & Y, const std::string & jointName,
                          const std::string & bodyName, bool visual)
                        : _model(model)
                        , _index(idx)
                        , _placement(placement)
                        , _inertia(Y)
                        , _jName(jointName)
                        , _bName(bodyName)
                        , _visual(visual)
        {}

        template <typename T> Model::Index operator()( T & operand ) const
        {
          return _model->addBody(_index, operand, _placement, _inertia, _jName, _bName, _visual);
        }
      };

    public:

      /* --- Convert From C++ to Python ------------------------------------- */
      // static PyObject* convert(Model const& modelConstRef)
      // {
      // 	Model * ptr = const_cast<Model*>(&modelConstRef);
      // 	return boost::python::incref(boost::python::object(ModelHandler(ptr)).ptr());
      // }
      static PyObject* convert(ModelHandler::SmartPtr_t const& ptr)
      {
	return boost::python::incref(boost::python::object(ModelHandler(ptr)).ptr());
      }

      /* --- Exposing C++ API to python through the handler ----------------- */
    template<class PyClass>
      void visit(PyClass& cl) const
      {
	cl
	  .def("getBodyId",&ModelPythonVisitor::getBodyId)
	  .def("createData",&ModelPythonVisitor::createData)

	  .def("__str__",&ModelPythonVisitor::toString)

	  .add_property("nq", &ModelPythonVisitor::nq)
	  .add_property("nv", &ModelPythonVisitor::nv)
	  .add_property("nbody", &ModelPythonVisitor::nbody)
	  .add_property("inertias",
			bp::make_function(&ModelPythonVisitor::inertias,
					  bp::return_internal_reference<>())  )
	  .add_property("jointPlacements",
			bp::make_function(&ModelPythonVisitor::jointPlacements,
					  bp::return_internal_reference<>())  )
    .add_property("joints",
      bp::make_function(&ModelPythonVisitor::joints,
            bp::return_internal_reference<>())  )
	  .add_property("parents",
			bp::make_function(&ModelPythonVisitor::parents,
					  bp::return_internal_reference<>())  )
	  .add_property("names",
			bp::make_function(&ModelPythonVisitor::names,
					  bp::return_internal_reference<>())  )
    .add_property("bodyNames",
		  bp::make_function(&ModelPythonVisitor::bodyNames,
            bp::return_internal_reference<>())  )
    .add_property("hasVisual",
      bp::make_function(&ModelPythonVisitor::hasVisual,
            bp::return_internal_reference<>())  )

    .def("addBody",&ModelPythonVisitor::addJointToModel)

      .add_property("nFixBody", &ModelPythonVisitor::nFixBody)
      .add_property("fix_lmpMi", bp::make_function(&ModelPythonVisitor::fix_lmpMi, bp::return_internal_reference<>()) )
      .add_property("fix_lastMovingParent",bp::make_function(&ModelPythonVisitor::fix_lastMovingParent,bp::return_internal_reference<>()) )
      .add_property("fix_hasVisual", bp::make_function(&ModelPythonVisitor::fix_hasVisual, bp::return_internal_reference<>())  )
      .add_property("fix_bodyNames", bp::make_function(&ModelPythonVisitor::fix_bodyNames, bp::return_internal_reference<>())  )

      .add_property("gravity",&ModelPythonVisitor::gravity,&ModelPythonVisitor::setGravity)
	  .def("BuildEmptyModel",&ModelPythonVisitor::maker_empty)
	  .staticmethod("BuildEmptyModel")
	  .def("BuildHumanoidSimple",&ModelPythonVisitor::maker_humanoidSimple)
	  .staticmethod("BuildHumanoidSimple")
	  ;
      }

      static Model::Index getBodyId( const ModelHandler & modelPtr, const std::string & name )
      { return  modelPtr->getBodyId(name); }
      static boost::shared_ptr<Data> createData(const ModelHandler& m )
      {	return boost::shared_ptr<Data>( new Data(*m) );      }

      static int nq( ModelHandler & m ) { return m->nq; }
      static int nv( ModelHandler & m ) { return m->nv; }
      static int nbody( ModelHandler & m ) { return m->nbody; }
      static std::vector<Inertia> & inertias( ModelHandler & m ) { return m->inertias; }
      static std::vector<SE3> & jointPlacements( ModelHandler & m ) { return m->jointPlacements; }
      static JointModelVector & joints( ModelHandler & m ) { return m->joints; }
      static std::vector<Model::Index> & parents( ModelHandler & m ) { return m->parents; }
      static std::vector<std::string> & names ( ModelHandler & m ) { return m->names; }
      static std::vector<std::string> & bodyNames ( ModelHandler & m ) { return m->bodyNames; }
      static std::vector<bool> & hasVisual ( ModelHandler & m ) { return m->hasVisual; }

      static Model::Index addJointToModel(  ModelHandler & modelPtr,
                                    Model::Index idx, bp::object joint,
                                    const SE3_fx & placement,
                                    const Inertia_fx & Y,
                                    const std::string & jointName,
                                    const std::string & bodyName,
                                    bool visual=false)
      {
        JointModelVariant variant = bp::extract<JointModelVariant> (joint);
        return boost::apply_visitor(add_body_visitor(modelPtr, idx, placement, Y, jointName, bodyName, visual), variant);
      }

      static int nFixBody( ModelHandler & m )                                     { return m->nFixBody; }
      static std::vector<SE3>          & fix_lmpMi           ( ModelHandler & m ) { return m->fix_lmpMi; }
      static std::vector<Model::Index> & fix_lastMovingParent( ModelHandler & m ) { return m->fix_lastMovingParent; }
      static std::vector<bool> & fix_hasVisual ( ModelHandler & m ) { return m->fix_hasVisual; }
      static std::vector<std::string> & fix_bodyNames ( ModelHandler & m ) { return m->fix_bodyNames; }

      static Motion gravity( ModelHandler & m ) { return m->gravity; }
      static void setGravity( ModelHandler & m,const Motion_fx & g ) { m->gravity = g; }

      static ModelHandler maker_empty()
      {
	return ModelHandler( new Model(),true );
      }
      static ModelHandler maker_humanoidSimple()
      {
	Model * model = new Model();
	buildModels::humanoidSimple(*model);
	return ModelHandler( model,true );
      }

      static std::string toString(const ModelHandler& m)
      {	  std::ostringstream s; s << *m; return s.str();       }

      ///
      /// \brief Provide equivalent to python list index function for
      ///        vectors.
      ///
      /// \param[in] x The input vector.
      /// \param[in] v The value of to look for in the vector.
      ///
      /// \return The index of the matching element of the vector. If
      ///         no element is found, return the size of the vector.
      ///
      template<typename T>
      static Model::Index index(std::vector<T> const& x,
                                typename std::vector<T>::value_type const& v)
      {
        Model::Index i = 0;
        for(typename std::vector<T>::const_iterator it = x.begin(); it != x.end(); ++it, ++i)
        {
          if(*it == v)
          {
            return i;
          }
        }
        return x.size();
      }

      /* --- Expose --------------------------------------------------------- */
      static void expose()
      {
        bp::class_< std::vector<Index> >("StdVec_Index")
          .def(bp::vector_indexing_suite< std::vector<Index> >());
        bp::class_< std::vector<std::string> >("StdVec_StdString")
          .def(bp::vector_indexing_suite< std::vector<std::string> >())
          .def("index", &ModelPythonVisitor::index<std::string>);
        bp::class_< std::vector<bool> >("StdVec_Bool")
          .def(bp::vector_indexing_suite< std::vector<bool> >());
        bp::class_< std::vector<double> >("StdVec_double")
          .def(bp::vector_indexing_suite< std::vector<double> >());
        bp::class_< JointModelVector >("StdVec_JointModelVector")
          .def(bp::vector_indexing_suite< JointModelVector, true >());

  bp::class_<ModelHandler>("Model",
         "Articulated rigid body model (const)",
         bp::no_init)
    .def(ModelPythonVisitor());

	/* Not sure if it is a good idea to enable automatic
	 * conversion. Prevent it for now */
	//bp::to_python_converter< Model,ModelPythonVisitor >();
	bp::to_python_converter< ModelHandler::SmartPtr_t,ModelPythonVisitor >();
      }

    };

  }} // namespace se3::python

#endif // ifndef __se3_python_model_hpp__


text:
(function() {
  'use strict';

  angular
    .module('core')
    .factory('dataService', dataService);

  // portfolioListService.$inject = ['dependencies'];

  /* @ngInject */
  function dataService($http) {
    var service = {
      get: get
    };

    return service;

    function get(apiPath) {
      var config = {};
      return $http.get(apiPath, config).then(function(response){
        return response.data;
      });
    }
  }
})();


text:
#ifndef IDL_GENCXXTYPEDCLASSDEFS_H
#define IDL_GENCXXTYPEDCLASSDEFS_H

#include "idl_genCorbaCxxHelper.h"
#include "idl_program.h"

idl_program idl_genCxxTypedClassDefsProgram (CxxTypeUserData *userData);

#endif /* IDL_GENCXXTYPEDCLASSDEFS_H */


text:
async function run() {
  // TODO Implement populate
  throw new Error('[populate] Not implemented');
}

module.exports = {
  run,
};


text:
/**
 * @module Wiki
 */
/// <reference path="./wikiPlugin.ts"/>
module Wiki {
  _module.controller("Wiki.DozerMappingsController", ["$scope", "$location", "$routeParams", "workspace", "jolokia", "wikiRepository", "$templateCache", ($scope, $location, $routeParams, workspace:Workspace, jolokia, wikiRepository:GitWikiRepository, $templateCache) => {
    var log:Logging.Logger = Logger.get("Dozer");

    Wiki.initScope($scope, $routeParams, $location);
    Dozer.schemaConfigure();

    $scope.profileId = Fabric.pagePathToProfileId($scope.pageId);
    $scope.versionId = $scope.branch || "1.0";

    $scope.schema = {};
    $scope.addDialog = new UI.Dialog();
    $scope.propertiesDialog = new UI.Dialog();
    $scope.deleteDialog = false;
    $scope.unmappedFieldsHasValid = false;
    $scope.modified = false;

    $scope.selectedItems = [];
    $scope.mappings = [];
    $scope.schemas = [];

    $scope.aName = '';
    $scope.bName = '';

    $scope.connectorStyle = [ "Bezier" ];

    $scope.main = "";
    $scope.tab = "Mappings";

    $scope.gridOptions = {
      selectedItems: $scope.selectedItems,
      data: 'mappings',
      displayFooter: false,
      showFilter: false,
      //sortInfo: { field: 'timestamp', direction: 'DESC'},
      filterOptions: {
        filterText: "searchText"
      },
      columnDefs: [
        {
          field: 'class_a',
          displayName: 'From',
          cellTemplate: '
{{row.entity.class_a.name}}
'
        },
        {
          field: 'class_b',
          displayName: 'To',
          cellTemplate: '
{{row.entity.class_b.name}}
'
        }
      ]
    };

    if ($scope.profileId) {
      Fabric.profileJolokia(jolokia, $scope.profileId, $scope.versionId, (containerJolokia) => {
        $scope.containerJolokia = containerJolokia;
        $scope.missingContainer = !containerJolokia ? true : false;
      });
    }

    $scope.$on("$routeChangeSuccess", function (event, current, previous) {
      // lets do this asynchronously to avoid Error: $digest already in progress
      setTimeout(updateView, 50);
    });

    $scope.triggerRefresh = (timeout = 500) => {
      $scope.main = "";
      setTimeout(() => {
        $scope.main = $templateCache.get("pageTemplate.html");
        Core.$apply($scope);
      }, timeout);
    };

    $scope.disableReload = () => {
      var aValue = Core.pathGet($scope, ["selectedMapping", "class_a", "value"]);
      var bValue = Core.pathGet($scope, ["selectedMapping", "class_b", "value"]);
      return aValue === $scope.aName && bValue === $scope.bName;
    };

    $scope.doReload = () => {
      $scope.selectedMapping.class_a.value = $scope.aName;
      $scope.selectedMapping.class_b.value = $scope.bName;
      $scope.triggerRefresh();
    };

    $scope.$watch('selectedMapping', (newValue, oldValue) => {
      if (newValue !== oldValue) {
        $scope.aName = newValue.class_a.value;
        $scope.bName = newValue.class_b.value;
        $scope.triggerRefresh();
      }
    });

    $scope.$watch('selectedMapping.class_a.value', (newValue, oldValue) => {
      if (newValue !== oldValue && newValue !== '') {
        $scope.fetchProperties(newValue, $scope.selectedMapping.class_a, 'Right');
      }
    });

    $scope.$watch('selectedMapping.class_b.value', (newValue, oldValue) => {
      if (newValue !== oldValue && newValue !== '') {
        $scope.fetchProperties(newValue, $scope.selectedMapping.class_b, 'Left');
      }
    });

    $scope.fetchProperties = (className, target, anchor) => {
      var introspectorMBean = Dozer.getIntrospectorMBean(workspace);
      if (introspectorMBean && !$scope.missingContainer) {
        var aJolokia: any = $scope.containerJolokia || jolokia;
        aJolokia.request({
          type: 'exec',
          mbean: introspectorMBean,
          operation: 'getProperties(java.lang.String)',
          arguments: [className]
        }, {
          success: (response) => {
            target.error = null;
            target.properties = response.value;
            var parentId = '';
            if (angular.isDefined(target.value)) {
              parentId = target.value;
            } else {
              parentId = target.path;
            }

            angular.forEach(target.properties, (property) => {
              property.id = Core.getUUID();
              property.path = parentId + '/' + property.displayName;
              property.anchor = anchor;

              // TODO - Let's see if we need to do this...
              /*
               var lookup = !Dozer.excludedPackages.any((excluded) => { return property.typeName.has(excluded); });
               if (lookup) {
               $scope.fetchProperties(property.typeName, property, anchor);
               }
               */
            });
            Core.$apply($scope);
          },
          error: (response) => {
            target.properties = null;
            target.error = {
              'type': response.error_type,
              'stackTrace': response.error
            };
            log.error("got: " + response);
            Core.$apply($scope);
          }
        });
      }
    };

    $scope.getSourceAndTarget = (info) => {
      var sourcePath = info.source.attr('field-path');
      var targetPath = info.target.attr('field-path');

      var sourceField = sourcePath.split('/').last();
      var targetField = sourcePath.split('/').last();

      return {
        from: sourceField,
        to: targetField
      };
    };

    function extractProperty(clazz, prop) {
      return (!clazz || !clazz.properties) ? null :
        clazz.properties.find((property) => {
        return property.path.endsWith('/' + prop);
      });
    }

    // The jsPlumb directive will call this after it's done it's thing...
    function addConnectionClickHandler(connection, jsplumb) {
      connection.bind('click', (connection) => {
        jsplumb.detach(connection);
      });
    }

    function getPaintStyle() {
      return {
        strokeStyle: UI.colors.sample(),
        lineWidth: 4
      };
    }

    $scope.jsPlumbCallback = (jsplumb, nodes, nodesById, connections) => {

      // Set up any connections loaded from the XML
      // TODO - currently we actually are only looking at the top-level properties
      angular.forEach($scope.selectedMapping.fields, (field) => {
        var a_property = extractProperty($scope.selectedMapping.class_a, field.a.value);
        var b_property = extractProperty($scope.selectedMapping.class_b, field.b.value);

        if (a_property && b_property) {
          var a_node = nodesById[a_property.id];
          var b_node = nodesById[b_property.id];

          var connection = $scope.jsPlumb.connect({
            source: a_node.el,
            target: b_node.el
          }, {
            connector: $scope.connectorStyle,
            maxConnections: 1,
            paintStyle: getPaintStyle()
          });

          //Ensure loaded connections can also be removed
          addConnectionClickHandler(connection, jsplumb);
          a_node.connections.push(connection);
          b_node.connections.push(connection);
        }
      });

      // Handle new connection events...
      jsplumb.bind('connection', (info) => {

        // Add a handler so we can click on a connection to make it go away
        addConnectionClickHandler(info.connection, jsplumb);
        info.connection.setPaintStyle(getPaintStyle());

        var newMapping = $scope.getSourceAndTarget(info);

        var field = new Dozer.Field(new Dozer.FieldDefinition(newMapping.from), new Dozer.FieldDefinition(newMapping.to));
        $scope.selectedMapping.fields.push(field);
        $scope.modified = true;
        Core.$apply($scope);
      });

      // Handle connection detach events...
      jsplumb.bind('connectionDetached', (info) => {
        var toDetach = $scope.getSourceAndTarget(info);
        var field = new Dozer.Field(new Dozer.FieldDefinition(toDetach.from), new Dozer.FieldDefinition(toDetach.to));
        $scope.selectedMapping.fields.remove(field);
        $scope.modified = true;
        Core.$apply($scope);
      });
    };

    $scope.formatStackTrace = (exception) => {
      return Log.formatStackTrace(exception);
    };

    $scope.addMapping = () => {
      var treeNode = $scope.rootTreeNode;
      if (treeNode) {
        var parentFolder = treeNode.data;
        var mapping = new Dozer.Mapping();
        var addedNode = Dozer.createMappingFolder(mapping, parentFolder);
        var added = treeNode.addChild(addedNode);
        if (added) {
          added.expand(true);
          added.select(true);
          added.activate(true);
          onTreeModified();
        }
        $scope.mappings.push(mapping);
        $scope.selectedMapping = mapping;
      }
    };

    $scope.addField = () => {
      if ($scope.selectedMapping) {
        // lets find all the possible unmapped fields we can map from...
        Dozer.findUnmappedFields(workspace, $scope.selectedMapping, (data) => {
          log.warn("has unmapped data fields: " + data);
          $scope.unmappedFields = data;
          $scope.unmappedFieldsHasValid = false;
          $scope.addDialog.open();
          Core.$apply($scope);
        });
      }
    };

    $scope.addAndCloseDialog = () => {
      log.info("About to add the unmapped fields " + JSON.stringify($scope.unmappedFields, null, "  "));
      if ($scope.selectedMapping) {
        // TODO whats the folder???
        angular.forEach($scope.unmappedFields, (unmappedField) => {
          if (unmappedField.valid) {
            // TODO detect exclude!
            var field = new Dozer.Field(new Dozer.FieldDefinition(unmappedField.fromField), new Dozer.FieldDefinition(unmappedField.toField));
            $scope.selectedMapping.fields.push(field);
            var treeNode = $scope.selectedMappingTreeNode;
            var mappingFolder = $scope.selectedMappingFolder;
            if (treeNode && mappingFolder) {
              var fieldFolder = Dozer.addMappingFieldFolder(field, mappingFolder);
              var added = treeNode.addChild(fieldFolder);
              if (added) {
                added.expand(true);
                added.select(true);
                added.activate(true);
                onTreeModified();
              }
            } else {
              log.warn("No treenode and folder for mapping node! treeNode " + treeNode + " mappingFolder " + mappingFolder);
            }
          }
        });
      }
      $scope.addDialog.close();
    };

    $scope.canDelete = () => {
      return $scope.selectedFolder ? true : false;
    };

    $scope.removeNode = () => {
      if ($scope.selectedFolder && $scope.treeNode) {
        // TODO deal with deleting fields
        var folder = $scope.selectedFolder;
        var entity = folder.entity;
        if (entity instanceof Dozer.Field) {
          // lets remove this from the parent mapping
          var mapping = Core.pathGet(folder, ["parent", "entity"]);
          if (mapping) {
            mapping.fields.remove(entity);
          }
        }
        $scope.selectedFolder.detach();
        $scope.treeNode.remove();
        $scope.selectedFolder = null;
        $scope.treeNode = null;
        onTreeModified();
      }
    };

    $scope.saveMappings = () => {
      $scope.model.mappings = $scope.mappings;
      var text = Dozer.saveToXmlText($scope.model);
      if (text) {
        var commitMessage = $scope.commitMessage || "Updated page " + $scope.pageId;
        wikiRepository.putPage($scope.branch, $scope.pageId, text, commitMessage, (status) => {
          Wiki.onComplete(status);
          $scope.modified = false;
          Core.notification("success", "Saved " + $scope.pageId)
          goToView();
          Core.$apply($scope);
        });
      }
    };

    $scope.save = () => {
      if ($scope.tab === "Mappings") {
        $scope.saveMappings();
        return;
      }
      if ($scope.model) {
        // lets copy the mappings from the tree
        var model = Dozer.loadModelFromTree($scope.rootTreeNode, $scope.model);
        var text = Dozer.saveToXmlText(model);
        if (text) {
          var commitMessage = $scope.commitMessage || "Updated page " + $scope.pageId;
          wikiRepository.putPage($scope.branch, $scope.pageId, text, commitMessage, (status) => {
            Wiki.onComplete(status);
            $scope.modified = false;
            Core.notification("success", "Saved " + $scope.pageId)
            goToView();
            Core.$apply($scope);
          });
        }
      }
    };

    $scope.cancel = () => {
      log.info("cancelling...");
      // TODO show dialog if folks are about to lose changes...
    };

    $scope.onRootTreeNode = (rootTreeNode) => {
      $scope.rootTreeNode = rootTreeNode;
    };

    $scope.onNodeSelect = (folder, treeNode) => {
      $scope.selectedFolder = folder;
      $scope.treeNode = treeNode;
      $scope.propertiesTemplate = null;
      $scope.dozerEntity = null;
      $scope.selectedDescription = "";
      $scope.selectedMapping = null;
      $scope.selectedMappingTreeNode = null;
      $scope.selectedMappingFolder = null;
      // now the model is bound, lets add a listener
      if ($scope.removeModelChangeListener) {
        $scope.removeModelChangeListener();
        $scope.removeModelChangeListener = null;
      }

      if (folder) {
        var entity = folder.entity;
        $scope.dozerEntity = entity;
        var propertiesTemplate = "app/wiki/html/dozerPropertiesEdit.html";
        if (entity instanceof Dozer.Field) {
          //var field: Dozer.Field = entity;
          $scope.propertiesTemplate = propertiesTemplate;
          $scope.nodeModel = io_hawt_dozer_schema_Field;
          $scope.selectedDescription = "Field Mapping";
          $scope.selectedMapping = Core.pathGet(folder, ["parent", "entity"]);
          $scope.selectedMappingFolder = folder.parent;
          $scope.selectedMappingTreeNode = treeNode.parent;
        }
        else if (entity instanceof Dozer.Mapping) {
          //var mapping: Dozer.Mapping = entity;
          $scope.propertiesTemplate = propertiesTemplate;
          $scope.nodeModel = io_hawt_dozer_schema_Mapping;
          $scope.selectedDescription = "Class Mapping";
          $scope.selectedMapping = entity;
          $scope.selectedMappingFolder = folder;
          $scope.selectedMappingTreeNode = treeNode;
        }
        if ($scope.selectedMapping && !$scope.removeModelChangeListener) {
/*
          TODO problem is we have many forms here so we end up creating lots of change events when really we don't change things!: )
          // maybe watch the entity instead?

          console.log("Adding onTreeModified form listener");
          $scope.removeModelChangeListener = $scope.$on("hawtio.form.modelChange", () => {
            console.log("form modified!");
            onTreeModified();
          });
*/
        }
      }

      Core.$apply($scope);
    };

    $scope.onUnmappedFieldChange = (unmappedField) => {
      unmappedField.valid = unmappedField.toField ? true : false;
      $scope.unmappedFieldsHasValid = $scope.unmappedFields.find(f => f.valid);
    };

    function findFieldNames(className, text) {
      //console.log("Finding the to field names for expression '" + text + "'  on class " + className);
      var properties = Dozer.findProperties(workspace, className, text, null);
      return properties.map(p => p.name);
    }

    $scope.fromFieldNames = (text) => {
      var className = Core.pathGet($scope.selectedMapping, ["class_a", "value"]);
      return findFieldNames(className, text);
    };

    $scope.toFieldNames = (text) => {
      var className = Core.pathGet($scope.selectedMapping, ["class_b", "value"]);
      return findFieldNames(className, text);
    };

    $scope.classNames = (text) => {
      // lets only query if the size is reasonable
      if (!text || text.length < 2) return [];
      return Core.time("Time the query of classes", () => {
        log.info("searching for class names with filter '" + text + "'");
        var answer =  Dozer.findClassNames(workspace, text);
        log.info("Found results: " + answer.length);
        return answer;
      })
    };

    updateView();

    function updateView() {
      $scope.pageId = Wiki.pageId($routeParams, $location);
      if (Git.getGitMBean(workspace)) {
        $scope.git = wikiRepository.getPage($scope.branch, $scope.pageId, $scope.objectId, onResults);
      }
    }

    function onResults(response) {
      var text = response.text;
      if (text) {
        if ($scope.responseText !== text) {
          $scope.responseText = text;
          // lets remove any dodgy characters so we can use it as a DOM id
          $scope.model = Dozer.loadDozerModel(text, $scope.pageId);

          $scope.mappings = Core.pathGet($scope.model, ["mappings"]);

          $scope.mappingTree = Dozer.createDozerTree($scope.model);
          if (!angular.isDefined($scope.selectedMapping)) {
            $scope.selectedMapping = $scope.mappings.first();
          }

          $scope.main = $templateCache.get("pageTemplate.html");
        }
      } else {
        log.warn("No XML found for page " + $scope.pageId);
      }
      Core.$apply($scope);
    }

    function onTreeModified() {
      $scope.modified = true;
    }

    function goToView() {
      // TODO lets navigate to the view if we have a separate view one day :)
      /*
       if ($scope.breadcrumbs && $scope.breadcrumbs.length > 1) {
       var viewLink = $scope.breadcrumbs[$scope.breadcrumbs.length - 2];
       console.log("goToView has found view " + viewLink);
       var path = Core.trimLeading(viewLink, "#");
       $location.path(path);
       } else {
       console.log("goToView has no breadcrumbs!");
       }
       */
    }
  }]);
}


text:
define([
  'aeris/maps/layers/advisories',
  'aeris/maps/layers/chlorophyll',
  'aeris/maps/layers/dewpoints',
  'aeris/maps/layers/heatindex',
  'aeris/maps/layers/humidity',
  'aeris/maps/layers/lightningstrikedensity',
  'aeris/maps/layers/precip',
  'aeris/maps/layers/qpf',
  'aeris/maps/layers/radar',
  'aeris/maps/layers/satellite',
  'aeris/maps/layers/satelliteglobal',
  'aeris/maps/layers/satellitevisible',
  'aeris/maps/layers/seasurfacetemps',
  'aeris/maps/layers/snowdepth',
  'aeris/maps/layers/snowfallaccum',
  'aeris/maps/layers/temps',
  'aeris/maps/layers/windchill',
  'aeris/maps/layers/winds',
  'aeris/maps/layers/osm'
], function() {});


text:
package org.springframework.binding.value.support;

import javax.swing.event.ListDataEvent;

import org.easymock.IArgumentMatcher;

/**
 * Custom ArgumentMatcher for EasyMock.
 *
 * @author Peter De Bruycker
 */
public class ListDataEventArgumentMatcher implements IArgumentMatcher {

	private ListDataEvent expected;

	public ListDataEventArgumentMatcher(ListDataEvent expected) {
		this.expected = expected;
	}

	public void appendTo(StringBuffer sb) {
		sb.append("javax.swing.event.ListDataEvent[");

		sb.append("type=").append(expected.getType()).append(", ");
		sb.append("index0=").append(expected.getIndex0()).append(", ");
		sb.append("index1=").append(expected.getIndex1()).append(", ");

		sb.append("]");
	}

	public boolean matches(Object value) {
		if (!(value instanceof ListDataEvent)) {
			return false;
		}

		ListDataEvent actual = (ListDataEvent) value;

		boolean matches = true;
		matches = matches && actual.getSource().equals(expected.getSource());
		matches = matches && actual.getType() == expected.getType();
		matches = matches && actual.getIndex0() == expected.getIndex0();
		matches = matches && actual.getIndex1() == expected.getIndex1();

		return matches;
	}

}


text:
@protocol PullingRefreshTableViewDelegate;
@interface PullingRefreshTableView : UITableView
{
    PullLoadingView *_headerView;
    PullLoadingView *_footerView;
    BOOL _isFooterInAction;

    UILabel *_msgLabel;
}

@property (nonatomic) BOOL reachedTheEnd;
@property (nonatomic) BOOL autoScrollToNextPage;
@property (nonatomic,getter = isHeaderOnly) BOOL headerOnly;
@property (assign,nonatomic) id <PullingRefreshTableViewDelegate> pullingDelegate;
-(id)initWithFrame:(CGRect)frame pullingDelegate:(id<PullingRefreshTableViewDelegate>)aPullingDelegate;
- (void)launchRefreshing;
- (void)flashMessage:(NSString *)msg;

- (void)tableViewDidEndDragging:(UIScrollView *)scrollView;
- (void)tableViewDidFinishedLoading;
- (void)tableViewDidScroll:(UIScrollView *)scrollView;

- (void)tableViewDidFinishedLoadingWithMessage:(NSString *)msg;
@end

@protocol PullingRefreshTableViewDelegate <NSObject>

@required
- (void)pullingTableViewDidStartRefreshing:(PullingRefreshTableView *)tableView;
@optional
//Implement this method if headerOnly is false
- (void)pullingTableViewDidStartLoading:(PullingRefreshTableView *)tableView;
//Implement the follows to set date you want,Or Ignore them to use current date
- (NSDate *)pullingTableViewRefreshingFinishedDate;
- (NSDate *)pullingTableViewLoadingFinishedDate;

@end


text:
<component name="ProjectDictionaryState">
  <dictionary name="pokusew">
    <words>
      <w>gitignore</w>
      <w>npmignore</w>
    </words>
  </dictionary>
</component>


text:
MYDIR=$(cd $(dirname "$0"); pwd)

PYTHONPATH=$MYDIR/src python $MYDIR/src/pytrain/Main.py


text:
<?php
/**
 * Widget API: WP_Widget_Text class
 *
 * @package WordPress
 * @subpackage Widgets
 * @since 4.4.0
 */

/**
 * Core class used to implement a Text widget.
 *
 * @since 2.8.0
 *
 * @see WP_Widget
 */
class WP_Widget_Text extends WP_Widget {

	/**
	 * Whether or not the widget has been registered yet.
	 *
	 * @since 4.8.1
	 * @var bool
	 */
	protected $registered = false;

	/**
	 * Sets up a new Text widget instance.
	 *
	 * @since 2.8.0
	 */
	public function __construct() {
		$widget_ops  = array(
			'classname'                   => 'widget_text',
			'description'                 => __( 'Arbitrary text.' ),
			'customize_selective_refresh' => true,
		);
		$control_ops = array(
			'width'  => 400,
			'height' => 350,
		);
		parent::__construct( 'text', __( 'Text' ), $widget_ops, $control_ops );
	}

	/**
	 * Add hooks for enqueueing assets when registering all widget instances of this widget class.
	 *
	 * @param int $number Optional. The unique order number of this widget instance
	 *                    compared to other instances of the same class. Default -1.
	 */
	public function _register_one( $number = -1 ) {
		parent::_register_one( $number );
		if ( $this->registered ) {
			return;
		}
		$this->registered = true;

		wp_add_inline_script( 'text-widgets', sprintf( 'wp.textWidgets.idBases.push( %s );', wp_json_encode( $this->id_base ) ) );

		if ( $this->is_preview() ) {
			add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_preview_scripts' ) );
		}

		// Note that the widgets component in the customizer will also do
		// the 'admin_print_scripts-widgets.php' action in WP_Customize_Widgets::print_scripts().
		add_action( 'admin_print_scripts-widgets.php', array( $this, 'enqueue_admin_scripts' ) );

		// Note that the widgets component in the customizer will also do
		// the 'admin_footer-widgets.php' action in WP_Customize_Widgets::print_footer_scripts().
		add_action( 'admin_footer-widgets.php', array( 'WP_Widget_Text', 'render_control_template_scripts' ) );
	}

	/**
	 * Determines whether a given instance is legacy and should bypass using TinyMCE.
	 *
	 * @since 4.8.1
	 *
	 * @param array $instance {
	 *     Instance data.
	 *
	 *     @type string      $text   Content.
	 *     @type bool|string $filter Whether autop or content filters should apply.
	 *     @type bool        $legacy Whether widget is in legacy mode.
	 * }
	 * @return bool Whether Text widget instance contains legacy data.
	 */
	public function is_legacy_instance( $instance ) {

		// Legacy mode when not in visual mode.
		if ( isset( $instance['visual'] ) ) {
			return ! $instance['visual'];
		}

		// Or, the widget has been added/updated in 4.8.0 then filter prop is 'content' and it is no longer legacy.
		if ( isset( $instance['filter'] ) && 'content' === $instance['filter'] ) {
			return false;
		}

		// If the text is empty, then nothing is preventing migration to TinyMCE.
		if ( empty( $instance['text'] ) ) {
			return false;
		}

		$wpautop         = ! empty( $instance['filter'] );
		$has_line_breaks = ( false !== strpos( trim( $instance['text'] ), "\n" ) );

		// If auto-paragraphs are not enabled and there are line breaks, then ensure legacy mode.
		if ( ! $wpautop && $has_line_breaks ) {
			return true;
		}

		// If an HTML comment is present, assume legacy mode.
		if ( false !== strpos( $instance['text'], '