text:
/**
 * Signer configuration.
 *
 */

#include "parser/signconfparser.h"
#include "shared/duration.h"
#include "shared/file.h"
#include "shared/log.h"
#include "shared/status.h"
#include "signer/signconf.h"

static const char* sc_str = "signconf";

/**
 * Create a new signer configuration with the 'empty' settings.
 *
 */
signconf_type*
signconf_create(void)
{
    signconf_type* sc = NULL;
    allocator_type* allocator = allocator_create(malloc, free);
    if (!allocator) {
        ods_log_error("[%s] unable to create signconf: allocator_create() "
            " failed", sc_str);
        return NULL;
    }
    sc = (signconf_type*) allocator_alloc(allocator, sizeof(signconf_type));
    if (!sc) {
        ods_log_error("[%s] unable to create signconf: allocator_alloc() "
            " failed", sc_str);
        allocator_cleanup(allocator);
        return NULL;
    }
    sc->allocator = allocator;
    sc->filename = NULL;
    /* Signatures */
    sc->sig_resign_interval = NULL;
    sc->sig_refresh_interval = NULL;
    sc->sig_validity_default = NULL;
    sc->sig_validity_denial = NULL;
    sc->sig_jitter = NULL;
    sc->sig_inception_offset = NULL;
    /* Denial of existence */
    sc->nsec3param_ttl = NULL;
    sc->nsec_type = 0;
    sc->nsec3_optout = 0;
    sc->nsec3_algo = 0;
    sc->nsec3_iterations = 0;
    sc->nsec3_salt = NULL;
    sc->nsec3params = NULL;
    /* Keys */
    sc->dnskey_ttl = NULL;
    sc->keys = NULL;
    /* Source of authority */
    sc->soa_ttl = NULL;
    sc->soa_min = NULL;
    sc->soa_serial = NULL;
    /* Other useful information */
    sc->max_zone_ttl = NULL;
    sc->last_modified = 0;
    return sc;
}

/**
 * Read signer configuration.
 *
 */
static ods_status
signconf_read(signconf_type* signconf, const char* scfile)
{
    const char* rngfile = ODS_SE_RNGDIR "/signconf.rng";
    ods_status status = ODS_STATUS_OK;
    FILE* fd = NULL;

    if (!scfile || !signconf) {
        return ODS_STATUS_ASSERT_ERR;
    }
    ods_log_debug("[%s] read signconf file %s", sc_str, scfile);
    status = parse_file_check(scfile, rngfile);
    if (status != ODS_STATUS_OK) {
        ods_log_error("[%s] unable to read signconf: parse error in "
            "file %s (%s)", sc_str, scfile, ods_status2str(status));
        return status;
    }
    fd = ods_fopen(scfile, NULL, "r");
    if (fd) {
        signconf->filename = allocator_strdup(signconf->allocator, scfile);
        signconf->sig_resign_interval = parse_sc_sig_resign_interval(scfile);
        signconf->sig_refresh_interval = parse_sc_sig_refresh_interval(scfile);
        signconf->sig_validity_default = parse_sc_sig_validity_default(scfile);
        signconf->sig_validity_denial = parse_sc_sig_validity_denial(scfile);
        signconf->sig_jitter = parse_sc_sig_jitter(scfile);
        signconf->sig_inception_offset = parse_sc_sig_inception_offset(scfile);
        signconf->nsec_type = parse_sc_nsec_type(scfile);
        if (signconf->nsec_type == LDNS_RR_TYPE_NSEC3) {
            signconf->nsec3param_ttl = parse_sc_nsec3param_ttl(scfile);
            signconf->nsec3_optout = parse_sc_nsec3_optout(scfile);
            signconf->nsec3_algo = parse_sc_nsec3_algorithm(scfile);
            signconf->nsec3_iterations = parse_sc_nsec3_iterations(scfile);
            signconf->nsec3_salt = parse_sc_nsec3_salt(signconf->allocator,
                scfile);
            signconf->nsec3params = nsec3params_create((void*) signconf,
            (uint8_t) signconf->nsec3_algo, (uint8_t) signconf->nsec3_optout,
            (uint16_t)signconf->nsec3_iterations, signconf->nsec3_salt);
            if (!signconf->nsec3params) {
                ods_log_error("[%s] unable to read signconf %s: "
                    "nsec3params_create() failed", sc_str, scfile);
                ods_fclose(fd);
                return ODS_STATUS_MALLOC_ERR;
            }
        }
        signconf->keys = parse_sc_keys((void*) signconf, scfile);
        signconf->dnskey_ttl = parse_sc_dnskey_ttl(scfile);
        signconf->soa_ttl = parse_sc_soa_ttl(scfile);
        signconf->soa_min = parse_sc_soa_min(scfile);
        signconf->soa_serial = parse_sc_soa_serial(signconf->allocator,
            scfile);
        signconf->max_zone_ttl = parse_sc_max_zone_ttl(scfile);
        ods_fclose(fd);
        return ODS_STATUS_OK;
    }
    ods_log_error("[%s] unable to read signconf: failed to open file %s",
        sc_str, scfile);
    return ODS_STATUS_ERR;
}

/**
 * Update signer configuration.
 *
 */
ods_status
signconf_update(signconf_type** signconf, const char* scfile,
    time_t last_modified)
{
    signconf_type* new_sc = NULL;
    time_t st_mtime = 0;
    ods_status status = ODS_STATUS_OK;

    if (!scfile || !signconf) {
        return ODS_STATUS_UNCHANGED;
    }
    /* is the file updated? */
    st_mtime = ods_file_lastmodified(scfile);
    if (st_mtime <= last_modified) {
        return ODS_STATUS_UNCHANGED;
    }
    /* if so, read the new signer configuration */
    new_sc = signconf_create();
    if (!new_sc) {
        ods_log_error("[%s] unable to update signconf: signconf_create() "
            "failed", sc_str);
        return ODS_STATUS_ERR;
    }
    status = signconf_read(new_sc, scfile);
    if (status == ODS_STATUS_OK) {
        new_sc->last_modified = st_mtime;
        if (signconf_check(new_sc) != ODS_STATUS_OK) {
            ods_log_error("[%s] unable to update signconf: signconf %s has "
                "errors", sc_str, scfile);
            signconf_cleanup(new_sc);
            return ODS_STATUS_CFG_ERR;
        }
        *signconf = new_sc;
    } else {
        ods_log_error("[%s] unable to update signconf: failed to read file "
            "%s (%s)", sc_str, scfile, ods_status2str(status));
        signconf_cleanup(new_sc);
    }
    return status;
}

/**
 * Backup duration.
 *
 */
static void
signconf_backup_duration(FILE* fd, const char* opt, duration_type* duration)
{
    char* str = duration2string(duration);
    fprintf(fd, "%s %s ", opt, str);
    free((void*) str?str:"(null)");
    return;
}

/**
 * Backup signconf values.
 *
 */
void
signconf_backup(FILE* fd, signconf_type* sc, const char* version)
{
    if (!fd || !sc) {
        return;
    }
    fprintf(fd, ";;Signconf: lastmod %u ", (unsigned) sc->last_modified);
    if (strcmp(version, ODS_SE_FILE_MAGIC_V2) &&
        strcmp(version, ODS_SE_FILE_MAGIC_V1)) {
        /* version 3 and up */
        fprintf(fd, "maxzonettl 0 "); /* prepare for enforcer ng */
    }
    signconf_backup_duration(fd, "resign", sc->sig_resign_interval);
    signconf_backup_duration(fd, "refresh", sc->sig_refresh_interval);
    signconf_backup_duration(fd, "valid", sc->sig_validity_default);
    signconf_backup_duration(fd, "denial", sc->sig_validity_denial);
    signconf_backup_duration(fd, "jitter", sc->sig_jitter);
    signconf_backup_duration(fd, "offset", sc->sig_inception_offset);
    fprintf(fd, "nsec %u ", (unsigned) sc->nsec_type);
    signconf_backup_duration(fd, "dnskeyttl", sc->dnskey_ttl);
    signconf_backup_duration(fd, "soattl", sc->soa_ttl);
    signconf_backup_duration(fd, "soamin", sc->soa_min);
    fprintf(fd, "serial %s ", sc->soa_serial?sc->soa_serial:"(null)");
    if (strcmp(version, ODS_SE_FILE_MAGIC_V2) == 0) {
        fprintf(fd, "audit 0");
    }
    fprintf(fd, "\n");
    return;
}

/**
 * Check the SOA/Serial type.
 *
 */
static int
signconf_soa_serial_check(const char* serial) {
    if (!serial) {
        return 1;
    }

    if (strlen(serial) == 4 && strncmp(serial, "keep", 4) == 0) {
        return 0;
    }
    if (strlen(serial) == 7 && strncmp(serial, "counter", 7) == 0) {
        return 0;
    }
    if (strlen(serial) == 8 && strncmp(serial, "unixtime", 8) == 0) {
        return 0;
    }
    if (strlen(serial) == 11 && strncmp(serial, "datecounter", 11) == 0) {
        return 0;
    }
    return 1;
}

/**
 * Check signer configuration settings.
 *
 */
ods_status
signconf_check(signconf_type* sc)
{
    ods_status status = ODS_STATUS_OK;

    if (!sc->sig_resign_interval) {
        ods_log_error("[%s] check failed: no signature resign interval found",
            sc_str);
        status = ODS_STATUS_CFG_ERR;
    }
    if (!sc->sig_refresh_interval) {
        ods_log_error("[%s] check failed: no signature resign interval found",
            sc_str);
        status = ODS_STATUS_CFG_ERR;
    }
    if (!sc->sig_validity_default) {
        ods_log_error("[%s] check failed: no signature default validity found",
            sc_str);
        status = ODS_STATUS_CFG_ERR;
    }
    if (!sc->sig_validity_denial) {
        ods_log_error("[%s] check failed: no signature denial validity found",
            sc_str);
        status = ODS_STATUS_CFG_ERR;
    }
    if (!sc->sig_jitter) {
        ods_log_error("[%s] check failed: no signature jitter found", sc_str);
        status = ODS_STATUS_CFG_ERR;
    }
    if (!sc->sig_inception_offset) {
        ods_log_error("[%s] check failed: no signature inception offset found",
            sc_str);
        status = ODS_STATUS_CFG_ERR;
    }
    if (sc->nsec_type == LDNS_RR_TYPE_NSEC3) {
        if (sc->nsec3_algo != LDNS_SHA1) {
            ods_log_error("[%s] check failed: invalid nsec3 algorithm",
                sc_str);
            status = ODS_STATUS_CFG_ERR;
        }
        /* iterations */
        /* salt */
        /* optout */
    } else if (sc->nsec_type != LDNS_RR_TYPE_NSEC) {
        ods_log_error("[%s] check failed: wrong nsec type %i", sc_str,
            sc->nsec_type);
        status = ODS_STATUS_CFG_ERR;
    }
    if (!sc->keys || sc->keys->count == 0) {
        ods_log_error("[%s] check failed: no keys found", sc_str);
        status = ODS_STATUS_CFG_ERR;
    }
    if (!sc->dnskey_ttl) {
        ods_log_error("[%s] check failed: no dnskey ttl found", sc_str);
        status = ODS_STATUS_CFG_ERR;
    }
    if (!sc->soa_ttl) {
        ods_log_error("[%s] check failed: no soa ttl found", sc_str);
        status = ODS_STATUS_CFG_ERR;
    }
    if (!sc->soa_min) {
        ods_log_error("[%s] check failed: no soa minimum found", sc_str);
        status = ODS_STATUS_CFG_ERR;
    }
    if (!sc->soa_serial) {
        ods_log_error("[%s] check failed: no soa serial type found", sc_str);
        status = ODS_STATUS_CFG_ERR;
    } else if (signconf_soa_serial_check(sc->soa_serial) != 0) {
        ods_log_error("[%s] check failed: wrong soa serial type %s", sc_str,
            sc->soa_serial);
        status = ODS_STATUS_CFG_ERR;
    }
    return status;
}

/**
 * Compare signer configurations on denial of existence material.
 *
 */
task_id
signconf_compare_denial(signconf_type* a, signconf_type* b)
{
    task_id new_task = TASK_NONE;
    if (!a || !b) {
        return TASK_NONE;
    }
    ods_log_assert(a);
    ods_log_assert(b);

   if (duration_compare(a->soa_min, b->soa_min)) {
       new_task = TASK_NSECIFY;
   } else if (a->nsec_type != b->nsec_type) {
       new_task = TASK_NSECIFY;
   } else if (a->nsec_type == LDNS_RR_TYPE_NSEC3) {
       if ((ods_strcmp(a->nsec3_salt, b->nsec3_salt) != 0) ||
           (a->nsec3_algo != b->nsec3_algo) ||
           (a->nsec3_iterations != b->nsec3_iterations) ||
           (a->nsec3_optout != b->nsec3_optout)) {

            new_task = TASK_NSECIFY;
        } else if (duration_compare(a->nsec3param_ttl, b->nsec3param_ttl)) {
           new_task = TASK_READ;
        }
    }
    return new_task;
}

/**
 * Print sign configuration.
 *
 */
void
signconf_print(FILE* out, signconf_type* sc, const char* name)
{
    char* s = NULL;

    fprintf(out, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    if (sc) {
        fprintf(out, "<SignerConfiguration>\n");
        fprintf(out, "\t<Zone name=\"%s\">\n", name?name:"(null)");
        /* Signatures */
        fprintf(out, "\t\t<Signatures>\n");
        s = duration2string(sc->sig_resign_interval);
        fprintf(out, "\t\t\t<Resign>%s</Resign>\n", s?s:"(null)");
        free((void*)s);
        s = duration2string(sc->sig_refresh_interval);
        fprintf(out, "\t\t\t<Refresh>%s</Refresh>\n", s?s:"(null)");
        free((void*)s);
        fprintf(out, "\t\t\t<Validity>\n");
        s = duration2string(sc->sig_validity_default);
        fprintf(out, "\t\t\t\t<Default>%s</Default>\n", s?s:"(null)");
        free((void*)s);
        s = duration2string(sc->sig_validity_denial);
        fprintf(out, "\t\t\t\t<Denial>%s</Denial>\n", s?s:"(null)");
        free((void*)s);
        fprintf(out, "\t\t\t</Validity>\n");
        s = duration2string(sc->sig_jitter);
        fprintf(out, "\t\t\t<Jitter>%s</Jitter>\n", s?s:"(null)");
        free((void*)s);
        s = duration2string(sc->sig_inception_offset);
        fprintf(out, "\t\t\t<InceptionOffset>%s</InceptionOffset>\n",
            s?s:"(null)");
        free((void*)s);
        fprintf(out, "\t\t</Signatures>\n");
        fprintf(out, "\n");
        /* Denial */
        fprintf(out, "\t\t<Denial>\n");
        if (sc->nsec_type == LDNS_RR_TYPE_NSEC) {
            fprintf(out, "\t\t\t<NSEC />\n");
        } else if (sc->nsec_type == LDNS_RR_TYPE_NSEC3) {
            fprintf(out, "\t\t\t<NSEC3>\n");
            if (sc->nsec3param_ttl) {
                s = duration2string(sc->nsec3param_ttl);
                fprintf(out, "\t\t\t\t<TTL>%s</TTL>\n", s?s:"(null)");
                free((void*)s);
            }
            if (sc->nsec3_optout) {
                fprintf(out, "\t\t\t\t<OptOut />\n");
            }
            fprintf(out, "\t\t\t\t<Hash>\n");
            fprintf(out, "\t\t\t\t\t<Algorithm>%i</Algorithm>\n",
                sc->nsec3_algo);
            fprintf(out, "\t\t\t\t\t<Iterations>%i</Iterations>\n",
                sc->nsec3_iterations);
            fprintf(out, "\t\t\t\t\t<Salt>%s</Salt>\n",
                sc->nsec3_salt?sc->nsec3_salt:"(null)");
            fprintf(out, "\t\t\t\t</Hash>\n");
            fprintf(out, "\t\t\t</NSEC3>\n");
        }
        fprintf(out, "\t\t</Denial>\n");
        fprintf(out, "\n");
        /* Keys */
        fprintf(out, "\t\t<Keys>\n");
        s = duration2string(sc->dnskey_ttl);
        fprintf(out, "\t\t\t<TTL>%s</TTL>\n", s?s:"(null)");
        free((void*)s);
        fprintf(out, "\n");
        keylist_print(out, sc->keys);
        fprintf(out, "\t\t</Keys>\n");
        fprintf(out, "\n");
        /* SOA */
        fprintf(out, "\t\t<SOA>\n");
        s = duration2string(sc->soa_ttl);
        fprintf(out, "\t\t\t<TTL>%s</TTL>\n", s?s:"(null)");
        free((void*)s);
        s = duration2string(sc->soa_min);
        fprintf(out, "\t\t\t<Minimum>%s</Minimum>\n", s?s:"(null)");
        free((void*)s);
        fprintf(out, "\t\t\t<Serial>%s</Serial>\n",
            sc->soa_serial?sc->soa_serial:"(null)");
        fprintf(out, "\t\t</SOA>\n");
        fprintf(out, "\n");
        fprintf(out, "\t</Zone>\n");
        fprintf(out, "</SignerConfiguration>\n");
    }
    return;
}

/**
 * Log sign configuration.
 *
 */
void
signconf_log(signconf_type* sc, const char* name)
{
    char* resign = NULL;
    char* refresh = NULL;
    char* validity = NULL;
    char* denial = NULL;
    char* jitter = NULL;
    char* offset = NULL;
    char* dnskeyttl = NULL;
    char* soattl = NULL;
    char* soamin = NULL;
    char* paramttl = NULL;

    if (sc) {
        resign = duration2string(sc->sig_resign_interval);
        refresh = duration2string(sc->sig_refresh_interval);
        validity = duration2string(sc->sig_validity_default);
        denial = duration2string(sc->sig_validity_denial);
        jitter = duration2string(sc->sig_jitter);
        offset = duration2string(sc->sig_inception_offset);
        dnskeyttl = duration2string(sc->dnskey_ttl);
        paramttl = duration2string(sc->nsec3param_ttl);
        soattl = duration2string(sc->soa_ttl);
        soamin = duration2string(sc->soa_min);
        /* signconf */
        ods_log_info("[%s] zone %s signconf: RESIGN[%s] REFRESH[%s] "
            "VALIDITY[%s] DENIAL[%s] JITTER[%s] OFFSET[%s] NSEC[%i] "
            "DNSKEYTTL[%s] SOATTL[%s] MINIMUM[%s] SERIAL[%s]",
            sc_str,
            name?name:"(null)",
            resign?resign:"(null)",
            refresh?refresh:"(null)",
            validity?validity:"(null)",
            denial?denial:"(null)",
            jitter?jitter:"(null)",
            offset?offset:"(null)",
            (int) sc->nsec_type,
            dnskeyttl?dnskeyttl:"(null)",
            soattl?soattl:"(null)",
            soamin?soamin:"(null)",
            sc->soa_serial?sc->soa_serial:"(null)");
        /* nsec3 parameters */
        if (sc->nsec_type == LDNS_RR_TYPE_NSEC3) {
            ods_log_debug("[%s] zone %s nsec3: PARAMTTL[%s] OPTOUT[%i] "
                "ALGORITHM[%u] ITERATIONS[%u] SALT[%s]",
                sc_str,
                name?name:"(null)",
                paramttl?paramttl:"PT0S",
                sc->nsec3_optout,
                sc->nsec3_algo,
                sc->nsec3_iterations,
                sc->nsec3_salt?sc->nsec3_salt:"(null)");
        }
        /* keys */
        keylist_log(sc->keys, name);
        /* cleanup */
        free((void*)resign);
        free((void*)refresh);
        free((void*)validity);
        free((void*)denial);
        free((void*)jitter);
        free((void*)offset);
        free((void*)dnskeyttl);
        free((void*)paramttl);
        free((void*)soattl);
        free((void*)soamin);
    }
    return;
}

/**
 * Clean up signer configuration.
 *
 */
void
signconf_cleanup(signconf_type* sc)
{
    allocator_type* allocator = NULL;
    if (!sc) {
        return;
    }
    duration_cleanup(sc->sig_resign_interval);
    duration_cleanup(sc->sig_refresh_interval);
    duration_cleanup(sc->sig_validity_default);
    duration_cleanup(sc->sig_validity_denial);
    duration_cleanup(sc->sig_jitter);
    duration_cleanup(sc->sig_inception_offset);
    duration_cleanup(sc->dnskey_ttl);
    duration_cleanup(sc->soa_ttl);
    duration_cleanup(sc->soa_min);
    duration_cleanup(sc->max_zone_ttl);
    keylist_cleanup(sc->keys);
    nsec3params_cleanup(sc->nsec3params);
    allocator = sc->allocator;
    allocator_deallocate(allocator, (void*) sc->filename);
    allocator_deallocate(allocator, (void*) sc->nsec3_salt);
    allocator_deallocate(allocator, (void*) sc->soa_serial);
    allocator_deallocate(allocator, (void*) sc);
    allocator_cleanup(allocator);
    return;
}


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

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import wicket.PageParameters;
import wicket.contrib.woogle.WoogleApplication;
import wicket.contrib.woogle.WoogleSession;
import wicket.contrib.woogle.components.SearchResult;
import wicket.contrib.woogle.domain.Search;
import wicket.markup.html.WebComponent;
import wicket.markup.html.basic.Label;
import wicket.markup.html.form.Button;
import wicket.markup.html.form.Form;
import wicket.markup.html.form.TextField;
import wicket.markup.html.link.BookmarkablePageLink;
import wicket.model.CompoundPropertyModel;
import wicket.model.Model;
import wicket.util.string.StringValueConversionException;
import wicket.util.string.Strings;

public class SearchPage extends WoogleBasePage {
	private static final long serialVersionUID = 1L;

	/** Logging */
	private static final Log log = LogFactory.getLog(SearchPage.class);

	public SearchPage(PageParameters parameters) {
		// Check for search criterias in the parameters
		String searchString = parameters.getString("search");
		if (Strings.isEmpty(searchString)) {
			searchString = null;
		}

		int page = 0;
		try {
			page = parameters.getInt("page");
		} catch (StringValueConversionException e) {
			// Ok, but we log it.
			log.debug("'page' parameter couldn't be converted to an int", e);
		}

		final Search search = new Search(searchString);

		// Search form
		add(new SearchForm("searchForm", search));

		// Stats
		add(new Label("indexPages", ""+WoogleApplication.get().getIndexPages()).setRenderBodyOnly(true));
		add(new BookmarkablePageLink("addSite", AddSitePage.class));

		// Result place holder
		if (searchString == null) {
//			add(new TopSearches("result").setOutputMarkupId(true));
			add(new WebComponent("result").setVisible(false));
		} else {
			// Save the search
			String sessionId = WoogleSession.get().getId();
			search.setSessionId(sessionId);
			search.setSearchTime(new Date());
			WoogleApplication.get().getSearchDAO().save(search);

			add(new SearchResult("result", searchString, page).setOutputMarkupId(true));
		}
	}

	private class SearchForm extends Form {
		private static final long serialVersionUID = 1L;

		private Search search;

		public SearchForm(String id, Search search) {
			super(id, new CompoundPropertyModel(search));

			this.search = search;

			add(new TextField("search"));
			add(new Button("searchButton", new Model("Search")));
		}

		@Override
		protected void onSubmit() {
			// Save the search
			String sessionId = WoogleSession.get().getId();
			search.setSessionId(sessionId);
			search.setSearchTime(new Date());
			WoogleApplication.get().getSearchDAO().save(search);

			// Redirect to search result page.
			// We use page parameters to get a bookmarkable url
			PageParameters parameters = new PageParameters();
			parameters.add("search", search.getSearch());
			setResponsePage(SearchPage.class, parameters);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.sqoop.authentication;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.sqoop.infrastructure.kerberos.MiniKdcInfrastructureRule;
import org.apache.sqoop.testcategories.sqooptest.IntegrationTest;
import org.apache.sqoop.testcategories.KerberizedTest;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.ExpectedException;

import static org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod.KERBEROS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;

@Category({KerberizedTest.class, IntegrationTest.class})
public class TestKerberosAuthenticator {

  private static final String KERBEROS_RULE_TEMPLATE = "RULE:[2:$1@$0](.*@%s)s/@%s//";

  @ClassRule
  public static MiniKdcInfrastructureRule miniKdc = new MiniKdcInfrastructureRule();

  private KerberosAuthenticator kerberosAuthenticator;

  @Rule
  public ExpectedException expectedException = ExpectedException.none();

  @Test
  public void testAuthenticateReturnsCurrentUserIfKerberosIsNotEnabled() throws Exception {
    kerberosAuthenticator = new KerberosAuthenticator(new Configuration(), miniKdc.getTestPrincipal(), miniKdc.getKeytabFilePath());

    assertSame(UserGroupInformation.getCurrentUser(), kerberosAuthenticator.authenticate());
  }

  @Test
  public void testAuthenticateReturnsAUserDifferentThanCurrentUserIfKerberosIsEnabled() throws Exception {
    kerberosAuthenticator = new KerberosAuthenticator(createKerberosConfiguration(), miniKdc.getTestPrincipal(), miniKdc.getKeytabFilePath());

    assertNotSame(UserGroupInformation.getCurrentUser(), kerberosAuthenticator.authenticate());
  }

  @Test
  public void testAuthenticateReturnsAKerberosAuthenticatedUserIfKerberosIsEnabled() throws Exception {
    kerberosAuthenticator = new KerberosAuthenticator(createKerberosConfiguration(), miniKdc.getTestPrincipal(), miniKdc.getKeytabFilePath());

    UserGroupInformation authenticatedUser = kerberosAuthenticator.authenticate();
    assertEquals(KERBEROS, authenticatedUser.getRealAuthenticationMethod());
  }

  @Test
  public void testAuthenticateReturnsAnAuthenticatedUserWithProperUsernameIfKerberosIsEnabled() throws Exception {
    kerberosAuthenticator = new KerberosAuthenticator(createKerberosConfiguration(), miniKdc.getTestPrincipal(), miniKdc.getKeytabFilePath());

    UserGroupInformation authenticatedUser = kerberosAuthenticator.authenticate();
    assertEquals(miniKdc.getTestPrincipal(), authenticatedUser.getUserName());
  }

  @Test
  public void testAuthenticateThrowsIfKerberosIsEnabledAndInvalidKeytabIsProvided() throws Exception {
    String invalidKeytabLocation = "invalid_keytab_location";
    kerberosAuthenticator = new KerberosAuthenticator(createKerberosConfiguration(), miniKdc.getTestPrincipal(), invalidKeytabLocation);

    expectedException.expect(RuntimeException.class);
    expectedException.expectMessage("Kerberos authentication failed!");
    kerberosAuthenticator.authenticate();
  }

  @Test
  public void testAuthenticateThrowsIfKerberosIsEnabledAndInvalidPrincipalIsProvided() throws Exception {
    String invalidPrincipal = "invalid_principal";
    kerberosAuthenticator = new KerberosAuthenticator(createKerberosConfiguration(), invalidPrincipal, miniKdc.getKeytabFilePath());

    expectedException.expect(RuntimeException.class);
    expectedException.expectMessage("Kerberos authentication failed!");
    kerberosAuthenticator.authenticate();
  }

  private Configuration createKerberosConfiguration() {
    Configuration configuration = new Configuration();
    configuration.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
    // Adding a rule for the realm used by the MiniKdc since the default kerberos configuration might contain another realm.
    configuration.set(CommonConfigurationKeys.HADOOP_SECURITY_AUTH_TO_LOCAL, buildKerberosRule());
    return configuration;
  }

  private String buildKerberosRule() {
    return String.format(KERBEROS_RULE_TEMPLATE, miniKdc.getRealm(), miniKdc.getRealm());
  }

}


text:
// Generated source
package org.jetbrains.wip.protocol.timeline;

/**
 * Tells whether timeline agent supports frame instrumentation.
 */
public final class SupportsFrameInstrumentation extends org.jetbrains.wip.protocol.WipRequest implements org.jetbrains.jsonProtocol.RequestWithResponse<org.jetbrains.wip.protocol.timeline.SupportsFrameInstrumentationResult, org.jetbrains.wip.protocol.ProtocolReponseReader> {

  @Override
  public String getMethodName() {
    return "Timeline.supportsFrameInstrumentation";
  }

  @Override
  public SupportsFrameInstrumentationResult readResult(com.google.gson.stream.JsonReaderEx jsonReader, org.jetbrains.wip.protocol.ProtocolReponseReader reader) {
    return reader.readTimelineSupportsFrameInstrumentationResult(jsonReader);
  }
}


text:
using QuantConnect.Data.Market;
using QuantConnect.Indicators;

namespace Strategies.SuperSmoothedDoubleStochasticStrategy
{
    public class SuperSmoothedDoubleStochastic : TradeBarIndicator
    {
        private readonly IndicatorBase<IndicatorDataPoint> _maximum;
        private readonly IndicatorBase<IndicatorDataPoint> _mininum;

        private readonly SimpleMovingAverage _firstSmoothing;

        private decimal _prevStochastic;
        private readonly Stochastic _stochastic;

        public IndicatorBase<TradeBar> Smoothed { get; private set; }

        public SuperSmoothedDoubleStochastic(string name, int period, int kPeriod, int dPeriod)
            : base(name)
        {
            _maximum = new Maximum(name + "_Max", period);
            _mininum = new Minimum(name + "_Min", period);
            _stochastic = new Stochastic(name + "_Stoch", period, kPeriod, dPeriod);
            _firstSmoothing = new SimpleMovingAverage(3);

            Smoothed = new FunctionalIndicator<TradeBar>(name + "_Smoothed",
                input => ComputeSmoothed(period, input),
                smoothed => _maximum.IsReady,
                () => _maximum.Reset()
                );
        }

        public SuperSmoothedDoubleStochastic(int period, int kPeriod, int dPeriod)
            : this("STO" + period, period, kPeriod, dPeriod)
        {
        }

        protected override decimal ComputeNextValue(TradeBar input)
        {
            _stochastic.Update(input);
            _maximum.Update(input.Time, _stochastic);
            _mininum.Update(input.Time, _stochastic);

            if (IsReady)
            {
                Smoothed.Update(input);
            }

            _prevStochastic = Smoothed;

            return Smoothed * 100;
        }

        private decimal ComputeSmoothed(int period, TradeBar input)
        {
            var denominator = _maximum - _mininum;
            var numerator = _stochastic - _mininum;
            decimal smoothed;
            if (denominator == 0m)
            {
                // if there's no range, just return constant zero
                smoothed = 0m;
            }
            else
            {
                smoothed = _maximum.Samples >= period ? numerator / denominator : new decimal(0.0);
            }

            _firstSmoothing.Update(input.Time, smoothed);

            if (_firstSmoothing.IsReady)
            {
                smoothed = 0.85m * _firstSmoothing + 0.15m * _prevStochastic;
            }

            return smoothed;
        }

        public override void Reset()
        {
            Smoothed.Reset();
            base.Reset();
        }

        public override bool IsReady => _stochastic.IsReady;
    }
}


text:
package org.apache.camel.component.xslt;

import java.util.Map;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;

import org.apache.camel.Endpoint;
import org.apache.camel.builder.xml.ResultHandlerFactory;
import org.apache.camel.builder.xml.XsltBuilder;
import org.apache.camel.builder.xml.XsltUriResolver;
import org.apache.camel.converter.jaxp.XmlConverter;
import org.apache.camel.impl.DefaultComponent;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ResourceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * An XSLT Component
 * for performing XSLT transforms of messages
 */
public class XsltComponent extends DefaultComponent {
    private static final transient Logger LOG = LoggerFactory.getLogger(XsltComponent.class);
    private XmlConverter xmlConverter;
    private URIResolver uriResolver;
    private boolean contentCache = true;

    public XmlConverter getXmlConverter() {
        return xmlConverter;
    }

    public void setXmlConverter(XmlConverter xmlConverter) {
        this.xmlConverter = xmlConverter;
    }

    public URIResolver getUriResolver() {
        return uriResolver;
    }

    public void setUriResolver(URIResolver uriResolver) {
        this.uriResolver = uriResolver;
    }

    public boolean isContentCache() {
        return contentCache;
    }

    public void setContentCache(boolean contentCache) {
        this.contentCache = contentCache;
    }

    protected Endpoint createEndpoint(String uri, final String remaining, Map<String, Object> parameters) throws Exception {
        String resourceUri = remaining;
        LOG.debug("{} using schema resource: {}", this, resourceUri);
        final XsltBuilder xslt = getCamelContext().getInjector().newInstance(XsltBuilder.class);

        // lets allow the converter to be configured
        XmlConverter converter = resolveAndRemoveReferenceParameter(parameters, "converter", XmlConverter.class);
        if (converter == null) {
            converter = getXmlConverter();
        }
        if (converter != null) {
            xslt.setConverter(converter);
        }

        String transformerFactoryClassName = getAndRemoveParameter(parameters, "transformerFactoryClass", String.class);
        TransformerFactory factory = null;
        if (transformerFactoryClassName != null) {
            // provide the class loader of this component to work in OSGi environments
            Class<?> factoryClass = getCamelContext().getClassResolver().resolveClass(transformerFactoryClassName, XsltComponent.class.getClassLoader());
            if (factoryClass != null) {
                factory = (TransformerFactory) getCamelContext().getInjector().newInstance(factoryClass);
            } else {
                LOG.warn("Cannot find the TransformerFactoryClass with the class name: {}", transformerFactoryClassName);
            }
        }

        if (parameters.get("transformerFactory") != null) {
            factory = resolveAndRemoveReferenceParameter(parameters, "transformerFactory", TransformerFactory.class);
        }

        if (factory != null) {
            xslt.getConverter().setTransformerFactory(factory);
        }

        ResultHandlerFactory resultHandlerFactory = resolveAndRemoveReferenceParameter(parameters, "resultHandlerFactory", ResultHandlerFactory.class);
        if (resultHandlerFactory != null) {
            xslt.setResultHandlerFactory(resultHandlerFactory);
        }

        Boolean failOnNullBody = getAndRemoveParameter(parameters, "failOnNullBody", Boolean.class);
        if (failOnNullBody != null) {
            xslt.setFailOnNullBody(failOnNullBody);
        }
        String output = getAndRemoveParameter(parameters, "output", String.class);
        configureOutput(xslt, output);

        Integer cs = getAndRemoveParameter(parameters, "transformerCacheSize", Integer.class, Integer.valueOf(0));
        xslt.transformerCacheSize(cs);

        // default to use the cache option from the component if the endpoint did not have the contentCache parameter
        boolean cache = getAndRemoveParameter(parameters, "contentCache", Boolean.class, contentCache);

        // if its a http uri, then append additional parameters as they are part of the uri
        if (ResourceHelper.isHttpUri(resourceUri)) {
            resourceUri = ResourceHelper.appendParameters(resourceUri, parameters);
        }

        // lookup custom resolver to use
        URIResolver resolver = resolveAndRemoveReferenceParameter(parameters, "uriResolver", URIResolver.class);
        if (resolver == null) {
            // not in endpoint then use component specific resolver
            resolver = getUriResolver();
        }
        if (resolver == null) {
            // fallback to use a Camel specific resolver
            resolver = new XsltUriResolver(getCamelContext().getClassResolver(), remaining);
        }
        // set resolver before input stream as resolver is used when loading the input stream
        xslt.setUriResolver(resolver);

        configureXslt(xslt, uri, remaining, parameters);

        return new XsltEndpoint(uri, this, xslt, resourceUri, cache);
    }

    protected void configureXslt(XsltBuilder xslt, String uri, String remaining, Map<String, Object> parameters) throws Exception {
        setProperties(xslt, parameters);
    }

    protected void configureOutput(XsltBuilder xslt, String output) throws Exception {
        if (ObjectHelper.isEmpty(output)) {
            return;
        }

        if ("string".equalsIgnoreCase(output)) {
            xslt.outputString();
        } else if ("bytes".equalsIgnoreCase(output)) {
            xslt.outputBytes();
        } else if ("DOM".equalsIgnoreCase(output)) {
            xslt.outputDOM();
        } else if ("file".equalsIgnoreCase(output)) {
            xslt.outputFile();
        } else {
            throw new IllegalArgumentException("Unknown output type: " + output);
        }
    }

}


text:
#!/bin/sh

test_description='test smart fetching over http via http-backend'
. ./test-lib.sh
. "$TEST_DIRECTORY"/lib-httpd.sh
start_httpd

test_expect_success 'setup repository' '
	git config push.default matching &&
	echo content >file &&
	git add file &&
	git commit -m one
'

test_expect_success 'create http-accessible bare repository' '
	mkdir "$HTTPD_DOCUMENT_ROOT_PATH/repo.git" &&
	(cd "$HTTPD_DOCUMENT_ROOT_PATH/repo.git" &&
	 git --bare init
	) &&
	git remote add public "$HTTPD_DOCUMENT_ROOT_PATH/repo.git" &&
	git push public master:master
'

setup_askpass_helper

cat >exp <<EOF
> GET /smart/repo.git/info/refs?service=git-upload-pack HTTP/1.1
> Accept: */*
> Accept-Encoding: gzip
> Pragma: no-cache
< HTTP/1.1 200 OK
< Pragma: no-cache
< Cache-Control: no-cache, max-age=0, must-revalidate
< Content-Type: application/x-git-upload-pack-advertisement
> POST /smart/repo.git/git-upload-pack HTTP/1.1
> Accept-Encoding: gzip
> Content-Type: application/x-git-upload-pack-request
> Accept: application/x-git-upload-pack-result
> Content-Length: xxx
< HTTP/1.1 200 OK
< Pragma: no-cache
< Cache-Control: no-cache, max-age=0, must-revalidate
< Content-Type: application/x-git-upload-pack-result
EOF
test_expect_success 'clone http repository' '
	GIT_CURL_VERBOSE=1 git clone --quiet $HTTPD_URL/smart/repo.git clone 2>err &&
	test_cmp file clone/file &&
	tr '\''\015'\'' Q <err |
	sed -e "
		s/Q\$//
		/^[*] /d
		/^$/d
		/^< $/d

		/^[^><]/{
			s/^/> /
		}

		/^> User-Agent: /d
		/^> Host: /d
		/^> POST /,$ {
			/^> Accept: [*]\\/[*]/d
		}
		s/^> Content-Length: .*/> Content-Length: xxx/
		/^> 00..want /d
		/^> 00.*done/d

		/^< Server: /d
		/^< Expires: /d
		/^< Date: /d
		/^< Content-Length: /d
		/^< Transfer-Encoding: /d
	" >act &&
	test_cmp exp act
'

test_expect_success 'fetch changes via http' '
	echo content >>file &&
	git commit -a -m two &&
	git push public &&
	(cd clone && git pull) &&
	test_cmp file clone/file
'

cat >exp <<EOF
GET  /smart/repo.git/info/refs?service=git-upload-pack HTTP/1.1 200
POST /smart/repo.git/git-upload-pack HTTP/1.1 200
GET  /smart/repo.git/info/refs?service=git-upload-pack HTTP/1.1 200
POST /smart/repo.git/git-upload-pack HTTP/1.1 200
EOF
test_expect_success 'used upload-pack service' '
	sed -e "
		s/^.* \"//
		s/\"//
		s/ [1-9][0-9]*\$//
		s/^GET /GET  /
	" >act <"$HTTPD_ROOT_PATH"/access.log &&
	test_cmp exp act
'

test_expect_success 'follow redirects (301)' '
	git clone $HTTPD_URL/smart-redir-perm/repo.git --quiet repo-p
'

test_expect_success 'follow redirects (302)' '
	git clone $HTTPD_URL/smart-redir-temp/repo.git --quiet repo-t
'

test_expect_success 'redirects re-root further requests' '
	git clone $HTTPD_URL/smart-redir-limited/repo.git repo-redir-limited
'

test_expect_success 'clone from password-protected repository' '
	echo two >expect &&
	set_askpass user@host pass@host &&
	git clone --bare "$HTTPD_URL/auth/smart/repo.git" smart-auth &&
	expect_askpass both user@host &&
	git --git-dir=smart-auth log -1 --format=%s >actual &&
	test_cmp expect actual
'

test_expect_success 'clone from auth-only-for-push repository' '
	echo two >expect &&
	set_askpass wrong &&
	git clone --bare "$HTTPD_URL/auth-push/smart/repo.git" smart-noauth &&
	expect_askpass none &&
	git --git-dir=smart-noauth log -1 --format=%s >actual &&
	test_cmp expect actual
'

test_expect_success 'clone from auth-only-for-objects repository' '
	echo two >expect &&
	set_askpass user@host pass@host &&
	git clone --bare "$HTTPD_URL/auth-fetch/smart/repo.git" half-auth &&
	expect_askpass both user@host &&
	git --git-dir=half-auth log -1 --format=%s >actual &&
	test_cmp expect actual
'

test_expect_success 'no-op half-auth fetch does not require a password' '
	set_askpass wrong &&
	git --git-dir=half-auth fetch &&
	expect_askpass none
'

test_expect_success 'redirects send auth to new location' '
	set_askpass user@host pass@host &&
	git -c credential.useHttpPath=true \
	  clone $HTTPD_URL/smart-redir-auth/repo.git repo-redir-auth &&
	expect_askpass both user@host auth/smart/repo.git
'

test_expect_success 'disable dumb http on server' '
	git --git-dir="$HTTPD_DOCUMENT_ROOT_PATH/repo.git" \
		config http.getanyfile false
'

test_expect_success 'GIT_SMART_HTTP can disable smart http' '
	(GIT_SMART_HTTP=0 &&
	 export GIT_SMART_HTTP &&
	 cd clone &&
	 test_must_fail git fetch)
'

test_expect_success 'invalid Content-Type rejected' '
	test_must_fail git clone $HTTPD_URL/broken_smart/repo.git 2>actual &&
	grep "not valid:" actual
'

test_expect_success 'create namespaced refs' '
	test_commit namespaced &&
	git push public HEAD:refs/namespaces/ns/refs/heads/master &&
	git --git-dir="$HTTPD_DOCUMENT_ROOT_PATH/repo.git" \
		symbolic-ref refs/namespaces/ns/HEAD refs/namespaces/ns/refs/heads/master
'

test_expect_success 'smart clone respects namespace' '
	git clone "$HTTPD_URL/smart_namespace/repo.git" ns-smart &&
	echo namespaced >expect &&
	git --git-dir=ns-smart/.git log -1 --format=%s >actual &&
	test_cmp expect actual
'

test_expect_success 'dumb clone via http-backend respects namespace' '
	git --git-dir="$HTTPD_DOCUMENT_ROOT_PATH/repo.git" \
		config http.getanyfile true &&
	GIT_SMART_HTTP=0 git clone \
		"$HTTPD_URL/smart_namespace/repo.git" ns-dumb &&
	echo namespaced >expect &&
	git --git-dir=ns-dumb/.git log -1 --format=%s >actual &&
	test_cmp expect actual
'

cat >cookies.txt <<EOF
127.0.0.1	FALSE	/smart_cookies/	FALSE	0	othername	othervalue
EOF
cat >expect_cookies.txt <<EOF

127.0.0.1	FALSE	/smart_cookies/	FALSE	0	othername	othervalue
127.0.0.1	FALSE	/smart_cookies/repo.git/info/	FALSE	0	name	value
EOF
test_expect_success 'cookies stored in http.cookiefile when http.savecookies set' '
	git config http.cookiefile cookies.txt &&
	git config http.savecookies true &&
	git ls-remote $HTTPD_URL/smart_cookies/repo.git master &&
	tail -3 cookies.txt >cookies_tail.txt &&
	test_cmp expect_cookies.txt cookies_tail.txt
'

test_expect_success 'transfer.hiderefs works over smart-http' '
	test_commit hidden &&
	test_commit visible &&
	git push public HEAD^:refs/heads/a HEAD:refs/heads/b &&
	git --git-dir="$HTTPD_DOCUMENT_ROOT_PATH/repo.git" \
		config transfer.hiderefs refs/heads/a &&
	git clone --bare "$HTTPD_URL/smart/repo.git" hidden.git &&
	test_must_fail git -C hidden.git rev-parse --verify a &&
	git -C hidden.git rev-parse --verify b
'

# create an arbitrary number of tags, numbered from tag-$1 to tag-$2
create_tags () {
	rm -f marks &&
	for i in $(test_seq "$1" "$2")
	do
		# don't use here-doc, because it requires a process
		# per loop iteration
		echo "commit refs/heads/too-many-refs-$1" &&
		echo "mark :$i" &&
		echo "committer git <git@example.com> $i +0000" &&
		echo "data 0" &&
		echo "M 644 inline bla.txt" &&
		echo "data 4" &&
		echo "bla" &&
		# make every commit dangling by always
		# rewinding the branch after each commit
		echo "reset refs/heads/too-many-refs-$1" &&
		echo "from :$1"
	done | git fast-import --export-marks=marks &&

	# now assign tags to all the dangling commits we created above
	tag=$(perl -e "print \"bla\" x 30") &&
	sed -e "s|^:\([^ ]*\) \(.*\)$|\2 refs/tags/$tag-\1|" <marks >>packed-refs
}

test_expect_success 'create 2,000 tags in the repo' '
	(
		cd "$HTTPD_DOCUMENT_ROOT_PATH/repo.git" &&
		create_tags 1 2000
	)
'

test_expect_success CMDLINE_LIMIT \
	'clone the 2,000 tag repo to check OS command line overflow' '
	run_with_limited_cmdline git clone $HTTPD_URL/smart/repo.git too-many-refs &&
	(
		cd too-many-refs &&
		git for-each-ref refs/tags >actual &&
		test_line_count = 2000 actual
	)
'

test_expect_success 'large fetch-pack requests can be split across POSTs' '
	GIT_CURL_VERBOSE=1 git -c http.postbuffer=65536 \
		clone --bare "$HTTPD_URL/smart/repo.git" split.git 2>err &&
	grep "^> POST" err >posts &&
	test_line_count = 2 posts
'

test_expect_success EXPENSIVE 'http can handle enormous ref negotiation' '
	(
		cd "$HTTPD_DOCUMENT_ROOT_PATH/repo.git" &&
		create_tags 2001 50000
	) &&
	git -C too-many-refs fetch -q --tags &&
	(
		cd "$HTTPD_DOCUMENT_ROOT_PATH/repo.git" &&
		create_tags 50001 100000
	) &&
	git -C too-many-refs fetch -q --tags &&
	git -C too-many-refs for-each-ref refs/tags >tags &&
	test_line_count = 100000 tags
'

stop_httpd
test_done


text:
@interface _PDDictionaryPropertyKey : NSObject

- (id)initWithKey:(id <NSCopying>)key stringRepresentation:(NSString *)stringKey;

@property (nonatomic, copy) id <NSCopying> key;
@property (nonatomic, copy) NSString *stringKey;

@end

#pragma mark - Implementation

@implementation NSDictionary (PDRuntimePropertyDescriptor)

- (NSArray *)PD_propertiesForPropertyDescriptors;
{
    NSMutableArray *properties = [[NSMutableArray alloc] initWithCapacity:self.count];

    [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSString *stringKey = [NSString stringWithFormat:@"%@", key];

        _PDDictionaryPropertyKey *containerIndex = [[_PDDictionaryPropertyKey alloc] initWithKey:key stringRepresentation:stringKey];
        [properties addObject:containerIndex];
    }];

    return properties;
}

- (PDRuntimePropertyDescriptor *)PD_propertyDescriptorForPropertyObject:(NSObject *)property;
{
    PDRuntimePropertyDescriptor *descriptor = [super PD_propertyDescriptorForPropertyObject:property];
    if (!descriptor) {
        if ([property isKindOfClass:[_PDDictionaryPropertyKey class]]) {
            descriptor = [self PD_propertyDescriptorForDictionaryContainerKey:(_PDDictionaryPropertyKey *)property];
        }
    }

    return descriptor;
}

- (PDRuntimePropertyDescriptor *)PD_propertyDescriptorForDictionaryContainerKey:(_PDDictionaryPropertyKey *)containerKey;
{
    PDRuntimePropertyDescriptor *descriptor = [[PDRuntimePropertyDescriptor alloc] init];

    id propertyValue = [self objectForKey:containerKey.key];

    descriptor.name = containerKey.stringKey;
    descriptor.value = [self PD_propertyDescriptorValueForObject:propertyValue];
    descriptor.writable = [NSNumber numberWithBool:NO];
    descriptor.configurable = [NSNumber numberWithBool:NO];
    descriptor.enumerable = [NSNumber numberWithBool:YES];
    descriptor.wasThrown = [NSNumber numberWithBool:NO];

    return descriptor;
}

@end

#pragma mark - _PDDictionaryPropertyKey

@implementation _PDDictionaryPropertyKey

@synthesize stringKey = _stringKey;
@synthesize key = _key;

- (id)initWithKey:(id<NSCopying>)key stringRepresentation:(NSString *)stringKey;
{
    if (!(self = [super self])) {
        return nil;
    }

    self.key = key;
    self.stringKey = stringKey;

    return self;
}

@end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>jester</artifactId>
        <groupId>org.jscep.jester</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>jester-common</artifactId>
    <packaging>jar</packaging>

    <name>Jester Common</name>
    <url>https://github.com/seize-the-dave/jester</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>
</project>


text:
'''
Created on Nov 27, 2012

@author:       Bo Zhao
@email:        Jakobzhao@gmail.com
@website:      http://yenching.org
@organization: The Ohio State University
'''

# retweet type
# 1: reply
# 2: comment
# 3: reply to a comment
# 4: a reply and a comment
# status type
# 0: original
# 1: reply
# 2: comments
import sqlite3
import math

import networkx as nx
import matplotlib.pylab as plt
import matplotlib
import numpy as np

from scipy import linalg

plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

#--------------------------------build network-----------------------------------

database = '../data/pm2.5.db'

conn = sqlite3.connect(database)#to name it with a specific word
cursor = conn.cursor()

cursor.execute('select id, source_name, target_name from user_edges')
edges = cursor.fetchall()
cursor.execute('select id, node from user_nodes')
nodes = cursor.fetchall()
conn.commit()
conn.close()

G = nx.DiGraph()
for node in nodes:
    G.add_node(node[1])
for edge in edges:
    G.add_edge(edge[1],edge[2])

degree_sequence=sorted(nx.degree(G).values(),reverse=True) # degree sequence
##print "Degree sequence", degree_sequence
dmax=max(degree_sequence)
#print "Degree histogram, max degree:",dmax
h,bins=matplotlib.numpy.histogram(degree_sequence,bins=dmax)
hmax=max(h)
#plt.axis([1,dmax,1,hmax])
#x=bins.compress(h)
#y=h.compress(h)
#print y
#plt.loglog(x,y,'b+',marker='+')
x, y , t = [], [],-1
for item in degree_sequence:
    if item != t:
        x.append(item)
        y.append(degree_sequence.count(item))
    t = item
print x
print y

plt.loglog(degree_sequence,'b+',marker='+')
#plt.loglog(x, y,'g+',marker='+')
plt.title("Degree Distribution")
plt.ylabel("degree")
plt.xlabel("count")

##===============================================
lnx = [math.log(f+1,math.e) for f in x]   # 对x进行对数转换

lny = [math.log(f+1,math.e) for f in y]   # 对y进行对数转换

a = np.mat([lnx,[1]*len(x)]).T          # 自变量矩阵a
b = np.mat(lny).T                       # 因变量矩阵b
(t,res,rank,s) = linalg.lstsq(a,b)      # 最小二乘法求系数

print t
r = t[0][0]
c = t[1][0]
x_ = x
y_ = [math.e**(r*a+c+1.6) for a in lnx]    # 根据求的的系数求出y*  1.5 is added by me.
plt.loglog(x_,y_,"r-")                  # 绘制拟合的曲线图

plt.savefig("../data/img/power_law.png")
plt.show()


text:
<bill session="115" type="h" number="2956" updated="2017-07-11T07:15:25Z">
  <state datetime="2017-06-20">REFERRED</state>
  <status>
    <introduced datetime="2017-06-20"/>
  </status>
  <introduced datetime="2017-06-20"/>
  <titles>
    <title type="short" as="introduced">Parental Notification and Intervention Act of 2017</title>
    <title type="short" as="introduced">Parental Notification and Intervention Act of 2017</title>
    <title type="official" as="introduced">To provide for parental notification and intervention in the case of an unemancipated minor seeking an abortion.</title>
    <title type="display">Parental Notification and Intervention Act of 2017</title>
  </titles>
  <sponsor bioguide_id="G000552"/>
  <cosponsors>
    <cosponsor bioguide_id="B001299" joined="2017-06-20"/>
    <cosponsor bioguide_id="C000266" joined="2017-06-20"/>
    <cosponsor bioguide_id="D000615" joined="2017-06-20"/>
    <cosponsor bioguide_id="G000578" joined="2017-07-10"/>
    <cosponsor bioguide_id="G000560" joined="2017-06-27"/>
    <cosponsor bioguide_id="G000576" joined="2017-06-22"/>
    <cosponsor bioguide_id="H001045" joined="2017-06-20"/>
    <cosponsor bioguide_id="H001052" joined="2017-06-21"/>
    <cosponsor bioguide_id="J000255" joined="2017-06-20"/>
    <cosponsor bioguide_id="K000362" joined="2017-06-20"/>
    <cosponsor bioguide_id="L000566" joined="2017-06-21"/>
    <cosponsor bioguide_id="O000168" joined="2017-06-20"/>
    <cosponsor bioguide_id="P000601" joined="2017-06-20"/>
    <cosponsor bioguide_id="W000821" joined="2017-06-20"/>
  </cosponsors>
  <actions>
    <action datetime="2017-06-20">
      <text>Introduced in House</text>
    </action>
    <action datetime="2017-06-20" state="REFERRED">
      <text>Referred to the House Committee on the Judiciary.</text>
    </action>
    <action datetime="2017-07-10">
      <text>Referred to the Subcommittee on the Constitution and Civil Justice.</text>
    </action>
  </actions>
  <committees>
    <committee subcommittee="" code="HSJU" name="House Judiciary" activity="Referral"/>
    <committee subcommittee="Constitution and Civil Justice" code="HSJU10" name="House Judiciary" activity="Referral"/>
  </committees>
  <relatedbills/>
  <subjects>
    <term name="Civil rights and liberties, minority issues"/>
    <term name="Abortion"/>
    <term name="Administrative law and regulatory procedures"/>
    <term name="Business investment and capital"/>
    <term name="Business records"/>
    <term name="Civil actions and liability"/>
    <term name="Competition and antitrust"/>
    <term name="Congressional oversight"/>
    <term name="Corporate finance and management"/>
    <term name="Crime and Law Enforcement"/>
    <term name="Domestic violence and child abuse"/>
    <term name="Emergency medical services and trauma care"/>
    <term name="Family relationships"/>
    <term name="Finance and Financial Sector"/>
    <term name="Financial services and investments"/>
    <term name="Government studies and investigations"/>
    <term name="Health personnel"/>
    <term name="Securities"/>
    <term name="Securities and Exchange Commission (SEC)"/>
    <term name="Small business"/>
  </subjects>
  <amendments/>
  <committee-reports/>
</bill>


text:
from functools import reduce
from io import BytesIO, StringIO
import os.path
import re
from uuid import uuid4

from django.core.files import File
from django.core.files.base import ContentFile
from django.db import IntegrityError
from django.db.models import Manager
from django.utils import timezone

__all__ = [
    'MailHeaderManager', 'BlacklistManager', 'DynamicAttachmentManager',
    'StaticAttachmentManager', 'SubscriptionManager',
]

class MailHeaderManager(Manager):

    def items(self):
        """Return headers as a list of tuples (name, value)."""
        for header in self.get_queryset():
            yield header.name, header.value

class DynamicAttachmentManager(Manager):

    def create(self, **kwargs):
        attachment = kwargs.pop('attachment')
        if isinstance(attachment, (str, bytes)):
            attachment = ContentFile(attachment)
        elif isinstance(attachment, (BytesIO, StringIO)):
            attachment = File(attachment)
        if not isinstance(attachment, File):
            raise TypeError(
                "'attachment' must be a 'django.core.files.File'.")
        filename = kwargs.get('filename')
        if not filename:
            filename = str(uuid4())
        obj = self.model(**kwargs)
        obj.attachment.save(filename, attachment, save=False)
        obj.save()
        return obj

class StaticAttachmentManager(Manager):

    def create(self, **kwargs):
        base_path = self.model._meta.get_field('attachment').path
        attachment = kwargs.pop('attachment')
        if not attachment.startswith(base_path + '/'):
            attachment = os.path.join(base_path, attachment)
        kwargs['attachment'] = attachment
        obj = self.model(**kwargs)
        obj.save()
        return obj

class BlacklistManager(Manager):

    raw_email_re = re.compile(r'.*<\s*([^<> ]+)\s*>')

    @staticmethod
    def _split_recipients(recipients):
        if isinstance(recipients, str):
            return list(filter(None, recipients.split(',')))
        else:
            return recipients

    @classmethod
    def _to_raw_email(cls, email):
        email = email.strip()
        match = cls.raw_email_re.match(email)
        if match:
            email = match.group(1)
        return email

    def filter_blacklisted(self, *args, **kwargs):
        recipients = list(map(self._split_recipients, args))
        ignore = kwargs.get('ignore')
        if ignore is True:
            return args
        flatten = map(self._to_raw_email,
                      reduce(lambda x, y: x+y if y else x, recipients, []))
        queryset = self.get_queryset().filter(email__in=flatten)
        if ignore:
            queryset = queryset.exclude(reason__in=ignore)
        blacklisted = queryset.values_list('email', flat=True)
        filtered = []
        for recipient_list in recipients:
            if recipient_list:
                filtered.append(', '.join(
                    r for r in recipient_list
                    if self._to_raw_email(r) not in blacklisted
                ))
            else:
                filtered.append(None)
        return filtered

class SubscriptionManager(Manager):

    def create_or_update(self, **kwargs):
        filter_kwargs = {'email': kwargs['email']}
        if 'subscription_type_id' in kwargs:
            filter_kwargs['subscription_type_id'] = kwargs['subscription_type_id']
        elif 'subscription_type' in kwargs:
            filter_kwargs['subscription_type'] = kwargs['subscription_type']
        else:
            raise KeyError("Missing subscription type")
        try:
            self.create(**kwargs)
        except IntegrityError:
            self.get_queryset().filter(**filter_kwargs).update(
                subscribed=kwargs['subscribed'], last_modified=timezone.now())


text:
using System;
using Newtonsoft.Json;

namespace Synology.FileStation.Search.Results
{
	public class FileOwnerResult
	{
		public string User { get; set; }

		public string Group { get; set; }

		public int Uid { get; set; }

		public int Gid { get; set; }
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html>
  <head>
    <title>Test JS Script Inclusion</title>

		<script type='text/javascript' src='test_html1.js'></script>
		<script type='text/javascript' src='test_html2.js'></script>
	</head>

	<body>

	</body>
</html>


text:
package org.apache.pulsar.io.kafka.source;

import com.google.common.collect.ImmutableMap;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.io.core.SourceContext;
import org.apache.pulsar.io.kafka.KafkaAbstractSource;
import org.apache.pulsar.io.kafka.KafkaSourceConfig;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import static org.mockito.Mockito.mock;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.expectThrows;
import static org.testng.Assert.fail;

public class KafkaAbstractSourceTest {

    private static class DummySource extends KafkaAbstractSource<String> {

        @Override
        public KafkaRecord buildRecord(ConsumerRecord<Object, Object> consumerRecord) {
            KafkaRecord record = new KafkaRecord(consumerRecord,
                    new String((byte[]) consumerRecord.value(), StandardCharsets.UTF_8),
                    Schema.STRING);
            return record;
        }

    }

    @Test
    public void testInvalidConfigWillThrownException() throws Exception {
        KafkaAbstractSource source = new DummySource();
        SourceContext ctx = mock(SourceContext.class);
        Map<String, Object> config = new HashMap<>();
        Assert.ThrowingRunnable openAndClose = ()->{
            try {
                source.open(config, ctx);
                fail();
            } finally {
                source.close();
            }
        };
        expectThrows(NullPointerException.class, openAndClose);
        config.put("topic", "topic_1");
        expectThrows(NullPointerException.class, openAndClose);
        config.put("bootstrapServers", "localhost:8080");
        expectThrows(NullPointerException.class, openAndClose);
        config.put("groupId", "test-group");
        config.put("fetchMinBytes", -1);
        expectThrows(IllegalArgumentException.class, openAndClose);
        config.put("fetchMinBytes", 1000);
        config.put("autoCommitEnabled", true);
        config.put("autoCommitIntervalMs", -1);
        expectThrows(IllegalArgumentException.class, openAndClose);
        config.put("autoCommitIntervalMs", 100);
        config.put("sessionTimeoutMs", -1);
        expectThrows(IllegalArgumentException.class, openAndClose);
        config.put("sessionTimeoutMs", 10000);
        config.put("heartbeatIntervalMs", -100);
        expectThrows(IllegalArgumentException.class, openAndClose);
        config.put("heartbeatIntervalMs", 20000);
        expectThrows(IllegalArgumentException.class, openAndClose);
        config.put("heartbeatIntervalMs", 5000);
        config.put("autoOffsetReset", "some-value");
        expectThrows(IllegalArgumentException.class, openAndClose);
        config.put("autoOffsetReset", "earliest");
        source.open(config, ctx);
        source.close();
    }

    @Test
    public void loadConsumerConfigPropertiesFromMapTest() throws Exception {
        Map<String, Object> config = new HashMap<>();
        config.put("consumerConfigProperties", "");
        KafkaSourceConfig kafkaSourceConfig = KafkaSourceConfig.load(config);
        assertNotNull(kafkaSourceConfig);
        assertNull(kafkaSourceConfig.getConsumerConfigProperties());

        config.put("consumerConfigProperties", null);
        kafkaSourceConfig = KafkaSourceConfig.load(config);
        assertNull(kafkaSourceConfig.getConsumerConfigProperties());

        config.put("consumerConfigProperties", ImmutableMap.of("foo", "bar"));
        kafkaSourceConfig = KafkaSourceConfig.load(config);
        assertEquals(kafkaSourceConfig.getConsumerConfigProperties(), ImmutableMap.of("foo", "bar"));
    }

    @Test
    public final void loadFromYamlFileTest() throws IOException {
        File yamlFile = getFile("kafkaSourceConfig.yaml");
        KafkaSourceConfig config = KafkaSourceConfig.load(yamlFile.getAbsolutePath());
        assertNotNull(config);
        assertEquals("localhost:6667", config.getBootstrapServers());
        assertEquals("test", config.getTopic());
        assertEquals(Long.parseLong("10000"), config.getSessionTimeoutMs());
        assertFalse(config.isAutoCommitEnabled());
        assertEquals("latest", config.getAutoOffsetReset());
        assertNotNull(config.getConsumerConfigProperties());
        Properties props = new Properties();
        props.putAll(config.getConsumerConfigProperties());
        props.put(ConsumerConfig.GROUP_ID_CONFIG, config.getGroupId());
        assertEquals("test-pulsar-consumer", props.getProperty("client.id"));
        assertEquals("SASL_PLAINTEXT", props.getProperty("security.protocol"));
        assertEquals("test-pulsar-io", props.getProperty(ConsumerConfig.GROUP_ID_CONFIG));
    }

    @Test
    public final void loadFromSaslYamlFileTest() throws IOException {
        File yamlFile = getFile("kafkaSourceConfigSasl.yaml");
        KafkaSourceConfig config = KafkaSourceConfig.load(yamlFile.getAbsolutePath());
        assertNotNull(config);
        assertEquals(config.getBootstrapServers(), "localhost:6667");
        assertEquals(config.getTopic(), "test");
        assertEquals(config.getSecurityProtocol(), SecurityProtocol.SASL_PLAINTEXT.name);
        assertEquals(config.getSaslMechanism(), "PLAIN");
        assertEquals(config.getSaslJaasConfig(), "org.apache.kafka.common.security.plain.PlainLoginModule required \nusername=\"alice\" \npassword=\"pwd\";");
        assertEquals(config.getSslEndpointIdentificationAlgorithm(), "");
        assertEquals(config.getSslTruststoreLocation(), "/etc/cert.pem");
        assertEquals(config.getSslTruststorePassword(), "cert_pwd");
    }

    private File getFile(String name) {
        ClassLoader classLoader = getClass().getClassLoader();
        return new File(classLoader.getResource(name).getFile());
    }
}


text:
HTTP_USERNAME = "{{ buildbot_credentials['http-user'] }}"
HTTP_PASSWORD = "{{ buildbot_credentials['http-pass'] }}"
SLAVE_PASSWORD = "{{ buildbot_credentials['slave-pass'] }}"
CHANGE_PASSWORD = "{{ buildbot_credentials['change-pass'] }}"
GITHUB_DOC_TOKEN = "{{ buildbot_credentials['gh-doc-token'] }}"
GITHUB_HOMEBREW_TOKEN = "{{ buildbot_credentials['gh-homebrew-token'] }}"
HOMU_BUILDBOT_SECRET = "{{ buildbot_credentials['homu-secret'] }}"
S3_UPLOAD_ACCESS_KEY_ID = \
    "{{ buildbot_credentials['s3-upload-access-key-id'] }}"
S3_UPLOAD_SECRET_ACCESS_KEY = \
    "{{ buildbot_credentials['s3-upload-secret-access-key'] }}"
GITHUB_STATUS_TOKEN = "{{ buildbot_credentials['gh-status-token'] }}"


text:
package wrap_test

import (
	"fmt"

	"github.com/bbrks/wrap/v2"
)

func ExampleWrap() {
	var loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate quam nibh, et faucibus enim gravida vel. Integer bibendum lectus et erat semper fermentum quis a risus. Fusce dignissim tempus metus non pretium. Nunc sagittis magna nec purus porttitor mollis. Pellentesque feugiat quam eget laoreet aliquet. Donec gravida congue massa, et sollicitudin turpis lacinia a. Fusce non tortor magna. Cras vel finibus tellus."

	// Wrap when lines exceed 80 chars.
	fmt.Println(wrap.Wrap(loremIpsum, 80))
	// Output:
	// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate quam
	// nibh, et faucibus enim gravida vel. Integer bibendum lectus et erat semper
	// fermentum quis a risus. Fusce dignissim tempus metus non pretium. Nunc sagittis
	// magna nec purus porttitor mollis. Pellentesque feugiat quam eget laoreet
	// aliquet. Donec gravida congue massa, et sollicitudin turpis lacinia a. Fusce non
	// tortor magna. Cras vel finibus tellus.
}

func ExampleWrapper_Wrap() {
	var loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate quam nibh, et faucibus enim gravida vel. Integer bibendum lectus et erat semper fermentum quis a risus. Fusce dignissim tempus metus non pretium. Nunc sagittis magna nec purus porttitor mollis. Pellentesque feugiat quam eget laoreet aliquet. Donec gravida congue massa, et sollicitudin turpis lacinia a. Fusce non tortor magna. Cras vel finibus tellus."

	w := wrap.NewWrapper()

	// Wrap when lines exceed 80 chars.
	fmt.Println(w.Wrap(loremIpsum, 80))
	// Output:
	// Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate quam
	// nibh, et faucibus enim gravida vel. Integer bibendum lectus et erat semper
	// fermentum quis a risus. Fusce dignissim tempus metus non pretium. Nunc sagittis
	// magna nec purus porttitor mollis. Pellentesque feugiat quam eget laoreet
	// aliquet. Donec gravida congue massa, et sollicitudin turpis lacinia a. Fusce non
	// tortor magna. Cras vel finibus tellus.
}

func ExampleWrapper_Wrap_paragraphs() {
	var loremIpsum = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pulvinar augue vel dui gravida, sed convallis ante aliquam. Morbi euismod felis in justo lobortis, eu egestas quam cursus. Ut ut tellus mattis, porttitor leo ut, porttitor ex. Nulla suscipit molestie ligula, quis porta nulla pellentesque ac. Cras ut vestibulum orci. Phasellus ante nisl, dignissim non nunc eget, dapibus convallis orci. Integer vel euismod mauris. Integer tortor elit, vestibulum eget augue vitae, vehicula commodo sapien. Integer iaculis maximus dui, vitae rutrum magna congue at. Praesent varius quam vitae rhoncus fringilla. Quisque ac ex sit amet enim aliquam rutrum in in tortor. Sed sit amet est finibus, congue purus et, ultrices quam. Aenean felis velit, ullamcorper at sagittis ut, aliquam eu mauris.

Phasellus vel lorem venenatis, condimentum risus quis, ultricies risus. Vivamus porttitor lorem sit amet bibendum congue. Mauris sem enim, rutrum in ipsum eget, porttitor placerat diam. Pellentesque ut pharetra augue. Maecenas in ante eget ex efficitur tincidunt. Cras ut ultrices nisl. Donec tristique tincidunt eros condimentum tempus. Morbi libero urna, pretium id turpis vel, cursus efficitur orci. Mauris ut elit felis. Duis ultrices nisl eget accumsan consectetur. Nullam blandit elit vel vulputate scelerisque. Nulla facilisi. Cras quis maximus odio. Nam orci est, tempor ac arcu eget, tincidunt consectetur risus. Donec quis faucibus velit.

Maecenas rhoncus semper nisi non luctus. Nam accumsan malesuada urna vel vehicula. Nullam quis dui in augue tristique sollicitudin. Praesent vulputate condimentum vestibulum. Morbi tincidunt consectetur velit non accumsan. Praesent sit amet vestibulum purus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla rhoncus urna ut aliquet congue. Sed ornare dignissim orci non imperdiet. Maecenas nec magna bibendum, cursus nisi ac, commodo arcu.

Sed auctor id leo at molestie. Donec sed cursus massa. Morbi semper lobortis dui. Sed mattis sem a molestie sodales. Cras consequat sapien semper, pretium nulla a, dignissim massa. Aliquam non ornare lacus. Cras gravida lorem tellus, et consectetur ante sodales ut.

Nunc mi enim, aliquam quis bibendum sed, commodo quis nulla. Aliquam vulputate arcu a volutpat semper. Donec nec mauris eros. Suspendisse velit ante, fermentum a odio non, porta dignissim nunc. Vestibulum condimentum at massa at malesuada. Etiam augue purus, interdum a est pretium, cursus interdum eros. Vestibulum et ligula dignissim, suscipit arcu et, congue sem. Integer posuere mauris id scelerisque sagittis. Proin cursus congue sem, nec pulvinar neque auctor eget. Suspendisse vitae mi ipsum. Nullam sed mauris posuere, accumsan ligula vitae, viverra tellus. Morbi quam turpis, sagittis vitae arcu vel, tempus sagittis neque. Vivamus dolor purus, blandit ac condimentum a, interdum in ipsum.`

	w := wrap.NewWrapper()

	fmt.Println(w.Wrap(loremIpsum, 80))
	// Output:
	// Lorem ipsum dolor sit amet, consectetur adipiscing elit. In pulvinar augue vel
	// dui gravida, sed convallis ante aliquam. Morbi euismod felis in justo lobortis,
	// eu egestas quam cursus. Ut ut tellus mattis, porttitor leo ut, porttitor ex.
	// Nulla suscipit molestie ligula, quis porta nulla pellentesque ac. Cras ut
	// vestibulum orci. Phasellus ante nisl, dignissim non nunc eget, dapibus convallis
	// orci. Integer vel euismod mauris. Integer tortor elit, vestibulum eget augue
	// vitae, vehicula commodo sapien. Integer iaculis maximus dui, vitae rutrum magna
	// congue at. Praesent varius quam vitae rhoncus fringilla. Quisque ac ex sit amet
	// enim aliquam rutrum in in tortor. Sed sit amet est finibus, congue purus et,
	// ultrices quam. Aenean felis velit, ullamcorper at sagittis ut, aliquam eu
	// mauris.
	//
	// Phasellus vel lorem venenatis, condimentum risus quis, ultricies risus. Vivamus
	// porttitor lorem sit amet bibendum congue. Mauris sem enim, rutrum in ipsum eget,
	// porttitor placerat diam. Pellentesque ut pharetra augue. Maecenas in ante eget
	// ex efficitur tincidunt. Cras ut ultrices nisl. Donec tristique tincidunt eros
	// condimentum tempus. Morbi libero urna, pretium id turpis vel, cursus efficitur
	// orci. Mauris ut elit felis. Duis ultrices nisl eget accumsan consectetur. Nullam
	// blandit elit vel vulputate scelerisque. Nulla facilisi. Cras quis maximus odio.
	// Nam orci est, tempor ac arcu eget, tincidunt consectetur risus. Donec quis
	// faucibus velit.
	//
	// Maecenas rhoncus semper nisi non luctus. Nam accumsan malesuada urna vel
	// vehicula. Nullam quis dui in augue tristique sollicitudin. Praesent vulputate
	// condimentum vestibulum. Morbi tincidunt consectetur velit non accumsan. Praesent
	// sit amet vestibulum purus. Orci varius natoque penatibus et magnis dis
	// parturient montes, nascetur ridiculus mus. Nulla rhoncus urna ut aliquet congue.
	// Sed ornare dignissim orci non imperdiet. Maecenas nec magna bibendum, cursus
	// nisi ac, commodo arcu.
	//
	// Sed auctor id leo at molestie. Donec sed cursus massa. Morbi semper lobortis
	// dui. Sed mattis sem a molestie sodales. Cras consequat sapien semper, pretium
	// nulla a, dignissim massa. Aliquam non ornare lacus. Cras gravida lorem tellus,
	// et consectetur ante sodales ut.
	//
	// Nunc mi enim, aliquam quis bibendum sed, commodo quis nulla. Aliquam vulputate
	// arcu a volutpat semper. Donec nec mauris eros. Suspendisse velit ante, fermentum
	// a odio non, porta dignissim nunc. Vestibulum condimentum at massa at malesuada.
	// Etiam augue purus, interdum a est pretium, cursus interdum eros. Vestibulum et
	// ligula dignissim, suscipit arcu et, congue sem. Integer posuere mauris id
	// scelerisque sagittis. Proin cursus congue sem, nec pulvinar neque auctor eget.
	// Suspendisse vitae mi ipsum. Nullam sed mauris posuere, accumsan ligula vitae,
	// viverra tellus. Morbi quam turpis, sagittis vitae arcu vel, tempus sagittis
	// neque. Vivamus dolor purus, blandit ac condimentum a, interdum in ipsum.
}

func ExampleWrapper_Wrap_cutLongWords() {
	var loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate quam nibh, et faucibus enim gravida vel."

	w := wrap.NewWrapper()
	w.CutLongWords = true

	// Wrap at 10 chars and cut words longer.
	fmt.Println(w.Wrap(loremIpsum, 10))
	// Output:
	// Lorem
	// ipsum
	// dolor sit
	// amet,
	// consectetu
	// r
	// adipiscing
	// elit. Sed
	// vulputate
	// quam nibh,
	// et
	// faucibus
	// enim
	// gravida
	// vel.
}

func ExampleWrapper_Wrap_short() {
	var loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate quam nibh, et faucibus enim gravida vel. Integer bibendum lectus et erat semper fermentum quis a risus. Fusce dignissim tempus metus non pretium. Nunc sagittis magna nec purus porttitor mollis. Pellentesque feugiat quam eget laoreet aliquet. Donec gravida congue massa, et sollicitudin turpis lacinia a. Fusce non tortor magna. Cras vel finibus tellus."

	w := wrap.NewWrapper()

	// Wrap on every word.
	fmt.Println(w.Wrap(loremIpsum, 1))
	// Output:
	// Lorem
	// ipsum
	// dolor
	// sit
	// amet,
	// consectetur
	// adipiscing
	// elit.
	// Sed
	// vulputate
	// quam
	// nibh,
	// et
	// faucibus
	// enim
	// gravida
	// vel.
	// Integer
	// bibendum
	// lectus
	// et
	// erat
	// semper
	// fermentum
	// quis
	// a
	// risus.
	// Fusce
	// dignissim
	// tempus
	// metus
	// non
	// pretium.
	// Nunc
	// sagittis
	// magna
	// nec
	// purus
	// porttitor
	// mollis.
	// Pellentesque
	// feugiat
	// quam
	// eget
	// laoreet
	// aliquet.
	// Donec
	// gravida
	// congue
	// massa,
	// et
	// sollicitudin
	// turpis
	// lacinia
	// a.
	// Fusce
	// non
	// tortor
	// magna.
	// Cras
	// vel
	// finibus
	// tellus.
}

func ExampleWrapper_Wrap_hyphens() {
	var loremIpsum = `
In this particular example, I will spam a lot of hyphenated words, which should wrap at some point, and test the multi-breakpoint feature of this package.

The girl was accident-prone, good-looking, quick-thinking, carbon-neutral, bad-tempered, sport-mad, fair-haired, camera-ready, and finally open-mouthed.
`

	w := wrap.NewWrapper()

	fmt.Println(w.Wrap(loremIpsum, 80))
	// Output:
	// In this particular example, I will spam a lot of hyphenated words, which should
	// wrap at some point, and test the multi-breakpoint feature of this package.
	//
	// The girl was accident-prone, good-looking, quick-thinking, carbon-neutral, bad
	// tempered, sport-mad, fair-haired, camera-ready, and finally open-mouthed.
}

func ExampleWrapper_Wrap_prefix() {
	var loremIpsum = "/* Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate quam nibh, et faucibus enim gravida vel. Integer bibendum lectus et erat semper fermentum quis a risus. Fusce dignissim tempus metus non pretium. Nunc sagittis magna nec purus porttitor mollis. Pellentesque feugiat quam eget laoreet aliquet. Donec gravida congue massa, et sollicitudin turpis lacinia a. Fusce non tortor magna. Cras vel finibus tellus. */"

	w := wrap.NewWrapper()

	// Trim the single-line block comment symbols from each input line.
	w.TrimInputPrefix = "/* "
	w.TrimInputSuffix = " */"

	// Prefix each new line with a single-line comment symbol.
	w.OutputLinePrefix = "// "

	// Wrap when lines exceed 80 chars.
	fmt.Println(w.Wrap(loremIpsum, 80))
	// Output:
	// // Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate quam
	// // nibh, et faucibus enim gravida vel. Integer bibendum lectus et erat semper
	// // fermentum quis a risus. Fusce dignissim tempus metus non pretium. Nunc
	// // sagittis magna nec purus porttitor mollis. Pellentesque feugiat quam eget
	// // laoreet aliquet. Donec gravida congue massa, et sollicitudin turpis lacinia
	// // a. Fusce non tortor magna. Cras vel finibus tellus.
}


text:
import { TestBed, inject } from '@angular/core/testing';

import { PlanService } from './plan.service';

describe('PlanService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [PlanService]
    });
  });

  it('should be created', inject([PlanService], (service: PlanService) => {
    expect(service).toBeTruthy();
  }));
});


text:
<?php

require_once(MCMANAGER_ABSPATH . "FileManager/Utils/ZipFile.class.php");

/**
 * This is the zip file system implementation of BaseFile.
 *
 * @package MCFileManager.filesystems
 */
class Moxiecode_ZipFileImpl extends Moxiecode_BaseFileImpl {
	// Private fields
	var $_config;
	var $_zipEntry;
	var $_zipPath;
	var $_innerPath;

	/**
	 * Creates a new absolute file.
	 *
	 * @param MCManager $manager MCManager reference.
	 * @param String $absolute_path Absolute path to local file.
	 * @param String $child_name Name of child file (Optional).
	 * @param String $type Optional file type.
	 */
	function Moxiecode_ZipFileImpl(&$manager, $absolute_path, $child_name = "", $type = MC_IS_FILE) {
		Moxiecode_BaseFileImpl::Moxiecode_BaseFileImpl($manager, $absolute_path, $child_name, $type);

		$matches = array();
		$this->_absPath = str_replace("zip://", "", $this->_absPath);
		preg_match("/^(.*?.zip)(.*?)$/i", $this->_absPath, $matches);

		$this->_zipPath = $matches[1];
		$this->_innerPath = $matches[2];

		if (!$this->_innerPath)
			$this->_innerPath = "/";
	}

	/**
	 * Returns the file name of a file.
	 *
	 * @return string File name of file.
	 */
	function getName() {
		return basename($this->_absPath);
	}

	/**
	 * Returns the absolute path of the file.
	 *
	 * @return String absolute path of the file.
	 */
	function getAbsolutePath() {
		return "zip://" . $this->_absPath;
	}

	/**
	 * Returns the parent files absolute path.
	 *
	 * @return String parent files absolute path.
	 */
	function getParent() {
		// If get parent on root the give it the local FS parent
		if ($this->_innerPath == "/") {
			$file = $this->_manager->getFile($this->_zipPath);
			return $file->getParent();
		}

		return Moxiecode_BaseFileImpl::getParent();
	}

	/**
	 * Returns the parent files File instance.
	 *
	 * @return File parent files File instance or false if there is no more parents.
	 */
	function &getParentFile() {
		if ($this->_innerPath == "/")
			return $this->_manager->getFile($this->getParent());

		$file = new Moxiecode_ZipFileImpl($this->_manager, $this->getParent());

		return $file;
	}

	/**
	 * Imports a local file to the file system, for example when users upload files.
	 *
	 * @param String $local_absolute_path Absolute path to local file to import.
	 */
	function importFile($local_absolute_path = "") {
		$zip =& $this->_getZip();

		$zip->open();

		if (is_file($local_absolute_path))
			$zip->addFile($this->_innerPath, $local_absolute_path);
		else
			$zip->addDirectory($this->_innerPath, $local_absolute_path);

		$status = $zip->commit();
		$zip->close();

		return $status;
	}

	/**
	 * Exports the file to the local system, for example a file from a zip or db file system.
	 *
	 * @param String $local_absolute_path Absolute path to local file.
	 * @return true/false state if it was exported or not.
	 */
	function exportFile($local_absolute_path) {
		$zip =& $this->_getZip();

		$zip->open();
		$zip->extract($this->_innerPath, $local_absolute_path, true);
		$zip->close();

		return true;
	}

	/**
	 * Returns true if the file exists.
	 *
	 * @return boolean true if the file exists.
	 */
	function exists() {
		// If zip root
		if ($this->_innerPath == "/")
			return true;

		// Look for item inside zip
		$entry =& $this->_getZipEntry();

		return $entry != null;
	}

	/**
	 * Returns true if the file is a directory.
	 *
	 * @return boolean true if the file is a directory.
	 */
	function isDirectory() {
		// If zip root
		if ($this->_innerPath == "/")
			return true;

		if (!$this->exists())
			return $this->_type == MC_IS_DIRECTORY;

		$entry =& $this->_getZipEntry();

		return $entry->isDirectory();
	}

	/**
	 * Returns last modification date in ms as an long.
	 *
	 * @return long last modification date in ms as an long.
	 */
	function getLastModified() {
		$entry =& $this->_getZipEntry();

		return $entry->getLastModified();
	}

	/**
	 * Returns creation date in ms as an long.
	 *
	 * @return long creation date in ms as an long.
	 */
	function getCreationDate() {
		$entry =& $this->_getZipEntry();

		return $entry->getLastModified();
	}

	/**
	 * Returns true if the files is readable.
	 *
	 * @return boolean true if the files is readable.
	 */
	function canRead() {
		return true;
	}

	/**
	 * Returns true if the files is writable.
	 *
	 * @return boolean true if the files is writable.
	 */
	function canWrite() {
		return true;
	}

	/**
	 * Returns file size as an long.
	 *
	 * @return long file size as an long.
	 */
	function getLength() {
		$entry =& $this->_getZipEntry();

		return $entry->getSize();
	}

	/**
	 * Copies this file to the specified file instance.
	 *
	 * @param File $dest File to copy to.
	 * @return boolean true - success, false - failure
	 */
	function copyTo(&$dest) {
		if (getClassName($dest) == 'moxiecode_localfileimpl')
			return $this->exportFile($dest->getAbsolutePath());

		if ($this->isDirectory()) {
			$handle_as_add_event = true;
			$treeHandler = new _ZipFileCopyDirTreeHandler($this->_manager, $this, $dest, $handle_as_add_event);

			$this->listTree($treeHandler);

			return true;
		} else {
			// From/To Zip
			if (getClassName($dest) == 'moxiecode_zipfileimpl') {
				$zip =& $this->_getZip();
				$toZip =& $dest->_getZip();

				$zip->open();
				$toZip->open();

				// Copy single file
				$entry =& $zip->getEntryByPath($this->_innerPath);
				if ($entry && $entry->isFile()) {
					$toZip->addData($dest->_innerPath, $entry->getData());
				} else {
					// Copy directory
					$entries =& $zip->listEntries($this->_innerPath, true);
					for ($i=0; $i<count($entries); $i++) {
						$entry =& $entries[$i];

						if ($entry->isFile())
							$toZip->addData($dest->_innerPath, $entry->getData());
						else
							$toZip->addDirectory($dest->_innerPath);
					}
				}

				$zip->close();
				$toZip->commit();
				$toZip->close();
			} else {
				// Copy non local fs file
				$inStream =& $this->open('rb');
				$outStream =& $dest->open('wb');

				if ($inStream && $outStream) {
					while (($buff = $inStream->read()) != null)
						$outStream->write($buff);
				}

				if ($inStream)
					$inStream->close();

				if ($outStream)
					$outStream->close();
			}
		}

		return true;
	}

	/**
	 * Deletes the file.
	 *
	 * @param boolean $deep If this option is enabled files will be deleted recurive.
	 * @return boolean true - success, false - failure
	 */
	function delete($deep = false) {
		$zip =& $this->_getZip();

		$zip->open();

		if ($this->isFile())
			$state = $zip->deleteFile($this->_innerPath);
		else
			$state = $zip->deleteDir($this->_innerPath, $deep);

		$zip->commit();
		$zip->close();

		return $state;
	}

	/**
	 * Returns an array of BaseFile instances based on the specified filter instance.
	 *
	 * @param FileFilter &$filter FileFilter instance to filter files by.
	 * @return Array array of File instances based on the specified filter instance.
	 */
	function &listFilesFiltered(&$filter) {
		$dirs = array();
		$files = array();
		$zip =& $this->_getZip();
		$entries = $zip->listEntries($this->_innerPath);

		// Dirs
		foreach ($entries as $entry) {
			$zipFile = new Moxiecode_ZipFileImpl($this->_manager, $this->_absPath, $entry->getName());

			$zipFile->_setZipEntry($entry);

			if ($filter->accept($zipFile) == BASIC_FILEFILTER_ACCEPTED) {
				if ($zipFile->isFile())
					$files[] = $zipFile;
				else
					$dirs[] = $zipFile;
			}
		}

		$zip->close();

		$ar = array_merge($dirs, $files); // Stupid PHP 5 notices

		return $ar;
	}

	/**
	 * Creates a new directory.
	 *
	 * @return boolean true- success, false - failure
	 */
	function mkdir() {
		$zip =& $this->_getZip();

		$zip->open();

		$state = $zip->addDirectory($this->_innerPath);

		$zip->commit();
		$zip->close();

		return $state;
	}

	/**
	 * Renames/Moves this file to the specified file instance.
	 *
	 * @param File $dest File to rename/move to.
	 * @return boolean true- success, false - failure
	 */
	function renameTo(&$dest) {
		// If move within the same zip
		if (getClassName($dest) == 'moxiecode_zipfileimpl' && $this->_zipPath == $dest->_zipPath) {
			$zip =& $this->_getZip();
			$zip->open();
			$zip->moveEntry($this->_innerPath, $dest->_innerPath);
			$zip->commit();
			$zip->close();
		} else {
			// Copy and delete
			$this->copyTo($dest);
			$this->delete(true);
		}

		return true;
	}

	/*
	 * Sets the last-modified time of the file or directory.
	 *
	 * @param String $datetime The new date/time to set the file, in timestamp format
	 * @return boolean true- success, false - failure
	 */
	function setLastModified($datetime) {
		$zip =& $this->_getZip();

		$zip->open();

		// Check for file
		$entry =& $zip->getEntryByPath($this->_innerPath);

		// Check for dir
		if (!$entry)
			$entry =& $zip->getEntryByPath($this->_innerPath . '/');

		// Update mod time
		$entry->setLastModified($datetime);

		$zip->commit();
		$zip->close();

		return $state;
	}

	/**
	 * Returns a merged name/value array of config elements.
	 *
	 * @return Array Merged name/value array of config elements.
	 */
	function getConfig() {
		$file =& $this->_manager->getFile($this->_zipPath);

		return $file->getConfig();
	}

	/**
	 * Opens a file stream by the specified mode. The default mode is rb.
	 *
	 * @param String $mode Mode to open file by, r, rb, w, wb etc.
	 * @return FileStream File stream implementation for the file system.
	 */
	function &open($mode = 'rb') {
		$ent = new Moxiecode_ZipFileStream($this, $mode);

		return $ent;
	}

	// * * Private methods

	function &_getZip() {
		$file = new Moxiecode_ZipFile($this->_zipPath);

		return $file;
	}

	function _setZipEntry(&$entry) {
		$this->_zipEntry = $entry;
	}

	function _getZipEntry() {
		if (!$this->_zipEntry) {
			$zip =& $this->_getZip();

			$zip->open();

			// Check for file
			$this->_zipEntry =& $zip->getEntryByPath($this->_innerPath);

			// Check for dir
			if (!$this->_zipEntry)
				$this->_zipEntry =& $zip->getEntryByPath($this->_innerPath . '/');

			$zip->close();
		}

		return $this->_zipEntry;
	}
}

class _ZipFileCopyDirTreeHandler extends Moxiecode_FileTreeHandler {
	var $_fromFile;
	var $_destFile;
	var $_manager;
	var $_handle_as_add_event;

	function _LocalCopyDirTreeHandler(&$manager, $from_file, $dest_file, $handle_as_add_event) {
		$this->_manager = $manager;
		$this->_fromFile = $from_file;
		$this->_destFile = $dest_file;
		$this->_handle_as_add_event = $handle_as_add_event;
	}

	/**
	 * Handles a file instance while looping an tree of directories.
	 *
	 * @param File $file File object reference
	 * @param int $level Current level of tree parse
	 * @return int State of what to do next can be CONTINUE, ABORT or ABORTFOLDER.
	 */
	function handle($file, $level) {
		$toPath = $this->_destFile->getAbsolutePath();
		$toPath .= substr($file->getAbsolutePath(), strlen($this->_fromFile->getAbsolutePath()));
		$toFile = $this->_manager->getFile($toPath);

		// Do action
		if ($file->isDirectory())
			$toFile->mkdir();
		else
			$file->copyTo($toFile);

		return $this->CONTINUE;
	}
}

class Moxiecode_ZipFileStream extends Moxiecode_FileStream {
	var $_file;
	var $_mode;
	var $_pos;
	var $_buff;

	function Moxiecode_ZipFileStream(&$file, $mode) {
		$this->_file =& $file;
		$this->_mode = $mode;
		$this->_buff = "";
		$this->_pos = 0;
	}

	function skip($bytes) {
		$data = read($bytes);

		return strlen($data);
	}

	function read($len = 1024) {
		// End of stream
		if ($this->_pos > 0)
			return null;

		$this->_pos++;

		// Open zip and extract the requested data
		$zip =& $this->_file->_getZip();
		$zip->open();
		$entry =& $zip->getEntryByPath($this->_file->_innerPath);
		$data = $entry->getData();
		$zip->close();

		return $data;
	}

	function readToEnd() {
		$data = "";

		while (($chunk = $this->read(1024)) != null)
			$data .= $chunk;

		return $data;
	}

	function write($buff, $len = -1) {
		if ($len == -1)
			$len = strlen($buff);
		else
			$buff = substr($buff, 0, $len);

		$this->_pos += $len;
		$this->_buff .= $buff;
	}

	function close() {
		if ($this->_mode == 'w' || $this->_mode == 'wb' || $this->_mode == 'a' || $this->_mode == 'ab') {
			// Open zip and write the requested data
			$zip =& $this->_file->_getZip();
			$zip->open();
			$entry =& $zip->getEntryByPath($this->_file->_innerPath);

			// Overwrite existing file or create new
			if (!$entry)
				$zip->addData($this->_file->_innerPath, $this->_buff);
			else {
				if ($this->_mode == 'a' || $this->_mode == 'ab')
					$entry->setData($entry->getData() . $this->_buff);
				else
					$entry->setData($this->_buff);
			}

			$this->_buff = null;
			$zip->commit();
			$zip->close();
		}
	}
}

/*
	// Copy from local to other filesystem
	$to->importFile($from->getAbsolutePath());

	// Move from local to other filesystem
	$to->importFile($from->getAbsolutePath());
	$from->delete();

	// Copy from other to local filesystem
	$from->exportFile($to->getAbsolutePath());

	// Move from local to other filesystem
	$from->exportFile($to->getAbsolutePath());
	$from->delete();

	// Stream contents from two filesystems
	$in =& $from->open('rb');
	$out =& $to->open('wb');

	while ($buff = $in->read(8192))
		$out->write($buff);

	$out->close();
*/

?>