text:
(function(scout, $, undefined) {
  __include("filetree/FileTreeField.js");
}(scout, jQuery));

redpajama_set_name: RedPajamaGithub


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

public static class SkinnedMeshTools
{
	// Return the list of all the new skinned mesh renderer added to root. Set recursively obj as inactive.
	public static List<GameObject> AddSkinnedMeshTo( GameObject obj, Transform root ){ return AddSkinnedMeshTo(obj, root, true); }
	// Return the list of all the new skinned mesh renderer added to root. Set recursively obj as inactive if hideFromObj is true.
	public static List<GameObject> AddSkinnedMeshTo( GameObject obj, Transform root, bool hideFromObj )
	{
		List<GameObject> result = new List<GameObject>();

		// Here, boneObj must be instatiated and active (at least the one with the renderer),
		// or else GetComponentsInChildren won't work.
		SkinnedMeshRenderer[] BonedObjects = obj.GetComponentsInChildren<SkinnedMeshRenderer>();
		foreach( SkinnedMeshRenderer smr in BonedObjects )
			result.Add( ProcessBonedObject( smr, root ) );

		if( hideFromObj )
			obj.SetActive( false );

		return result;
	}

	private static GameObject ProcessBonedObject( SkinnedMeshRenderer ThisRenderer, Transform root )
	{
		// Create the SubObject
		GameObject newObject = new GameObject( ThisRenderer.gameObject.name );
		newObject.transform.parent = root;

		// Add the renderer
		SkinnedMeshRenderer NewRenderer = newObject.AddComponent( typeof( SkinnedMeshRenderer ) ) as SkinnedMeshRenderer;

		// Assemble Bone Structure
		Transform[] MyBones = new Transform[ ThisRenderer.bones.Length ];

		// As clips are using bones by their names, we find them that way.
		for( int i = 0; i < ThisRenderer.bones.Length; i++ )
			MyBones[ i ] = FindChildByName( ThisRenderer.bones[ i ].name, root );

		// Assemble Renderer
		NewRenderer.bones = MyBones;
		NewRenderer.sharedMesh = ThisRenderer.sharedMesh;
		NewRenderer.materials = ThisRenderer.materials;

		return newObject;
	}

	// Recursive search of the child by name.
	private static Transform FindChildByName( string ThisName, Transform ThisGObj )
	{
		Transform ReturnObj;

		// If the name match, we're return it
		if( ThisGObj.name == ThisName )
			return ThisGObj.transform;

		// Else, we go continue the search horizontaly and verticaly
		foreach( Transform child in ThisGObj )
		{
			ReturnObj = FindChildByName( ThisName, child );

			if( ReturnObj != null )
				return ReturnObj;
		}

		return null;
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace StatTag.Core.Utility
{
    public class CodeParserUtil
    {
        private static readonly Regex TrailingLineComment = new Regex("(?<![\\*\"'])\\/\\/[^\\r\\n]*");

        /// <summary>
        /// Takes trailing comments and strips them from the input string.  This accounts for newlines so that
        /// all trailing comments in a single string are managed, and it doesn't remove all of the text after
        /// the first comment start it sees.
        /// </summary>
        /// <example>
        /// Input
        ///     Test line one // comment\r\nTest line two
        /// Output
        ///     Test line one \r\nTest line two
        /// </example>
        /// <param name="originalText"></param>
        /// <returns></returns>
        public static string StripTrailingComments(string originalText)
        {
            if (string.IsNullOrWhiteSpace(originalText))
            {
                return originalText;
            }

            return TrailingLineComment.Replace(originalText, "");
        }
    }
}


text:
require 'test_helper'

class BillsControllerTest < ActionController::TestCase
  setup do
    @bill = bills(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:bills)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create bill" do
    assert_difference('Bill.count') do
      post :create, bill: { bill_flg: @bill.bill_flg, billing_plan_line_id: @bill.billing_plan_line_id, duedate: @bill.duedate, memo: @bill.memo, name: @bill.name, payment_flg: @bill.payment_flg }
    end

    assert_redirected_to bill_path(assigns(:bill))
  end

  test "should show bill" do
    get :show, id: @bill
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @bill
    assert_response :success
  end

  test "should update bill" do
    patch :update, id: @bill, bill: { bill_flg: @bill.bill_flg, billing_plan_line_id: @bill.billing_plan_line_id, duedate: @bill.duedate, memo: @bill.memo, name: @bill.name, payment_flg: @bill.payment_flg }
    assert_redirected_to bill_path(assigns(:bill))
  end

  test "should destroy bill" do
    assert_difference('Bill.count', -1) do
      delete :destroy, id: @bill
    end

    assert_redirected_to bills_path
  end
end


text:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.views.static import serve

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

urlpatterns = patterns('',
    url(r'^', include('tx_elevators.urls',
        namespace='tx_elevators', app_name='tx_elevators')),

    # Go ahead and serve static media
    url(r'^static/(?P<path>.*)$', serve, {
        'document_root': settings.STATIC_ROOT,
    }),
)

# extra urlpatterns for development used for serving media and for serving a
# dummy favicon.
if settings.DEBUG:
    from django.http import HttpResponse

    def favicon(request):
        image_data = open("example_project/static/favicon.ico", "rb").read()
        return HttpResponse(image_data, mimetype="image/x-icon")

    urlpatterns += patterns('',
        url(r'^admin/', include(admin.site.urls)),

        url(r'^media/(?P<path>.*)$', serve, {
            'document_root': settings.MEDIA_ROOT,
        }),
        url(r'^favicon.ico$', favicon),
    )


text:
package de.ihrig.fwla.display.testutil;

import static org.easymock.EasyMock.*;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.aop.support.AopUtils;

public abstract class MockedTest {

	private Object[] allMocks(Object... localMocks) throws Exception {
		List<Object> localMocksList = Arrays.asList(localMocks);
		List<Object> fieldMocks = Arrays.asList(getFieldMocks());

		List<Object> allMocks = new ArrayList<>();
		allMocks.addAll(localMocksList);
		allMocks.addAll(fieldMocks);

		return allMocks.toArray();
	}

	protected final void doReplay(Object... localMocks) throws Exception {
		replay(allMocks(localMocks));
	}

	protected final void doVerify(Object... localMocks) throws Exception {
		verify(allMocks(localMocks));
	}

	protected Object[] getFieldMocks() throws Exception {
		Field[] fields = getClass().getDeclaredFields();
		Set<Object> fieldMocks = new HashSet<>();

		for (Field field : fields) {
			field.setAccessible(true);
			Object possibleMock = field.get(this);

			if (possibleMock != null && isMocked(possibleMock)) {
				fieldMocks.add(possibleMock);
			}
		}

		return fieldMocks.toArray();
	}

	private boolean isMocked(Object object) {
		return Proxy.isProxyClass(object.getClass())
				|| AopUtils.isAopProxy(object) || AopUtils.isCglibProxy(object)
				|| toStringStartsWithEasyMock(object);
	}

	private boolean toStringStartsWithEasyMock(Object object) {
		return object.toString().startsWith("EasyMock for class ");
	}
}


text:
package org.netbeans.nbbuild;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.taskdefs.Property;
import org.apache.tools.ant.taskdefs.SignJar;
import org.apache.tools.ant.taskdefs.SignJar.JarConfigResolved;
import org.apache.tools.ant.taskdefs.SignJar.JarsConfig;
import org.apache.tools.ant.taskdefs.Taskdef;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.ResourceCollection;
import org.apache.tools.ant.types.ZipFileSet;
import org.apache.tools.ant.types.resources.FileResource;
import org.xml.sax.SAXException;

import com.google.common.base.Optional;
import com.google.common.io.Files;

/** Generates JNLP files for signed versions of the module JAR files.
 *
 * @author Jaroslav Tulach, Jesse Glick
 */
public class MakeJnlp2 extends Task
{
    /** the files to work on */
    private ResourceCollection files;

    private String alias;

    private String storePass;

    private String keystore;

    private String storeType;

    // +p
    private boolean signingForce = true;

    // +p
    private String signingTsaCert;

    // +p
    private String signingTsaUrl;

    // +p
    private String signingMaxMemory = "96m";

    // +p
    private int signingRetryCount = 1;

    // +p
    private int nbThreads = 1;

    // +p
    private List<Property> extraManifestAttributes;

    // +p
    private boolean unsignFirst;

    // +p
    private List<JarsConfig> jarsConfigs;

    // +p
    private File basedir;

    // +p
    private boolean pack200 = false;

    // +p
    private Integer pack200Effort;

    // +p
    private boolean optimize = false;

    public boolean isOptimize()
    {
        return optimize;
    }

    public void setOptimize(boolean optimize)
    {
        this.optimize = optimize;
    }

    public FileSet createModules()
    throws BuildException {
        FileSet fs = new FileSet();
        fs.setProject(getProject());
        addConfigured(fs);
        return fs;
    }

    public void addConfigured(ResourceCollection rc) throws BuildException {
        if (files != null) throw new BuildException("modules can be specified just once");
        files = rc;
    }

    private SignJar createSignTask()
    {
        Taskdef taskdef = (Taskdef) getProject().createTask( "taskdef" );
        taskdef.setClassname( SignJar.class.getName() );
        taskdef.setName( "signjar" );
        taskdef.execute();

        final SignJar signTask = (SignJar) getProject().createTask( "signjar" );

        signTask.setAlias( alias );
        signTask.setStorepass( storePass );
        signTask.setKeystore( keystore );
        signTask.setStoretype( storeType );
        signTask.setForce( signingForce );
        signTask.setTsacert( signingTsaCert );
        signTask.setTsaurl( signingTsaUrl );
        signTask.setMaxmemory( signingMaxMemory );
        signTask.setRetryCount( signingRetryCount );
        signTask.setUnsignFirst( unsignFirst );
        signTask.setExtraManifestAttributes( extraManifestAttributes );
        signTask.setJarsConfigs( jarsConfigs );
        signTask.setBasedir( getBasedir() );
        signTask.setPack200( pack200 );
        signTask.setPack200Effort( pack200Effort );

        return signTask;
    }

    private File targetFile;
    public void setDir(File t) {
        targetFile = t;
    }

    public void setAlias(String a) {
        this.alias = a;
    }

    public void setStorePass(String p) {
        this.storePass = p;
    }

    public void setKeystore(String k) {
        this.keystore = k;
    }

    public void setStoreType(String t) {
        this.storeType = t;
    }

    private String codebase = "$$codebase";
    public void setCodebase(String s) {
        this.codebase = s;
    }

    private boolean verify;
    public void setVerify(boolean v) {
        this.verify = v;
    }

    public void setSigningForce( boolean signingForce )
    {
        this.signingForce = signingForce;
    }

    public void setSigningTsaCert( String signingTsaCert )
    {
        this.signingTsaCert = signingTsaCert;
    }

    public void setSigningTsaUrl( String signingTsaUrl )
    {
        this.signingTsaUrl = signingTsaUrl;
    }

    public void setSigningMaxMemory( String signingMaxMemory )
    {
        this.signingMaxMemory = signingMaxMemory;
    }

    public void setSigningRetryCount( int signingRetryCount )
    {
        this.signingRetryCount = signingRetryCount;
    }

    public void setNbThreads( int nbThreads )
    {
        this.nbThreads = nbThreads;
    }

    public boolean isUnsignFirst()
    {
        return unsignFirst;
    }

    public void setUnsignFirst(boolean unsignFirst)
    {
        this.unsignFirst = unsignFirst;
    }

    public List<Property> getExtraManifestAttributes()
    {
        return extraManifestAttributes;
    }

    public void setExtraManifestAttributes(List<Property> extraManifestAttributes)
    {
        this.extraManifestAttributes = extraManifestAttributes;
    }

    public List<JarsConfig> getJarsConfigs()
    {
        return jarsConfigs;
    }

    public void setJarsConfigs(List<JarsConfig> jarsConfigs)
    {
        this.jarsConfigs = jarsConfigs;
    }

    public boolean isPack200()
    {
        return pack200;
    }

    public void setPack200(boolean pack200)
    {
        this.pack200 = pack200;
    }

    public Integer getPack200Effort()
    {
        return pack200Effort;
    }

    public void setPack200Effort(Integer pack200Effort)
    {
        this.pack200Effort = pack200Effort;
    }

    private String verifyExcludes;
    /** Comma separated list of allowed excluded names of files during verify
     * phase.
     */
    public void setVerifyExcludes(String s) {
        this.verifyExcludes = s;
    }

    public File getBasedir()
    {
        return basedir;
    }

    public void setBasedir(File basedir)
    {
        this.basedir = basedir;
    }

    private String permissions = "<all-permissions/>";
    /**
     * XML fragment pasted into the security part of the .jnlp file.
     * Should default to "<all-permissions/>"
     */
    public void setPermissions(String s) {
        permissions = s;
    }

    private FileSet indirectJars;
    /**
     * Other JARs which should be copied into the destination directory and referred to as resources,
     * even though they are not listed as Class-Path extensions of the module and would not normally
     * be in its effective classpath. The basedir of the fileset should be a cluster root; for each
     * such JAR, a file META-INF/clusterpath/$relpath will be inserted in the JAR, where $relpath is the
     * relative path within the cluster. This permits the JAR to be located at runtime in a flat classpath,
     * using ClassLoader.getResource.
     */
    public void addIndirectJars(FileSet fs) {
        indirectJars = fs;
    }

    private FileSet indirectFiles;
    /**
     * Other non-JAR files which should be made available to InstalledFileLocator.
     * The basedir of the fileset should be a cluster root; each
     * such file will be packed into a ZIP entry META-INF/files/$relpath
     * where the JAR will be available at runtime in a flat classpath,
     * using ClassLoader.getResource.
     */
    public void addIndirectFiles(FileSet fs) {
        indirectFiles = fs;
    }

    private boolean signJars = true;
    /**
     * Whether the final jars should be signed or not. Defaults to true
     * (if not supplied).
     */
    public void setSignJars(boolean s) {
        this.signJars = s;
    }

    private boolean processJarVersions = false;
    /**
     * Whether to add versions and sizes of jars into jnlp files. Defaults to false
     * (if not supplied).
     * @param b
     */
    public void setProcessJarVersions(boolean b) {
      this.processJarVersions = b;
    }

    private Map<String, String> jarVersions;
    /**
     * Explicit definition of jar file versions (for jars without versions specified
     * in manifest file)
     * @param jarVersions
     */
    public void setJarVersions(Map<String, String> jarVersions) {
      this.jarVersions = jarVersions;
    }

    private Set<String> nativeLibraries;
    public void setNativeLibraries(Set<String> libs) {
      this.nativeLibraries = libs;
    }

    private Set<File> jarDirectories;

    private String includelocales;

    public void setIncludelocales(String includelocales)
    {
        this.includelocales = includelocales;
    }

    // +p -> return locales (wow)
    private Set<String> executedLocales;

    public Set<String> getExecutedLocales()
    {
        return executedLocales;
    }

    /**
     * Signs or copies the given files according to the signJars variable value.
     */
    private JarConfigResolved signOrCopy(File from, File to)
    {
        final JarConfigResolved[] jarConfigResolved = new JarConfigResolved[1];

        if (!from.exists() && from.getParentFile().getName().equals("locale")) {
            // skip missing locale files, probably the best fix for #103301
            log("Localization file " + from + " is referenced, but cannot be found. Skipping.", Project.MSG_WARN);
            return jarConfigResolved[0];
        }

        if (signJars) {

            if (to != null) {
                // #125970: might be .../modules/locale/something_ja.jar
                to.getParentFile().mkdirs();
            }

            SignJar signJar = createSignTask();

            signJar.setSigningListener(
                new SignJar.SigningListener()
                {
                    @Override
                    public void beforeSigning( JarConfigResolved jarConfig )
                    {
                        jarConfigResolved[0] = jarConfig;
                    }
                });

            signJar.setJar( from );
            signJar.setSignedjar( to );

            signJar.execute();

        } else if (to != null) {
            Copy copy = (Copy)getProject().createTask("copy");
            copy.setFile(from);
            copy.setTofile(to);
            copy.execute();
        }

        if (processJarVersions)
        {
          if (jarDirectories == null)
          {
            jarDirectories = new HashSet<File>();
          }

          jarDirectories.add(new File(to.getParent()));
        }

        return jarConfigResolved[0];
    }

    @Override
    public void execute() throws BuildException {
        if (targetFile == null) throw new BuildException("Output dir must be provided");
        if (files == null) throw new BuildException("modules must be provided");
        try {
            generateFiles();
            if (processJarVersions && jarDirectories!=null && jarDirectories.size() > 0) {
              generateVersionXMLFiles();
            }
        } catch (IOException ex) {
            throw new BuildException(ex);
        }
    }

//
    final Map<String, File> fileDigestMap = new HashMap<String, File>();
//

    private void generateFiles() throws IOException, BuildException {

        final Set<String> declaredLocales = new HashSet<String>();

        final boolean useAllLocales;

        if ("*".equals(includelocales))
        {
            useAllLocales = true;
        }
        else if ("".equals(includelocales))
        {
            useAllLocales = false;
        }
        else
        {
            useAllLocales = false;
            StringTokenizer tokenizer = new StringTokenizer(includelocales, ",");
            while (tokenizer.hasMoreElements())
            {
                declaredLocales.add(tokenizer.nextToken());
            }
        }

        final Set<String> indirectFilePaths = new HashSet<String>();
        for (FileSet fs : new FileSet[] {indirectJars, indirectFiles}) {
            if (fs != null) {
                DirectoryScanner scan = fs.getDirectoryScanner(getProject());
                for (String f : scan.getIncludedFiles()) {
                    indirectFilePaths.add(f.replace(File.pathSeparatorChar, '/'));
                }
            }
        }

        final ExecutorService executorService = Executors.newFixedThreadPool( nbThreads );

        final List<BuildException> exceptions = new ArrayList<BuildException>();

        for ( final Iterator fileIt = files.iterator(); fileIt.hasNext(); )
        {
            if ( !exceptions.isEmpty() )
            {
                break;
            }

            final FileResource fr = (FileResource) fileIt.next();
            final File jar = fr.getFile();

            if (!jar.canRead()) {
                throw new BuildException("Cannot read file: " + jar);
            }

//
            if ( optimize && checkDuplicate( jar ).isPresent() )
            {
                continue;
            }
//

            executorService.execute( new Runnable()
            {
                @Override
                public void run()
                {
                    JarFile theJar = null;
                    try
                    {
                        theJar = new JarFile(jar);

                        String codenamebase = JarWithModuleAttributes.extractCodeName(theJar.getManifest().getMainAttributes());
                        if (codenamebase == null) {
                            throw new BuildException("Not a NetBeans Module: " + jar);
                        }
                        if (
                            codenamebase.equals("org.objectweb.asm.all") &&
                            jar.getParentFile().getName().equals("core") &&
                            jar.getParentFile().getParentFile().getName().startsWith("platform")
                        )
                        {
                            return;
                        }

                        {
                            int slash = codenamebase.indexOf('/');
                            if (slash >= 0) {
                                codenamebase = codenamebase.substring(0, slash);
                            }
                        }
                        String dashcnb = codenamebase.replace('.', '-');

                        String title;
                        String oneline;
                        String shrt;
                        String osDep = null;

                        {
                            String bundle = theJar.getManifest().getMainAttributes().getValue("OpenIDE-Module-Localizing-Bundle");
                            Properties prop = new Properties();
                            if (bundle != null) {
                                ZipEntry en = theJar.getEntry(bundle);
                                if (en == null) {
                                    throw new BuildException("Cannot find entry: " + bundle + " in file: " + jar);
                                }
                                InputStream is = theJar.getInputStream(en);
                                prop.load(is);
                                is.close();
                            }
                            title = prop.getProperty("OpenIDE-Module-Name", codenamebase);
                            oneline = prop.getProperty("OpenIDE-Module-Short-Description", title);
                            shrt = prop.getProperty("OpenIDE-Module-Long-Description", oneline);
                        }

                        {
                            String osMan = theJar.getManifest().getMainAttributes().getValue("OpenIDE-Module-Requires");
                            if (osMan != null) {
                                if (osMan.indexOf("org.openide.modules.os.MacOSX") >= 0) { // NOI18N
                                    osDep = "Mac OS X"; // NOI18N
                                } else if (osMan.indexOf("org.openide.modules.os.Linux") >= 0) { // NOI18N
                                    osDep = "Linux"; // NOI18N
                                } else if (osMan.indexOf("org.openide.modules.os.Solaris") >= 0) { // NOI18N
                                    osDep = "Solaris"; // NOI18N
                                } else if (osMan.indexOf("org.openide.modules.os.Windows") >= 0) { // NOI18N
                                    osDep = "Windows"; // NOI18N
                                }
                            }
                        }

                        Map<String,List<File>> localizedFiles = verifyExtensions(jar, theJar.getManifest(), dashcnb, codenamebase, verify, indirectFilePaths);

                        executedLocales = localizedFiles.keySet();

                        new File(targetFile, dashcnb).mkdir();

                        File signed = new File(new File(targetFile, dashcnb), jar.getName());

                        // +p
                        final JarConfigResolved jarConfig = signOrCopy( jar, signed );

                        File jnlp = new File(targetFile, dashcnb + ".jnlp");
                        StringWriter writeJNLP = new StringWriter();
                        writeJNLP.write("<?xml version='1.0' encoding='UTF-8'?>\n");
                        writeJNLP.write("<!DOCTYPE jnlp PUBLIC \"-//Sun Microsystems, Inc//DTD JNLP Descriptor 6.0//EN\" \"http://java.sun.com/dtd/JNLP-6.0.dtd\">\n");
                        writeJNLP.write("<jnlp spec='1.0+' codebase='" + codebase + "'>\n");
                        writeJNLP.write("  <information>\n");
                        writeJNLP.write("   <title>" + XMLUtil.toElementContent(title) + "</title>\n");
                        writeJNLP.write("   <vendor>NetBeans</vendor>\n");
                        writeJNLP.write("   <description kind='one-line'>" + XMLUtil.toElementContent(oneline) + "</description>\n");
                        writeJNLP.write("   <description kind='short'>" + XMLUtil.toElementContent(shrt) + "</description>\n");
                        writeJNLP.write("  </information>\n");

                        String realPermissions = permissions;
                        if ( ( jarConfig != null ) && ( jarConfig.getExtraManifestAttributes() != null ) )
                        {
                            String jarPermissions =
                                        jarConfig.getExtraManifestAttributes().getValue( "Permissions" );

                            if ( jarPermissions != null )
                            {
                                if ( "all-permissions".equals( jarPermissions ) )
                                {
                                    realPermissions = "<security><all-permissions/></security>\n";
                                }
                                else
                                {
                                    realPermissions = "";
                                }
                            }
                        }

                        writeJNLP.write( realPermissions );

                        if (osDep == null) {
                            writeJNLP.write("  <resources>\n");
                        } else {
                            writeJNLP.write("  <resources os='" + osDep + "'>\n");
                        }
                        writeJNLP.write(
                            "<property name=\"jnlp.packEnabled\" value=\"" + String.valueOf( pack200 ) + "\"/>\n");
                        writeJNLP.write(constructJarHref(jar, dashcnb));

                        processExtensions( jar, theJar.getManifest(), writeJNLP, dashcnb, codebase, realPermissions );
                        processIndirectJars(writeJNLP, dashcnb);
                        processIndirectFiles(writeJNLP, dashcnb);

                        writeJNLP.write("  </resources>\n");

                        if (useAllLocales || !declaredLocales.isEmpty()) {

                            // write down locales
                            for (Map.Entry<String,List<File>> e : localizedFiles.entrySet()) {
                                final String locale = e.getKey();

                                if (!declaredLocales.isEmpty() && !declaredLocales.contains(locale)) {
                                    continue;
                                }

                                final List<File> allFiles = e.getValue();

                                writeJNLP.write("  <resources locale='" + locale + "'>\n");

                                for (File n : allFiles) {
                                    log("generating locale " + locale + " for " + n, Project.MSG_VERBOSE);
                                    String name = n.getName();
                                    String clusterRootPrefix = jar.getParent() + File.separatorChar;
                                    String absname = n.getAbsolutePath();
                                    if (absname.startsWith(clusterRootPrefix)) {
                                        name = absname.substring(clusterRootPrefix.length()).replace(File.separatorChar, '-');
                                    }
                                    File t = new File(new File(targetFile, dashcnb), name);
                                    signOrCopy(n, t);
                                    writeJNLP.write(constructJarHref(n, dashcnb, name));
                                }

                                writeJNLP.write("  </resources>\n");

                            }
                        }

                        writeJNLP.write("  <component-desc/>\n");
                        writeJNLP.write("</jnlp>\n");
                        writeJNLP.close();

                        // +p
                        Files.write( writeJNLP.toString(), jnlp, Charset.forName("UTF-8") );
                    }
                    catch ( Exception e )
                    {
                        exceptions.add( new BuildException( e ) );
                    }
                    finally
                    {
                        if ( theJar != null )
                        {
                            try
                            {
                                theJar.close();
                            }
                            catch ( IOException e ) {}
                        }
                    }
                }
            } );
        }

        executorService.shutdown();

        try
        {
            executorService.awaitTermination( Long.MAX_VALUE, TimeUnit.NANOSECONDS );
        }
        catch (Exception e)
        {
            throw new BuildException(e);
        }

        if ( !exceptions.isEmpty() )
        {
            throw exceptions.get( 0 );
        }
    }

    private Map<String,List<File>> verifyExtensions(File f, Manifest mf, String dashcnb, String codebasename, boolean verify, Set<String> indirectFilePaths) throws IOException, BuildException {
        Map<String,List<File>> localizedFiles = new HashMap<String,List<File>>();

        File clusterRoot = f.getParentFile();
        String moduleDirPrefix = "";
        File updateTracking;
        log("Verifying extensions for: " + codebasename + ", cluster root: " + clusterRoot + ", verify: " + verify, Project.MSG_DEBUG);
        for(;;) {
            updateTracking = new File(clusterRoot, "update_tracking");
            if (updateTracking.isDirectory()) {
                break;
            }
            moduleDirPrefix = clusterRoot.getName() + "/" + moduleDirPrefix;
            clusterRoot = clusterRoot.getParentFile();
            if (clusterRoot == null || !clusterRoot.exists()) {
                if (!verify) {
                    return localizedFiles;
                }

                throw new BuildException("Cannot find update_tracking directory for module " + f);
            }
        }

        File ut = new File(updateTracking, dashcnb + ".xml");
        if (!ut.exists()) {
            throw new BuildException("The file " + ut + " for module " + codebasename + " cannot be found");
        }

        Map<String,String> fileToOwningModule = new HashMap<String,String>();
        try {
            ModuleSelector.readUpdateTracking(getProject(), ut.toString(), fileToOwningModule);
        } catch (IOException ex) {
            throw new BuildException(ex);
        } catch (ParserConfigurationException ex) {
            throw new BuildException(ex);
        } catch (SAXException ex) {
            throw new BuildException(ex);
        }

        log("project files: " + fileToOwningModule, Project.MSG_DEBUG);
        String name = relative(f, clusterRoot);
        log("  removing: " + name, Project.MSG_DEBUG);
        removeWithLocales(fileToOwningModule, name, clusterRoot, localizedFiles);
        name = "config/Modules/" + dashcnb + ".xml";
        log("  removing: " + name, Project.MSG_DEBUG);
        removeWithLocales(fileToOwningModule, name, clusterRoot, localizedFiles);
        name = "config/ModuleAutoDeps/" + dashcnb + ".xml";
        log("  removing: " + name, Project.MSG_DEBUG);
        removeWithLocales(fileToOwningModule, name, clusterRoot, localizedFiles);
        name = "update_tracking/" + dashcnb + ".xml";
        log("  removing: " + name, Project.MSG_DEBUG);
        removeWithLocales(fileToOwningModule, name, clusterRoot, localizedFiles);

        String path = mf.getMainAttributes().getValue("Class-Path");
        if (path != null) {
            StringTokenizer tok = new StringTokenizer(path, ", ");
            while(tok.hasMoreElements()) {
                String s = tok.nextToken();
                File e = new File(f.getParentFile(), s);
                String r = relative(e, clusterRoot);
                removeWithLocales(fileToOwningModule, r, clusterRoot, localizedFiles);
            }
        }

        fileToOwningModule.remove("ant/nblib/" + dashcnb + ".jar");

        fileToOwningModule.remove("VERSION.txt"); // cluster release information

        fileToOwningModule.keySet().removeAll(indirectFilePaths);

        if (verifyExcludes != null) {
            StringTokenizer tok = new StringTokenizer(verifyExcludes, ", ");
            while(tok.hasMoreElements()) {
                removeWithLocales(fileToOwningModule, tok.nextToken(), clusterRoot, localizedFiles);
            }
        }

        if (verify) {
            if (!fileToOwningModule.isEmpty()) {
                throw new BuildException(
                    "Cannot build JNLP for module " + f + " as these files are in " +
                    "module's NBM, but are not referenced from any path (see harness/README for properties you can define to fix):\n" + fileToOwningModule.keySet()
                );
            }
        }

        return localizedFiles;
    }

    private static void removeWithLocales(Map<String,String> removeFrom, String removeWhat, File clusterRoot, Map<String,List<File>> recordLocales) {
        if (removeFrom.remove(removeWhat) != null && removeWhat.endsWith(".jar")) {
            int basedir = removeWhat.lastIndexOf('/');
            String base = basedir == -1 ? "" : removeWhat.substring(0, basedir);
            String name = removeWhat.substring(basedir + 1, removeWhat.length() - 4);
            Pattern p = Pattern.compile(base + "/locale/" + name + "(|_[a-zA-Z0-9_]+)\\.jar");

            Iterator it = removeFrom.keySet().iterator();
            while (it.hasNext()) {
                String s = (String)it.next();
                Matcher m = p.matcher(s);
                if (m.matches()) {
                    String locale = m.group(1).substring(1);

                    List<File> l = recordLocales.get(locale);
                    if (l == null) {
                        l = new ArrayList<File>();
                        recordLocales.put(locale, l);
                    }
                    l.add(new File(clusterRoot, s.replace('/', File.separatorChar)));
                    it.remove();
                }
            }
        }
    }

    private void processExtensions(
                        File f, Manifest mf, Writer fileWriter, String dashcnb,
                        String codebase,
                        String permissions )
        throws IOException, BuildException
    {

        File nblibJar = new File(new File(new File(f.getParentFile().getParentFile(), "ant"), "nblib"), dashcnb + ".jar");
        if (nblibJar.isFile()) {
            File ext = new File(new File(targetFile, dashcnb), "ant-nblib-" + nblibJar.getName());
            fileWriter.write(constructJarHref(ext, dashcnb));
            signOrCopy(nblibJar, ext);
        }

        String path = mf.getMainAttributes().getValue("Class-Path");
        if (path == null) {
            return;
        }

        StringTokenizer tok = new StringTokenizer(path, ", ");
        while(tok.hasMoreElements()) {
            String s = tok.nextToken();

            if (s.contains("${java.home}"))
            {
                continue;
            }

            File e = new File(f.getParentFile(), s);
            if (!e.canRead()) {
                throw new BuildException("Cannot read extension " + e + " referenced from " + f);
            }

//
            if ( optimize && checkDuplicate( e ).isPresent() )
            {
                continue;
            }
//

            String n = e.getName();
            if (n.endsWith(".jar")) {
                n = n.substring(0, n.length() - 4);
            }
            File ext = new File(new File(targetFile, dashcnb), s.replace("../", "").replace('/', '-'));

            if (isSigned(e) != null) {
                signOrCopy(e, ext);
//                Copy copy = (Copy)getProject().createTask("copy");
//                copy.setFile(e);
//                copy.setTofile(ext);
//                copy.execute();

                String extJnlpName = dashcnb + '-' + ext.getName().replaceFirst("\\.jar$", "") + ".jnlp";
                File jnlp = new File(targetFile, extJnlpName);

                FileWriter writeJNLP = new FileWriter(jnlp);
                writeJNLP.write("<?xml version='1.0' encoding='UTF-8'?>\n");
                writeJNLP.write("<!DOCTYPE jnlp PUBLIC \"-//Sun Microsystems, Inc//DTD JNLP Descriptor 6.0//EN\" \"http://java.sun.com/dtd/JNLP-6.0.dtd\">\n");
                writeJNLP.write("<jnlp spec='1.0+' codebase='" + codebase + "'>\n");
                writeJNLP.write("  <information>\n");
                writeJNLP.write("    <title>" + n + "</title>\n");
                writeJNLP.write("    <vendor>NetBeans</vendor>\n");
                writeJNLP.write("  </information>\n");
                writeJNLP.write(permissions +"\n");
                writeJNLP.write("  <resources>\n");
                writeJNLP.write(
                    "<property name=\"jnlp.packEnabled\" value=\"" + String.valueOf( pack200 ) + "\"/>\n");
                writeJNLP.write(constructJarHref(ext, dashcnb));
                writeJNLP.write("  </resources>\n");
                writeJNLP.write("  <component-desc/>\n");
                writeJNLP.write("</jnlp>\n");
                writeJNLP.close();

                fileWriter.write("    <extension name='" + e.getName().replaceFirst("\\.jar$", "") + "' href='" + extJnlpName + "'/>\n");
            } else {
                signOrCopy(e, ext);

                fileWriter.write(constructJarHref(ext, dashcnb));
            }
        }
    }

    private void processIndirectJars(Writer fileWriter, String dashcnb) throws IOException, BuildException {
        if (indirectJars == null) {
            return;
        }
        DirectoryScanner scan = indirectJars.getDirectoryScanner(getProject());
        for (String f : scan.getIncludedFiles()) {
            File jar = new File(scan.getBasedir(), f);

            if ( optimize && checkDuplicate( jar ).isPresent() )
            {
                continue;
            }

            String rel = f.replace(File.separatorChar, '/');
            String sig;
            try {
                sig = isSigned(jar);
            } catch (IOException x) {
                throw new BuildException("Cannot check signature on " + jar, x, getLocation());
            }
            // javaws will reject .zip files even with signatures.
            String rel2 = rel.endsWith(".jar") ? rel : rel.replaceFirst("(\\.zip)?$", ".jar");
            File ext = new File(new File(targetFile, dashcnb), rel2.replace('/', '-').replaceFirst("^modules-", ""));
            Zip jartask = (Zip) getProject().createTask("jar");
            jartask.setDestFile(ext);
            ZipFileSet zfs = new ZipFileSet();
            zfs.setSrc(jar);
            if (sig != null) {
                // Need to cancel original signature since we are adding one entry to the JAR.
                zfs.setExcludes("META-INF/" + sig + ".*");
            }
            jartask.addZipfileset(zfs);
            zfs = new ZipFileSet();
            File blank = File.createTempFile("empty", "");
            blank.deleteOnExit();
            zfs.setFile(blank);
            zfs.setFullpath("META-INF/clusterpath/" + rel);
            jartask.addZipfileset(zfs);
            jartask.execute();
            blank.delete();

            fileWriter.write(constructJarHref(ext, dashcnb));
            signOrCopy(ext, null);
        }
    }

    private void processIndirectFiles(Writer fileWriter, String dashcnb) throws IOException, BuildException {
        if (indirectFiles == null) {
            return;
        }
        DirectoryScanner scan = indirectFiles.getDirectoryScanner(getProject());
        Map<String,File> entries = new LinkedHashMap<String,File>();
        for (String f : scan.getIncludedFiles()) {
            entries.put(f.replace(File.separatorChar, '/'), new File(scan.getBasedir(), f));
        }
        if (entries.isEmpty()) {
            return;
        }
        File ext = new File(new File(targetFile, dashcnb), "extra-files.jar");
        Zip jartask = (Zip) getProject().createTask("jar");
        jartask.setDestFile(ext);
        for (Map.Entry<String,File> entry : entries.entrySet()) {
            ZipFileSet zfs = new ZipFileSet();
            zfs.setFile(entry.getValue());
            zfs.setFullpath("META-INF/files/" + entry.getKey());
            jartask.addZipfileset(zfs);
        }
        jartask.execute();
        fileWriter.write(constructJarHref(ext, dashcnb));
        signOrCopy(ext, null);
    }

    private String relative(File file, File root) {
        String sfile = file.toString().replace(File.separatorChar, '/');
        String sroot = (root.toString() + File.separator).replace(File.separatorChar, '/');
        if (sfile.startsWith(sroot)) {
            try {
                String result = new URI(null, sfile.substring(sroot.length()), null).normalize().getPath();
                return result;
            } catch (URISyntaxException x) {
                throw new BuildException(x, getLocation()); // or just ignore?
            }
        }
        return sfile;
    }

    /** return alias if signed, or null if not */
    private static String isSigned(File f) throws IOException {
        JarFile jar = new JarFile(f);
        try {
            Enumeration<JarEntry> en = jar.entries();
            while (en.hasMoreElements()) {
                Matcher m = SF.matcher(en.nextElement().getName());
                if (m.matches()) {
                    return m.group(1);
                }
            }
            return null;
        } finally {
            jar.close();
        }
    }
    private static final Pattern SF = Pattern.compile("META-INF/(.+)\\.SF");

    /**
     * returns version of jar file depending on manifest.mf or explicitly specified
     * @param jar
     * @return
     * @throws IOException
     */
    private String getJarVersion(JarFile jar) throws IOException {
        String version = jar.getManifest().getMainAttributes().getValue("OpenIDE-Module-Specification-Version");
        if (version == null) {
          version = jar.getManifest().getMainAttributes().getValue("Specification-Version");
        }
        if (version == null && jarVersions != null) {
          version = jarVersions.get(jar.getName());
        }
        return version;
      }

    /**
     * Constructs jar or nativelib tag for jars
     * @param f
     * @param dashcnb
     * @return
     * @throws IOException
     */
    private String constructJarHref(File f, String dashcnb) throws IOException {
        return constructJarHref(f, dashcnb, f.getName());
    }

    /**
     * Constructs jar or nativelib tag for jars using custom name
     * @param f
     * @param dashcnb
     * @return
     * @throws IOException
     */
    private String constructJarHref(File f, String dashcnb, String name) throws IOException {
        String tag = "jar";
        if (nativeLibraries != null && nativeLibraries.contains(name)) {
            tag = "nativelib";
        }
        if (processJarVersions) {
            if (!f.exists()) {
                throw new BuildException("JAR file " + f + " does not exist, cannot extract required versioning info.");
            }
            JarFile extJar = new JarFile(f);
            String version = getJarVersion(extJar);
            if (version != null) {
                return "    <" + tag + " href='" + dashcnb + '/' + name + "' version='" + version + "' size='" + f.length() + "'/>\n";
            }
        }
        return "    <" + tag + " href='" + dashcnb + '/' + name + "'/>\n";
    }

    private void generateVersionXMLFiles() throws IOException {
        FileSet fs = new FileSet();
        fs.setIncludes("**/*.jar");
        for (File directory : jarDirectories) {
            fs.setDir(directory);
            DirectoryScanner scan = fs.getDirectoryScanner(getProject());
            StringWriter writeVersionXML = new StringWriter();
            writeVersionXML.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            writeVersionXML.append("<jnlp-versions>\n");
            for (String jarName : scan.getIncludedFiles()) {
                File jar = new File(scan.getBasedir(), jarName);
                JarFile jarFile = new JarFile(jar);
                String version = getJarVersion(jarFile);
                if (version != null) {
                    writeVersionXML.append("    <resource>\n        <pattern>\n            <name>");
                    writeVersionXML.append(jar.getName());
                    writeVersionXML.append("</name>\n            <version-id>");
                    writeVersionXML.append(version);
                    writeVersionXML.append("</version-id>\n        </pattern>\n        <file>");
                    writeVersionXML.append(jar.getName());
                    writeVersionXML.append("</file>\n    </resource>\n");
                } else {
                    writeVersionXML.append("    <!-- No version found for ");
                    writeVersionXML.append(jar.getName());
                    writeVersionXML.append(" -->\n");
                }
            }
            writeVersionXML.append("</jnlp-versions>\n");
            writeVersionXML.close();

            File versionXML = new File(directory, "version.xml");
            FileWriter w = new FileWriter(versionXML);
            w.write(writeVersionXML.toString());
            w.close();
        }
    }

    private Optional<File> checkDuplicate( File f )
        throws IOException
    {
        final String digest = new String( DigestUtils.getSha1Digest().digest( Files.toByteArray( f ) ) );

        final File jarFile = fileDigestMap.get( digest );

        if ( jarFile == null )
        {
            fileDigestMap.put( digest, f );

            return Optional.absent();
        }

        return Optional.of( jarFile );
    }
}


text:
Fluent Assertions extensions for Autofac.

- Introductory Blog Post [Fluently testing your Autofac configuration](http://awesome-incremented.blogspot.de/2016/01/fluently-testing-your-autofac.html)


text:
'use strict';

import 'mocha';
import { expect } from 'chai';

import { tmpdir } from 'os';
import { join as pathjoin } from 'path';
import { readFileSync } from 'fs';

import { randomFilename } from '@google-github-actions/actions-utils';

import { WorkloadIdentityClient } from '../../src/client/workload_identity_client';

describe('WorkloadIdentityClient', () => {
  describe('#getProjectID', () => {
    it('extracts project ID from the service account email', async () => {
      const client = new WorkloadIdentityClient({
        providerID: 'my-provider',
        token: 'my-token',
        serviceAccount: 'my-service@my-project.iam.gserviceaccount.com',
        audience: 'my-aud',
        oidcTokenRequestURL: 'https://example.com/',
        oidcTokenRequestToken: 'token',
      });

      const result = await client.getProjectID();
      expect(result).to.eq('my-project');
    });

    it('prefers the override if given', async () => {
      const client = new WorkloadIdentityClient({
        projectID: 'my-other-project',
        providerID: 'my-provider',
        token: 'my-token',
        serviceAccount: 'my-service@my-project.iam.gserviceaccount.com',
        audience: 'my-aud',
        oidcTokenRequestURL: 'https://example.com/',
        oidcTokenRequestToken: 'token',
      });

      const result = await client.getProjectID();
      expect(result).to.eq('my-other-project');
    });

    it('throws an error when extraction fails', async () => {
      const fn = () => {
        return new WorkloadIdentityClient({
          providerID: 'my-provider',
          token: 'my-token',
          serviceAccount: 'my-service@developers.google.com',
          audience: 'my-aud',
          oidcTokenRequestURL: 'https://example.com/',
          oidcTokenRequestToken: 'token',
        });
      };
      return expect(fn).to.throw(Error);
    });
  });

  describe('#getServiceAccount', () => {
    it('returns the provided value', async () => {
      const client = new WorkloadIdentityClient({
        projectID: 'my-project',
        providerID: 'my-provider',
        serviceAccount: 'my-service@my-project.iam.gserviceaccount.com',
        token: 'my-token',
        audience: 'my-aud',
        oidcTokenRequestURL: 'https://example.com/',
        oidcTokenRequestToken: 'token',
      });
      const result = await client.getServiceAccount();
      expect(result).to.eq('my-service@my-project.iam.gserviceaccount.com');
    });
  });

  describe('#createCredentialsFile', () => {
    it('writes the file', async () => {
      const outputFile = pathjoin(tmpdir(), randomFilename());
      const client = new WorkloadIdentityClient({
        projectID: 'my-project',
        providerID: 'my-provider',
        serviceAccount: 'my-service@my-project.iam.gserviceaccount.com',
        token: 'my-token',
        audience: 'my-aud',
        oidcTokenRequestURL: 'https://example.com/',
        oidcTokenRequestToken: 'token',
      });

      const exp = {
        audience: '//iam.googleapis.com/my-provider',
        credential_source: {
          format: {
            subject_token_field_name: 'value',
            type: 'json',
          },
          headers: {
            Authorization: 'Bearer token',
          },
          url: 'https://example.com/?audience=my-aud',
        },
        service_account_impersonation_url:
          'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/my-service@my-project.iam.gserviceaccount.com:generateAccessToken',
        subject_token_type: 'urn:ietf:params:oauth:token-type:jwt',
        token_url: 'https://sts.googleapis.com/v1/token',
        type: 'external_account',
      };

      const pth = await client.createCredentialsFile(outputFile);
      const data = readFileSync(pth);
      const got = JSON.parse(data.toString('utf8'));

      expect(got).to.deep.equal(exp);
    });
  });
});


text:
package cn.berserker.platform;

import android.app.Activity;
import cn.berserker.model.Notification;
import cn.berserker.model.ResultCode;
import cn.berserker.model.Item;
import cn.berserker.utils.Tools;

public class PaymentCenter {
	static PaymentCenter paymentCenter = null;
	ControlCenter mCenter = null;

	/*
	 *	Use this to initialize PaymentCenter.
	 *	If you has your own server to generate orderId, you may need to create appid and appkey for each one.
	 *	Notification was global callback, all message could transfer by it. You could change this arch to create
	 *	notify callback for every payment request.
	 *	For initialize need to cast much time, so it should be intialize asap, when you open the app.
	 *	If you only intialize it before payment, it may spend much time, and let user feel bad...
	 */
	public static PaymentCenter initialize(Activity activity, String appId, String appKey, Notification notify) {
		if (null == paymentCenter) {
			try {
				paymentCenter = new PaymentCenter(activity, appId, appKey, notify);
				if(null != notify) {
					notify.notifyMessage(Notification.INIT, ResultCode.INIT_SUCC, "");
				}
			} catch (Exception e) {
				paymentCenter = null;
				if(null != notify) {
					notify.notifyMessage(Notification.INIT, ResultCode.INIT_FAIL, "");
				}
			}
		}
		return paymentCenter;
	}

	private PaymentCenter(Activity activity, String appId, String appKey, Notification notify) throws Exception {
		try {
			mCenter = new ControlCenter(activity, appId, appKey, notify);
			mCenter.loadPlugin(activity);
		} catch(Exception e) {
			e.printStackTrace();
			mCenter.onDestroy(activity, true);
			throw new Exception("PaymentPlatform initialize error!");
		}
	}

	/*
	 *	User need to implement item, and platform would read it, and prepare for the payment.
	 */
	public void startPurchase(Activity activity, Item info) {
		mCenter.startPurchase(activity, info);
	}

	/*
	 * free all resource when you leave.
	 */
	public void destroy(Activity activity) {
		mCenter.onDestroy(activity, false);
		mCenter = null;
		paymentCenter = null;
	}
}


text:
<?php

require_once dirname(__FILE__) . '/../../tools/helpers/bookstore/BookstoreTestBase.php';

/**
 * Tests the character encoding support of the adapter.
 *
 * This test assumes that the created database supports UTF-8.  For this to work,
 * this file also has to be UTF-8.
 *
 * The database is relaoded before every test and flushed after every test.  This
 * means that you can always rely on the contents of the databases being the same
 * for each test method in this class.  See the BookstoreDataPopulator::populate()
 * method for the exact contents of the database.
 *
 * @see        BookstoreDataPopulator
 * @author     Hans Lellelid <hans@xmpl.org>
 * @package    misc
 */
class CharacterEncodingTest extends BookstoreTestBase
{
	/**
	 * Database adapter.
	 * @var        DBAdapter
	 */
	private $adapter;

	public function setUp()
	{
		parent::setUp();
		if (!extension_loaded('iconv')) {
			throw new Exception("Character-encoding tests require iconv extension to be loaded.");
		}
	}

	public function testUtf8()
	{
		$this->markTestSkipped();

		$db = Propel::getDB(BookPeer::DATABASE_NAME);

		$title = "Смерть на брудершафт. Младенец и черт";
		//        1234567890123456789012345678901234567
		//                 1         2         3

		$a = new Author();
		$a->setFirstName("Б.");
		$a->setLastName("АКУНИН");

		$p = new Publisher();
		$p->setName("Детектив российский, остросюжетная проза");

		$b = new Book();
		$b->setTitle($title);
		$b->setISBN("B-59246");
		$b->setAuthor($a);
		$b->setPublisher($p);
		$b->save();

		$b->reload();

		$this->assertEquals(37, iconv_strlen($b->getTitle(), 'utf-8'), "Expected 37 characters (not bytes) in title.");
		$this->assertTrue(strlen($b->getTitle()) > iconv_strlen($b->getTitle(), 'utf-8'), "Expected more bytes than characters in title.");

	}

	public function testInvalidCharset()
	{
		$this->markTestSkipped();

		$db = Propel::getDB(BookPeer::DATABASE_NAME);
		if ($db instanceof DBSQLite) {
			$this->markTestSkipped();
		}

		$a = new Author();
		$a->setFirstName("Б.");
		$a->setLastName("АКУНИН");
		$a->save();

		$authorNameWindows1251 = iconv("utf-8", "windows-1251", $a->getLastName());
		$a->setLastName($authorNameWindows1251);

		// Different databases seem to handle invalid data differently (no surprise, I guess...)
		if ($db instanceof DBPostgres) {
			try {
				$a->save();
				$this->fail("Expected an exception when saving non-UTF8 data to database.");
			} catch (Exception $x) {
				print $x;
			}

		} else {

			// No exception is thrown by MySQL ... (others need to be tested still)
			$a->save();
			$a->reload();

			$this->assertEquals("",$a->getLastName(), "Expected last_name to be empty (after inserting invalid charset data)");
		}

	}

}


text:
package org.estatio.module.party.fixtures.person.builders;

import java.util.Collection;
import java.util.List;

import javax.inject.Inject;

import com.google.common.collect.Lists;

import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.fixturescripts.BuilderScriptAbstract;

import org.estatio.module.party.dom.Person;
import org.estatio.module.party.dom.role.IPartyRoleType;
import org.estatio.module.party.dom.role.PartyRole;
import org.estatio.module.party.dom.role.PartyRoleTypeService;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

@EqualsAndHashCode(of={"person", "partyRoleTypes"}, callSuper = false)
@ToString(of={"person", "partyRoleTypes"})
@Accessors(chain = true)
public final class PersonPartyRolesBuilder
        extends BuilderScriptAbstract<List<PartyRole>,PersonPartyRolesBuilder> {

    @Getter @Setter
    private Person person;

    @Getter
    private List<IPartyRoleType> partyRoleTypes = Lists.newArrayList();

    @Programmatic
    public PersonPartyRolesBuilder addPartyRoleType(IPartyRoleType partyRoleType) {
        partyRoleTypes.add(partyRoleType);
        return this;
    }
    @Programmatic
    public PersonPartyRolesBuilder addPartyRoleTypes(Collection<IPartyRoleType> partyRoleTypes) {
        this.partyRoleTypes.addAll(partyRoleTypes);
        return this;
    }

    @Getter
    private List<PartyRole> object = Lists.newArrayList();

    @Override
    public void execute(ExecutionContext executionContext) {

        checkParam("person", executionContext, Person.class);

        for (IPartyRoleType partyRoleType : partyRoleTypes) {
            final PartyRole partyRole = partyRoleTypeService.createRole(person, partyRoleType);
            object.add(partyRole);
        }
    }

    @Inject
    PartyRoleTypeService partyRoleTypeService;

}


text:
<?php

namespace ApaiIO\ResponseTransformer;

/**
 * A responsetransformer transforming a xml to a domdocument
 *
 * @author Jan Eichhorn <exeu65@googlemail.com>
 */
class XmlToDomDocument implements ResponseTransformerInterface
{
    /**
     * {@inheritdoc}
     */
    public function transform($response)
    {
        $document = new \DOMDocument('1.0', 'UTF-8');
        $document->loadXML($response);

        return $document;
    }
}


text:
#import "ANWelcomeWeightGenderMetricsViewController.h"
#import "ANRootNavigationController.h"
#import "ANGaugeView.h"
#import "ANAccount.h"

@interface ANWelcomeWeightGenderMetricsViewController ()

@property (nonatomic, weak) IBOutlet UIButton *nextButton;

@end

@implementation ANWelcomeWeightGenderMetricsViewController

#pragma mark Interface Actions

- (IBAction)backButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)nextButtonPressed:(id)sender {
    ANAccount *account = [ANAccount currentAccount];

    account.accountWeight = @(self.gaugeView.currentValue);
    account.accountWeightMetrics = self.weightMetrics;
    account.accountGender = self.gender;

    [(ANRootNavigationController *)self.navigationController pushViewControllerWithIdentifier:@"welcomeHeightMetricsViewController" animated:YES];
}

#pragma mark View lifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.nextButton.layer.masksToBounds = YES;
    self.nextButton.layer.cornerRadius = 3.0f;

    [self setGender:GenderMale];
    [self setWeightMetrics:WeightMetricsKg];
    [self.gaugeView setCurrentValue:defaultMaleWeight];
}

- (BOOL)shouldAutorotate {
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}

@end


text:
require 'spec_helper'

describe AuthenticationHelper do
  # error when invoking this path, so faking it here.
  def person_omniauth_authorize_path(options ={})
    '/path/here'
  end

  context "unlink_from_facebook_link" do
    it "should return the link" do
      unlink_from_facebook_link.should have_selector 'a.connectacct-link.facebook-auth.disconnect-fb', :href => confirm_facebook_unlinking_path
    end
  end

  context "link_with_facebook_link" do
    it "should return the correct link" do
      link_with_facebook_link.should have_selector 'a.connectacct-link.facebook-auth', :href => "/path/here"
    end
  end

  context "facebook_sign_in_link" do
    it "should return the correct link" do
      facebook_sign_in_link.should have_selector 'a.createacct-link.facebook-auth.fb-login-btn', :href => "/path/here"
    end
  end

  context "person_omniauth_authorize_path_or_url" do
    it "should return the url if https" do
      SecureUrlHelper.stub(:https?).and_return(true)
      person_omniauth_authorize_path_or_url(:facebook).should == 'https://test.host/people/auth/facebook'
    end
    it "should return the path if not https" do
      SecureUrlHelper.stub(:https?).and_return(false)
      person_omniauth_authorize_path_or_url(:facebook).should == '/path/here'
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll_help"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="45dp"
        android:background="@drawable/hold_title_bg"
        android:gravity="center_vertical" >

        <TextView
            style="@style/TextView.Middle.White"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="@string/str_help_str" />

        <Button
            android:id="@+id/btn_about_back"
            style="@style/TextView.Small.White"
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:background="@drawable/title_left_btn_bg"
            android:text="@string/app_back" />
    </RelativeLayout>

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@color/body_bg" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/help_icon"
                style="@style/text_shadow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:maxWidth="250dp"
                android:text="@string/app_name"
                android:textColor="#F5761D"
                android:textSize="40sp"
                android:typeface="monospace" />

            <TextView
                android:id="@+id/tv_about_version"
                style="@style/text_shadow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:text="@string/app_version"
                android:textColor="@color/body_text" />

            <TextView
                android:id="@+id/help_context"
                style="@style/text_shadow"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_marginTop="15dp"
                android:text="@string/str_help_context"
                android:textColor="@color/body_text"
                android:textSize="17sp" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="15dp"
                android:layout_marginTop="60dp"
                android:orientation="vertical" >

                <TextView
                    style="@style/text_shadow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:gravity="center"
                    android:text="@string/app_company"
                    android:textColor="#366596"
                    android:textSize="15sp" />

                <TextView
                    style="@style/text_shadow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="5dp"
                    android:gravity="center"
                    android:text="@string/app_copyright_date"
                    android:textColor="#dd787878"
                    android:textSize="15sp" />

                <TextView
                    style="@style/text_shadow"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginTop="5dp"
                    android:gravity="center"
                    android:text="@string/app_all_right"
                    android:textColor="#dd787878"
                    android:textSize="15sp" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</LinearLayout>


text:
package org.apereo.portal.events;

import javax.servlet.http.HttpServletRequest;
import org.apereo.portal.security.IPerson;

/** Publishes events related to layouts */
public interface IPortalLayoutEventFactory {

    //  ********** Portlet in Layout Events **********//

    void publishPortletAddedToLayoutPortalEvent(
            HttpServletRequest request,
            Object source,
            IPerson layoutOwner,
            long layoutId,
            String parentFolderId,
            String fname);

    void publishPortletAddedToLayoutPortalEvent(
            Object source, IPerson layoutOwner, long layoutId, String parentFolderId, String fname);

    void publishPortletMovedInLayoutPortalEvent(
            HttpServletRequest request,
            Object source,
            IPerson layoutOwner,
            long layoutId,
            String oldParentFolderId,
            String newParentFolderId,
            String fname);

    void publishPortletMovedInLayoutPortalEvent(
            Object source,
            IPerson layoutOwner,
            long layoutId,
            String oldParentFolderId,
            String newParentFolderId,
            String fname);

    void publishPortletDeletedFromLayoutPortalEvent(
            HttpServletRequest request,
            Object source,
            IPerson layoutOwner,
            long layoutId,
            String oldParentFolderId,
            String fname);

    void publishPortletDeletedFromLayoutPortalEvent(
            Object source,
            IPerson layoutOwner,
            long layoutId,
            String oldParentFolderId,
            String fname);

    void publishFolderAddedToLayoutPortalEvent(
            HttpServletRequest request,
            Object source,
            IPerson layoutOwner,
            long layoutId,
            String newFolderId);

    //********** Folder in Layout Events **********//

    void publishFolderAddedToLayoutPortalEvent(
            Object source, IPerson layoutOwner, long layoutId, String newFolderId);

    void publishFolderMovedInLayoutPortalEvent(
            HttpServletRequest request,
            Object source,
            IPerson layoutOwner,
            long layoutId,
            String oldParentFolderId,
            String movedFolderId);

    void publishFolderMovedInLayoutPortalEvent(
            Object source,
            IPerson layoutOwner,
            long layoutId,
            String oldParentFolderId,
            String movedFolderId);

    void publishFolderDeletedFromLayoutPortalEvent(
            HttpServletRequest request,
            Object source,
            IPerson layoutOwner,
            long layoutId,
            String oldParentFolderId,
            String deletedFolderId,
            String deletedFolderName);

    void publishFolderDeletedFromLayoutPortalEvent(
            Object source,
            IPerson layoutOwner,
            long layoutId,
            String oldParentFolderId,
            String deletedFolderId,
            String deletedFolderName);
}


text:
@interface SPCreateCompleteViewController : SPBaseViewController

@end


text:
using System;

namespace QuotesinStrings
{
    class QuotesinStrings
    {
        static void Main()
        {

            string escaped = "The \"use\" of quotations causes difficulties.";
            string quoted = @"The ""use"" of quotations causes difficulties.";

            Console.WriteLine(escaped);
            Console.WriteLine(quoted);
        }
    }
}


text:
/*
 * (c) 2015 CenturyLink. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.centurylink.cloud.sdk.server.services.dsl.domain.group;

import com.centurylink.cloud.sdk.core.client.ClcClientException;

import java.time.Duration;
import java.time.OffsetDateTime;

import static com.centurylink.cloud.sdk.core.preconditions.Preconditions.checkNotNull;

/**
 * @author aliaksandr.krasitski
 */
public class ServerMonitoringConfigValidator {
    private ServerMonitoringFilter config;

    private void checkMonitoringConfig(ServerMonitoringFilter config) {
        checkNotNull(config.getFrom(), "From date must be not a null");

        if (config.getInterval() == null) {
            config.interval(
                config.getType() == MonitoringType.HOURLY
                    ? ServerMonitoringFilter.DEFAULT_HOURLY_INTERVAL
                    : ServerMonitoringFilter.DEFAULT_REALTIME_INTERVAL
            );
        }

        OffsetDateTime to = config.getTo() != null ? config.getTo() : OffsetDateTime.now();

        if (config.getFrom().isAfter(to)) {
            throw new ClcClientException("Start date cannot be more than end date");
        }

        if (Duration.between(config.getFrom(), to).getSeconds() < config.getInterval().getSeconds()) {
            throw new ClcClientException("Interval must fit within start/end date");
        }
    }

    public MonitoringConfigValidator getValidator(ServerMonitoringFilter config) {
        this.config = config;
        switch (config.getType()) {
            case HOURLY: {
                return new HourlyMonitoringConfigValidator();
            }
            case REALTIME: {
                return new RealtimeMonitoringConfigValidator();
            }
            case LATEST: {
                return new LatestMonitoringConfigValidator();
            }
            default: return null;
        }
    }

    interface MonitoringConfigValidator {
        default void validate() {
            //no validation needed
        }
    }

    class HourlyMonitoringConfigValidator implements MonitoringConfigValidator{
        @Override
        public void validate() {
            checkMonitoringConfig(config);

            if (config.getFrom().isBefore(OffsetDateTime.now().minusDays(ServerMonitoringFilter.MAX_HOURLY_PERIOD_DAYS))) {
                throw new ClcClientException(String.format(
                    "Start date must be within the past %s day(s)",
                        ServerMonitoringFilter.MAX_HOURLY_PERIOD_DAYS)
                );
            }

            if (config.getInterval().toHours() < ServerMonitoringFilter.MIN_HOURLY_INTERVAL_HOURS) {
                throw new ClcClientException(String.format(
                    "Interval must be not less than %s hour(s)",
                        ServerMonitoringFilter.MIN_HOURLY_INTERVAL_HOURS)
                );
            }
        }
    }

    class RealtimeMonitoringConfigValidator implements MonitoringConfigValidator {

        @Override
        public void validate() {
            checkMonitoringConfig(config);

            if (config.getFrom().isBefore(
                    OffsetDateTime.now().minusHours(ServerMonitoringFilter.MAX_REALTIME_PERIOD_HOURS))
            ) {
                throw new ClcClientException(String.format(
                    "Start date must be within the past %s hour(s)",
                        ServerMonitoringFilter.MAX_REALTIME_PERIOD_HOURS)
                );
            }

            if (config.getInterval().toMinutes() < ServerMonitoringFilter.MIN_REALTIME_INTERVAL_MINUTES) {
                throw new ClcClientException(String.format(
                    "Interval must be not less than %s minute(s)",
                        ServerMonitoringFilter.MIN_REALTIME_INTERVAL_MINUTES)
                );
            }
        }
    }

    class LatestMonitoringConfigValidator implements MonitoringConfigValidator {}
}


text:
from __future__ import absolute_import, division, print_function, unicode_literals

import pytest ; pytest

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# Standard library imports

# External imports

# Bokeh imports
from bokeh._testing.util.api import verify_all

# Module under test
#import bokeh.sampledata.unemployment as bsu

#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------

ALL = (
    'data',
)

#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------

Test___all__ = pytest.mark.sampledata(verify_all("bokeh.sampledata.unemployment", ALL))

@pytest.mark.sampledata
def test_data():
    import bokeh.sampledata.unemployment as bsu
    assert isinstance(bsu.data, dict)

    # don't check detail for external data

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------


text:
package kr.simula.formula.core.wrapper;

import java.util.List;

import kr.simula.formula.core.Context;
import kr.simula.formula.core.EvalException;
import kr.simula.formula.core.Function;
import kr.simula.formula.core.Gettable;
import kr.simula.formula.core.GrammarTokens;
import kr.simula.formula.core.Ref;
import kr.simula.formula.core.ref.GettableRef;
import kr.simula.formula.core.ref.TypeLateBinding;

/**
 *

 * @author kighie@gmail.com
 * @param <T>
 * @since 1.0
 */
public class ClosureCallWrapper<T> extends AbstractNode implements Gettable<T>, TypeLateBinding<T> {
	/**
	 *
	 */
	private static final long serialVersionUID = -5345606569254867627L;
	protected final GettableRef<Function<?>> closureRef;
	protected final Gettable<?>[] args;
	private Class<? extends T> type;

	/**
	 * @param closureRef
	 * @param args
	 */
	public ClosureCallWrapper(GettableRef<Function<?>> closureRef, Gettable<?>[] args) {
		this.closureRef = closureRef;
		this.args = args;
	}

//	@Override
//	public ValueType valueType() {
//		return ValueTypeUtils.getValueType(type);
//	}

	@Override
	public String getToken() {
		return GrammarTokens.FUNC_CALL;
	};

	@Override
	public Class<? extends T> type() {
		return type;
	}

	@Override
	public void setRequiredType(Class<? extends T> requiredType) {
		this.type = requiredType;
	}

	protected String getFunctionName(){
		return closureRef.qualifiedName().getName();
	}

	@Override
	public String getExpression() {
		StringBuilder buf = new StringBuilder();
		buf.append("(").append(closureRef);
		for(Gettable<?> n : args){
			buf.append(" ").append(n.getExpression());
		}
		buf.append(")");

		return buf.toString();
	}

	@Override
	public T get(Context context) {
		@SuppressWarnings("unchecked")
		Function<T> function = (Function<T>)closureRef.get(context);

		if(function != null){
			if( function instanceof FunctionSpi){
				return evalLocalFunction((FunctionSpi<T>)function, context);
			} else {
				return evalBuiltInFunction(function, context);
			}
		} else {
			throw new EvalException(closureRef, closureRef + " is not registered.");
		}
	}

	protected T evalLocalFunction(FunctionSpi<T> localFn, Context context){
		List<Ref> argDecls = localFn.getArgs();
		int length = argDecls.size();

		if(args.length != length){
			throw new EvalException(this, closureRef.qualifiedName().getName() + " has " + args.length + " args."
					+ " But original function needs " + length + "args.");
		}
		Ref argD;
		Object argV;

		for(int i=0;i<length;i++){
			argD = argDecls.get(i);
			argV = args[i].get(context);
			context.setReference(argD.qualifiedName(), argV);
		}

		return localFn.evalFunc(context);
	}

	protected T evalBuiltInFunction(Function<T> function, Context context){
		int length = args.length;

		Object[] arguments = new Object[length];

		for(int i=0;i<length;i++){
			arguments[i] = args[i].get(context);
		}

		return function.eval(arguments);
	}
}


text:
package com.azure.resourcemanager.deploymentmanager.implementation;

import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.deploymentmanager.fluent.StepsClient;
import com.azure.resourcemanager.deploymentmanager.fluent.models.StepResourceInner;
import com.azure.resourcemanager.deploymentmanager.models.StepResource;
import com.azure.resourcemanager.deploymentmanager.models.Steps;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public final class StepsImpl implements Steps {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(StepsImpl.class);

    private final StepsClient innerClient;

    private final com.azure.resourcemanager.deploymentmanager.DeploymentManager serviceManager;

    public StepsImpl(
        StepsClient innerClient, com.azure.resourcemanager.deploymentmanager.DeploymentManager serviceManager) {
        this.innerClient = innerClient;
        this.serviceManager = serviceManager;
    }

    public StepResource getByResourceGroup(String resourceGroupName, String stepName) {
        StepResourceInner inner = this.serviceClient().getByResourceGroup(resourceGroupName, stepName);
        if (inner != null) {
            return new StepResourceImpl(inner, this.manager());
        } else {
            return null;
        }
    }

    public Response<StepResource> getByResourceGroupWithResponse(
        String resourceGroupName, String stepName, Context context) {
        Response<StepResourceInner> inner =
            this.serviceClient().getByResourceGroupWithResponse(resourceGroupName, stepName, context);
        if (inner != null) {
            return new SimpleResponse<>(
                inner.getRequest(),
                inner.getStatusCode(),
                inner.getHeaders(),
                new StepResourceImpl(inner.getValue(), this.manager()));
        } else {
            return null;
        }
    }

    public void deleteByResourceGroup(String resourceGroupName, String stepName) {
        this.serviceClient().delete(resourceGroupName, stepName);
    }

    public Response<Void> deleteWithResponse(String resourceGroupName, String stepName, Context context) {
        return this.serviceClient().deleteWithResponse(resourceGroupName, stepName, context);
    }

    public List<StepResource> list(String resourceGroupName) {
        List<StepResourceInner> inner = this.serviceClient().list(resourceGroupName);
        if (inner != null) {
            return Collections
                .unmodifiableList(
                    inner
                        .stream()
                        .map(inner1 -> new StepResourceImpl(inner1, this.manager()))
                        .collect(Collectors.toList()));
        } else {
            return Collections.emptyList();
        }
    }

    public Response<List<StepResource>> listWithResponse(String resourceGroupName, Context context) {
        Response<List<StepResourceInner>> inner = this.serviceClient().listWithResponse(resourceGroupName, context);
        if (inner != null) {
            return new SimpleResponse<>(
                inner.getRequest(),
                inner.getStatusCode(),
                inner.getHeaders(),
                inner
                    .getValue()
                    .stream()
                    .map(inner1 -> new StepResourceImpl(inner1, this.manager()))
                    .collect(Collectors.toList()));
        } else {
            return null;
        }
    }

    public StepResource getById(String id) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String stepName = Utils.getValueFromIdByName(id, "steps");
        if (stepName == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'steps'.", id)));
        }
        return this.getByResourceGroupWithResponse(resourceGroupName, stepName, Context.NONE).getValue();
    }

    public Response<StepResource> getByIdWithResponse(String id, Context context) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String stepName = Utils.getValueFromIdByName(id, "steps");
        if (stepName == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'steps'.", id)));
        }
        return this.getByResourceGroupWithResponse(resourceGroupName, stepName, context);
    }

    public void deleteById(String id) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String stepName = Utils.getValueFromIdByName(id, "steps");
        if (stepName == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'steps'.", id)));
        }
        this.deleteWithResponse(resourceGroupName, stepName, Context.NONE).getValue();
    }

    public Response<Void> deleteByIdWithResponse(String id, Context context) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String stepName = Utils.getValueFromIdByName(id, "steps");
        if (stepName == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'steps'.", id)));
        }
        return this.deleteWithResponse(resourceGroupName, stepName, context);
    }

    private StepsClient serviceClient() {
        return this.innerClient;
    }

    private com.azure.resourcemanager.deploymentmanager.DeploymentManager manager() {
        return this.serviceManager;
    }

    public StepResourceImpl define(String name) {
        return new StepResourceImpl(name, this.manager());
    }
}