text:
package org.jbpm.eclipse.action;

import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl;
import org.kie.api.definition.process.Connection;
import org.kie.api.definition.process.Node;
import org.kie.api.definition.process.NodeContainer;
import org.kie.api.definition.process.Process;
import org.drools.core.xml.SemanticModules;
import org.eclipse.core.internal.resources.File;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.jbpm.bpmn2.xml.BPMNDISemanticModule;
import org.jbpm.bpmn2.xml.BPMNExtensionsSemanticModule;
import org.jbpm.bpmn2.xml.BPMNSemanticModule;
import org.jbpm.compiler.xml.XmlProcessReader;
import org.jbpm.compiler.xml.processes.RuleFlowMigrator;
import org.jbpm.eclipse.JBPMEclipsePlugin;
import org.jbpm.process.core.context.variable.Variable;
import org.jbpm.process.core.context.variable.VariableScope;
import org.jbpm.ruleflow.core.RuleFlowProcess;
import org.jbpm.workflow.core.impl.NodeImpl;
import org.jbpm.workflow.core.node.CompositeNode;
import org.jbpm.workflow.core.node.EndNode;
import org.jbpm.workflow.core.node.EventNode;
import org.jbpm.workflow.core.node.FaultNode;
import org.jbpm.workflow.core.node.ForEachNode;
import org.jbpm.workflow.core.node.HumanTaskNode;
import org.jbpm.workflow.core.node.Join;
import org.jbpm.workflow.core.node.RuleSetNode;
import org.jbpm.workflow.core.node.Split;
import org.jbpm.workflow.core.node.StartNode;
import org.jbpm.workflow.core.node.SubProcessNode;
import org.jbpm.workflow.core.node.TimerNode;
import org.jbpm.workflow.core.node.WorkItemNode;

public class GenerateBPMN2JUnitTests implements IObjectActionDelegate {

    private IFile file;
    private IWorkbenchPart targetPart;
    private boolean firstHumanTask = true;

    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
        this.targetPart = targetPart;
    }

    public void run(IAction action) {
        if (file != null && file.exists()) {
            try {
                generateJUnitTests();
            } catch (Throwable t) {
                JBPMEclipsePlugin.log(t);
            }
        }

    }

    public void selectionChanged(IAction action, ISelection selection) {
        if (selection instanceof IStructuredSelection) {
            IStructuredSelection structured = (IStructuredSelection) selection;
            if (structured.size() == 1) {
                Object element = structured.getFirstElement();
                if (element instanceof IFile) {
                    file = (IFile) element;
                }
            }
        }
    }

    public void generateJUnitTests() {
    	firstHumanTask = true;
        try {
            final IJavaProject javaProject = JavaCore.create(file.getProject());
            if (javaProject == null || !javaProject.exists()) {
                return;
            }
            InputStreamReader isr = new InputStreamReader(((File) file).getContents());
            KnowledgeBuilderConfigurationImpl configuration = new KnowledgeBuilderConfigurationImpl();
            SemanticModules modules = configuration.getSemanticModules();
            modules.addSemanticModule(new BPMNSemanticModule());
            modules.addSemanticModule(new BPMNDISemanticModule());
            modules.addSemanticModule(new BPMNExtensionsSemanticModule());
            XmlProcessReader xmlReader = new XmlProcessReader( modules, Thread.currentThread().getContextClassLoader() );
            String xml = RuleFlowMigrator.convertReaderToString(isr);
            Reader reader = new StringReader(xml);
            List<Process> processes = xmlReader.read(reader);
            if (processes != null && processes.size() == 1) {
            	final RuleFlowProcess process = (RuleFlowProcess) processes.get(0);
            	String packageName = process.getPackageName();
            	if (packageName == null || packageName.trim().length() == 0 || "org.drools.bpmn2".equals(packageName)) {
            		packageName = "org.jbpm";
            	}
            	final String pName = packageName;
                WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
                    public void execute(final IProgressMonitor monitor)
                            throws CoreException {
                        try {
                            IFolder folder = file.getProject().getFolder("src/main/java");
                            IPackageFragmentRoot packageFragmentRoot = javaProject
                                    .getPackageFragmentRoot(folder);
                            IPackageFragment packageFragment = packageFragmentRoot
                                    .createPackageFragment(pName, true, monitor);
                        	String processName = process.getName();
                        	processName = processName.replaceAll("\\s", "_");
                        	if (processName == null || processName.trim().length() == 0) {
                        		processName = "Process";
                        	}
                        	String fileName = processName + "JUnitTest";
                        	String output =
                        		"package " + pName + ";\n" +
                				"\n" +
                				"import java.util.ArrayList;\n" +
                				"import java.util.HashMap;\n" +
                				"import java.util.List;\n" +
                				"import java.util.Map;\n" +
                        		"\n" +
                        		"import org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler;\n" +
                        		"import org.jbpm.test.JbpmJUnitTestCase;\n" +
                        		"\n" +
                        		"import org.junit.Test;\n" +
                        		"\n" +
                        		"import org.kie.api.runtime.KieSession;\n" +
                        		"import org.kie.api.runtime.process.ProcessInstance;\n" +
                        		"import org.kie.api.task.TaskService;\n" +
                        		"import org.kie.api.task.model.TaskSummary;\n" +
                        		"\n" +
                        		"public class " + fileName + " extends JbpmJUnitTestCase {\n" +
                        		"\n";
                        	boolean containsHumanTasks = containsHumanTasks(process);
                        	if (containsHumanTasks) {
                        		output +=
                        			"    public " + fileName + "() {\n" +
                					"        super(true);\n" +
                					"    }\n" +
                					"\n";
                        	}
                        	Map<String, String> cases = new HashMap<String, String>();
                        	Map<String, String> ongoingCases = new HashMap<String, String>();
                        	boolean done = processNodes("", process.getStart(null), "", cases, ongoingCases);
                        	if (!done) {
                        		if (ongoingCases.size() == 1) {
                        			cases.put("Implicit", ongoingCases.values().iterator().next());
                        		} else {
                        			throw new IllegalArgumentException("Could not create implicit case: " + ongoingCases.size());
                        		}
                        	}
                        	for (Map.Entry<String, String> entry: cases.entrySet()) {
	                        	output +=
	                        		"	@Test\n" +
	                        		"    public void test" + entry.getKey() + "() {\n" +
	                        		"        KieSession ksession = createKnowledgeSession(\"" + file.getName() + "\");\n";
	                        	Set<String> serviceTasks = new HashSet<String>();
	                        	containsServiceTasks(serviceTasks, process);
	                        	for (String service: serviceTasks) {
	                        		output += "        ksession.getWorkItemManager().registerWorkItemHandler(\"" + service + "\", new SystemOutWorkItemHandler());\n";
	                        	}
	                        	if (containsHumanTasks) {
	                        		output += "        TaskService taskService = getTaskService();\n";
	                        	}
	                        	List<Variable> variables = process.getVariableScope().getVariables();
	                        	if (variables != null && variables.size() > 0) {
		                        	output +=
	                    				"        Map<String, Object> params = new HashMap<String, Object>();\n" +
	                    				"        // initialize variables here if necessary\n";
		                        	for (Variable v: variables) {
		                        		output +=
		                        			"        // params.put(\"" + v.getName() + "\", value); // type " + v.getType().getStringType() + "\n";
		                        	}
		                        	output +=
		                				"        ProcessInstance processInstance = ksession.startProcess(\"" + process.getId() + "\", params);\n";
	                        	} else {
	                        		output +=
		                				"        ProcessInstance processInstance = ksession.startProcess(\"" + process.getId() + "\");\n";
	                        	}
	                        	output +=
	                				entry.getValue() +
	                				"        // do your checks here\n" +
	        						"        // for example, assertProcessInstanceCompleted(processInstance.getId(), ksession);\n" +
	        						"    }\n" +
	        						"\n";
                        	}
                        	output +="}";
                            packageFragment.createCompilationUnit(fileName + ".java", output, true, monitor);
                        } catch (Exception e) {
                            e.printStackTrace();
                            MessageDialog.openError(null, "Error", e.getMessage());
                        }
                    }
                };

                try {
                    new ProgressMonitorDialog(targetPart.getSite().getShell()).run(false, true, op);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    private boolean processNodes(String name, Node currentNode, String testCode, Map<String, String> cases, Map<String, String> ongoingCases) {
    	if (currentNode instanceof Split) {
    		Split split = (Split) currentNode;
    		switch (split.getType()) {
    			case Split.TYPE_AND:
    				boolean done = false;
    				String startTestCode = testCode;
    				int counter = 1;
    				for (Connection c: split.getDefaultOutgoingConnections()) {
    					if (processNodes(name + counter++, c.getTo(), startTestCode, cases, ongoingCases)) {
    						done = true;
    					}
    				}
    				if (!done) {
        				String implicitCompleteTestCode = startTestCode;
    					for (String ongoingCase: ongoingCases.values()) {
							implicitCompleteTestCode += ongoingCase.substring(startTestCode.length(), ongoingCase.length());
    					}
    					ongoingCases.clear();
    					ongoingCases.put(name, implicitCompleteTestCode);
    				}
    				return done;
    			case Split.TYPE_XOR:
    			case Split.TYPE_OR:
    				int i = 1;
    				done = true;
    				for (Connection c: split.getDefaultOutgoingConnections()) {
    					String newTestCode = testCode +
    						"        // please make sure that the following constraint is selected to node " + c.getTo().getName() + ":\n" +
							"        // " + split.getConstraint(c).getConstraint() + "\n";
    					if (!processNodes(name + "Constraint" + i++, c.getTo(), newTestCode, cases, ongoingCases)) {
    						done = false;
    					}
    				}
    				return done;
    			default:
    				throw new IllegalArgumentException("Unknown split type " + split.getType());
    		}
    	} else if (currentNode instanceof EndNode) {
    		EndNode endNode = (EndNode) currentNode;
    		if (endNode.isTerminate()) {
    			cases.put(name, testCode);
    			return true;
    		} else {
    			ongoingCases.put(name, testCode);
    			return false;
    		}
    	} else if (currentNode instanceof HumanTaskNode) {
    		HumanTaskNode taskNode = (HumanTaskNode) currentNode;
    		String actorId = (String) taskNode.getWork().getParameter("ActorId");
    		if (actorId == null) {
    			actorId = "";
    		}
    		String groupId = (String) taskNode.getWork().getParameter("GroupId");
    		if (groupId == null) {
    			groupId = "";
    		}
    		String[] actorIds = new String[0];
    		if (actorId.trim().length() > 0) {
    			actorIds = actorId.split(",");
    		}
    		String[] groupIds = new String[0];
    		if (groupId.trim().length() > 0) {
    			groupIds = groupId.split(",");
    		}
    		actorId = actorIds.length > 0 ? actorIds[0] : "";
    		if (firstHumanTask) {
	    		testCode +=
	    			"        // execute task\n" +
	    			"        String actorId = \"" + actorId + "\";\n" +
	    			"        List<TaskSummary> list = taskService.getTasksAssignedAsPotentialOwner(actorId, \"en-UK\");\n" +
	    			"        TaskSummary task = list.get(0);\n";
    		} else {
	    		testCode +=
	    			"        // execute task\n" +
	    			"        actorId = \"" + actorId + "\";\n" +
	    			"        list = taskService.getTasksAssignedAsPotentialOwner(actorId, \"en-UK\");\n" +
	    			"        task = list.get(0);\n";
    		}
    		if (actorIds.length > 1 || groupIds.length > 0) {
    			testCode +=
        			"        taskService.claim(task.getId(), actorId);\n";
    		}
    		if (firstHumanTask) {
	    		testCode +=
	    			"        taskService.start(task.getId(), actorId);\n" +
					"        Map<String, Object> results = new HashMap<String, Object>();\n" +
					"        // add results here\n";
	    		firstHumanTask = false;
    		} else {
	    		testCode +=
	    			"        taskService.start(task.getId(), actorId);\n" +
					"        results = new HashMap<String, Object>();\n" +
					"        // add results here\n";
    		}
    		for (Map.Entry<String, String> entry: taskNode.getOutMappings().entrySet()) {
    			String type = null;
    			VariableScope variableScope = (VariableScope) taskNode.resolveContext(VariableScope.VARIABLE_SCOPE, entry.getValue());
    			if (variableScope != null) {
    				type = variableScope.findVariable(entry.getValue()).getType().getStringType();
    			}
    			testCode +=
    				"        // results.put(\"" + entry.getKey() + "\", value);" + (type == null ? "" : " // type " + type) + "\n";
    		}
    		testCode +=
    			"        taskService.complete(task.getId(), actorId, results);\n" +
    			"\n";
    		return processNodes(name, ((NodeImpl) currentNode).getTo().getTo(), testCode, cases, ongoingCases);
    	} else if (currentNode instanceof WorkItemNode) {
    		WorkItemNode taskNode = (WorkItemNode) currentNode;
    		testCode +=
    			"        // if necessary, complete request for service task \"" + taskNode.getWork().getName() + "\"\n";
    		return processNodes(name, ((NodeImpl) currentNode).getTo().getTo(), testCode, cases, ongoingCases);
    	} else if (currentNode instanceof EventNode) {
    		EventNode eventNode = (EventNode) currentNode;
    		testCode +=
    			"        ksession.signalEvent(\"" + eventNode.getType() + "\", null, processInstance.getId());\n";
    		return processNodes(name, ((NodeImpl) currentNode).getTo().getTo(), testCode, cases, ongoingCases);
    	} else if (currentNode instanceof TimerNode) {
    		testCode +=
    			"        // wait for timer to expire\n" +
    		    "        // for example, try { Thread.sleep(delay); } catch (Exception e) { /* Do nothing */ }";
    		// TODO simulation time
    		return processNodes(name, ((NodeImpl) currentNode).getTo().getTo(), testCode, cases, ongoingCases);
    	} else if (currentNode instanceof ForEachNode) {
    		CompositeNode compositeNode = ((ForEachNode) currentNode).getCompositeNode();
    		testCode +=
    			"        // --> triggering each element in the collection:\n";
    		boolean done = true;
        	for (Node node: compositeNode.getNodes()) {
	    		if (node instanceof StartNode) {
	    			StartNode startNode = (StartNode) node;
	    			if (startNode.getTriggers() == null || startNode.getTriggers().isEmpty()) {
	    				done = processNodes(name, startNode.getTo().getTo(), testCode, cases, ongoingCases);
	    				break;
	    			}
	    		}
        	}
        	if (done) {
        		for (Map.Entry<String, String> c: cases.entrySet()) {
        			if (c.getKey().startsWith(name)) {
        				cases.put(c.getKey(), c.getValue() +
    	        			"        // <-- do this for one element in the collection:\n");
        			}
        		}
        		return true;
        	} else {
        		if (ongoingCases.size() == 1) {
        			testCode = ongoingCases.values().iterator().next() +
    					"        // <-- do this for each element in the collection:\n";
        			return processNodes(name + "Implicit", ((NodeImpl) currentNode).getTo().getTo(), testCode, cases, ongoingCases);
        		} else {
        			throw new IllegalArgumentException("Could not create implicit case: " + ongoingCases.size());
        		}
        	}
    	} else if (currentNode instanceof CompositeNode) {
    		CompositeNode compositeNode = (CompositeNode) currentNode;
    		boolean done = true;
        	for (Node node: compositeNode.getNodes()) {
	    		if (node instanceof StartNode) {
	    			StartNode startNode = (StartNode) node;
	    			if (startNode.getTriggers() == null || startNode.getTriggers().isEmpty()) {
	    				done = processNodes(name, startNode.getTo().getTo(), testCode, cases, ongoingCases);
	    				break;
	    			}
	    		}
        	}
        	if (done) {
        		return true;
        	} else {
        		if (ongoingCases.size() == 1) {
        			return processNodes(name + "Implicit", ((NodeImpl) currentNode).getTo().getTo(), ongoingCases.values().iterator().next(), cases, ongoingCases);
        		} else {
        			throw new IllegalArgumentException("Could not create implicit case: " + ongoingCases.size());
        		}
        	}
    	} else if (currentNode instanceof RuleSetNode) {
    		testCode +=
    			"        ksession.fireAllRules();\n";
    		return processNodes(name, ((NodeImpl) currentNode).getTo().getTo(), testCode, cases, ongoingCases);
    	} else if (currentNode instanceof SubProcessNode) {
    		SubProcessNode subProcessNode = (SubProcessNode) currentNode;
    		if (subProcessNode.isWaitForCompletion()) {
	    		testCode +=
        			"        // invoking subprocess " + subProcessNode.getProcessId() + ", if necessary make sure it is completed\n";
    		}
    		return processNodes(name, ((NodeImpl) currentNode).getTo().getTo(), testCode, cases, ongoingCases);
    	} else if (currentNode instanceof FaultNode) {
    		FaultNode faultNode = (FaultNode) currentNode;
    		testCode +=
    			"        // handle fault " + faultNode.getFaultName() + " if necessary\n";
    		return true;
    	} else if (currentNode instanceof Join) {
    		// TODO looping
    		Join join = (Join) currentNode;
    		switch (join.getType()) {
				case Join.TYPE_AND:
					// TODO: cannot just call processNodes as this will add it to the cases if an end is reached,
					// while it should also still include the work that is necessary to complete the other branches
		    		// processNodes(name, ((NodeImpl) currentNode).getTo().getTo(), testCode, cases, ongoingCases);
		    		// TODO: this isn't 100% correct, as a join should only wait for the other incoming connections,
		    		// not all other non-terminating connections, but not doing this would make test ignore the other
		    		// branches of the divering parallel gateway
		    		// return false;
					throw new IllegalArgumentException("Generation of tests that include a convering parallel gateway is not yet supported");
				case Join.TYPE_XOR:
		    		return processNodes(name, ((NodeImpl) currentNode).getTo().getTo(), testCode, cases, ongoingCases);
				default:
					throw new IllegalArgumentException("Unknown join type " + join.getType());
			}
    	} else if (currentNode instanceof NodeImpl) {
    		return processNodes(name, ((NodeImpl) currentNode).getTo().getTo(), testCode, cases, ongoingCases);
    	} else {
    		throw new IllegalArgumentException("Unknown node " + currentNode);
    	}

    }

    private static boolean containsHumanTasks(NodeContainer c) {
    	for (Node node: c.getNodes()) {
    		if (node instanceof HumanTaskNode) {
    			return true;
    		}
    		if (node instanceof NodeContainer) {
    			if (containsHumanTasks((NodeContainer) node)) {
    				return true;
    			}
    		}
    	}
    	return false;
    }

    private void containsServiceTasks(Set<String> result, NodeContainer c) {
    	for (Node node: c.getNodes()) {
    		if (node instanceof WorkItemNode && !(node instanceof HumanTaskNode)) {
    			result.add(((WorkItemNode) node).getWork().getName());
    		}
    		if (node instanceof NodeContainer) {
    			containsServiceTasks(result, (NodeContainer) node);
    		}
    	}
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Reconstruction
{
    internal class Startup
    {
        internal static void Main()
        {

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef FTDEBUG_H_
#define FTDEBUG_H_

#include <ft2build.h>
#include FT_CONFIG_CONFIG_H
#include FT_FREETYPE_H

FT_BEGIN_HEADER

  /* force the definition of FT_DEBUG_LEVEL_ERROR if FT_DEBUG_LEVEL_TRACE */
  /* is already defined; this simplifies the following #ifdefs            */
  /*                                                                      */
#ifdef FT_DEBUG_LEVEL_TRACE
#undef  FT_DEBUG_LEVEL_ERROR
#define FT_DEBUG_LEVEL_ERROR
#endif

  /**************************************************************************
   *
   * Define the trace enums as well as the trace levels array when they are
   * needed.
   *
   */

#ifdef FT_DEBUG_LEVEL_TRACE

#define FT_TRACE_DEF( x )  trace_ ## x ,

  /* defining the enumeration */
  typedef enum  FT_Trace_
  {
#include FT_INTERNAL_TRACE_H
    trace_count

  } FT_Trace;

  /* a pointer to the array of trace levels, */
  /* provided by `src/base/ftdebug.c'        */
  extern int*  ft_trace_levels;

#undef FT_TRACE_DEF

#endif /* FT_DEBUG_LEVEL_TRACE */

  /**************************************************************************
   *
   * Define the FT_TRACE macro
   *
   * IMPORTANT!
   *
   * Each component must define the macro FT_COMPONENT to a valid FT_Trace
   * value before using any TRACE macro.
   *
   */

#ifdef FT_DEBUG_LEVEL_TRACE

  /* we need two macros here to make cpp expand `FT_COMPONENT' */
#define FT_TRACE_COMP( x )   FT_TRACE_COMP_( x )
#define FT_TRACE_COMP_( x )  trace_ ## x

#define FT_TRACE( level, varformat )                                       \
          do                                                               \
          {                                                                \
            if ( ft_trace_levels[FT_TRACE_COMP( FT_COMPONENT )] >= level ) \
              FT_Message varformat;                                        \
          } while ( 0 )

#else /* !FT_DEBUG_LEVEL_TRACE */

#define FT_TRACE( level, varformat )  do { } while ( 0 )      /* nothing */

#endif /* !FT_DEBUG_LEVEL_TRACE */

  /**************************************************************************
   *
   * @function:
   *   FT_Trace_Get_Count
   *
   * @description:
   *   Return the number of available trace components.
   *
   * @return:
   *   The number of trace components.  0 if FreeType 2 is not built with
   *   FT_DEBUG_LEVEL_TRACE definition.
   *
   * @note:
   *   This function may be useful if you want to access elements of the
   *   internal trace levels array by an index.
   */
  FT_BASE( FT_Int )
  FT_Trace_Get_Count( void );

  /**************************************************************************
   *
   * @function:
   *   FT_Trace_Get_Name
   *
   * @description:
   *   Return the name of a trace component.
   *
   * @input:
   *   The index of the trace component.
   *
   * @return:
   *   The name of the trace component.  This is a statically allocated
   *   C~string, so do not free it after use.  `NULL` if FreeType is not
   *   built with FT_DEBUG_LEVEL_TRACE definition.
   *
   * @note:
   *   Use @FT_Trace_Get_Count to get the number of available trace
   *   components.
   */
  FT_BASE( const char* )
  FT_Trace_Get_Name( FT_Int  idx );

  /**************************************************************************
   *
   * @function:
   *   FT_Trace_Disable
   *
   * @description:
   *   Switch off tracing temporarily.  It can be activated again with
   *   @FT_Trace_Enable.
   */
  FT_BASE( void )
  FT_Trace_Disable( void );

  /**************************************************************************
   *
   * @function:
   *   FT_Trace_Enable
   *
   * @description:
   *   Activate tracing.  Use it after tracing has been switched off with
   *   @FT_Trace_Disable.
   */
  FT_BASE( void )
  FT_Trace_Enable( void );

  /**************************************************************************
   *
   * You need two opening and closing parentheses!
   *
   * Example: FT_TRACE0(( "Value is %i", foo ))
   *
   * Output of the FT_TRACEX macros is sent to stderr.
   *
   */

#define FT_TRACE0( varformat )  FT_TRACE( 0, varformat )
#define FT_TRACE1( varformat )  FT_TRACE( 1, varformat )
#define FT_TRACE2( varformat )  FT_TRACE( 2, varformat )
#define FT_TRACE3( varformat )  FT_TRACE( 3, varformat )
#define FT_TRACE4( varformat )  FT_TRACE( 4, varformat )
#define FT_TRACE5( varformat )  FT_TRACE( 5, varformat )
#define FT_TRACE6( varformat )  FT_TRACE( 6, varformat )
#define FT_TRACE7( varformat )  FT_TRACE( 7, varformat )

  /**************************************************************************
   *
   * Define the FT_ERROR macro.
   *
   * Output of this macro is sent to stderr.
   *
   */

#ifdef FT_DEBUG_LEVEL_ERROR

#define FT_ERROR( varformat )  FT_Message  varformat

#else  /* !FT_DEBUG_LEVEL_ERROR */

#define FT_ERROR( varformat )  do { } while ( 0 )      /* nothing */

#endif /* !FT_DEBUG_LEVEL_ERROR */

  /**************************************************************************
   *
   * Define the FT_ASSERT and FT_THROW macros.  The call to `FT_Throw` makes
   * it possible to easily set a breakpoint at this function.
   *
   */

#ifdef FT_DEBUG_LEVEL_ERROR

#define FT_ASSERT( condition )                                      \
          do                                                        \
          {                                                         \
            if ( !( condition ) )                                   \
              FT_Panic( "assertion failed on line %d of file %s\n", \
                        __LINE__, __FILE__ );                       \
          } while ( 0 )

#define FT_THROW( e )                                   \
          ( FT_Throw( FT_ERR_CAT( FT_ERR_PREFIX, e ),   \
                      __LINE__,                         \
                      __FILE__ )                      | \
            FT_ERR_CAT( FT_ERR_PREFIX, e )            )

#else /* !FT_DEBUG_LEVEL_ERROR */

#define FT_ASSERT( condition )  do { } while ( 0 )

#define FT_THROW( e )  FT_ERR_CAT( FT_ERR_PREFIX, e )

#endif /* !FT_DEBUG_LEVEL_ERROR */

  /**************************************************************************
   *
   * Define `FT_Message` and `FT_Panic` when needed.
   *
   */

#ifdef FT_DEBUG_LEVEL_ERROR

#include "stdio.h"  /* for vfprintf() */

  /* print a message */
  FT_BASE( void )
  FT_Message( const char*  fmt,
              ... );

  /* print a message and exit */
  FT_BASE( void )
  FT_Panic( const char*  fmt,
            ... );

  /* report file name and line number of an error */
  FT_BASE( int )
  FT_Throw( FT_Error     error,
            int          line,
            const char*  file );

#endif /* FT_DEBUG_LEVEL_ERROR */

  FT_BASE( void )
  ft_debug_init( void );

FT_END_HEADER

#endif /* FTDEBUG_H_ */

/* END */


text:
find . -name "*.pyc" -print | xargs rm

if [ -z "$VCAP_APP_PORT" ];
  then SERVER_PORT=5000;
  else SERVER_PORT="$VCAP_APP_PORT";
fi

echo [$0] port is------------------- $SERVER_PORT
python manage.py syncdb --noinput
echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'luyuhao627@gmail.com', 'admin')" | python manage.py shell

echo [$0] Starting Django Server...
python manage.py runserver 0.0.0.0:$SERVER_PORT --noreload


text:
'use babel'

import * as _ from 'lodash'
import { Disposable, CompositeDisposable } from 'atom'

export default class GrammarManager extends Disposable {
  constructor () {
    super(() => {
      this.disposables.dispose()
      this.grammars = new Set()
      this.grammarMap = new Map()
      this.checkedScopes = new Map()
    })
    this.disposables = new CompositeDisposable()
    this.grammars = new Set()
    this.grammarMap = new Map()
    this.checkedScopes = new Map()
  }

  getGrammar (textEditor) {
    return this.grammarMap.get(textEditor.getGrammar().scopeName)
  }

  getEmbeddedGrammar (scopeDescriptor) {
    let path = scopeDescriptor.getScopesArray().slice(1)
    let i = path.length
    while (i--) {
      const grammar = this.grammarMap.get(path[i])
      if (grammar) return grammar
    }
  }

  updateLanguage (textEditor) {
    const grammar = this.getGrammar(textEditor)
    if (grammar && grammar.findLanguageTags) {
      const l = grammar.findLanguageTags(textEditor)
      global.languageManager.setLanguages(textEditor, (l && l.length > 0) ? l : null, 'auto')
    }
  }

  isIgnored (scopeDescriptor) {
    let path = scopeDescriptor.getScopesArray()
    let i = path.length
    while (i--) {
      if (this.checkedScopes.has(path[i])) {
        const v = this.checkedScopes.get(path[i])
        return !(_.isFunction(v) ? v() : v)
      }
    }
    return true
  }

  consumeGrammar (grammars) {
    grammars = _.castArray(grammars)
    for (const grammar of grammars) {
      this.grammars.add(grammar)
      for (const scope of grammar.grammarScopes) {
        this.grammarMap.set(scope, grammar)
      }
      if (grammar.checkedScopes) {
        _.forEach(grammar.checkedScopes, (value, key) => this.checkedScopes.set(key, value))
      } else {
        _.forEach(grammar.grammarScopes, key => this.checkedScopes.set(key, true))
      }
    }
    let textEditor = atom.workspace.getActiveTextEditor()
    if (textEditor) global.languageManager.getLanguages(textEditor)
    // global.languageManager.updateDictionaries
    return new Disposable(() => {
      for (const grammar of grammars) {
        this.grammars.delete(grammar)
        for (const scope of grammar.grammarScopes) {
          this.grammarMap.delete(scope)
        }
        if (grammar.checkedScopes) {
          _.forEach(grammar.checkedScopes, (value, key) => this.checkedScopes.delete(key))
        } else {
          _.forEach(grammar.grammarScopes, key => this.checkedScopes.delete(key))
        }
      }
    })
  }
}


text:
package org.tatools.sunshine.testng;

import java.util.ArrayList;
import java.util.List;
import org.tatools.sunshine.core.Status;
import org.testng.ISuite;
import org.testng.ISuiteResult;
import org.testng.ITestContext;

/**
 * The class provides an implementation of the {@link Status} of TestNG execution.
 *
 * @author Dmytro Serdiuk (dmytro.serdiuk@gmail.com)
 * @version $Id$
 * @since 0.2
 */
public class TestNGStatus implements Status {

    private final short exit_code;
    private final List<ISuite> reports;
    private final List<Integer> counts;

    public TestNGStatus(int status, List<ISuite> suites) {
        this.exit_code = (short) status;
        this.reports = suites;
        this.counts = new ArrayList<>(3);
    }

    @Override
    public final short code() {
        return this.exit_code;
    }

    @Override
    public final int runCount() {
        this.calculate();
        return this.counts.get(0).intValue();
    }

    @Override
    public final int failureCount() {
        this.calculate();
        return this.counts.get(1).intValue();
    }

    @Override
    public final int ignoreCount() {
        this.calculate();
        return this.counts.get(2).intValue();
    }

    private void calculate() {
        if (!this.counts.isEmpty()) return;
        int passed = 0;
        int failed = 0;
        int skipped = 0;

        for (ISuite suite : this.reports) {
            for (ISuiteResult result : suite.getResults().values()) {
                final ITestContext testContext = result.getTestContext();
                passed += testContext.getPassedTests().size();
                failed += testContext.getFailedTests().size();
                skipped += testContext.getSkippedTests().size();
            }
        }
        this.counts.add(0, passed + failed + skipped);
        this.counts.add(1, failed);
        this.counts.add(2, skipped);
    }
}


text:
struct cmd_results *cmd_fullscreen(int argc, char **argv) {
	struct cmd_results *error = NULL;
	if ((error = checkarg(argc, "fullscreen", EXPECTED_AT_MOST, 2))) {
		return error;
	}
	if (!root->outputs->length) {
		return cmd_results_new(CMD_FAILURE,
				"Can't run this command while there's no outputs connected.");
	}
	struct sway_node *node = config->handler_context.node;
	struct sway_container *container = config->handler_context.container;
	struct sway_workspace *workspace = config->handler_context.workspace;
	if (node->type == N_WORKSPACE && workspace->tiling->length == 0) {
		return cmd_results_new(CMD_FAILURE,
				"Can't fullscreen an empty workspace");
	}

	// If in the scratchpad, operate on the highest container
	if (container && !container->workspace) {
		while (container->parent) {
			container = container->parent;
		}
	}

	bool is_fullscreen = false;
	for (struct sway_container *curr = container; curr; curr = curr->parent) {
		if (curr->fullscreen_mode != FULLSCREEN_NONE) {
			container = curr;
			is_fullscreen = true;
			break;
		}
	}

	bool global = false;
	bool enable = !is_fullscreen;

	if (argc >= 1) {
		if (strcasecmp(argv[0], "global") == 0) {
			global = true;
		} else {
			enable = parse_boolean(argv[0], is_fullscreen);
		}
	}

	if (argc >= 2) {
		global = strcasecmp(argv[1], "global") == 0;
	}

	if (enable && node->type == N_WORKSPACE) {
		// Wrap the workspace's children in a container so we can fullscreen it
		container = workspace_wrap_children(workspace);
		workspace->layout = L_HORIZ;
		seat_set_focus_container(config->handler_context.seat, container);
	}

	enum sway_fullscreen_mode mode = FULLSCREEN_NONE;
	if (enable) {
		mode = global ? FULLSCREEN_GLOBAL : FULLSCREEN_WORKSPACE;
	}

	container_set_fullscreen(container, mode);
	arrange_root();

	return cmd_results_new(CMD_SUCCESS, NULL);
}


text:
#ifndef _IPT_CLUSTERIP_H_target
#define _IPT_CLUSTERIP_H_target

#include <linux/types.h>

enum clusterip_hashmode {
    CLUSTERIP_HASHMODE_SIP = 0,
    CLUSTERIP_HASHMODE_SIP_SPT,
    CLUSTERIP_HASHMODE_SIP_SPT_DPT,
};

#define CLUSTERIP_HASHMODE_MAX CLUSTERIP_HASHMODE_SIP_SPT_DPT

#define CLUSTERIP_MAX_NODES 16

#define CLUSTERIP_FLAG_NEW 0x00000001

struct clusterip_config;

struct ipt_clusterip_tgt_info {

	__u32 flags;

	/* only relevant for new ones */
	__u8 clustermac[6];
	__u16 num_total_nodes;
	__u16 num_local_nodes;
	__u16 local_nodes[CLUSTERIP_MAX_NODES];
	__u32 hash_mode;
	__u32 hash_initval;

	/* Used internally by the kernel */
	struct clusterip_config *config;
};

#endif /*_IPT_CLUSTERIP_H_target*/


text:
require 'chefspec'

COOKBOOK_PATH = ENV['COOKBOOK_PATH'] || File.expand_path("../../cookbooks", __FILE__)

RSpec.configure do |config|
  config.cookbook_path = [COOKBOOK_PATH]

  config.tty   = true
  config.color = true
  config.order = 'random'
end


text:
'use strict';

/* eslint-env jest */
const assert = require('assert');
const path = require('path');
const fs = require('fs');

const run = require('../../run');
const parseChromeFlags = require('../../run').parseChromeFlags;
const fastConfig = {
  'extends': 'lighthouse:default',
  'settings': {
    'onlyAudits': ['viewport'],
  },
};

const getFlags = require('../../cli-flags').getFlags;

describe('CLI run', function() {
  it('runLighthouse completes a LH round trip', () => {
    const url = 'chrome://version';
    const filename = path.join(process.cwd(), 'run.ts.results.json');
    const timeoutFlag = `--max-wait-for-load=${9000}`;
    const flags = getFlags(`--output=json --output-path=${filename} ${timeoutFlag} ${url}`);
    return run.runLighthouse(url, flags, fastConfig).then(passedResults => {
      const {lhr} = passedResults;
      assert.ok(fs.existsSync(filename));
      const results = JSON.parse(fs.readFileSync(filename, 'utf-8'));
      assert.equal(results.audits.viewport.rawValue, false);

      // passed results match saved results
      assert.strictEqual(results.fetchTime, lhr.fetchTime);
      assert.strictEqual(results.url, lhr.url);
      assert.strictEqual(results.audits.viewport.rawValue, lhr.audits.viewport.rawValue);
      assert.strictEqual(
          Object.keys(results.audits).length,
          Object.keys(lhr.audits).length);
      assert.deepStrictEqual(results.timing, lhr.timing);

      fs.unlinkSync(filename);
    });
  }, 20 * 1000);
});

describe('flag coercing', () => {
  it('should force to array', () => {
    assert.deepStrictEqual(getFlags(`--only-audits foo chrome://version`).onlyAudits, ['foo']);
  });
});

describe('saveResults', () => {
  it('will quit early if we\'re in gather mode', async () => {
    const result = await run.saveResults(undefined, {gatherMode: true});
    assert.equal(result, undefined);
  });
});

describe('Parsing --chrome-flags', () => {
  it('returns boolean flags that are true as a bare flag', () => {
    assert.deepStrictEqual(parseChromeFlags('--debug'), ['--debug']);
  });

  it('returns boolean flags that are false with value', () => {
    assert.deepStrictEqual(parseChromeFlags('--debug=false'), ['--debug=false']);
  });

  it('returns empty when passed undefined', () => {
    assert.deepStrictEqual(parseChromeFlags(), []);
  });

  it('keeps --no-flags untouched, #3003', () => {
    assert.deepStrictEqual(parseChromeFlags('--no-sandbox'), ['--no-sandbox']);
  });

  it('handles numeric values', () => {
    assert.deepStrictEqual(parseChromeFlags('--log-level=0'), ['--log-level=0']);
  });

  it('handles flag values with spaces in them (#2817)', () => {
    assert.deepStrictEqual(
      parseChromeFlags('--user-agent="iPhone UA Test"'),
      ['--user-agent=iPhone UA Test']
    );

    assert.deepStrictEqual(
      parseChromeFlags('--host-resolver-rules="MAP www.example.org:443 127.0.0.1:8443"'),
      ['--host-resolver-rules=MAP www.example.org:443 127.0.0.1:8443']
    );
  });

  it('returns all flags as provided', () => {
    assert.deepStrictEqual(
      parseChromeFlags('--spaces="1 2 3 4" --debug=false --verbose --more-spaces="9 9 9"'),
      ['--spaces=1 2 3 4', '--debug=false', '--verbose', '--more-spaces=9 9 9']
    );
  });
});


text:
from django.conf.urls.defaults import handler404, handler500, include, \
                                        patterns, url
from django.conf import settings
from django.views.generic.simple import redirect_to

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

js_info_web = {
    'packages': ('sendinel')
}

urlpatterns = patterns('',
    url(r'^$', redirect_to, {'url': 'web/'}),
    (r'^groups/', include('sendinel.groups.urls')),
    (r'^infoservices/', include('sendinel.infoservices.urls')),
    (r'^medicine/', include('sendinel.medicines.urls')),
    (r'^web/', include('sendinel.web.urls')),
    (r'^notifications/', include('sendinel.notifications.urls')),
    (r'^i18n/', include('django.conf.urls.i18n')),
    url(r'^jsi18n/', 'django.views.i18n.javascript_catalog', js_info_web,
        name = "jsi18n"),
    # (r'^admin/jsi18n/$', 'django.views.i18n.javascript_catalog'),

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs'
    # to INSTALLED_APPS to enable admin documentation:
    (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    (r'^accounts/login/$', 'django.contrib.auth.views.login'),
)
if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^mediaweb/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': settings.MEDIA_ROOT}),
        (r'^admin_media/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': settings.MEDIA_ROOT}),
    )


text:
package org.apache.spark.api.python

import java.io.{File, PrintWriter}

import scala.io.Source

import org.scalatest.Matchers

import org.apache.spark.{SharedSparkContext, SparkConf, SparkFunSuite}
import org.apache.spark.internal.config.Kryo._
import org.apache.spark.serializer.KryoSerializer
import org.apache.spark.util.Utils

// This test suite uses SharedSparkContext because we need a SparkEnv in order to deserialize
// a PythonBroadcast:
class PythonBroadcastSuite extends SparkFunSuite with Matchers with SharedSparkContext {
  test("PythonBroadcast can be serialized with Kryo (SPARK-4882)") {
    val broadcastedString = "Hello, world!"
    def assertBroadcastIsValid(broadcast: PythonBroadcast): Unit = {
      val source = Source.fromFile(broadcast.path)
      val contents = source.mkString
      source.close()
      contents should be (broadcastedString)
    }
    withTempDir { tempDir =>
      val broadcastDataFile: File = {
        val file = new File(tempDir, "broadcastData")
        val printWriter = new PrintWriter(file)
        printWriter.write(broadcastedString)
        printWriter.close()
        file
      }
      val broadcast = new PythonBroadcast(broadcastDataFile.getAbsolutePath)
      assertBroadcastIsValid(broadcast)
      val conf = new SparkConf().set(KRYO_REGISTRATION_REQUIRED, true)
      val deserializedBroadcast =
        Utils.clone[PythonBroadcast](broadcast, new KryoSerializer(conf).newInstance())
      assertBroadcastIsValid(deserializedBroadcast)
    }
  }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>QUnit Logs Test Suite</title>
	<link rel="stylesheet" href="../qunit/qunit.css">

test markup


text:
<?php
if (!defined('IN_FINECMS')) exit('No permission resources');

return array(
    "DROP TABLE IF EXISTS `{prefix}shop_address`;",
	"CREATE TABLE IF NOT EXISTS `{prefix}shop_address` (
  `id` mediumint(8) NOT NULL AUTO_INCREMENT,
  `userid` mediumint(8) NOT NULL,
  `username` char(20) NOT NULL,
  `name` char(20) NOT NULL,
  `address` varchar(200) NOT NULL,
  `zip` char(6) NOT NULL,
  `tel` char(20) NOT NULL,
  `default_value` tinyint(1) NOT NULL COMMENT '默认地址',
  PRIMARY KEY (`id`),
  KEY `userid` (`userid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;",
    "DROP TABLE IF EXISTS `{prefix}shop_order`;",
	"CREATE TABLE IF NOT EXISTS `{prefix}shop_order` (
  `id` mediumint(8) NOT NULL AUTO_INCREMENT,
  `order_sn` bigint(20) NOT NULL COMMENT '订单编号',
  `userid` mediumint(8) NOT NULL,
  `username` char(20) NOT NULL,
  `items` text NOT NULL COMMENT '商品信息array格式',
  `addtime` int(10) NOT NULL COMMENT '订购时间',
  `paytime` int(10) NOT NULL COMMENT '支付时间',
  `sendtime` int(10) NOT NULL COMMENT '发货时间',
  `confirmtime` int(10) NOT NULL COMMENT '确认时间',
  `price` decimal(10,2) NOT NULL COMMENT '价格',
  `shipping_id` char(20) NOT NULL COMMENT '运单编号',
  `shipping_name` varchar(20) NOT NULL COMMENT '物流名称',
  `shipping_price` decimal(5,2) NOT NULL COMMENT '物流价格',
  `name` varchar(20) NOT NULL COMMENT '收货人',
  `address` varchar(200) NOT NULL COMMENT '收货地址',
  `zip` char(6) NOT NULL COMMENT '邮政编码',
  `tel` char(20) NOT NULL COMMENT '联系电话',
  `status` tinyint(1) NOT NULL,
  `adminlog` text NOT NULL COMMENT '操作日志',
  `note` varchar(200) NOT NULL COMMENT '备注信息',
  PRIMARY KEY (`id`),
  UNIQUE KEY `order_sn` (`order_sn`),
  KEY `userid` (`userid`),
  KEY `addtime` (`addtime`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;",
    "DROP TABLE IF EXISTS `{prefix}shop_shipping`;",
	"CREATE TABLE IF NOT EXISTS `{prefix}shop_shipping` (
  `id` smallint(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL COMMENT '物流名称',
  `price` decimal(5,2) NOT NULL COMMENT '运送价格',
  `description` text NOT NULL COMMENT '描述',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;"
);


text:
namespace Kvasir {
//General Purpose Input_Output Port (PH)
    namespace PhData{    ///<PH Data Register
        using Addr = Register::Address<0x400c0700,0xffffffe0,0x00000000,unsigned>;
        ///PH0
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ph0{};
        ///PH1
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ph1{};
        ///PH2
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ph2{};
        ///PH3
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> ph3{};
        ///PH4
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ph4{};
    }
    namespace PhCr{    ///<PH Control Register
        using Addr = Register::Address<0x400c0704,0xffffffe0,0x00000000,unsigned>;
        ///PH0C
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ph0c{};
        ///PH1C
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ph1c{};
        ///PH2C
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ph2c{};
        ///PH3C
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> ph3c{};
        ///PH4C
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ph4c{};
    }
    namespace PhFr1{    ///<PH Function Register 1
        using Addr = Register::Address<0x400c0708,0xfffffffa,0x00000000,unsigned>;
        ///PH0F1
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ph0f1{};
        ///PH2F1
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ph2f1{};
    }
    namespace PhFr3{    ///<PH Function Register 3
        using Addr = Register::Address<0x400c0710,0xffffffe3,0x00000000,unsigned>;
        ///PH2F3
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ph2f3{};
        ///PH3F3
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> ph3f3{};
        ///PH4F3
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ph4f3{};
    }
    namespace PhOd{    ///<PH Open Drain Control Register
        using Addr = Register::Address<0x400c0728,0xffffffe0,0x00000000,unsigned>;
        ///PH0OD
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ph0od{};
        ///PH1OD
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ph1od{};
        ///PH2OD
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ph2od{};
        ///PH3OD
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> ph3od{};
        ///PH4OD
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ph4od{};
    }
    namespace PhPup{    ///<PH Pull-Up Control Register
        using Addr = Register::Address<0x400c072c,0xffffffe0,0x00000000,unsigned>;
        ///PH0UP
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ph0up{};
        ///PH1UP
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ph1up{};
        ///PH2UP
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ph2up{};
        ///PH3UP
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> ph3up{};
        ///PH4UP
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ph4up{};
    }
    namespace PhIe{    ///<PH Input Enable Control Register
        using Addr = Register::Address<0x400c0738,0xffffffe0,0x00000000,unsigned>;
        ///PH0IE
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ph0ie{};
        ///PH1IE
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ph1ie{};
        ///PH2IE
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ph2ie{};
        ///PH3IE
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> ph3ie{};
        ///PH4IE
        constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ph4ie{};
    }
}


text:
package com.android.supervolley.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Named pair for a form-encoded request.
 *

 * Values are converted to strings using {@link String#valueOf(Object)} and then form URL encoded.
 * {@code null} values are ignored. Passing a {@link java.util.List List} or array will result in a
 * field pair for each non-{@code null} item.
 *

 * Simple Example:
 *

 * @FormUrlEncoded
 * @POST("/")
 * Call<ResponseBody> example(
 *     @Field("name") String name,
 *     @Field("occupation") String occupation);
 *

 * Calling with {@code foo.example("Bob Smith", "President")} yields a request body of
 * {@code name=Bob+Smith&occupation=President}.
 *

 * Array/Varargs Example:
 *

 * @FormUrlEncoded
 * @POST("/list")
 * Call<ResponseBody> example(@Field("name") String... names);
 *

 * Calling with {@code foo.example("Bob Smith", "Jane Doe")} yields a request body of
 * {@code name=Bob+Smith&name=Jane+Doe}.
 *
 * @see FormUrlEncoded
 * @see FieldMap
 */
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface Field {
    String value();

    /**
     * Specifies whether the {@linkplain #value() name} and value are already URL encoded.
     */
    boolean encoded() default false;
}


text:
package akkeeper.master.route

import java.util.concurrent.TimeUnit

import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.testkit.{ImplicitSender, TestKit}
import akka.util.Timeout
import akkeeper.api._
import org.scalatest.{BeforeAndAfterAll, FlatSpecLike, Matchers}

class ContainerControllerSpec(testSystem: ActorSystem) extends TestKit(testSystem)
  with FlatSpecLike with Matchers with ImplicitSender with RestTestUtils
  with DeployApiJsonProtocol with ContainerApiJsonProtocol with BeforeAndAfterAll {

  def this() = this(ActorSystem("ContainerControllerSpec"))

  override protected def afterAll(): Unit = {
    system.terminate()
    super.afterAll()
  }

  def createContainerDefinition(name: String): ContainerDefinition = {
    val memory = 1024
    val cpus = 1
    ContainerDefinition(name, cpus = cpus, memory = memory, actors = Seq.empty)
  }

  "Container Controller" should "return container by its ID" in {
    val controller = ContainerController(self)
    withHttpServer(controller.route) { restPort =>
      val response = get[ContainerGetResult]("/containers/containerName", restPort)

      val request = expectMsgClass(classOf[GetContainer])
      request.name shouldBe "containerName"
      val getResult = ContainerGetResult(request.requestId,
        createContainerDefinition("containerName"))
      lastSender ! getResult

      val (code, actualResult) = await(response)
      code shouldBe StatusCodes.OK.intValue
      actualResult shouldBe getResult
    }
  }

  it should "return 404 if the request container was not found" in {
    val controller = ContainerController(self)
    withHttpServer(controller.route) { restPort =>
      val response = get[ContainerNotFound]("/containers/containerName", restPort)

      val request = expectMsgClass(classOf[GetContainer])
      request.name shouldBe "containerName"
      val notFound = ContainerNotFound(request.requestId, "containerName")
      lastSender ! notFound

      val (code, actualResult) = await(response)
      code shouldBe StatusCodes.NotFound.intValue
      actualResult shouldBe notFound
    }
  }

  it should "return all available containers" in {
    val controller = ContainerController(self)
    withHttpServer(controller.route) { restPort =>
      val response = get[ContainersList]("/containers/", restPort)

      val request = expectMsgClass(classOf[GetContainers])
      val list = ContainersList(request.requestId, Seq("containerName"))
      lastSender ! list

      val (code, actualResult) = await(response)
      code shouldBe StatusCodes.OK.intValue
      actualResult shouldBe list
    }
  }

  it should "fail if unexpected error occurred" in {
    val timeoutMilliseconds = 100
    implicit val timeout = Timeout(timeoutMilliseconds, TimeUnit.MILLISECONDS)
    val controller = ContainerController(self)
    withHttpServer(controller.route) { restPort =>
      val response = getRaw("/containers/", restPort)

      expectMsgClass(classOf[GetContainers])

      val (code, _) = await(response)
      code shouldBe StatusCodes.InternalServerError.intValue
    }
  }

  it should "fail if the unexpected response arrives from the service" in {
    val controller = ContainerController(self)
    withHttpServer(controller.route) { restPort =>
      val response = getRaw("/containers/", restPort)

      val request = expectMsgClass(classOf[GetContainers])
      lastSender ! InstancesList(request.requestId, Seq.empty)

      val (code, _) = await(response)
      code shouldBe StatusCodes.InternalServerError.intValue
    }
  }
}


text:
function ClientInputManager() {
  this.events = {};
  this.listen();
}

ClientInputManager.prototype.on = function (event, callback) {
  if (!this.events[event]) {
    this.events[event] = [];
  }
  this.events[event].push(callback);
};

ClientInputManager.prototype.emit = function (event, data) {
  var callbacks = this.events[event];
  if (callbacks) {
    callbacks.forEach(function (callback) {
      callback(data);
    });
  }
};

ClientInputManager.prototype.highLight = function(platform) {
  var platformField = document.getElementById(platform);
  var allPlatforms = document.getElementsByClassName("member");
  this.setColor(platformField, allPlatforms);
}

ClientInputManager.prototype.setColor = function(selected, others) {
  selected.style.backgroundColor = '#e1a011';
  selected.style.color = 'white';
  selected.style['box-shadow'] = '0px 1px 0px #AFA586';

  for (var i = 0; i < others.length; i++ ){
    if (others[i] != selected){
      others[i].style.backgroundColor = '#FAEBCA';
      others[i].style['box-shadow'] = 'none';
      others[i].style.color = 'rgba(0, 0, 0, 0.70)';
    };
  };
}

ClientInputManager.prototype.listen = function () {
  var self = this;

  var pusher = new Pusher('514e04bbf50ba9b0b0b6', {
    authTransport: 'jsonp',
    authEndpoint: 'http://mysterious-forest-1989.herokuapp.com/pusher/auth'
  });

  var channel = pusher.subscribe('private-bnr_2048_channel');

  channel.bind('client-send_direction', function(data) {
    var map = {
      "up": 0, // Up
      "right": 1, // Right
      "down": 2, // Down
      "left": 3, // Left
    };

    var mapped = map[data.direction];
    self.emit("move", mapped);
    self.highLight(data.name);
  });

  var retry = document.querySelector(".retry-button");
  retry.addEventListener("click", this.restart.bind(this));
  retry.addEventListener("touchend", this.restart.bind(this));

  var keepPlaying = document.querySelector(".keep-playing-button");
  keepPlaying.addEventListener("click", this.keepPlaying.bind(this));
  keepPlaying.addEventListener("touchend", this.keepPlaying.bind(this));

  // Listen to swipe events
  var touchStartClientX, touchStartClientY;
  var gameContainer = document.getElementsByClassName("game-container")[0];

  gameContainer.addEventListener("touchstart", function (event) {
    if (event.touches.length > 1) return;

    touchStartClientX = event.touches[0].clientX;
    touchStartClientY = event.touches[0].clientY;
    event.preventDefault();
  });

  gameContainer.addEventListener("touchmove", function (event) {
    event.preventDefault();
  });

  gameContainer.addEventListener("touchend", function (event) {
    if (event.touches.length > 0) return;

    var dx = event.changedTouches[0].clientX - touchStartClientX;
    var absDx = Math.abs(dx);

    var dy = event.changedTouches[0].clientY - touchStartClientY;
    var absDy = Math.abs(dy);

    if (Math.max(absDx, absDy) > 10) {
      // (right : left) : (down : up)
      self.emit("move", absDx > absDy ? (dx > 0 ? 1 : 3) : (dy > 0 ? 2 : 0));
    }
  });
};

ClientInputManager.prototype.restart = function (event) {
  event.preventDefault();
  this.emit("restart");
};

ClientInputManager.prototype.keepPlaying = function (event) {
  event.preventDefault();
  this.emit("keepPlaying");
};


text:
using System;

namespace SeraphimEngine.Exceptions
{
    /// <summary>
    /// Class ScriptManagerInitializationException.
    /// </summary>
    [Serializable]
    public class ScriptManagerInitializationException : Exception
    {
    }
}


text:
const express = require('express')
const app = require('../../app.js')
const router = express.Router()

const auth = require('../auth')
if (auth.routes) {
  router.use(auth.routes)
}

const access = require('../access')
if (access.routes) {
  router.use(access.routes)
}

if (app.opts.production === false) {
  router.use(require('./post-adduser'))
}

router.use(require('./all-docs'))
router.use(require('./bulk-get'))
router.use(require('./local'))
router.use(require('./get-root'))
router.use(require('./get-database'))
router.use(require('./revs-diff'))
router.use(require('./bulk-docs'))
router.use(require('./changes'))
router.use(require('./delete-document'))
router.use(require('./put-attachment'))
router.use(require('./delete-attachment'))
router.use(require('./get-attachment'))
router.use(require('./get-document'))
router.use(require('./insert-document'))
router.use(require('./update-document'))

module.exports = router


text:
pre
  code
    include javascript-new-lines.js


text:
from __future__ import absolute_import, division, print_function

__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: kubevirt_rs

short_description: Manage KubeVirt virtual machine replica sets

description:
    - Use Openshift Python SDK to manage the state of KubeVirt virtual machine replica sets.

version_added: "2.8"

author: KubeVirt Team (@kubevirt)

options:
    state:
        description:
            - Create or delete virtual machine replica sets.
        default: "present"
        choices:
            - present
            - absent
        type: str
    name:
        description:
            - Name of the virtual machine replica set.
        required: true
        type: str
    namespace:
        description:
            - Namespace where the virtual machine replica set exists.
        required: true
        type: str
    selector:
        description:
            - "Selector is a label query over a set of virtual machine."
        required: true
        type: dict
    replicas:
        description:
            - Number of desired pods. This is a pointer to distinguish between explicit zero and not specified.
            - Replicas defaults to 1 if newly created replica set.
        type: int

extends_documentation_fragment:
  - k8s_auth_options
  - kubevirt_vm_options
  - kubevirt_common_options

requirements:
  - python >= 2.7
  - openshift >= 0.8.2
'''

EXAMPLES = '''
- name: Create virtual machine replica set 'myvmir'
  kubevirt_rs:
      state: presnet
      name: myvmir
      namespace: vms
      wait: true
      replicas: 3
      memory: 64M
      labels:
        myvmi: myvmi
      selector:
        matchLabels:
            myvmi: myvmi
      disks:
         - name: containerdisk
           volume:
             containerDisk:
               image: kubevirt/cirros-container-disk-demo:latest
               path: /custom-disk/cirros.img
           disk:
             bus: virtio

- name: Remove virtual machine replica set 'myvmir'
  kubevirt_rs:
      state: absent
      name: myvmir
      namespace: vms
      wait: true
'''

RETURN = '''
kubevirt_rs:
  description:
    - The virtual machine virtual machine replica set managed by the user.
    - "This dictionary contains all values returned by the KubeVirt API all options
       are described here U(https://kubevirt.io/api-reference/master/definitions.html#_v1_virtualmachineinstance)"
  returned: success
  type: complex
  contains: {}
'''

import copy
import traceback

from ansible.module_utils.k8s.common import AUTH_ARG_SPEC

from ansible.module_utils.kubevirt import (
    virtdict,
    KubeVirtRawModule,
    VM_COMMON_ARG_SPEC,
)

KIND = 'VirtualMachineInstanceReplicaSet'
VMIR_ARG_SPEC = {
    'replicas': {'type': 'int'},
    'selector': {'type': 'dict'},
}

class KubeVirtVMIRS(KubeVirtRawModule):

    @property
    def argspec(self):
        """ argspec property builder """
        argument_spec = copy.deepcopy(AUTH_ARG_SPEC)
        argument_spec.update(copy.deepcopy(VM_COMMON_ARG_SPEC))
        argument_spec.update(copy.deepcopy(VMIR_ARG_SPEC))
        return argument_spec

    def wait_for_replicas(self, replicas):
        """ Wait for ready_replicas to equal the requested number of replicas. """
        resource = self.find_supported_resource(KIND)
        return_obj = None

        for event in resource.watch(namespace=self.namespace, timeout=self.params.get('wait_timeout')):
            entity = event['object']
            if entity.metadata.name != self.name:
                continue
            status = entity.get('status', {})
            readyReplicas = status.get('readyReplicas', 0)
            if readyReplicas == replicas:
                return_obj = entity
                break

        if not return_obj:
            self.fail_json(msg="Error fetching the patched object. Try a higher wait_timeout value.")
        if replicas and return_obj.status.readyReplicas is None:
            self.fail_json(msg="Failed to fetch the number of ready replicas. Try a higher wait_timeout value.")
        if replicas and return_obj.status.readyReplicas != replicas:
            self.fail_json(msg="Number of ready replicas is {0}. Failed to reach {1} ready replicas within "
                               "the wait_timeout period.".format(return_obj.status.ready_replicas, replicas))
        return return_obj.to_dict()

    def execute_module(self):
        # Parse parameters specific for this module:
        definition = virtdict()
        selector = self.params.get('selector')
        replicas = self.params.get('replicas')

        if selector:
            definition['spec']['selector'] = selector

        if replicas is not None:
            definition['spec']['replicas'] = replicas

        # Execute the CURD of VM:
        template = definition['spec']['template']
        dummy, definition = self.construct_vm_definition(KIND, definition, template)
        result_crud = self.execute_crud(KIND, definition)
        changed = result_crud['changed']
        result = result_crud.pop('result')

        # When creating a new VMIRS object without specifying `replicas`, assume it's '1' to make the
        # wait logic work correctly
        if changed and result_crud['method'] == 'create' and replicas is None:
            replicas = 1

        # Wait for the new number of ready replicas after a CRUD update
        # Note1: doesn't work correctly when reducing number of replicas due to how VMIRS works (as of kubevirt 1.5.0)
        # Note2: not the place to wait for the VMIs to get deleted when deleting the VMIRS object; that *might* be
        #        achievable in execute_crud(); keywords: orphanDependents, propagationPolicy, DeleteOptions
        if self.params.get('wait') and replicas is not None and self.params.get('state') == 'present':
            result = self.wait_for_replicas(replicas)

        # Return from the module:
        self.exit_json(**{
            'changed': changed,
            'kubevirt_rs': result,
            'result': result_crud,
        })

def main():
    module = KubeVirtVMIRS()
    try:
        module.execute_module()
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())

if __name__ == '__main__':
    main()


text:
class CreateEmailQueues < ActiveRecord::Migration
  def self.up
    create_table :email_queues do |t|
      t.integer :person_id
      t.text :email
      t.integer :application_status_type_id

      t.timestamps
    end
  end

  def self.down
    drop_table :email_queues
  end
end


text:
package org.pentaho.di.core.database;

import org.junit.Before;
import org.junit.Test;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaBigNumber;
import org.pentaho.di.core.row.value.ValueMetaBoolean;
import org.pentaho.di.core.row.value.ValueMetaDate;
import org.pentaho.di.core.row.value.ValueMetaInteger;
import org.pentaho.di.core.row.value.ValueMetaInternetAddress;
import org.pentaho.di.core.row.value.ValueMetaNumber;
import org.pentaho.di.core.row.value.ValueMetaString;
import org.pentaho.di.core.row.value.ValueMetaTimestamp;

import java.net.MalformedURLException;
import java.net.URL;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.pentaho.di.core.database.Hive2DatabaseMeta.URL_PREFIX;

/**
 * Created by bryan on 10/20/15.
 */
public class ImpalaDatabaseMetaTest {
  private ImpalaDatabaseMeta impalaDatabaseMeta;

  @Before
  public void setup() throws Throwable {
    impalaDatabaseMeta = new ImpalaDatabaseMeta();
  }

  @Test
  public void testVersionConstructor() throws Throwable {
    int majorVersion = 22;
    int minorVersion = 33;
    impalaDatabaseMeta = new ImpalaDatabaseMeta( majorVersion, minorVersion );
    assertEquals( Integer.valueOf( majorVersion ), impalaDatabaseMeta.driverMajorVersion );
    assertEquals( Integer.valueOf( minorVersion ), impalaDatabaseMeta.driverMinorVersion );
  }

  @Test
  public void testGetAccessTypeList() {
    assertArrayEquals( new int[] { DatabaseMeta.TYPE_ACCESS_NATIVE }, impalaDatabaseMeta.getAccessTypeList() );
  }

  @Test
  public void testGetDriverClass() {
    assertEquals( ImpalaDatabaseMeta.DRIVER_CLASS_NAME, impalaDatabaseMeta.getDriverClass() );
  }

  @Test
  public void testGetFieldDefinitionBoolean() {
    assertGetFieldDefinition( new ValueMetaBoolean(), "boolName", "BOOLEAN" );
  }

  @Test
  public void testGetFieldDefinitionDate() {
    impalaDatabaseMeta.driverMajorVersion = 0;
    impalaDatabaseMeta.driverMinorVersion = 8;
    assertGetFieldDefinition( new ValueMetaDate(), "dateName", "TIMESTAMP" );
  }

  @Test( expected = IllegalArgumentException.class )
  public void testGetFieldDefinitionDateUnsupported() {
    impalaDatabaseMeta.driverMajorVersion = 0;
    impalaDatabaseMeta.driverMinorVersion = 7;
    assertGetFieldDefinition( new ValueMetaDate(), "dateName", "TIMESTAMP" );
  }

  @Test
  public void testGetFieldDefinitionTimestamp() {
    impalaDatabaseMeta.driverMajorVersion = 0;
    impalaDatabaseMeta.driverMinorVersion = 8;
    assertGetFieldDefinition( new ValueMetaTimestamp(), "timestampName", "TIMESTAMP" );
  }

  @Test( expected = IllegalArgumentException.class )
  public void testGetFieldDefinitionUnsupported() {
    impalaDatabaseMeta.driverMajorVersion = 0;
    impalaDatabaseMeta.driverMinorVersion = 7;
    assertGetFieldDefinition( new ValueMetaTimestamp(), "timestampName", "TIMESTAMP" );
  }

  @Test
  public void testGetFieldDefinitionString() {
    assertGetFieldDefinition( new ValueMetaString(), "stringName", "STRING" );
  }

  @Test
  public void testGetFieldDefinitionNumber() {
    String numberName = "numberName";
    ValueMetaInterface valueMetaInterface = new ValueMetaNumber();
    valueMetaInterface.setName( numberName );
    valueMetaInterface.setPrecision( 0 );
    valueMetaInterface.setLength( 9 );
    assertGetFieldDefinition( valueMetaInterface, "INT" );

    valueMetaInterface.setLength( 18 );
    assertGetFieldDefinition( valueMetaInterface, "BIGINT" );

    valueMetaInterface.setLength( 19 );
    assertGetFieldDefinition( valueMetaInterface, "FLOAT" );

    valueMetaInterface.setPrecision( 10 );
    valueMetaInterface.setLength( 16 );
    assertGetFieldDefinition( valueMetaInterface, "FLOAT" );

    valueMetaInterface.setLength( 15 );
    assertGetFieldDefinition( valueMetaInterface, "DOUBLE" );
  }

  @Test
  public void testGetFieldDefinitionInteger() {
    String integerName = "integerName";
    ValueMetaInterface valueMetaInterface = new ValueMetaInteger();
    valueMetaInterface.setName( integerName );
    valueMetaInterface.setPrecision( 0 );
    valueMetaInterface.setLength( 9 );
    assertGetFieldDefinition( valueMetaInterface, "INT" );

    valueMetaInterface.setLength( 18 );
    assertGetFieldDefinition( valueMetaInterface, "BIGINT" );

    valueMetaInterface.setLength( 19 );
    assertGetFieldDefinition( valueMetaInterface, "FLOAT" );
  }

  @Test
  public void testGetFieldDefinitionBigNumber() {
    String bigNumberName = "bigNumberName";
    ValueMetaInterface valueMetaInterface = new ValueMetaBigNumber();
    valueMetaInterface.setName( bigNumberName );
    valueMetaInterface.setPrecision( 0 );
    valueMetaInterface.setLength( 9 );
    assertGetFieldDefinition( valueMetaInterface, "INT" );

    valueMetaInterface.setLength( 18 );
    assertGetFieldDefinition( valueMetaInterface, "BIGINT" );

    valueMetaInterface.setLength( 19 );
    assertGetFieldDefinition( valueMetaInterface, "FLOAT" );

    valueMetaInterface.setPrecision( 10 );
    valueMetaInterface.setLength( 16 );
    assertGetFieldDefinition( valueMetaInterface, "FLOAT" );

    valueMetaInterface.setLength( 15 );
    assertGetFieldDefinition( valueMetaInterface, "DOUBLE" );
  }

  @Test
  public void testGetFieldDefinition() {
    assertGetFieldDefinition( new ValueMetaInternetAddress(), "internetAddressName", "" );
  }

  @Test
  public void testGetURL() throws KettleDatabaseException, MalformedURLException {
    String testHostname = "testHostname";
    int port = 9429;
    String testDbName = "testDbName";
    String urlString = impalaDatabaseMeta.getURL( testHostname, "" + port, testDbName );
    assertTrue( urlString.startsWith( URL_PREFIX ) );
    // Use known prefix
    urlString = "http://" + urlString.substring( URL_PREFIX.length() );
    URL url = new URL( urlString );
    assertEquals( testHostname, url.getHost() );
    assertEquals( port, url.getPort() );
    assertEquals( "/" + testDbName + ImpalaDatabaseMeta.AUTH_NO_SASL, url.getPath() );
  }

  @Test
  public void testGetURLPrincipal() throws KettleDatabaseException, MalformedURLException {
    String testHostname = "testHostname";
    int port = 9429;
    String testDbName = "testDbName";
    impalaDatabaseMeta.getAttributes().put( "principal", "testP" );
    String urlString = impalaDatabaseMeta.getURL( testHostname, "" + port, testDbName );
    assertTrue( urlString.startsWith( URL_PREFIX ) );
    // Use known prefix
    urlString = "http://" + urlString.substring( URL_PREFIX.length() );
    URL url = new URL( urlString );
    assertEquals( testHostname, url.getHost() );
    assertEquals( port, url.getPort() );
    assertEquals( "/" + testDbName, url.getPath() );

    impalaDatabaseMeta.getAttributes().remove( "principal" );
    impalaDatabaseMeta.getAttributes()
      .put( ImpalaDatabaseMeta.ATTRIBUTE_PREFIX_EXTRA_OPTION + impalaDatabaseMeta.getPluginId() + ".principal",
        "testP" );
    urlString = impalaDatabaseMeta.getURL( testHostname, "" + port, testDbName );
    assertTrue( urlString.startsWith( URL_PREFIX ) );
    // Use known prefix
    urlString = "http://" + urlString.substring( URL_PREFIX.length() );
    url = new URL( urlString );
    assertEquals( testHostname, url.getHost() );
    assertEquals( port, url.getPort() );
    assertEquals( "/" + testDbName, url.getPath() );
  }

  @Test
  public void testGetURLEmptyPort() throws KettleDatabaseException, MalformedURLException {
    String testHostname = "testHostname";
    String testDbName = "testDbName";
    String urlString = impalaDatabaseMeta.getURL( testHostname, "", testDbName );
    assertTrue( urlString.startsWith( URL_PREFIX ) );
    // Use known prefix
    urlString = "http://" + urlString.substring( URL_PREFIX.length() );
    URL url = new URL( urlString );
    assertEquals( testHostname, url.getHost() );
    assertEquals( impalaDatabaseMeta.getDefaultDatabasePort(), url.getPort() );
    assertEquals( "/" + testDbName + ImpalaDatabaseMeta.AUTH_NO_SASL, url.getPath() );
  }

  @Test
  public void testGetUsedLibraries() {
    assertArrayEquals( new String[] { ImpalaDatabaseMeta.JAR_FILE }, impalaDatabaseMeta.getUsedLibraries() );
  }

  @Test
  public void testGetDefaultDatabasePort() {
    assertEquals( ImpalaDatabaseMeta.DEFAULT_PORT, impalaDatabaseMeta.getDefaultDatabasePort() );
  }

  private void assertGetFieldDefinition( ValueMetaInterface valueMetaInterface, String name, String expectedType ) {
    valueMetaInterface = valueMetaInterface.clone();
    valueMetaInterface.setName( name );
    assertGetFieldDefinition( valueMetaInterface, expectedType );
  }

  private void assertGetFieldDefinition( ValueMetaInterface valueMetaInterface, String expectedType ) {
    assertEquals( expectedType, impalaDatabaseMeta.getFieldDefinition( valueMetaInterface, null, null, false, false,
      false ) );
    assertEquals( valueMetaInterface.getName() + " " + expectedType,
      impalaDatabaseMeta.getFieldDefinition( valueMetaInterface, null, null, false, true, false ) );
  }
}


text:
// This file is automatically generated.

package adila.db;

/*
 * Hisense EG98
 *
 * DEVICE: EG98TW
 * MODEL: EG98
 */
final class eg98tw_eg98 {
    public static final String DATA = "Hisense|EG98|";
}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.androidmanagement.v1.model;

/**
 * Information about security related device settings on device.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Android Management API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class DeviceSettings extends com.google.api.client.json.GenericJson {

  /**
   * Whether ADB (https://developer.android.com/studio/command-line/adb.html) is enabled on the
   * device.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean adbEnabled;

  /**
   * Whether developer mode is enabled on the device.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean developmentSettingsEnabled;

  /**
   * Encryption status from DevicePolicyManager.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String encryptionStatus;

  /**
   * Whether the device is secured with PIN/password.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean isDeviceSecure;

  /**
   * Whether the storage encryption is enabled.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean isEncrypted;

  /**
   * Whether installing apps from unknown sources is enabled.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean unknownSourcesEnabled;

  /**
   * Whether Google Play Protect verification (https://support.google.com/accounts/answer/2812853)
   * is enforced on the device.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Boolean verifyAppsEnabled;

  /**
   * Whether ADB (https://developer.android.com/studio/command-line/adb.html) is enabled on the
   * device.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getAdbEnabled() {
    return adbEnabled;
  }

  /**
   * Whether ADB (https://developer.android.com/studio/command-line/adb.html) is enabled on the
   * device.
   * @param adbEnabled adbEnabled or {@code null} for none
   */
  public DeviceSettings setAdbEnabled(java.lang.Boolean adbEnabled) {
    this.adbEnabled = adbEnabled;
    return this;
  }

  /**
   * Whether developer mode is enabled on the device.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getDevelopmentSettingsEnabled() {
    return developmentSettingsEnabled;
  }

  /**
   * Whether developer mode is enabled on the device.
   * @param developmentSettingsEnabled developmentSettingsEnabled or {@code null} for none
   */
  public DeviceSettings setDevelopmentSettingsEnabled(java.lang.Boolean developmentSettingsEnabled) {
    this.developmentSettingsEnabled = developmentSettingsEnabled;
    return this;
  }

  /**
   * Encryption status from DevicePolicyManager.
   * @return value or {@code null} for none
   */
  public java.lang.String getEncryptionStatus() {
    return encryptionStatus;
  }

  /**
   * Encryption status from DevicePolicyManager.
   * @param encryptionStatus encryptionStatus or {@code null} for none
   */
  public DeviceSettings setEncryptionStatus(java.lang.String encryptionStatus) {
    this.encryptionStatus = encryptionStatus;
    return this;
  }

  /**
   * Whether the device is secured with PIN/password.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIsDeviceSecure() {
    return isDeviceSecure;
  }

  /**
   * Whether the device is secured with PIN/password.
   * @param isDeviceSecure isDeviceSecure or {@code null} for none
   */
  public DeviceSettings setIsDeviceSecure(java.lang.Boolean isDeviceSecure) {
    this.isDeviceSecure = isDeviceSecure;
    return this;
  }

  /**
   * Whether the storage encryption is enabled.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getIsEncrypted() {
    return isEncrypted;
  }

  /**
   * Whether the storage encryption is enabled.
   * @param isEncrypted isEncrypted or {@code null} for none
   */
  public DeviceSettings setIsEncrypted(java.lang.Boolean isEncrypted) {
    this.isEncrypted = isEncrypted;
    return this;
  }

  /**
   * Whether installing apps from unknown sources is enabled.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getUnknownSourcesEnabled() {
    return unknownSourcesEnabled;
  }

  /**
   * Whether installing apps from unknown sources is enabled.
   * @param unknownSourcesEnabled unknownSourcesEnabled or {@code null} for none
   */
  public DeviceSettings setUnknownSourcesEnabled(java.lang.Boolean unknownSourcesEnabled) {
    this.unknownSourcesEnabled = unknownSourcesEnabled;
    return this;
  }

  /**
   * Whether Google Play Protect verification (https://support.google.com/accounts/answer/2812853)
   * is enforced on the device.
   * @return value or {@code null} for none
   */
  public java.lang.Boolean getVerifyAppsEnabled() {
    return verifyAppsEnabled;
  }

  /**
   * Whether Google Play Protect verification (https://support.google.com/accounts/answer/2812853)
   * is enforced on the device.
   * @param verifyAppsEnabled verifyAppsEnabled or {@code null} for none
   */
  public DeviceSettings setVerifyAppsEnabled(java.lang.Boolean verifyAppsEnabled) {
    this.verifyAppsEnabled = verifyAppsEnabled;
    return this;
  }

  @Override
  public DeviceSettings set(String fieldName, Object value) {
    return (DeviceSettings) super.set(fieldName, value);
  }

  @Override
  public DeviceSettings clone() {
    return (DeviceSettings) super.clone();
  }

}


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Configuration;
using osu.Framework.Screens;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Primitives;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Modes;
using osu.Game.Screens.Backgrounds;
using OpenTK;
using osu.Game.Screens.Play;
using osu.Framework.Audio.Sample;
using osu.Framework.Graphics.Transforms;
using osu.Game.Beatmaps.Drawables;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics;
using osu.Framework.Input;
using OpenTK.Input;
using System.Collections.Generic;
using osu.Framework.Threading;
using osu.Game.Overlays.Mods;
using osu.Game.Overlays;
using osu.Game.Screens.Select.Options;

namespace osu.Game.Screens.Select
{
    public class PlaySongSelect : OsuScreen
    {
        private Bindable<PlayMode> playMode = new Bindable<PlayMode>();
        private BeatmapDatabase database;
        protected override BackgroundScreen CreateBackground() => new BackgroundScreenBeatmap(Beatmap);

        private CarouselContainer carousel;
        private TrackManager trackManager;
        private DialogOverlay dialogOverlay;

        private static readonly Vector2 wedged_container_size = new Vector2(0.5f, 225);
        private BeatmapInfoWedge beatmapInfoWedge;

        private ModSelectOverlay modSelect;

        private static readonly Vector2 background_blur = new Vector2(20);
        private CancellationTokenSource initialAddSetsTask;

        private SampleChannel sampleChangeDifficulty;
        private SampleChannel sampleChangeBeatmap;

        private List<BeatmapGroup> beatmapGroups;

        private BeatmapOptionsOverlay beatmapOptions;
        private Footer footer;

        OsuScreen player;

        private FilterControl filter;
        public FilterControl Filter
        {
            get
            {
                return filter;
            }
            private set
            {
                if (filter != value)
                {
                    filter = value;
                    filterChanged();
                }
            }
        }

        [BackgroundDependencyLoader(permitNulls: true)]
        private void load(BeatmapDatabase beatmaps, AudioManager audio, DialogOverlay dialog, Framework.Game game,
            OsuGame osu, OsuColour colours)
        {
            const float carousel_width = 640;
            const float filter_height = 100;

            beatmapGroups = new List<BeatmapGroup>();
            Children = new Drawable[]
            {
                new ParallaxContainer
                {
                    Padding = new MarginPadding { Top = filter_height },
                    ParallaxAmount = 0.005f,
                    RelativeSizeAxes = Axes.Both,
                    Children = new[]
                    {
                        new WedgeBackground
                        {
                            RelativeSizeAxes = Axes.Both,
                            Padding = new MarginPadding
                            {
                                Right = carousel_width * 0.76f
                            },
                        },
                    }
                },
                carousel = new CarouselContainer
                {
                    RelativeSizeAxes = Axes.Y,
                    Size = new Vector2(carousel_width, 1),
                    Anchor = Anchor.CentreRight,
                    Origin = Anchor.CentreRight,
                },
                filter = new FilterControl
                {
                    RelativeSizeAxes = Axes.X,
                    Height = filter_height,
                    FilterChanged = () => filterChanged(),
                    Exit = Exit,
                },
                beatmapInfoWedge = new BeatmapInfoWedge
                {
                    Alpha = 0,
                    Size = wedged_container_size,
                    RelativeSizeAxes = Axes.X,
                    Margin = new MarginPadding
                    {
                        Top = 20,
                        Right = 20,
                    },
                },
                beatmapOptions = new BeatmapOptionsOverlay
                {
                    OnRemoveFromUnplayed = null,
                    OnClearLocalScores = null,
                    OnEdit = null,
                    OnDelete = promptDelete,
                    Margin = new MarginPadding
                    {
                        Bottom = 50,
                    },
                },
                modSelect = new ModSelectOverlay
                {
                    RelativeSizeAxes = Axes.X,
                    Origin = Anchor.BottomCentre,
                    Anchor = Anchor.BottomCentre,
                    Margin = new MarginPadding
                    {
                        Bottom = 50,
                    },
                },
                footer = new Footer
                {
                    OnBack = Exit,
                    OnStart = () =>
                    {
                        if (player != null || Beatmap == null)
                            return;

                        (player = new PlayerLoader(new Player
                        {
                            BeatmapInfo = carousel.SelectedGroup.SelectedPanel.Beatmap,
                            PreferredPlayMode = playMode.Value
                        })).LoadAsync(Game, l => Push(player));
                    }
                },
            };

            footer.AddButton(@"mods", colours.Yellow, modSelect.ToggleVisibility);
            footer.AddButton(@"random", colours.Green, carousel.SelectRandom);
            footer.AddButton(@"options", colours.Blue, beatmapOptions.ToggleVisibility);

            if (osu != null)
                playMode.BindTo(osu.PlayMode);
            playMode.ValueChanged += playMode_ValueChanged;

            if (database == null)
                database = beatmaps;

            database.BeatmapSetAdded += onBeatmapSetAdded;
            database.BeatmapSetRemoved += onBeatmapSetRemoved;

            trackManager = audio.Track;
            dialogOverlay = dialog;

            sampleChangeDifficulty = audio.Sample.Get(@"SongSelect/select-difficulty");
            sampleChangeBeatmap = audio.Sample.Get(@"SongSelect/select-expand");

            initialAddSetsTask = new CancellationTokenSource();

            Task.Factory.StartNew(() => addBeatmapSets(game, initialAddSetsTask.Token), initialAddSetsTask.Token);
        }

        private ScheduledDelegate filterTask;

        private void filterChanged(bool debounce = true, bool eagerSelection = true)
        {
            filterTask?.Cancel();
            filterTask = Scheduler.AddDelayed(() =>
            {
                filterTask = null;
                var search = filter.Search;
                BeatmapGroup newSelection = null;
                carousel.Sort(filter.Sort);
                foreach (var beatmapGroup in carousel)
                {
                    var set = beatmapGroup.BeatmapSet;

                    bool hasCurrentMode = set.Beatmaps.Any(bm => bm.Mode == playMode);

                    bool match = hasCurrentMode;

                    match &= string.IsNullOrEmpty(search)
                        || (set.Metadata.Artist ?? "").IndexOf(search, StringComparison.InvariantCultureIgnoreCase) != -1
                        || (set.Metadata.ArtistUnicode ?? "").IndexOf(search, StringComparison.InvariantCultureIgnoreCase) != -1
                        || (set.Metadata.Title ?? "").IndexOf(search, StringComparison.InvariantCultureIgnoreCase) != -1
                        || (set.Metadata.TitleUnicode ?? "").IndexOf(search, StringComparison.InvariantCultureIgnoreCase) != -1;

                    if (match)
                    {
                        if (newSelection == null || beatmapGroup.BeatmapSet.OnlineBeatmapSetID == Beatmap.BeatmapSetInfo.OnlineBeatmapSetID)
                        {
                            if (newSelection != null)
                                newSelection.State = BeatmapGroupState.Collapsed;
                            newSelection = beatmapGroup;
                        }
                        else
                            beatmapGroup.State = BeatmapGroupState.Collapsed;
                    }
                    else
                    {
                        beatmapGroup.State = BeatmapGroupState.Hidden;
                    }
                }

                if (newSelection != null)
                {
                    if (newSelection.BeatmapPanels.Any(b => b.Beatmap.ID == Beatmap.BeatmapInfo.ID))
                        carousel.SelectBeatmap(Beatmap.BeatmapInfo, false);
                    else if (eagerSelection)
                        carousel.SelectBeatmap(newSelection.BeatmapSet.Beatmaps[0], false);
                }
            }, debounce ? 250 : 0);
        }

        private void onBeatmapSetAdded(BeatmapSetInfo s) => Schedule(() => addBeatmapSet(s, Game, true));

        private void onBeatmapSetRemoved(BeatmapSetInfo s) => Schedule(() => removeBeatmapSet(s));

        protected override void OnEntering(Screen last)
        {
            base.OnEntering(last);
            ensurePlayingSelected();

            changeBackground(Beatmap);

            Content.FadeInFromZero(250);

            beatmapInfoWedge.MoveToX(-50);
            beatmapInfoWedge.MoveToX(0, 800, EasingTypes.OutQuint);

            filter.Activate();
        }

        protected override void OnResuming(Screen last)
        {
            player = null;

            changeBackground(Beatmap);
            ensurePlayingSelected();
            base.OnResuming(last);

            Content.FadeIn(250);

            Content.ScaleTo(1, 250, EasingTypes.OutSine);

            filter.Activate();
        }

        protected override void OnSuspending(Screen next)
        {
            Content.ScaleTo(1.1f, 250, EasingTypes.InSine);

            Content.FadeOut(250);

            filter.Deactivate();
            base.OnSuspending(next);
        }

        protected override bool OnExiting(Screen next)
        {
            beatmapInfoWedge.MoveToX(-100, 800, EasingTypes.InQuint);
            beatmapInfoWedge.RotateTo(10, 800, EasingTypes.InQuint);

            Content.FadeOut(100);

            filter.Deactivate();
            return base.OnExiting(next);
        }

        protected override void Dispose(bool isDisposing)
        {
            base.Dispose(isDisposing);

            database.BeatmapSetAdded -= onBeatmapSetAdded;
            database.BeatmapSetRemoved -= onBeatmapSetRemoved;

            initialAddSetsTask.Cancel();
        }

        private void playMode_ValueChanged(object sender, EventArgs e)
        {
            filterChanged(false);
        }

        private void changeBackground(WorkingBeatmap beatmap)
        {
            var backgroundModeBeatmap = Background as BackgroundScreenBeatmap;
            if (backgroundModeBeatmap != null)
            {
                backgroundModeBeatmap.Beatmap = beatmap;
                backgroundModeBeatmap.BlurTo(background_blur, 1000);
                backgroundModeBeatmap.FadeTo(1, 250);
            }

            if (beatmap != null)
                beatmapInfoWedge.UpdateBeatmap(beatmap);
        }

        /// <summary>
        /// The global Beatmap was changed.
        /// </summary>
        protected override void OnBeatmapChanged(WorkingBeatmap beatmap)
        {
            base.OnBeatmapChanged(beatmap);

            //todo: change background in selectionChanged instead; support per-difficulty backgrounds.
            changeBackground(beatmap);
            carousel.SelectBeatmap(beatmap?.BeatmapInfo);
        }

        /// <summary>
        /// selection has been changed as the result of interaction with the carousel.
        /// </summary>
        private void selectionChanged(BeatmapGroup group, BeatmapInfo beatmap)
        {
            bool beatmapSetChange = false;

            if (!beatmap.Equals(Beatmap?.BeatmapInfo))
            {
                if (beatmap.BeatmapSetInfoID == Beatmap?.BeatmapInfo.BeatmapSetInfoID)
                    sampleChangeDifficulty.Play();
                else
                {
                    sampleChangeBeatmap.Play();
                    beatmapSetChange = true;
                }
                Beatmap = database.GetWorkingBeatmap(beatmap, Beatmap);
            }
            ensurePlayingSelected(beatmapSetChange);
        }

        private void ensurePlayingSelected(bool preview = false)
        {
            Track track = Beatmap?.Track;

            if (track != null)
            {
                trackManager.SetExclusive(track);
                if (preview)
                    track.Seek(Beatmap.Beatmap.Metadata.PreviewTime);
                track.Start();
            }
        }

        private void addBeatmapSet(BeatmapSetInfo beatmapSet, Framework.Game game, bool select = false)
        {
            beatmapSet = database.GetWithChildren<BeatmapSetInfo>(beatmapSet.ID);
            beatmapSet.Beatmaps.ForEach(b =>
            {
                database.GetChildren(b);
                if (b.Metadata == null) b.Metadata = beatmapSet.Metadata;
            });

            var group = new BeatmapGroup(beatmapSet, database)
            {
                SelectionChanged = selectionChanged,
                StartRequested = b => footer.StartButton.TriggerClick()
            };

            //for the time being, let's completely load the difficulty panels in the background.
            //this likely won't scale so well, but allows us to completely async the loading flow.
            Task.WhenAll(group.BeatmapPanels.Select(panel => panel.LoadAsync(game))).ContinueWith(task => Schedule(delegate
            {
                beatmapGroups.Add(group);

                group.State = BeatmapGroupState.Collapsed;
                carousel.AddGroup(group);

                filterChanged(false, false);

                if (Beatmap == null || select)
                    carousel.SelectBeatmap(beatmapSet.Beatmaps.First());
                else
                    carousel.SelectBeatmap(Beatmap.BeatmapInfo);
            }));
        }

        private void removeBeatmapSet(BeatmapSetInfo beatmapSet)
        {
            var group = beatmapGroups.Find(b => b.BeatmapSet.ID == beatmapSet.ID);
            if (group == null) return;

            if (carousel.SelectedGroup == group)
                carousel.SelectNext();

            beatmapGroups.Remove(group);
            carousel.RemoveGroup(group);

            if (beatmapGroups.Count == 0)
                Beatmap = null;
        }

        private void addBeatmapSets(Framework.Game game, CancellationToken token)
        {
            foreach (var beatmapSet in database.Query<BeatmapSetInfo>().Where(b => !b.DeletePending))
            {
                if (token.IsCancellationRequested) return;
                addBeatmapSet(beatmapSet, game);
            }
        }

        private void promptDelete()
        {
            if (Beatmap != null)
                dialogOverlay?.Push(new BeatmapDeleteDialog(Beatmap));
        }

        protected override bool OnKeyDown(InputState state, KeyDownEventArgs args)
        {
            switch (args.Key)
            {
                case Key.Enter:
                    footer.StartButton.TriggerClick();
                    return true;
                case Key.Delete:
                    if (state.Keyboard.ShiftPressed)
                    {
                        promptDelete();
                        return true;
                    }
                    break;
            }

            return base.OnKeyDown(state, args);
        }
    }
}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m160318_141637_create_file extends Migration
{
    const TABLE_NAME = 'file';
    public function up()
    {
        $this->createTable(self::TABLE_NAME,[
            'id' => $this->primaryKey(),
            'time' => $this->string([10])->notNull()->defaultValue('2016-01')
        ]);
    }

    public function down()
    {
        echo "m160318_141637_create_file cannot be reverted.\n";

        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}