text:
package me.yluo.ruisiapp.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;

import java.io.File;
import java.math.BigDecimal;

import me.yluo.ruisiapp.App;
import me.yluo.ruisiapp.database.SQLiteHelper;
import me.yluo.ruisiapp.myhttp.HttpUtil;

/**
 * Created by yang on 16-6-20.
 * 计算和清除缓存
 */
public class DataManager {

    public static String getTotalCacheSize(Context context) {
        long cacheSize = 0;
        try {
            cacheSize = getFolderSize(context.getCacheDir());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                cacheSize += getFolderSize(context.getExternalCacheDir());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return getFormatSize(cacheSize);
    }

    /**
     * 清除本应用所有的数据
     */
    public static void cleanApplicationData(Context context, String... filepath) {
        SharedPreferences perUserInfo = context.getSharedPreferences(App.MY_SHP_NAME,
                Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = perUserInfo.edit();
        boolean isRemember = perUserInfo.getBoolean(App.IS_REMBER_PASS_USER, false);
        String userName = perUserInfo.getString(App.LOGIN_NAME, "");
        String userPass = perUserInfo.getString(App.LOGIN_PASS, "");

        cleanInternalCache(context);
        cleanExternalCache(context);
        cleanSharedPreference(context);
        cleanFiles(context);

        cleanDatabaseByName(context, SQLiteHelper.DATABASE_NAME);

        for (String filePath : filepath) {
            cleanCustomCache(filePath);
        }
        //删除cookie
        HttpUtil.exit();

        // 先清理shp数据,然后把之前保存的用户名和密码保存
        editor.clear();
        editor.apply();
        editor.putBoolean(App.IS_REMBER_PASS_USER, isRemember);
        editor.putString(App.LOGIN_NAME, userName);
        editor.putString(App.LOGIN_PASS, userPass);
        editor.apply();
    }

    private static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();

            if (fileList == null) {
                return 0;
            }
            for (File aFileList : fileList) {
                // 如果下面还有文件
                if (aFileList == null) {
                    continue;
                }
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 格式化单位
     */
    private static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
//            return size + "Byte";
            return "0K";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

    /***
     * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache)
     */
    private static void cleanInternalCache(Context context) {
        deleteFilesByDirectory(context.getCacheDir());
    }

    /***
     * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs)
     */
    private static void cleanSharedPreference(Context context) {
        deleteFilesByDirectory(new File("/data/data/" + context.getPackageName() + "/shared_prefs"));
    }

    /**
     * 按名字清除本应用数据库
     */
    private static void cleanDatabaseByName(Context context, String dbName) {
        context.deleteDatabase(dbName);
    }

    /**
     * 清除/data/data/com.xxx.xxx/files
     */
    private static void cleanFiles(Context context) {
        deleteFilesByDirectory(context.getFilesDir());
    }

    /**
     * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
     */
    private static void cleanExternalCache(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteFilesByDirectory(context.getExternalCacheDir());
        }
    }

    /**
     * 清除自定义路径下的文件,使用需小心,请不要误删。而且只支持目录下的文件删除
     */
    private static void cleanCustomCache(String filePath) {
        deleteFilesByDirectory(new File(filePath));
    }

    /***
     * 删除方法 这里只会删除某个文件夹下的文件,如果传入的directory是个文件,将不做处理
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }
}


text:
package org.apache.directory.server.operations.bind;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.OperationNotSupportedException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;

import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPException;
import netscape.ldap.LDAPUrl;

import org.apache.commons.lang.ArrayUtils;
import org.apache.directory.api.asn1.util.Asn1StringUtils;
import org.apache.directory.api.ldap.model.constants.SupportedSaslMechanisms;
import org.apache.directory.api.ldap.model.message.Control;
import org.apache.directory.api.ldap.model.message.controls.OpaqueControl;
import org.apache.directory.api.ldap.util.JndiUtils;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ContextEntry;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreateIndex;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.apache.directory.server.ldap.handlers.extended.StoredProcedureExtendedOperationHandler;
import org.apache.directory.server.ldap.handlers.sasl.MechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.SimpleMechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.cramMD5.CramMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.digestMD5.DigestMd5MechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.gssapi.GssapiMechanismHandler;
import org.apache.directory.server.ldap.handlers.sasl.ntlm.NtlmMechanismHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * A set of miscellaneous tests.
 *
 * @author Apache Directory Project
 */
@RunWith(FrameworkRunner.class)
@CreateDS(allowAnonAccess = true, name = "MiscBindIT-class",
    partitions =
        {
            @CreatePartition(
                name = "example",
                suffix = "dc=aPache,dc=org",
                contextEntry = @ContextEntry(
                    entryLdif =
                    "dn: dc=aPache,dc=org\n" +
                        "dc: aPache\n" +
                        "objectClass: top\n" +
                        "objectClass: domain\n\n"),
                indexes =
                    {
                        @CreateIndex(attribute = "objectClass"),
                        @CreateIndex(attribute = "dc"),
                        @CreateIndex(attribute = "ou")
                })
    })
@CreateLdapServer(
    transports =
        {
            @CreateTransport(protocol = "LDAP")
    })
public class MiscBindIT extends AbstractLdapTestUnit
{
    private boolean oldAnnonymousAccess;

    @Before
    public void init() throws Exception
    {
        getLdapServer().addExtendedOperationHandler( new StoredProcedureExtendedOperationHandler() );

        // Setup SASL Mechanisms

        Map<String, MechanismHandler> mechanismHandlerMap = new HashMap<String, MechanismHandler>();
        mechanismHandlerMap.put( SupportedSaslMechanisms.PLAIN, new SimpleMechanismHandler() );

        CramMd5MechanismHandler cramMd5MechanismHandler = new CramMd5MechanismHandler();
        mechanismHandlerMap.put( SupportedSaslMechanisms.CRAM_MD5, cramMd5MechanismHandler );

        DigestMd5MechanismHandler digestMd5MechanismHandler = new DigestMd5MechanismHandler();
        mechanismHandlerMap.put( SupportedSaslMechanisms.DIGEST_MD5, digestMd5MechanismHandler );

        GssapiMechanismHandler gssapiMechanismHandler = new GssapiMechanismHandler();
        mechanismHandlerMap.put( SupportedSaslMechanisms.GSSAPI, gssapiMechanismHandler );

        NtlmMechanismHandler ntlmMechanismHandler = new NtlmMechanismHandler();
        mechanismHandlerMap.put( SupportedSaslMechanisms.NTLM, ntlmMechanismHandler );
        mechanismHandlerMap.put( SupportedSaslMechanisms.GSS_SPNEGO, ntlmMechanismHandler );

        getLdapServer().setSaslMechanismHandlers( mechanismHandlerMap );
        oldAnnonymousAccess = getLdapServer().getDirectoryService().isAllowAnonymousAccess();
    }

    @After
    public void revertAnonnymous()
    {
        getLdapServer().getDirectoryService().setAllowAnonymousAccess( oldAnnonymousAccess );
    }

    /**
     * Test to make sure anonymous binds are disabled when going through
     * the wire protocol.
     *
     * @throws Exception if anything goes wrong
     */
    @Test
    public void testDisableAnonymousBinds() throws Exception
    {
        getLdapServer().getDirectoryService().setAllowAnonymousAccess( false );

        // Use the SUN JNDI provider to hit server port and bind as anonymous
        final Hashtable<String, Object> env = new Hashtable<String, Object>();

        env.put( Context.PROVIDER_URL, "ldap://localhost:" + getLdapServer().getPort() + "/ou=system" );
        env.put( Context.SECURITY_AUTHENTICATION, "none" );
        env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );

        try
        {
            new InitialDirContext( env );
            fail();
        }
        catch ( Exception e )
        {
            // We should get here
        }

        try
        {
            // Use the netscape API as JNDI cannot be used to do a search without
            // first binding.
            LDAPUrl url = new LDAPUrl( "localhost", getLdapServer().getPort(), "ou=system", new String[]
                { "vendorName" }, 0, "(ObjectClass=*)" );
            LDAPConnection.search( url );

            fail();
        }
        catch ( LDAPException e )
        {
            // Expected result
        }
    }

    /**
     * Test to make sure anonymous binds are allowed on the RootDSE even when disabled
     * in general when going through the wire protocol.
     *
     * @throws Exception if anything goes wrong
     */
    @Test
    public void testEnableAnonymousBindsOnRootDse() throws Exception
    {
        getLdapServer().getDirectoryService().setAllowAnonymousAccess( true );

        // Use the SUN JNDI provider to hit server port and bind as anonymous
        Hashtable<String, Object> env = new Hashtable<String, Object>();

        env.put( Context.PROVIDER_URL, "ldap://localhost:" + getLdapServer().getPort() + "/" );
        env.put( Context.SECURITY_AUTHENTICATION, "none" );
        env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );

        InitialDirContext ctx = new InitialDirContext( env );
        SearchControls cons = new SearchControls();
        cons.setSearchScope( SearchControls.OBJECT_SCOPE );
        NamingEnumeration<SearchResult> list = ctx.search( "", "(objectClass=*)", cons );

        SearchResult result = null;

        if ( list.hasMore() )
        {
            result = list.next();
        }

        assertFalse( list.hasMore() );
        list.close();

        assertNotNull( result );
        assertEquals( "", result.getName().trim() );
    }

    /**
     * Test to make sure that if anonymous binds are allowed a user may search
     * within a a partition.
     *
     * @throws Exception if anything goes wrong
     */
    @Test
    public void testAnonymousBindsEnabledBaseSearch() throws Exception
    {
        getLdapServer().getDirectoryService().setAllowAnonymousAccess( true );

        // Use the SUN JNDI provider to hit server port and bind as anonymous
        Hashtable<String, Object> env = new Hashtable<String, Object>();

        env.put( Context.PROVIDER_URL, "ldap://localhost:" + getLdapServer().getPort() + "/" );
        env.put( Context.SECURITY_AUTHENTICATION, "none" );
        env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );

        InitialDirContext ctx = new InitialDirContext( env );
        SearchControls cons = new SearchControls();
        cons.setSearchScope( SearchControls.OBJECT_SCOPE );
        NamingEnumeration<SearchResult> list = ctx.search( "dc=apache,dc=org", "(objectClass=*)", cons );
        SearchResult result = null;

        if ( list.hasMore() )
        {
            result = list.next();
        }

        assertFalse( list.hasMore() );
        list.close();

        assertNotNull( result );
        assertNotNull( result.getAttributes().get( "dc" ) );
    }

    /**
     * Reproduces the problem with
     * DIREVE-239.
     *
     * @throws Exception if anything goes wrong
     */
    @Test
    public void testAdminAccessBug() throws Exception
    {
        getLdapServer().getDirectoryService().setAllowAnonymousAccess( true );

        // Use the SUN JNDI provider to hit server port and bind as anonymous

        final Hashtable<String, Object> env = new Hashtable<String, Object>();

        env.put( Context.PROVIDER_URL, "ldap://localhost:" + getLdapServer().getPort() );
        env.put( "java.naming.ldap.version", "3" );
        env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );

        Attributes attributes = new BasicAttributes( true );
        Attribute objectClass = new BasicAttribute( "objectClass" );
        objectClass.add( "top" );
        objectClass.add( "organizationalUnit" );
        attributes.put( objectClass );
        attributes.put( "ou", "blah" );
        InitialDirContext ctx = new InitialDirContext( env );
        ctx.createSubcontext( "ou=blah,ou=system", attributes );
        SearchControls controls = new SearchControls();
        controls.setSearchScope( SearchControls.OBJECT_SCOPE );
        controls.setReturningAttributes( new String[]
            { "+" } );
        NamingEnumeration<SearchResult> list = ctx.search( "ou=blah,ou=system", "(objectClass=*)", controls );
        SearchResult result = list.next();
        list.close();
        Attribute creatorsName = result.getAttributes().get( "creatorsName" );
        assertEquals( "", creatorsName.get() );
        ctx.destroySubcontext( "ou=blah,ou=system" );
    }

    /**
     * Test case for <a href="http://issues.apache.org/jira/browse/DIREVE-284" where users in
     * mixed case partitions were not able to authenticate properly.  This test case creates
     * a new partition under dc=aPache,dc=org, it then creates the example user in the JIRA
     * issue and attempts to authenticate as that user.
     *
     * @throws Exception if the user cannot authenticate or test fails
     */
    @Test
    public void testUserAuthOnMixedCaseSuffix() throws Exception
    {
        getLdapServer().getDirectoryService().setAllowAnonymousAccess( true );

        Hashtable<String, Object> env = new Hashtable<String, Object>();

        env.put( Context.PROVIDER_URL, "ldap://localhost:" + getLdapServer().getPort() + "/dc=aPache,dc=org" );
        env.put( "java.naming.ldap.version", "3" );
        env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
        InitialDirContext ctx = new InitialDirContext( env );
        Attributes attrs = ctx.getAttributes( "" );
        assertTrue( attrs.get( "dc" ).get().equals( "aPache" ) );

        Attributes user = new BasicAttributes( "cn", "Kate Bush", true );
        Attribute oc = new BasicAttribute( "objectClass" );
        oc.add( "top" );
        oc.add( "person" );
        oc.add( "organizationalPerson" );
        oc.add( "inetOrgPerson" );
        user.put( oc );
        user.put( "sn", "Bush" );
        user.put( "userPassword", "Aerial" );
        ctx.createSubcontext( "cn=Kate Bush", user );

        env.put( Context.SECURITY_AUTHENTICATION, "simple" );
        env.put( Context.SECURITY_CREDENTIALS, "Aerial" );
        env.put( Context.SECURITY_PRINCIPAL, "cn=Kate Bush,dc=aPache,dc=org" );

        InitialDirContext userCtx = new InitialDirContext( env );
        assertNotNull( userCtx );

        ctx.destroySubcontext( "cn=Kate Bush" );
    }

    @Test
    public void testFailureWithUnsupportedControl() throws Exception
    {
        Control unsupported = new OpaqueControl( "1.1.1.1" );
        unsupported.setCritical( true );

        getLdapServer().getDirectoryService().setAllowAnonymousAccess( true );

        Hashtable<String, Object> env = new Hashtable<String, Object>();

        env.put( Context.PROVIDER_URL, "ldap://localhost:" + getLdapServer().getPort() + "/ou=system" );
        env.put( "java.naming.ldap.version", "3" );
        env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
        env.put( Context.SECURITY_AUTHENTICATION, "simple" );
        env.put( Context.SECURITY_CREDENTIALS, "secret" );
        env.put( Context.SECURITY_PRINCIPAL, "uid=admin,ou=system" );
        InitialLdapContext ctx = new InitialLdapContext( env, null );

        Attributes user = new BasicAttributes( "cn", "Kate Bush", true );
        Attribute oc = new BasicAttribute( "objectClass" );
        oc.add( "top" );
        oc.add( "person" );
        oc.add( "organizationalPerson" );
        oc.add( "inetOrgPerson" );
        user.put( oc );
        user.put( "sn", "Bush" );
        user.put( "userPassword", "Aerial" );
        ctx.setRequestControls( JndiUtils.toJndiControls( getLdapServer().getDirectoryService().getLdapCodecService(),
            new Control[]
                { unsupported } ) );

        try
        {
            ctx.createSubcontext( "cn=Kate Bush", user );
            fail();
        }
        catch ( OperationNotSupportedException e )
        {
        }

        unsupported.setCritical( false );
        ctx.setRequestControls( JndiUtils.toJndiControls( getLdapServer().getDirectoryService().getLdapCodecService(),
            new Control[]
                { unsupported } ) );

        DirContext kate = ctx.createSubcontext( "cn=Kate Bush", user );
        assertNotNull( kate );
        assertTrue( ArrayUtils.isEquals( Asn1StringUtils.getBytesUtf8( "Aerial" ), kate.getAttributes( "" ).get(
            "userPassword" ).get() ) );

        ctx.destroySubcontext( "cn=Kate Bush" );
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;
using live.asp.net.Models;
using live.asp.net.Services;
using live.asp.net.ViewModels;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;

namespace live.asp.net.Controllers
{
    [Route("/admin")]
    [Authorize("Admin")]
    public class AdminController : Controller
    {
        private readonly ILiveShowDetailsService _liveShowDetails;
        private readonly IMemoryCache _memoryCache;
        private readonly AppSettings _appSettings;
        private readonly IHostingEnvironment _env;
        private readonly TelemetryClient _telemetry;
        private readonly IObjectMapper _mapper;

        public AdminController(
            IHostingEnvironment env,
            ILiveShowDetailsService liveShowDetails,
            IMemoryCache memoryCache,
            IOptions<AppSettings> appSettings,
            IObjectMapper mapper,
            TelemetryClient telemetry)
        {
            _liveShowDetails = liveShowDetails;
            _memoryCache = memoryCache;
            _appSettings = appSettings.Value;
            _env = env;
            _mapper = mapper;
            _telemetry = telemetry;
        }

        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var model = new AdminViewModel
            {
                SuccessMessage = (string)TempData[nameof(AdminViewModel.SuccessMessage)]
            };

            var liveShowDetails = await _liveShowDetails.LoadAsync();

            UpdateAdminViewModel(model, liveShowDetails);

            return View(model);
        }

        [ModelMetadataType(typeof(AdminViewModel))]
        public class AdminInputModel
        {
            public string LiveShowEmbedUrl { get; set; }

            public string LiveShowHtml { get; set; }

            public DateTime? NextShowDatePst { get; set; }

            public string AdminMessage { get; set; }
        }

        [HttpPost]
        public async Task<IActionResult> Save(AdminInputModel input)
        {
            var liveShowDetails = await _liveShowDetails.LoadAsync() ?? new LiveShowDetails();

            if (!ModelState.IsValid)
            {
                // Model validation error, just return and let the error render
                var viewModel = new AdminViewModel();
                UpdateAdminViewModel(viewModel, liveShowDetails);

                return View(nameof(Index), viewModel);
            }

            if (!string.IsNullOrEmpty(input.LiveShowEmbedUrl))
            {
                // Convert live show url to HTTPS if need be
                if (input.LiveShowEmbedUrl.StartsWith("http://"))
                {
                    input.LiveShowEmbedUrl = "https://" + input.LiveShowEmbedUrl.Substring("http://".Length);
                }

                // Convert watch URL to embed URL
                if (input.LiveShowEmbedUrl.StartsWith("https://www.youtube.com/watch?v=", StringComparison.OrdinalIgnoreCase))
                {
                    var queryIndex = input.LiveShowEmbedUrl.LastIndexOf("?v=", StringComparison.OrdinalIgnoreCase);
                    var showIdLength = input.LiveShowEmbedUrl.IndexOf('&', queryIndex) - 3 - queryIndex;
                    var showId = showIdLength > 0 ? input.LiveShowEmbedUrl.Substring(queryIndex + 3, showIdLength) : input.LiveShowEmbedUrl.Substring(queryIndex + 3);
                    input.LiveShowEmbedUrl = $"https://www.youtube.com/embed/{showId}";
                }
            }

            TrackShowEvent(input, liveShowDetails);

            _mapper.Map(input, liveShowDetails);
            liveShowDetails.NextShowDateUtc = input.NextShowDatePst?.ConvertFromPtcToUtc();

            await _liveShowDetails.SaveAsync(liveShowDetails);

            TempData[nameof(AdminViewModel.SuccessMessage)] = "Live show details saved successfully!";

            return RedirectToAction(nameof(Index));
        }

        [HttpPost("clearcache")]
        public IActionResult ClearCache()
        {
            _memoryCache.Remove(YouTubeShowsService.CacheKey);

            TempData[nameof(AdminViewModel.SuccessMessage)] = "YouTube cache cleared successfully!";

            return RedirectToAction(nameof(Index));
        }

        private void TrackShowEvent(AdminInputModel input, LiveShowDetails liveShowDetails)
        {
            if (_telemetry.IsEnabled())
            {
                var showStarted = string.IsNullOrEmpty(liveShowDetails.LiveShowEmbedUrl) && !string.IsNullOrEmpty(input.LiveShowEmbedUrl);
                var showEnded = !string.IsNullOrEmpty(liveShowDetails.LiveShowEmbedUrl) && string.IsNullOrEmpty(input.LiveShowEmbedUrl);

                if (showStarted || showEnded)
                {
                    var showEvent = new EventTelemetry(showStarted ? "Show Started" : "Show Ended");
                    showEvent.Properties.Add("Show Embed URL", showStarted ? input.LiveShowEmbedUrl : liveShowDetails.LiveShowEmbedUrl);
                    _telemetry.TrackEvent(showEvent);
                }
            }
        }

        private void UpdateAdminViewModel(AdminViewModel model, LiveShowDetails liveShowDetails)
        {
            _mapper.Map(liveShowDetails, model);
            model.NextShowDatePst = liveShowDetails?.NextShowDateUtc?.ConvertFromUtcToPst();

            var nextTuesday = GetNextTuesday();
            model.NextShowDateSuggestionPstAM = nextTuesday.AddHours(10).ToString("yyyy-MM-ddTHH:mm");
            model.NextShowDateSuggestionPstPM = nextTuesday.AddHours(15).AddMinutes(45).ToString("yyyy-MM-ddTHH:mm");

            model.AppSettings = _appSettings;
            model.EnvironmentName = _env.EnvironmentName;
        }

        private DateTime GetNextTuesday()
        {
            var nowPst = DateTime.UtcNow.ConvertFromUtcToPst();
            var remainingDays = 7 - ((int) nowPst.DayOfWeek + 5) % 7;
            var nextTuesday = nowPst.AddDays(remainingDays);

            return nextTuesday.Date;
        }
    }
}


text:
title: Go becomes more stable
date: 2011-03-16
by:
- Andrew Gerrand
tags:
- release
summary: Moving from weekly unstable Go releases toward less frequent, more stable ones.
---

The Go project is moving fast. As we learn more about Go we are compelled
to change our tools,
libraries, and occasionally even the language itself.
We permit backward-incompatible changes so that we can learn from,
rather than immortalize, our mistakes.
We believe flexibility at this stage of Go's development is essential
to the project's development and,
ultimately, its longevity.

Since Go's launch we have been making releases approximately once a week.
Accompanying each release are [notes describing what changed](/doc/devel/release.html),
with any backwards-incompatible changes signposted.
Questions I hear often are "Is Go stable? How can I be sure that I won't
have to update my Go code every week?" The answer to those questions are
now "Yes," and "You won't."

With this week's release we're introducing a new release tagging scheme.
We intend to continue with our weekly releases,
but have renamed the existing tags from `release` to `weekly`.
The `release` tag will now be applied to one hand-picked stable release each month or two.
This more relaxed release schedule should make life easier for the average Go programmer.

Users will still need to update their code periodically (this is the cost
of using a young language) but with less frequency.
An additional benefit is that by tagging stable releases less often we can
put more effort into automating updates.
To this end we have introduced gofix, a tool that will help you update your code.

The revision formerly tagged `release.2011-03-07.1` (now `weekly.2011-03-07.1`)
has been nominated our first stable release,
and has been given the tag `release.r56`.
As we tag each stable release we will post an announcement to the new [golang-announce](http://groups.google.com/group/golang-announce) mailing list.
(Why not [subscribe now](http://groups.google.com/group/golang-announce/subscribe)?)

What's the upshot of all this? You can continue to keep your Go installation
updated using `hg update release`,
but now you should only need to update when we tag a new stable release.
If you wish to stay at the leading edge, you should switch to the weekly
tag with `hg update weekly`.

Happy coding!


text:
var searchData=
[
  ['welcomelastplayermenu',['WelcomeLastPlayerMenu',['../class_symp_1_1_welcome_last_player_menu.html',1,'Symp']]],
  ['welcomeunknownmenu',['WelcomeUnknownMenu',['../class_symp_1_1_welcome_unknown_menu.html',1,'Symp']]],
  ['window',['Window',['../class_symp_1_1_window.html',1,'Symp']]]
];


text:
function [time,data] = acquireData(NI,sampleRate,duration)
    %Gathers data for <duration> seconds.

    data = zeros(duration*sampleRate,1);
    time = zeros(duration*sampleRate,1);
    lastIndex = 1;
    flushdata(NI); %Clear current available samples
    availableSamples = 0;
    while lastIndex < duration*sampleRate
        while availableSamples == 0
            pause(duration); %wait for average time required to get 1 sample
            availableSamples = NI.SamplesAvailable;
        end
        [newData newTime] = getdata(NI,availableSamples); %get new data since last read

        %%% add new data:
        data(lastIndex:availableSamples+lastIndex-1) = newData;
        time(lastIndex:availableSamples+lastIndex-1) = newTime;

        lastIndex = lastIndex + availableSamples;
        availableSamples = 0;
    end

end


text:
namespace HandyUtilities.PoolSystem
{
    using UnityEngine;

    public abstract class PooledObject<T> : MonoBehaviour where T : PooledObject<T>
    {
        Transform m_transform;

        public abstract PoolContainer<T> pool { get; set; }

        bool m_isActive = true;

        public abstract T Object { get; }

        public Transform cachedTransform
        {
            get
            {
                return m_transform;
            }
        }

        public virtual bool isVisible
        {
            get
            {
                return true;
            }
        }

        public bool isActive { get { return m_isActive; } }

        public virtual void Init()
        {
            m_transform = transform;
        }

        public virtual void Pick()
        {
            SetActive(true);
        }

        public void SetActive(bool active)
        {
            gameObject.SetActive(active);
            m_isActive = active;
        }

        public virtual bool IsReadyToPick()
        {
            return !isActive;
        }

        public virtual void Prepare()
        {

        }

        public virtual void ResetObject()
        {
            SetActive(false);
        }
    }
}


text:
package com.angkorteam.fintech.dto.builder.client.center;

import java.io.Serializable;

import io.github.openunirest.http.JsonNode;

public class CenterNoteBuilder implements Serializable {

    private String centerId;
    private boolean hasCenterId;

    public CenterNoteBuilder withCenterId(String centerId) {
        this.centerId = centerId;
        this.hasCenterId = true;
        return this;
    }

    private String note;
    private boolean hasNote;

    public CenterNoteBuilder withNote(String note) {
        this.note = note;
        this.hasNote = true;
        return this;
    }

    public JsonNode build() {
        JsonNode object = new com.angkorteam.fintech.dto.JsonNode();

        if (this.hasCenterId) {
            object.getObject().put("centerId", this.centerId);
        }

        if (this.hasNote) {
            object.getObject().put("note", this.note);
        }

        return object;
    }

}


text:
<?php
namespace Chamilo\Core\Repository\ContentObject\Portfolio\Display\Component;

use Chamilo\Core\Repository\ContentObject\Portfolio\Display\Manager;
use Chamilo\Core\Repository\Integration\Chamilo\Core\Tracking\Storage\DataClass\Activity;
use Chamilo\Core\Repository\Storage\DataClass\ComplexContentObjectItem;
use Chamilo\Core\Tracking\Storage\DataClass\Event;
use Chamilo\Libraries\Translation\Translation;
use Chamilo\Libraries\Utilities\Utilities;

/**
 * Component that allows the removal of items from the portfolio (folder)
 *
 * @package repository\content_object\portfolio\display
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 */
class DeleterComponent extends Manager
{

    /**
     * Executes this component
     */
    public function run()
    {
        $selected_steps = $this->getRequest()->get(self::PARAM_STEP);
        if (! is_array($selected_steps))
        {
            $selected_steps = array($selected_steps);
        }

        $path = $this->get_root_content_object()->get_complex_content_object_path();

        $available_nodes = array();

        $failures = 0;

        foreach ($selected_steps as $selected_step)
        {
            try
            {
                $selected_node = $path->get_node($selected_step);

                if ($this->canEditComplexContentObjectPathNode($selected_node->get_parent()))
                {
                    $available_nodes[] = $selected_node;
                }
                else
                {
                    $failures++;
                }
            }
            catch(\Exception $ex)
            {
                $failures++;
            }
        }

        if (count($available_nodes) == 0)
        {
            $parameters = array(
                self::PARAM_ACTION => self::ACTION_VIEW_COMPLEX_CONTENT_OBJECT,
                self::PARAM_STEP => $this->get_current_node()->get_parent()->get_id());

            $this->redirect(
                Translation::get(
                    'NoObjectsToDelete',
                    array('OBJECTS' => Translation::get('ComplexContentObjectItems')),
                    Utilities::COMMON_LIBRARIES),
                true,
                $parameters);
        }

        foreach ($available_nodes as $available_node)
        {
            $complex_content_object_item_id = $available_node->get_complex_content_object_item()->get_id();
            $complex_content_object_item = \Chamilo\Core\Repository\Storage\DataManager::retrieve_by_id(
                ComplexContentObjectItem::class_name(),
                $complex_content_object_item_id);

            $current_parents_content_object_ids = $available_node->get_parents_content_object_ids(false, true);

            $success = $complex_content_object_item->delete();

            if ($success)
            {
                Event::trigger(
                    'Activity',
                    \Chamilo\Core\Repository\Manager::context(),
                    array(
                        Activity::PROPERTY_TYPE => Activity::ACTIVITY_DELETE_ITEM,
                        Activity::PROPERTY_USER_ID => $this->get_user_id(),
                        Activity::PROPERTY_DATE => time(),
                        Activity::PROPERTY_CONTENT_OBJECT_ID => $available_node->get_parent()->get_content_object()->get_id(),
                        Activity::PROPERTY_CONTENT => $available_node->get_parent()->get_content_object()->get_title() .
                             ' > ' . $available_node->get_content_object()->get_title()));

                $hashes = array();
                $hashes[] = $available_node->get_hash();

                $descendants = $available_node->get_descendants();
                foreach ($descendants as $descendant)
                {
                    $hashes[] = $descendant->get_hash();
                }

                if (! \Chamilo\Core\Repository\ContentObject\Portfolio\Storage\DataManager::delete_node_ids($hashes))
                {
                    $failures ++;
                }
            }
            else
            {
                $failures ++;
            }

            $this->get_root_content_object()->get_complex_content_object_path()->reset();
            $new_node = $this->get_root_content_object()->get_complex_content_object_path()->follow_path_by_content_object_ids(
                $current_parents_content_object_ids);
        }

        $parameters = array();
        $parameters[self::PARAM_ACTION] = self::ACTION_VIEW_COMPLEX_CONTENT_OBJECT;

        if ($failures > 0)
        {
            $parameters[self::PARAM_STEP] = $this->get_current_node()->get_parent()->get_id();
        }
        else
        {
            $parameters[self::PARAM_STEP] = $new_node->get_id();
        }

        $this->redirect(
            Translation::get(
                $failures > 0 ? 'ObjectsNotDeleted' : 'ObjectsDeleted',
                array('OBJECTS' => Translation::get('ComplexContentObjectItems')),
                Utilities::COMMON_LIBRARIES),
            $failures > 0,
            array(
                self::PARAM_ACTION => self::ACTION_VIEW_COMPLEX_CONTENT_OBJECT,
                self::PARAM_STEP => $new_node->get_id()));
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="chrome=1">

  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link href='http://fonts.googleapis.com/css?family=Source+Code+Pro' rel='stylesheet' type='text/css'>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">


text:
<extends:toolkit:form.field/>
<use:element path="toolkit:form/pattern/input" as="pattern:input"/>

<block:element>
  <div
    class="js-sf-pattern-input sf-pattern-input @if(injected('error')) is-invalid@endif@if(injected('success')) is-valid@endif ${class}"
    data-name="${name}" data-value="${value}" data-field="true"
    @if(injected('autosubmit')) data-autosubmit="true" @endif >
    <input type="hidden" data-sf-custom-form-element-input name="${name}">
    ${context}
  </div>
</block:element>


text:
{% extends "base.html" %}
{% block body %}

Tanner's Cache Quest

                    Part 1: CSH has a firedemon. Learn about it and what service it performs. The product name is key.

                        Answer:
                        <input type="text" class="form-control" data-question="1">

                            <button class="btn btn-default" type="button" data-question="1">Check</button>
                            <button type="button" class="btn btn-default" data-container="body" data-toggle="popover"
                                    data-placement="right"
                                    data-content="Meet some Root Type People." data-original-title=""
                                    title="">
                                 Hint
                            </button>

                    Part 2: Meet some 3DAs. Find out what type of plastic our Makerbot uses.

                        Answer:
                        <input type="text" class="form-control" data-question="2">

                            <button class="btn btn-default" type="button" data-question="2">Check</button>
                            <button type="button" class="btn btn-default" data-container="body" data-toggle="popover"
                                    data-placement="right"
                                    data-content="Find a 3D Print admin" data-original-title=""
                                    title="">
                                 Hint
                            </button>

                    Part 3: Learn about the four drink machines on floor. One of the four is the key you need.

                        Answer:
                        <input type="text" class="form-control" data-question="3">

                            <button class="btn btn-default" type="button" data-question="3">Check</button>
                            <button type="button" class="btn btn-default" data-container="body" data-toggle="popover"
                                    data-placement="right"
                                    data-content="Find the youngest drink admin." data-original-title=""
                                    title="">
                                 Hint
                            </button>

                    Part 4: Learn about the CSH Constitution. The key is to know which command you need to "build" the CSH Constitution.

                        Answer:
                        <input type="text" class="form-control" data-question="4">

                            <button class="btn btn-default" type="button" data-question="4">Check</button>
                            <button type="button" class="btn btn-default" data-container="body" data-toggle="popover"
                                    data-placement="right"
                                    data-content="Find a Constitutional Maintainer." data-original-title=""
                                    title="">
                                 Hint
                            </button>

                    Part 5: CSHers each have their own key to floor. Well its more of a button. What protocol does it use?

                        Answer:
                        <input type="text" class="form-control" data-question="5">

                            <button class="btn btn-default" type="button" data-question="5">Check</button>
                            <button type="button" class="btn btn-default" data-container="body" data-toggle="popover"
                                    data-placement="right"
                                    data-content="Spelling is key. Datasheets are reliable." data-original-title=""
                                    title="">
                                 Hint
                            </button>

{% endblock %}


text:
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Image Gallery</title>

	<link rel="stylesheet" href="styles/layout.css" type="text/css" media="screen" />

Snapshots

Choose an image.


text:
excel-macros
============

Collection of Microsoft Excel VBA macros.


text:
#include "third_party/blink/renderer/core/html/html_frame_set_element.h"

#include "third_party/blink/renderer/bindings/core/v8/script_event_listener.h"
#include "third_party/blink/renderer/core/css/css_property_names.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/events/mouse_event.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/html/html_collection.h"
#include "third_party/blink/renderer/core/html/html_frame_element.h"
#include "third_party/blink/renderer/core/html_names.h"
#include "third_party/blink/renderer/core/layout/layout_frame_set.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"

namespace blink {

HTMLFrameSetElement::HTMLFrameSetElement(Document& document)
    : HTMLElement(html_names::kFramesetTag, document),
      border_(6),
      border_set_(false),
      border_color_set_(false),
      frameborder_(true),
      frameborder_set_(false),
      noresize_(false) {
  SetHasCustomStyleCallbacks();
  UseCounter::Count(document, WebFeature::kHTMLFrameSetElement);
}

bool HTMLFrameSetElement::IsPresentationAttribute(
    const QualifiedName& name) const {
  if (name == html_names::kBordercolorAttr)
    return true;
  return HTMLElement::IsPresentationAttribute(name);
}

void HTMLFrameSetElement::CollectStyleForPresentationAttribute(
    const QualifiedName& name,
    const AtomicString& value,
    MutableCSSPropertyValueSet* style) {
  if (name == html_names::kBordercolorAttr)
    AddHTMLColorToStyle(style, CSSPropertyID::kBorderColor, value);
  else
    HTMLElement::CollectStyleForPresentationAttribute(name, value, style);
}

void HTMLFrameSetElement::ParseAttribute(
    const AttributeModificationParams& params) {
  const QualifiedName& name = params.name;
  const AtomicString& value = params.new_value;
  if (name == html_names::kRowsAttr) {
    if (!value.IsNull()) {
      row_lengths_ = ParseListOfDimensions(value.GetString());
      SetNeedsStyleRecalc(kSubtreeStyleChange,
                          StyleChangeReasonForTracing::FromAttribute(name));
    }
  } else if (name == html_names::kColsAttr) {
    if (!value.IsNull()) {
      col_lengths_ = ParseListOfDimensions(value.GetString());
      SetNeedsStyleRecalc(kSubtreeStyleChange,
                          StyleChangeReasonForTracing::FromAttribute(name));
    }
  } else if (name == html_names::kFrameborderAttr) {
    if (!value.IsNull()) {
      if (EqualIgnoringASCIICase(value, "no") ||
          EqualIgnoringASCIICase(value, "0")) {
        frameborder_ = false;
        frameborder_set_ = true;
      } else if (EqualIgnoringASCIICase(value, "yes") ||
                 EqualIgnoringASCIICase(value, "1")) {
        frameborder_set_ = true;
      }
    } else {
      frameborder_ = false;
      frameborder_set_ = false;
    }
  } else if (name == html_names::kNoresizeAttr) {
    noresize_ = true;
  } else if (name == html_names::kBorderAttr) {
    if (!value.IsNull()) {
      border_ = value.ToInt();
      border_set_ = true;
    } else {
      border_set_ = false;
    }
  } else if (name == html_names::kBordercolorAttr) {
    border_color_set_ = !value.IsEmpty();
  } else if (name == html_names::kOnafterprintAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kAfterprint,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnbeforeprintAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kBeforeprint,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnloadAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kLoad,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnbeforeunloadAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kBeforeunload,
        CreateAttributeEventListener(
            GetDocument().GetFrame(), name, value,
            JSEventHandler::HandlerType::kOnBeforeUnloadEventHandler));
  } else if (name == html_names::kOnunloadAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kUnload,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnpagehideAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kPagehide,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnpageshowAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kPageshow,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnblurAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kBlur,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnerrorAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kError,
        CreateAttributeEventListener(
            GetDocument().GetFrame(), name, value,
            JSEventHandler::HandlerType::kOnErrorEventHandler));
  } else if (name == html_names::kOnfocusAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kFocus,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnfocusinAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kFocusin,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnfocusoutAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kFocusout,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (RuntimeEnabledFeatures::OrientationEventEnabled() &&
             name == html_names::kOnorientationchangeAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kOrientationchange,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnhashchangeAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kHashchange,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnmessageAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kMessage,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnresizeAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kResize,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnscrollAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kScroll,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnstorageAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kStorage,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnonlineAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kOnline,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnofflineAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kOffline,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnpopstateAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kPopstate,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (name == html_names::kOnlanguagechangeAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kLanguagechange,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (RuntimeEnabledFeatures::PortalsEnabled(&GetDocument()) &&
             name == html_names::kOnportalactivateAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kPortalactivate,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else if (RuntimeEnabledFeatures::TimeZoneChangeEventEnabled() &&
             name == html_names::kOntimezonechangeAttr) {
    GetDocument().SetWindowAttributeEventListener(
        event_type_names::kTimezonechange,
        CreateAttributeEventListener(GetDocument().GetFrame(), name, value));
  } else {
    HTMLElement::ParseAttribute(params);
  }
}

bool HTMLFrameSetElement::LayoutObjectIsNeeded(
    const ComputedStyle& style) const {
  // For compatibility, frames layoutObject even when display: none is set.
  return true;
}

LayoutObject* HTMLFrameSetElement::CreateLayoutObject(
    const ComputedStyle& style,
    LegacyLayout legacy) {
  if (style.ContentBehavesAsNormal())
    return new LayoutFrameSet(this);
  return LayoutObject::CreateObject(this, style, legacy);
}

void HTMLFrameSetElement::AttachLayoutTree(AttachContext& context) {
  // Inherit default settings from parent frameset
  // FIXME: This is not dynamic.
  if (HTMLFrameSetElement* frameset =
          Traversal<HTMLFrameSetElement>::FirstAncestor(*this)) {
    if (!frameborder_set_)
      frameborder_ = frameset->HasFrameBorder();
    if (frameborder_) {
      if (!border_set_)
        border_ = frameset->Border();
      if (!border_color_set_)
        border_color_set_ = frameset->HasBorderColor();
    }
    if (!noresize_)
      noresize_ = frameset->NoResize();
  }

  HTMLElement::AttachLayoutTree(context);
}

void HTMLFrameSetElement::DefaultEventHandler(Event& evt) {
  auto* mouse_event = DynamicTo<MouseEvent>(evt);
  if (mouse_event && !noresize_ && GetLayoutObject() &&
      GetLayoutObject()->IsFrameSet()) {
    if (ToLayoutFrameSet(GetLayoutObject())->UserResize(*mouse_event)) {
      evt.SetDefaultHandled();
      return;
    }
  }
  HTMLElement::DefaultEventHandler(evt);
}

Node::InsertionNotificationRequest HTMLFrameSetElement::InsertedInto(
    ContainerNode& insertion_point) {
  if (insertion_point.isConnected() && GetDocument().GetFrame()) {
    // A document using <frameset> likely won't literally have a body, but as
    // far as the client is concerned, the frameset is effectively the body.
    GetDocument().WillInsertBody();
  }
  return HTMLElement::InsertedInto(insertion_point);
}
void HTMLFrameSetElement::WillRecalcStyle(const StyleRecalcChange) {
  if (NeedsStyleRecalc() && GetLayoutObject()) {
    GetLayoutObject()->SetNeedsLayoutAndFullPaintInvalidation(
        layout_invalidation_reason::kStyleChange);
    ClearNeedsStyleRecalc();
  }
}

}  // namespace blink


text:
namespace applicationGateway.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Response for ApplicationGatewayAvailableWafRuleSets API service call.
    /// </summary>
    public partial class ApplicationGatewayAvailableWafRuleSetsResult
    {
        /// <summary>
        /// Initializes a new instance of the
        /// ApplicationGatewayAvailableWafRuleSetsResult class.
        /// </summary>
        public ApplicationGatewayAvailableWafRuleSetsResult()
        {
          CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// ApplicationGatewayAvailableWafRuleSetsResult class.
        /// </summary>
        /// <param name="value">The list of application gateway rule
        /// sets.</param>
        public ApplicationGatewayAvailableWafRuleSetsResult(IList<ApplicationGatewayFirewallRuleSet> value = default(IList<ApplicationGatewayFirewallRuleSet>))
        {
            Value = value;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the list of application gateway rule sets.
        /// </summary>
        [JsonProperty(PropertyName = "value")]
        public IList<ApplicationGatewayFirewallRuleSet> Value { get; set; }

    }
}


text:
package cmd

import (
	"bytes"
	"context"
	"testing"

	"istio.io/istio/security/pkg/pki/ca"

	"k8s.io/api/admissionregistration/v1beta1"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes/fake"
)

const (
	exampleCACert = `-----BEGIN CERTIFICATE-----
MIIDCzCCAfOgAwIBAgIQbfOzhcKTldFipQ1X2WXpHDANBgkqhkiG9w0BAQsFADAv
MS0wKwYDVQQDEyRhNzU5YzcyZC1lNjcyLTQwMzYtYWMzYy1kYzAxMDBmMTVkNWUw
HhcNMTkwNTE2MjIxMTI2WhcNMjQwNTE0MjMxMTI2WjAvMS0wKwYDVQQDEyRhNzU5
YzcyZC1lNjcyLTQwMzYtYWMzYy1kYzAxMDBmMTVkNWUwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQC6sSAN80Ci0DYFpNDumGYoejMQai42g6nSKYS+ekvs
E7uT+eepO74wj8o6nFMNDu58+XgIsvPbWnn+3WtUjJfyiQXxmmTg8om4uY1C7R1H
gMsrL26pUaXZ/lTE8ZV5CnQJ9XilagY4iZKeptuZkxrWgkFBD7tr652EA3hmj+3h
4sTCQ+pBJKG8BJZDNRrCoiABYBMcFLJsaKuGZkJ6KtxhQEO9QxJVaDoSvlCRGa8R
fcVyYQyXOZ+0VHZJQgaLtqGpiQmlFttpCwDiLfMkk3UAd79ovkhN1MCq+O5N7YVt
eVQWaTUqUV2tKUFvVq21Zdl4dRaq+CF5U8uOqLY/4Kg9AgMBAAGjIzAhMA4GA1Ud
DwEB/wQEAwICBDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCg
oF71Ey2b1QY22C6BXcANF1+wPzxJovFeKYAnUqwh3rF7pIYCS/adZXOKlgDBsbcS
MxAGnCRi1s+A7hMYj3sQAbBXttc31557lRoJrx58IeN5DyshT53t7q4VwCzuCXFT
3zRHVRHQnO6LHgZx1FuKfwtkhfSXDyYU2fQYw2Hcb9krYU/alViVZdE0rENXCClq
xO7AQk5MJcGg6cfE5wWAKU1ATjpK4CN+RTn8v8ODLoI2SW3pfsnXxm93O+pp9HN4
+O+1PQtNUWhCfh+g6BN2mYo2OEZ8qGSxDlMZej4YOdVkW8PHmFZTK0w9iJKqM5o1
V6g5gZlqSoRhICK09tpc
-----END CERTIFICATE-----`
	exampleIssuedCert = `-----BEGIN CERTIFICATE-----
MIIDGDCCAgCgAwIBAgIRAKvYcPLFqnJcwtshCGfNzTswDQYJKoZIhvcNAQELBQAw
LzEtMCsGA1UEAxMkYTc1OWM3MmQtZTY3Mi00MDM2LWFjM2MtZGMwMTAwZjE1ZDVl
MB4XDTE5MDgwNjE5NTU0NVoXDTI0MDgwNDE5NTU0NVowCzEJMAcGA1UEChMAMIIB
IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyLIFJU5yJ5VXhbmizir+7Glm
1tVEYXKGiqYbMRbfsFm7V6Z4l00D9/eHvfTXaFpqhv6HBm31MArjYB3OaaV6krvT
whBUEPSkGBFe/eMPSFWBW27a0nw0cK2s/5yuFhTRtcUrZ9+ojJg4IS3oSm2UZ6UJ
DuNI3qwB6OlPQOcWX8uEp4eAaolD1lIbLRQYvxYrBqnyCZBLE+MJgA1/VB3dAECB
TxPtAqcwLFcvsM5ABys8yK8FrqRn5Bx54NiztgG+yU30W33xjdqzmEmuIIk4JjPU
ZQRsug7XClDvQKM6lbYcYS1td2zT08hdgURFXJ9VR64ALFp00/bvglpryu8FmQID
AQABo1MwUTAMBgNVHRMBAf8EAjAAMEEGA1UdEQQ6MDiCHHByb3RvbXV0YXRlLmlz
dGlvLXN5c3RlbS5zdmOCGHByb3RvbXV0YXRlLmlzdGlvLXN5c3RlbTANBgkqhkiG
9w0BAQsFAAOCAQEAhcVEZSuNMqMUJrWVb3b+6pmw9o1f7j6a51KWxOiIl6YuTYFS
WaR0lHSW8wLesjsjm1awWO/F3QRuYWbalANy7434GMAGF53u/uc+Z8aE3EItER9o
SpAJos6OfJqyok7JXDdOYRDD5/hBerj68R9llWzNJd27/1jZ0NF2sIE1W4QFddy/
+8YA4+IqwkWB5/LbeRznl3EjFZDpCEJk0gg5XwAR5eIEy4QU8GueTwrDkssFdBGq
0naco7/Es7CWQscYdKHAgYgk0UAyu8sGV235Uw3hlOrbZ/kqvyUmsSujgT8irmDV
e+5z6MTAO6ktvHdQlSuH6ARn47bJrZOlkttAhg==
-----END CERTIFICATE-----
`
)

var (
	fakeCACert = []byte("fake-CA-cert")
)

func TestCheckCertificate(t *testing.T) {
	testCases := map[string]struct {
		cert       string
		shouldFail bool
	}{
		"cert valid": {
			cert:       exampleCACert,
			shouldFail: false,
		},
		"cert invalid": {
			cert:       "invalid-cert",
			shouldFail: true,
		},
	}

	for tcName, tc := range testCases {
		err := checkCertificate([]byte(tc.cert))
		if tc.shouldFail {
			if err == nil {
				t.Errorf("%v: should have failed", tcName)
			}
		} else if err != nil {
			t.Errorf("%v: should not fail, but err: %v", tcName, err)
		}
	}
}

func TestVerifyCertChain(t *testing.T) {
	testCases := map[string]struct {
		cert       string
		caCert     string
		shouldFail bool
	}{
		"cert chain valid": {
			cert:       exampleIssuedCert,
			caCert:     exampleCACert,
			shouldFail: false,
		},
		"cert chain invalid": {
			cert:       exampleCACert,
			caCert:     exampleIssuedCert,
			shouldFail: true,
		},
	}

	for tcName, tc := range testCases {
		err := veriyCertChain([]byte(tc.cert), []byte(tc.caCert))
		if tc.shouldFail {
			if err == nil {
				t.Errorf("%v: should have failed", tcName)
			}
		} else if err != nil {
			t.Errorf("%v: should not fail, but err: %v", tcName, err)
		}
	}
}

func TestEnableCliOptionsValidation(t *testing.T) {
	testCases := map[string]struct {
		opt        enableCliOptions
		shouldFail bool
	}{
		"valid option 1": {
			opt: enableCliOptions{
				enableValidationWebhook:      true,
				validationWebhookConfigPath:  "config",
				validatingWebhookServiceName: "service",
				webhookSecretName:            "secret",
				webhookSecretNameSpace:       "secret-ns",
			},
			shouldFail: false,
		},
		"valid option 2": {
			opt: enableCliOptions{
				enableMutationWebhook:      true,
				mutatingWebhookConfigPath:  "config",
				mutatingWebhookServiceName: "service",
				webhookSecretName:          "secret",
				webhookSecretNameSpace:     "secret-ns",
			},
			shouldFail: false,
		},
		"valid option 3": {
			opt: enableCliOptions{
				enableValidationWebhook:      true,
				validationWebhookConfigPath:  "config",
				validatingWebhookServiceName: "service",
				enableMutationWebhook:        true,
				mutatingWebhookConfigPath:    "config",
				mutatingWebhookServiceName:   "service",
				webhookSecretName:            "secret",
				webhookSecretNameSpace:       "secret-ns",
			},
			shouldFail: false,
		},
		"invalid option 1": {
			opt: enableCliOptions{
				enableValidationWebhook:      true,
				validatingWebhookServiceName: "service",
				webhookSecretName:            "secret",
				webhookSecretNameSpace:       "secret-ns",
			},
			shouldFail: true,
		},
		"invalid option 2": {
			opt: enableCliOptions{
				enableValidationWebhook:     true,
				validationWebhookConfigPath: "config",
				webhookSecretName:           "secret",
				webhookSecretNameSpace:      "secret-ns",
			},
			shouldFail: true,
		},
		"invalid option 3": {
			opt: enableCliOptions{
				enableMutationWebhook:      true,
				mutatingWebhookServiceName: "service",
				webhookSecretName:          "secret",
				webhookSecretNameSpace:     "secret-ns",
			},
			shouldFail: true,
		},
		"invalid option 4": {
			opt: enableCliOptions{
				enableMutationWebhook:     true,
				mutatingWebhookConfigPath: "config",
				webhookSecretName:         "secret",
				webhookSecretNameSpace:    "secret-ns",
			},
			shouldFail: true,
		},
		"invalid option 5": {
			opt: enableCliOptions{
				enableValidationWebhook: false,
				enableMutationWebhook:   false,
			},
			shouldFail: true,
		},
		"invalid option 6": { // webhook secret namespace is required but missing
			opt: enableCliOptions{
				enableValidationWebhook:      true,
				validationWebhookConfigPath:  "config",
				validatingWebhookServiceName: "service",
				webhookSecretName:            "secret",
			},
			shouldFail: true,
		},
	}

	for tcName, tc := range testCases {
		err := tc.opt.Validate()
		if tc.shouldFail {
			if err == nil {
				t.Errorf("%v: opt (%v) should have failed", tcName, tc.opt)
			}
		} else if err != nil {
			t.Errorf("%v: opt (%v) should not fail, but err: %v", tcName, tc.opt, err)
		}
	}
}

func TestDisableCliOptionsValidation(t *testing.T) {
	testCases := map[string]struct {
		opt        disableCliOptions
		shouldFail bool
	}{
		"valid option 1": {
			opt: disableCliOptions{
				disableValidationWebhook:    true,
				validatingWebhookConfigName: "foo",
			},
			shouldFail: false,
		},
		"valid option 2": {
			opt: disableCliOptions{
				disableInjectionWebhook:   true,
				mutatingWebhookConfigName: "bar",
			},
			shouldFail: false,
		},
		"valid option 3": {
			opt: disableCliOptions{
				disableValidationWebhook:    true,
				validatingWebhookConfigName: "foo",
				disableInjectionWebhook:     true,
				mutatingWebhookConfigName:   "bar",
			},
			shouldFail: false,
		},
		"invalid option 1": {
			opt: disableCliOptions{
				disableValidationWebhook:    true,
				validatingWebhookConfigName: "",
			},
			shouldFail: true,
		},
		"invalid option 2": {
			opt: disableCliOptions{
				disableInjectionWebhook:   true,
				mutatingWebhookConfigName: "",
			},
			shouldFail: true,
		},
		"invalid option 3": {
			opt: disableCliOptions{
				disableValidationWebhook: false,
				disableInjectionWebhook:  false,
			},
			shouldFail: true,
		},
	}

	for tcName, tc := range testCases {
		err := tc.opt.Validate()
		if tc.shouldFail {
			if err == nil {
				t.Errorf("%v: opt (%v) should have failed", tcName, tc.opt)
			}
		} else if err != nil {
			t.Errorf("%v: opt (%v) should not fail, but err: %v", tcName, tc.opt, err)
		}
	}
}

func TestStatusCliOptionsValidation(t *testing.T) {
	testCases := map[string]struct {
		opt        statusCliOptions
		shouldFail bool
	}{
		"valid option 1": {
			opt: statusCliOptions{
				validationWebhook:           true,
				validatingWebhookConfigName: "foo",
			},
			shouldFail: false,
		},
		"valid option 2": {
			opt: statusCliOptions{
				injectionWebhook:          true,
				mutatingWebhookConfigName: "bar",
			},
			shouldFail: false,
		},
		"valid option 3": {
			opt: statusCliOptions{
				validationWebhook:           true,
				validatingWebhookConfigName: "foo",
				injectionWebhook:            true,
				mutatingWebhookConfigName:   "bar",
			},
			shouldFail: false,
		},
		"invalid option 1": {
			opt: statusCliOptions{
				validationWebhook:           true,
				validatingWebhookConfigName: "",
			},
			shouldFail: true,
		},
		"invalid option 2": {
			opt: statusCliOptions{
				injectionWebhook:          true,
				mutatingWebhookConfigName: "",
			},
			shouldFail: true,
		},
		"invalid option 3": {
			opt: statusCliOptions{
				validationWebhook: false,
				injectionWebhook:  false,
			},
			shouldFail: true,
		},
	}

	for tcName, tc := range testCases {
		err := tc.opt.Validate()
		if tc.shouldFail {
			if err == nil {
				t.Errorf("%v: opt (%v) should have failed", tcName, tc.opt)
			}
		} else if err != nil {
			t.Errorf("%v: opt (%v) should not fail, but err: %v", tcName, tc.opt, err)
		}
	}
}

func TestDisableWebhookConfig(t *testing.T) {
	var buf bytes.Buffer
	testCases := map[string]struct {
		opt                           disableCliOptions
		createValidatingWebhookConfig bool
		createMutatingWebhookConfig   bool
		shouldFail                    bool
	}{
		"disable validating webhook config": {
			opt: disableCliOptions{
				disableValidationWebhook:    true,
				validatingWebhookConfigName: "protovalidate",
			},
			createValidatingWebhookConfig: true,
			createMutatingWebhookConfig:   true,
			shouldFail:                    false,
		},
		"disable mutating webhook config": {
			opt: disableCliOptions{
				disableInjectionWebhook:   true,
				mutatingWebhookConfigName: "protomutate",
			},
			createValidatingWebhookConfig: true,
			createMutatingWebhookConfig:   true,
			shouldFail:                    false,
		},
		"disable validating and mutating webhook configs": {
			opt: disableCliOptions{
				disableValidationWebhook:    true,
				validatingWebhookConfigName: "protovalidate",
				disableInjectionWebhook:     true,
				mutatingWebhookConfigName:   "protomutate",
			},
			createValidatingWebhookConfig: true,
			createMutatingWebhookConfig:   true,
			shouldFail:                    false,
		},
		"disable non-existing validating webhook config": {
			opt: disableCliOptions{
				disableValidationWebhook:    true,
				validatingWebhookConfigName: "protovalidate",
			},
			createValidatingWebhookConfig: false,
			createMutatingWebhookConfig:   false,
			shouldFail:                    true,
		},
		"disable non-existing mutating webhook config": {
			opt: disableCliOptions{
				disableInjectionWebhook:   true,
				mutatingWebhookConfigName: "protomutate",
			},
			createValidatingWebhookConfig: false,
			createMutatingWebhookConfig:   false,
			shouldFail:                    true,
		},
	}

	for tcName, tc := range testCases {
		client := fake.NewSimpleClientset()
		if tc.createValidatingWebhookConfig {
			webhookConfig, err := buildValidatingWebhookConfig(
				[]byte(exampleCACert),
				"./testdata/webhook/example-validating-webhook-config.yaml")
			if err != nil {
				t.Fatalf("%v: err when build validatingwebhookconfiguration: %v", tcName, err)
			}
			_, err = createValidatingWebhookConfig(client, webhookConfig, &buf)
			if err != nil {
				t.Fatalf("%v: err when creating validatingwebhookconfiguration: %v", tcName, err)
			}
		}
		if tc.createMutatingWebhookConfig {
			webhookConfig, err := buildMutatingWebhookConfig(
				[]byte(exampleCACert),
				"./testdata/webhook/example-mutating-webhook-config.yaml")
			if err != nil {
				t.Fatalf("%v: err when build mutatingwebhookconfiguration: %v", tcName, err)
			}
			_, err = createMutatingWebhookConfig(client, webhookConfig, &buf)
			if err != nil {
				t.Fatalf("%v: error when creating mutatingwebhookconfiguration: %v", tcName, err)
			}
		}

		validationErr, injectionErr := disableWebhookConfig(client, &tc.opt)
		if tc.shouldFail {
			if validationErr == nil && injectionErr == nil {
				t.Errorf("%v: should have failed", tcName)
			}
		} else {
			if validationErr != nil {
				t.Errorf("%v: should not fail, but err when disabling validation webhook: %v", tcName, validationErr)
			}
			if injectionErr != nil {
				t.Errorf("%v: should not fail, but err when disabling injection webhook: %v", tcName, injectionErr)
			}
		}
	}
}

func TestBuildValidatingWebhookConfig(t *testing.T) {
	configFile := "./testdata/webhook/example-validating-webhook-config.yaml"
	configName := "protovalidate"
	webhookConfig, err := buildValidatingWebhookConfig(fakeCACert, configFile)
	if err != nil {
		t.Fatalf("err building validating webhook config %v: %v", configName, err)
	}
	if webhookConfig.Name != configName {
		t.Fatalf("webhookConfig.Name (%v) is different from %v", webhookConfig.Name, configName)
	}
	for i := range webhookConfig.Webhooks {
		if !bytes.Equal(webhookConfig.Webhooks[i].ClientConfig.CABundle, fakeCACert) {
			t.Fatalf("webhookConfig CA bundle(%v) is different from %v",
				webhookConfig.Webhooks[i].ClientConfig.CABundle, fakeCACert)
		}
	}
}

func TestBuildMutatingWebhookConfig(t *testing.T) {
	configFile := "./testdata/webhook/example-mutating-webhook-config.yaml"
	configName := "protomutate"
	webhookConfig, err := buildMutatingWebhookConfig(fakeCACert, configFile)
	if err != nil {
		t.Fatalf("err building mutating webhook config %v: %v", configName, err)
	}
	if webhookConfig.Name != configName {
		t.Fatalf("webhookConfig.Name (%v) is different from %v", webhookConfig.Name, configName)
	}
	for i := range webhookConfig.Webhooks {
		if !bytes.Equal(webhookConfig.Webhooks[i].ClientConfig.CABundle, fakeCACert) {
			t.Fatalf("webhookConfig CA bundle(%v) is different from %v",
				webhookConfig.Webhooks[i].ClientConfig.CABundle, fakeCACert)
		}
	}
}

func TestCreateValidatingWebhookConfig(t *testing.T) {
	var buf bytes.Buffer
	testCases := map[string]struct {
		createWebhookConfig bool
		updateWebhookConfig bool
		shouldFail          bool
	}{
		"create a valid webhook config": {
			createWebhookConfig: true,
			updateWebhookConfig: false,
			shouldFail:          false,
		},
		"update a valid webhook config": {
			createWebhookConfig: true,
			updateWebhookConfig: true,
			shouldFail:          false,
		},
	}

	for tcName, tc := range testCases {
		client := fake.NewSimpleClientset()
		var webhookConfig *v1beta1.ValidatingWebhookConfiguration
		var err error
		if tc.createWebhookConfig {
			webhookConfig, err = buildValidatingWebhookConfig(
				[]byte(exampleCACert),
				"./testdata/webhook/example-validating-webhook-config.yaml")
			if err != nil {
				t.Fatalf("%v: err when build ValidatingWebhookConfiguration: %v", tcName, err)
			}
			_, err = createValidatingWebhookConfig(client, webhookConfig, &buf)
			if err != nil {
				t.Fatalf("%v: error when creating ValidatingWebhookConfiguration: %v", tcName, err)
			}
			if len(webhookConfig.Webhooks) == 0 {
				t.Fatalf("%v: empty webhooks in the webhook configuration", tcName)
			}
		}
		if tc.updateWebhookConfig {
			webhookConfig.Webhooks[0].ClientConfig.CABundle = []byte("new-ca-bundle")
			updated, err := createValidatingWebhookConfig(client, webhookConfig, &buf)
			if err != nil {
				t.Fatalf("%v: error when updating ValidatingWebhookConfiguration: %v", tcName, err)
			}
			if len(updated.Webhooks) == 0 {
				t.Fatalf("%v: empty webhooks in the updated webhook configuration", tcName)
			}
			if string(updated.Webhooks[0].ClientConfig.CABundle) != "new-ca-bundle" {
				t.Fatalf("%v: the updated CA bundle does not match new-ca-bundle", tcName)
			}
		}
	}
}

func TestCreateMutatingWebhookConfig(t *testing.T) {
	var buf bytes.Buffer
	testCases := map[string]struct {
		createWebhookConfig bool
		updateWebhookConfig bool
		shouldFail          bool
	}{
		"create a valid webhook config": {
			createWebhookConfig: true,
			updateWebhookConfig: false,
			shouldFail:          false,
		},
		"update a valid webhook config": {
			createWebhookConfig: true,
			updateWebhookConfig: true,
			shouldFail:          false,
		},
	}

	for tcName, tc := range testCases {
		client := fake.NewSimpleClientset()
		var webhookConfig *v1beta1.MutatingWebhookConfiguration
		var err error
		if tc.createWebhookConfig {
			webhookConfig, err = buildMutatingWebhookConfig(
				[]byte(exampleCACert),
				"./testdata/webhook/example-mutating-webhook-config.yaml")
			if err != nil {
				t.Fatalf("%v: err when build MutatingWebhookConfiguration: %v", tcName, err)
			}
			_, err = createMutatingWebhookConfig(client, webhookConfig, &buf)
			if err != nil {
				t.Fatalf("%v: error when creating MutatingWebhookConfiguration: %v", tcName, err)
			}
			if len(webhookConfig.Webhooks) == 0 {
				t.Fatalf("%v: empty webhooks in the webhook configuration", tcName)
			}
		}
		if tc.updateWebhookConfig {
			webhookConfig.Webhooks[0].ClientConfig.CABundle = []byte("new-ca-bundle")
			updated, err := createMutatingWebhookConfig(client, webhookConfig, &buf)
			if err != nil {
				t.Fatalf("%v: error when updating MutatingWebhookConfiguration: %v", tcName, err)
			}
			if len(updated.Webhooks) == 0 {
				t.Fatalf("%v: empty webhooks in the updated webhook configuration", tcName)
			}
			if string(updated.Webhooks[0].ClientConfig.CABundle) != "new-ca-bundle" {
				t.Fatalf("%v: the updated CA bundle does not match new-ca-bundle", tcName)
			}
		}
	}
}

func TestDisplayValidationWebhookConfig(t *testing.T) {
	var buf bytes.Buffer
	testCases := map[string]struct {
		opt                           statusCliOptions
		createValidatingWebhookConfig bool
		shouldFail                    bool
	}{
		"display validating webhook config": {
			opt: statusCliOptions{
				validationWebhook:           true,
				validatingWebhookConfigName: "protovalidate",
			},
			createValidatingWebhookConfig: true,
			shouldFail:                    false,
		},
		"display non-existing validating webhook config": {
			opt: statusCliOptions{
				validationWebhook:           true,
				validatingWebhookConfigName: "protovalidate",
			},
			createValidatingWebhookConfig: false,
			shouldFail:                    true,
		},
	}

	for tcName, tc := range testCases {
		client := fake.NewSimpleClientset()
		if tc.createValidatingWebhookConfig {
			webhookConfig, err := buildValidatingWebhookConfig(
				[]byte(exampleCACert),
				"./testdata/webhook/example-validating-webhook-config.yaml")
			if err != nil {
				t.Fatalf("%v: err when build validatingwebhookconfiguration: %v", tcName, err)
			}
			_, err = createValidatingWebhookConfig(client, webhookConfig, &buf)
			if err != nil {
				t.Fatalf("%v: error when creating validatingwebhookconfiguration: %v", tcName, err)
			}
		}

		validationErr := displayValidationWebhookConfig(client, &tc.opt, &buf)
		if tc.shouldFail {
			if validationErr == nil {
				t.Errorf("%v: should have failed", tcName)
			}
		} else {
			if validationErr != nil {
				t.Errorf("%v: should not fail, but err when displaying validation webhook: %v", tcName, validationErr)
			}
		}
	}
}

func TestDisplayMutationWebhookConfig(t *testing.T) {
	var buf bytes.Buffer
	testCases := map[string]struct {
		opt                         statusCliOptions
		createMutatingWebhookConfig bool
		shouldFail                  bool
	}{
		"disable mutating webhook config": {
			opt: statusCliOptions{
				injectionWebhook:          true,
				mutatingWebhookConfigName: "protomutate",
			},
			createMutatingWebhookConfig: true,
			shouldFail:                  false,
		},
		"disable non-existing mutating webhook config": {
			opt: statusCliOptions{
				injectionWebhook:          true,
				mutatingWebhookConfigName: "protomutate",
			},
			createMutatingWebhookConfig: false,
			shouldFail:                  true,
		},
	}

	for tcName, tc := range testCases {
		client := fake.NewSimpleClientset()

		if tc.createMutatingWebhookConfig {
			webhookConfig, err := buildMutatingWebhookConfig(
				[]byte(exampleCACert),
				"./testdata/webhook/example-mutating-webhook-config.yaml")
			if err != nil {
				t.Fatalf("%v: err when build mutatingwebhookconfiguration: %v", tcName, err)
			}
			_, err = createMutatingWebhookConfig(client, webhookConfig, &buf)
			if err != nil {
				t.Fatalf("%v: error when creating mutatingwebhookconfiguration: %v", tcName, err)
			}
		}

		injectionErr := displayMutationWebhookConfig(client, &tc.opt, &buf)
		if tc.shouldFail {
			if injectionErr == nil {
				t.Errorf("%v: should have failed", tcName)
			}
		} else {
			if injectionErr != nil {
				t.Errorf("%v: should not fail, but err when displaying injection webhook: %v", tcName, injectionErr)
			}
		}
	}
}

func TestDisplayWebhookConfig(t *testing.T) {
	var buf bytes.Buffer
	testCases := map[string]struct {
		opt                           statusCliOptions
		createValidatingWebhookConfig bool
		createMutatingWebhookConfig   bool
		shouldFail                    bool
	}{
		"display validating webhook config": {
			opt: statusCliOptions{
				validationWebhook:           true,
				validatingWebhookConfigName: "protovalidate",
			},
			createValidatingWebhookConfig: true,
			createMutatingWebhookConfig:   true,
			shouldFail:                    false,
		},
		"display mutating webhook config": {
			opt: statusCliOptions{
				injectionWebhook:          true,
				mutatingWebhookConfigName: "protomutate",
			},
			createValidatingWebhookConfig: true,
			createMutatingWebhookConfig:   true,
			shouldFail:                    false,
		},
		"display validating and mutating webhook configs": {
			opt: statusCliOptions{
				validationWebhook:           true,
				validatingWebhookConfigName: "protovalidate",
				injectionWebhook:            true,
				mutatingWebhookConfigName:   "protomutate",
			},
			createValidatingWebhookConfig: true,
			createMutatingWebhookConfig:   true,
			shouldFail:                    false,
		},
		"display non-existing validating webhook config": {
			opt: statusCliOptions{
				validationWebhook:           true,
				validatingWebhookConfigName: "protovalidate",
			},
			createValidatingWebhookConfig: false,
			createMutatingWebhookConfig:   false,
			shouldFail:                    true,
		},
		"display non-existing mutating webhook config": {
			opt: statusCliOptions{
				injectionWebhook:          true,
				mutatingWebhookConfigName: "protomutate",
			},
			createValidatingWebhookConfig: false,
			createMutatingWebhookConfig:   false,
			shouldFail:                    true,
		},
	}

	for tcName, tc := range testCases {
		client := fake.NewSimpleClientset()
		if tc.createValidatingWebhookConfig {
			webhookConfig, err := buildValidatingWebhookConfig(
				[]byte(exampleCACert),
				"./testdata/webhook/example-validating-webhook-config.yaml")
			if err != nil {
				t.Fatalf("%v: err when build validatingwebhookconfiguration: %v", tcName, err)
			}
			_, err = createValidatingWebhookConfig(client, webhookConfig, &buf)
			if err != nil {
				t.Fatalf("%v: error when creating validatingwebhookconfiguration: %v", tcName, err)
			}
		}
		if tc.createMutatingWebhookConfig {
			webhookConfig, err := buildMutatingWebhookConfig(
				[]byte(exampleCACert),
				"./testdata/webhook/example-mutating-webhook-config.yaml")
			if err != nil {
				t.Fatalf("%v: err when build mutatingwebhookconfiguration: %v", tcName, err)
			}
			_, err = createMutatingWebhookConfig(client, webhookConfig, &buf)
			if err != nil {
				t.Fatalf("%v: error when creating mutatingwebhookconfiguration: %v", tcName, err)
			}
		}

		validationErr, injectionErr := displayWebhookConfig(client, &tc.opt, &buf)
		if tc.shouldFail {
			if validationErr == nil && injectionErr == nil {
				t.Errorf("%v: should have failed", tcName)
			}
		} else {
			if validationErr != nil {
				t.Errorf("%v: should not fail, but err when displaying validation webhook: %v", tcName, validationErr)
			}
			if injectionErr != nil {
				t.Errorf("%v: should not fail, but err when displaying injection webhook: %v", tcName, injectionErr)
			}
		}
	}
}

func TestReadCertFromSecret(t *testing.T) {
	testCases := map[string]struct {
		createSecret bool
		shouldFail   bool
	}{
		"read a valid secret": {
			createSecret: true,
			shouldFail:   false,
		},
		"read an invalid secret": {
			createSecret: false,
			shouldFail:   true,
		},
	}

	for tcName, tc := range testCases {
		client := fake.NewSimpleClientset()

		if tc.createSecret {
			secret := &v1.Secret{
				Data: map[string][]byte{},
				ObjectMeta: metav1.ObjectMeta{
					Annotations: nil,
					Name:        "foo",
					Namespace:   "bar",
				},
				Type: "test-secret",
			}
			secret.Data = map[string][]byte{
				ca.CertChainID:  []byte("dummy-cert"),
				ca.PrivateKeyID: []byte("dummy-key"),
				ca.RootCertID:   []byte("dummy-root"),
			}
			_, err := client.CoreV1().Secrets("bar").Create(context.TODO(), secret, metav1.CreateOptions{})
			if err != nil {
				t.Fatalf("%v: error when creating secret foo: %v", tcName, err)
			}
		}
		cert, err := readCertFromSecret(client, "foo", "bar")

		if tc.shouldFail {
			if err == nil {
				t.Errorf("%v: should have failed", tcName)
			}
		} else {
			if err != nil {
				t.Errorf("%v: should not fail, but err: %v", tcName, err)
			}
			if len(cert) == 0 {
				t.Errorf("%v: should not fail, but read returns empty cert", tcName)
			}
		}
	}
}

func TestReadCACertFromSA(t *testing.T) {
	testCases := map[string]struct {
		create     bool
		shouldFail bool
	}{
		"read a valid service account": {
			create:     true,
			shouldFail: false,
		},
		"read an invalid service account": {
			create:     false,
			shouldFail: true,
		},
	}

	for tcName, tc := range testCases {
		client := fake.NewSimpleClientset()
		if tc.create {
			secret := &v1.Secret{
				Data: map[string][]byte{},
				ObjectMeta: metav1.ObjectMeta{
					Annotations: nil,
					Name:        "foo",
					Namespace:   "bar",
				},
				Type: "test-secret",
			}
			secret.Data = map[string][]byte{
				ca.CertChainID:   []byte("dummy-cert"),
				ca.PrivateKeyID:  []byte("dummy-key"),
				ca.RootCertID:    []byte("dummy-root"),
				caKeyInK8sSecret: []byte("dummy-cert"),
			}
			_, err := client.CoreV1().Secrets("bar").Create(context.TODO(), secret, metav1.CreateOptions{})
			if err != nil {
				t.Fatalf("%v: error when creating secret foo: %v", tcName, err)
			}
			sa := &v1.ServiceAccount{
				ObjectMeta: metav1.ObjectMeta{
					Annotations: nil,
					Name:        "foo",
					Namespace:   "bar",
				},
			}
			sa.Secrets = append(sa.Secrets, v1.ObjectReference{
				Name:      "foo",
				Namespace: "bar",
			})
			_, err = client.CoreV1().ServiceAccounts("bar").Create(context.TODO(), sa, metav1.CreateOptions{})
			if err != nil {
				t.Fatalf("%v: error when creating service account foo: %v", tcName, err)
			}
		}

		cert, err := readCACertFromSA(client, "bar", "foo")
		if tc.shouldFail {
			if err == nil {
				t.Errorf("%v: should have failed", tcName)
			}
		} else {
			if err != nil {
				t.Errorf("%v: should not fail, but err: %v", tcName, err)
			}
			if len(cert) == 0 {
				t.Errorf("%v: should not fail, but read returns empty cert", tcName)
			}
		}
	}
}


text:
package ru.justnero.study.dsmnm.lab03;

import javafx.scene.control.TreeItem;

public interface IConvertible {

    TreeItem<String> convert();

}


text:
module FChange
  # Notifier wraps a single instance of FChange.
  # It's possible to have more than one instance,
  # but usually unnecessary.
  #
  # @example
  #   # Create the notifier
  #   notifier = FChange::Notifier.new
  #
  #   # Run this callback whenever the file path/to/foo.txt is read
  #   notifier.watch("path/to/foo/", :all_events) do
  #     puts "foo was accessed!"
  #   end
  #
  #   # Nothing happens until you run the notifier!
  #   notifier.run
  class Notifier

    #
    INFINITE = 0xFFFFFFFF

    #
    WAIT_OBJECT_0 = 0x00000000

    # A hash from {Watcher} ids to the instances themselves.
    #
    # @private
    # @return [{Fixnum => Watcher}]
    attr_reader :watchers

    attr_reader :dwChangeHandles
    attr_reader :lp_dwChangeHandles

    # Creates a new {Notifier}.
    #
    # @return [Notifier]
    def initialize
      @watchers = {}
      @dwChangeHandles = []
      @lp_dwChangeHandles = 0
    end

    # Adds a new {Watcher} to the queue.
    def add_watcher(watcher)

      @watchers[watcher.id] = watcher

      @dwChangeHandles.push watcher.id

      # Pack event handles into newly created storage area
      # to be used for Win32 call
      @lp_dwChangeHandles = dwChangeHandles.pack("L" * dwChangeHandles.count)

    end

    # Watches a file or directory for changes,
    # calling the callback when there are.
    # This is only activated once \{#process} or \{#run} is called.
    #
    # **Note that by default, this does not recursively watch subdirectories
    # of the watched directory**.
    # To do so, use the `:recursive` flag.
    #
    # `:recursive`
    # : Recursively watch any subdirectories that are created.
    #
    # @param path [String] The path to the file or directory
    # @param flags [Array<Symbol>] Which events to watch for
    # @yield [event] A block that will be called
    #   whenever one of the specified events occur
    # @yieldparam event [Event] The Event object containing information
    #   about the event that occured
    # @return [Watcher] A Watcher set up to watch this path for these events
    # @raise [SystemCallError] if the file or directory can't be watched,
    #   e.g. if the file isn't found, read access is denied,
    #   or the flags don't contain any events
    def watch(path, *flags, &callback)
      recursive = flags.include?(:recursive)
      #:latency = 0.5
      flags = flags - [:recursive]
      if flags.empty?
        @flags = [:all_events]
      else
        @flags = flags.freeze
      end
      Watcher.new(self, path, recursive, *@flags, &callback)
    end

    # Starts the notifier watching for filesystem events.
    # Blocks until \{#stop} is called.
    #
    # @see #process
    def run
      @stop = false
      process until @stop
    end

    # Stop watching for filesystem events.
    # That is, if we're in a \{#run} loop,
    # exit out as soon as we finish handling the events.
    def stop
      @stop = true
    end

    # Blocks until there are one or more filesystem events
    # that this notifier has watchers registered for.
    # Once there are events, the appropriate callbacks are called
    # and this function returns.
    #
    # @see #run
    def process
      read_events.each {|event| event.callback!}
    end

    # Blocks until there are one or more filesystem events
    # that this notifier has watchers registered for.
    # Once there are events, returns their {Event} objects.
    #
    # @private
    def read_events

      # can return WAIT_TIMEOUT  = 0x00000102
      dwWaitStatus = Native.WaitForMultipleObjects(@dwChangeHandles.count,
        @lp_dwChangeHandles, 0, 500)

      events = []

      # this call blocks all threads completely.
      @dwChangeHandles.each_index do |index|
        if dwWaitStatus == WAIT_OBJECT_0 + index

          ev = Event.new(@watchers[@dwChangeHandles[index]])
          events << ev

          r = Native.FindNextChangeNotification(@dwChangeHandles[index])
          if r == 0
              raise SystemCallError.new("Failed to watch", r)
          end
        end
      end
      events
    end

    def close

    end

  end
end


text:
package io.agora.easeui.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import io.agora.CallBack;
import io.agora.chat.ChatClient;
import io.agora.chat.ChatMessage;
import io.agora.chat.ImageMessageBody;
import io.agora.chatdemo.R;
import io.agora.easeui.utils.EaseFileUtils;
import io.agora.easeui.widget.photoview.EasePhotoView;
import io.agora.easeui.widget.photoview.PhotoViewAttacher;
import io.agora.util.EMLog;

/**
 * download and show original photoView
 *
 */
public class EaseShowImageActivity extends Activity {
	private static final String TAG = "ShowBigImage";
	private ProgressDialog pd;
	private EasePhotoView photoView;
	private int default_res;
	private boolean isDownloaded;
	private ProgressBar loadLocalPb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.ease_activity_show_big_image);
		super.onCreate(savedInstanceState);

		photoView = (EasePhotoView) findViewById(R.id.image);
		loadLocalPb = (ProgressBar) findViewById(R.id.pb_load_local);
		default_res = getIntent().getIntExtra("default_image", R.drawable.ease_default_image);
		Uri uri = getIntent().getParcelableExtra("uri");
		String msgId = getIntent().getExtras().getString("messageId");
		EMLog.d(TAG, "show big photoView uri:" + uri + " messageId:" + msgId);

		//show the photoView if it exist in local path
		if (EaseFileUtils.isFileExistByUri(this, uri)) {
			EMLog.d(TAG, "showbigimage file exists. directly show it");
			Glide.with(this).load(uri).into(photoView);
		} else if (msgId != null) { //download photoView from server
			EMLog.d(TAG, "download remote photoView");
			downloadImage(msgId);
		} else {
			photoView.setImageResource(default_res);
		}

		photoView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
			@Override public void onPhotoTap(View view, float x, float y) {
				finish();
			}
		});
	}

	/**
	 * download photoView
	 *
	 * @param msgId
	 */
	@SuppressLint("NewApi")
	private void downloadImage(final String msgId) {
		String str1 = getResources().getString(R.string.Download_the_pictures);
		pd = new ProgressDialog(this);
		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pd.setCanceledOnTouchOutside(false);
		pd.setMessage(str1);
		pd.show();
		final ChatMessage msg = ChatClient.getInstance().chatManager().getMessage(msgId);
		if(msg == null) {
		    EMLog.e(TAG, "msgId: "+msgId +" not find local message!");
		    return;
		}
		final CallBack callback = new CallBack() {
			public void onSuccess() {

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (!isFinishing() && !isDestroyed()) {
							if (pd != null) {
								pd.dismiss();
							}
							isDownloaded = true;
							Uri localUrlUri = ((ImageMessageBody) msg.getBody()).getLocalUri();
							Glide.with(EaseShowImageActivity.this)
									.load(localUrlUri)
									.apply(new RequestOptions().error(default_res))
									.into(photoView);
						}
					}
				});
			}

			public void onError(int error, String msg) {
				EMLog.e(TAG, "offline file transfer error:" + msg);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (EaseShowImageActivity.this.isFinishing() || EaseShowImageActivity.this.isDestroyed()) {
						    return;
						}
                        photoView.setImageResource(default_res);
						if (pd != null) {
							pd.dismiss();
						}
					}
				});
			}

			public void onProgress(final int progress, String status) {
				EMLog.d(TAG, "Progress: " + progress);
				final String str2 = getResources().getString(R.string.Download_the_pictures_new);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
                        if (EaseShowImageActivity.this.isFinishing() || EaseShowImageActivity.this.isDestroyed()) {
                            return;
                        }
						pd.setMessage(str2 + progress + "%");
					}
				});
			}
		};

		msg.setMessageStatusCallback(callback);

		ChatClient.getInstance().chatManager().downloadAttachment(msg);
	}

	@Override
	public void onBackPressed() {
		if (isDownloaded)
			setResult(RESULT_OK);
		finish();
	}
}


text:
<?php

namespace Recca0120\Generator;

use Illuminate\Support\Arr;
use Illuminate\Filesystem\Filesystem;
use Recca0120\Generator\Fixers\UseSortFixer;

class Generator
{
    private $config;

    private $fils;

    private $useSortFixer;

    public function __construct($config, Filesystem $files = null, UseSortFixer $useSortFixer = null)
    {
        $this->config = $config;
        $this->files = $files ?: new Filesystem;
        $this->useSortFixer = $useSortFixer ?: new UseSortFixer();
    }

    public function generate($command, $name)
    {
        $config = Arr::get($this->config, $command, []);

        return new Code(
            $name,
            $config,
            $this->generateDependencies($name, Arr::get($config, 'dependencies', [])),
            $this->files,
            $this->useSortFixer
        );
    }

    private function generateDependencies($name, $dependencies)
    {
        $codes = [];
        foreach ($dependencies as $dependency) {
            $dependencyConfig = Arr::get($this->config, $dependency, []);
            $depencyCodes = $this->generateDependencies($name, array_get($dependencyConfig, 'dependencies', []));

            $codes[$dependency] = new Code(
                $name,
                $dependencyConfig,
                $depencyCodes,
                $this->files,
                $this->useSortFixer
            );

            $codes = array_merge($codes, $depencyCodes);
        }

        return $codes;
    }
}


text:
package com.ray3k.skincomposer.dialog.scenecomposer.undoables;

import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposer;
import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposerEvents;
import com.ray3k.skincomposer.dialog.scenecomposer.DialogSceneComposerModel;

public class SplitPaneChildSecondUndoable implements SceneComposerUndoable {
    private DialogSceneComposerModel.SimSplitPane splitPane;
    private DialogSceneComposer dialog;
    private DialogSceneComposerModel.SimActor childSecond;
    private DialogSceneComposerModel.SimActor previousChildSecond;

    public SplitPaneChildSecondUndoable(DialogSceneComposerEvents.WidgetType widgetType) {
        dialog = DialogSceneComposer.dialog;
        splitPane = (DialogSceneComposerModel.SimSplitPane) dialog.simActor;

        previousChildSecond = splitPane.childSecond;

        switch (widgetType) {
            case BUTTON:
                childSecond = new DialogSceneComposerModel.SimButton();
                break;
            case CHECK_BOX:
                childSecond = new DialogSceneComposerModel.SimCheckBox();
                break;
            case IMAGE:
                childSecond = new DialogSceneComposerModel.SimImage();
                break;
            case IMAGE_BUTTON:
                childSecond = new DialogSceneComposerModel.SimImageButton();
                break;
            case IMAGE_TEXT_BUTTON:
                childSecond = new DialogSceneComposerModel.SimImageTextButton();
                break;
            case LABEL:
                childSecond = new DialogSceneComposerModel.SimLabel();
                break;
            case LIST:
                childSecond = new DialogSceneComposerModel.SimList();
                break;
            case PROGRESS_BAR:
                childSecond = new DialogSceneComposerModel.SimProgressBar();
                break;
            case SELECT_BOX:
                childSecond = new DialogSceneComposerModel.SimSelectBox();
                break;
            case SLIDER:
                childSecond = new DialogSceneComposerModel.SimSlider();
                break;
            case TEXT_BUTTON:
                childSecond = new DialogSceneComposerModel.SimTextButton();
                break;
            case TEXT_FIELD:
                childSecond = new DialogSceneComposerModel.SimTextField();
                break;
            case TEXT_AREA:
                childSecond = new DialogSceneComposerModel.SimTextArea();
                break;
            case TOUCH_PAD:
                childSecond = new DialogSceneComposerModel.SimTouchPad();
                break;
            case CONTAINER:
                childSecond = new DialogSceneComposerModel.SimContainer();
                break;
            case HORIZONTAL_GROUP:
                childSecond = new DialogSceneComposerModel.SimHorizontalGroup();
                break;
            case SCROLL_PANE:
                childSecond = new DialogSceneComposerModel.SimScrollPane();
                break;
            case STACK:
                childSecond = new DialogSceneComposerModel.SimStack();
                break;
            case SPLIT_PANE:
                childSecond = new DialogSceneComposerModel.SimSplitPane();
                break;
            case TABLE:
                childSecond = new DialogSceneComposerModel.SimTable();
                break;
            case TREE:
                childSecond = new DialogSceneComposerModel.SimTree();
                break;
            case VERTICAL_GROUP:
                childSecond = new DialogSceneComposerModel.SimVerticalGroup();
                break;
        }
        childSecond.parent = splitPane;
    }

    @Override
    public void undo() {
        splitPane.childSecond = previousChildSecond;

        if (dialog.simActor != splitPane) {
            dialog.simActor = splitPane;
            dialog.populateProperties();
        }
        dialog.populatePath();
        dialog.model.updatePreview();
    }

    @Override
    public void redo() {
        splitPane.childSecond = childSecond;

        if (dialog.simActor != splitPane.childSecond) {
            dialog.simActor = splitPane.childSecond;
            dialog.populateProperties();
        }
        dialog.populatePath();
        dialog.model.updatePreview();
    }

    @Override
    public String getRedoString() {
        return "Redo \"Set second child for SplitPane\"";
    }

    @Override
    public String getUndoString() {
        return "Undo \"Set second child for SplitPane\"";
    }
}


text:
const express = require("express"),
      app = express(),
      fs = require("fs"),
      log = require("fancy-log"),
      bodyParser = require("body-parser"),
      db = require("./db");

app.use(bodyParser.json());

fs.readdir("./routes/", (err, files) => {
  if (err) log.error(err);

  let routeLinks = files.filter(f => f.split(".").pop() === "js");
  routeLinks.forEach((f, i) => {
    var props = require("./routes/" + f);
    log(`${i + 1}: ${f} Route loaded `);
    props(app);
  });
});

function serve() {
  app.listen(process.env.PORT || 8080, function() {
    log("API -> Now listening for requests");
  });
}

db.link().then((db) => {
  serve();
}).catch((err) => {
  log.error(err);
});


text:
#include "src/c-utils.h"

void
c_utils_version(version* output)
{
  version_parse(output, xstr(C_UTILS_VERSION));
}