text:
#region Copyright (c) Lokad 2009-2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Lokad.Diagnostics;

namespace Lokad.Cloud.ServiceFabric.Runtime
{
	///
	/// Round robin scheduler with adaptive modifications: tasks that claim to have
	/// more work ready are given the chance to continue until they reach a fixed
	/// time limit (greedy), and the scheduling is slowed down when all available
	/// services skip execution consecutively.
	///
	public class Scheduler
	{
		readonly Func<IEnumerable<CloudService>> _serviceProvider;
		readonly Func<CloudService, ServiceExecutionFeedback> _schedule;
		readonly object _sync = new object();

		/// Duration to keep pinging the same cloud service if service is active.
		readonly TimeSpan _moreOfTheSame = 60.Seconds();

		/// Resting duration.
		readonly TimeSpan _idleSleep = 10.Seconds();

		CloudService _currentService;
		volatile bool _isRunning;

		// Instrumentation
		readonly ExecutionCounter _countIdleSleep;
		readonly ExecutionCounter _countBusyExecute;

		///
		/// Creates a new instance of the Scheduler class.
		///
		/// <param name="serviceProvider">Provider of available cloud services</param>
		/// <param name="schedule">Action to be invoked when a service is scheduled to run</param>
		public Scheduler(Func<IEnumerable<CloudService>> serviceProvider, Func<CloudService, ServiceExecutionFeedback> schedule)
		{
			_serviceProvider = serviceProvider;
			_schedule = schedule;

			// Instrumentation
			ExecutionCounters.Default.RegisterRange(new[]
				{
					_countIdleSleep = new ExecutionCounter("Runtime.IdleSleep", 0, 0),
					_countBusyExecute = new ExecutionCounter("Runtime.BusyExecute", 0, 0)
				});
		}

		public CloudService CurrentlyScheduledService
		{
			get { return _currentService; }
		}

		public IEnumerable<Action> Schedule()
		{
			var services = _serviceProvider().ToArray();
			var currentServiceIndex = -1;
			var skippedConsecutively = 0;

			_isRunning = true;

			while (_isRunning)
			{
				currentServiceIndex = (currentServiceIndex + 1) % services.Length;
				_currentService = services[currentServiceIndex];

				var result = ServiceExecutionFeedback.DontCare;
				var isRunOnce = false;

				// 'more of the same pattern'
				// as long the service is active, keep triggering the same service
				// for at least 1min (in order to avoid a single service to monopolize CPU)
				var start = DateTimeOffset.UtcNow;

				while (DateTimeOffset.UtcNow.Subtract(start) < _moreOfTheSame && _isRunning && DemandsImmediateStart(result))
				{
					yield return () =>
						{
							var busyExecuteTimestamp = _countBusyExecute.Open();
							result = _schedule(_currentService);
							_countBusyExecute.Close(busyExecuteTimestamp);
						};
					isRunOnce |= WasSuccessfullyExecuted(result);
				}

				skippedConsecutively = isRunOnce ? 0 : skippedConsecutively + 1;
				if (skippedConsecutively >= services.Length && _isRunning)
				{
					// We are not using 'Thread.Sleep' because we want the worker
					// to terminate fast if 'Stop' is requested.

					var idleSleepTimestamp = _countIdleSleep.Open();
					lock (_sync)
					{
						Monitor.Wait(_sync, _idleSleep);
					}
					_countIdleSleep.Close(idleSleepTimestamp);

					skippedConsecutively = 0;
				}
			}

			_currentService = null;
		}

		/// Waits until the current service completes, and stop the scheduling.
		/// <remarks>This method CANNOT be used in case the environment is stopping,
		/// because the termination is going to be way too slow.</remarks>
		public void AbortWaitingSchedule()
		{
			_isRunning = false;
			lock (_sync)
			{
				Monitor.Pulse(_sync);
			}
		}

		///
		/// The service was successfully executed and it might make sense to execute
		/// it again immediately (greedy).
		///
		bool DemandsImmediateStart(ServiceExecutionFeedback feedback)
		{
			return feedback == ServiceExecutionFeedback.WorkAvailable
				|| feedback == ServiceExecutionFeedback.DontCare;
		}

		///
		/// The service was actually executed (not skipped) and did not fail.
		///
		bool WasSuccessfullyExecuted(ServiceExecutionFeedback feedback)
		{
			return feedback != ServiceExecutionFeedback.Skipped
				&& feedback != ServiceExecutionFeedback.Failed;
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using Humanizer;
using MicroNetCore.Models;
using MicroNetCore.Models.Extensions;

namespace MicroNetCore.Rest.Models
{
    public sealed class ViewModelPropertyGenerator : IViewModelPropertyGenerator
    {
        #region Constants

        private const MethodAttributes VmMethodAttributes =
            MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig | MethodAttributes.Virtual;

        #endregion

        public void Addproperty(TypeBuilder typeBuilder, PropertyInfo property)
        {
            var propertyType = property.PropertyType;

            if (typeof(IEnumerable<IModel>).IsAssignableFrom(propertyType))
            {
                var modelType = propertyType.GetGenericArguments().First();

                if (modelType.IsRelationModel())
                    AddRelationCollectionProperty(typeBuilder, property);
                else if (modelType.IsEntityModel())
                    AddEntityCollectionProperty(typeBuilder, property);
                else
                    AddSimpleProperty(typeBuilder, property);
            }
            else
            {
                if (propertyType.IsEntityModel())
                    AddEntityProperty(typeBuilder, property);
                else
                    AddSimpleProperty(typeBuilder, property);
            }
        }

        private static void AddSimpleProperty(TypeBuilder typeBuilder, PropertyInfo property)
        {
            var fieldBuilder = typeBuilder.DefineField(
                property.Name.Camelize(),
                property.PropertyType,
                FieldAttributes.Private);

            var propertyBuilder = typeBuilder.DefineProperty(
                property.Name,
                property.Attributes,
                property.PropertyType,
                new Type[0]);

            propertyBuilder.SetSetMethod(GetSetMethod(typeBuilder, propertyBuilder, fieldBuilder));
            propertyBuilder.SetGetMethod(GetGetMethod(typeBuilder, propertyBuilder, fieldBuilder));
        }

        // Make property of SimpleGetViewModel<> type instead of Model
        private static void AddEntityProperty(TypeBuilder typeBuilder, PropertyInfo property)
        {
            var fieldBuilder = typeBuilder.DefineField(
                property.Name.Camelize(),
                property.PropertyType,
                FieldAttributes.Private);

            var propertyBuilder = typeBuilder.DefineProperty(
                property.Name,
                property.Attributes,
                property.PropertyType,
                new Type[0]);

            propertyBuilder.SetSetMethod(GetSetMethod(typeBuilder, propertyBuilder, fieldBuilder));
            propertyBuilder.SetGetMethod(GetGetMethod(typeBuilder, propertyBuilder, fieldBuilder));
        }

        // Make property of ICollection<SimpleGetViewModel<>> type instead ICollection<>
        private static void AddEntityCollectionProperty(TypeBuilder typeBuilder, PropertyInfo property)
        {
            var fieldBuilder = typeBuilder.DefineField(
                property.Name.Camelize(),
                property.PropertyType,
                FieldAttributes.Private);

            var propertyBuilder = typeBuilder.DefineProperty(
                property.Name,
                property.Attributes,
                property.PropertyType,
                new Type[0]);

            propertyBuilder.SetSetMethod(GetSetMethod(typeBuilder, propertyBuilder, fieldBuilder));
            propertyBuilder.SetGetMethod(GetGetMethod(typeBuilder, propertyBuilder, fieldBuilder));
        }

        // Make property of ICollection<SimpleGetViewModel<>> type instead ICollection<>
        private static void AddRelationCollectionProperty(TypeBuilder typeBuilder, PropertyInfo property)
        {
            var relationType = property.PropertyType.GetGenericArguments().First();
            var relatedType = relationType.GetRelationType(property.DeclaringType);

            var fieldBuilder = typeBuilder.DefineField(
                property.Name.Camelize(),
                typeof(ICollection<>).MakeGenericType(relatedType),
                FieldAttributes.Private);

            var propertyBuilder = typeBuilder.DefineProperty(
                property.Name,
                property.Attributes,
                typeof(ICollection<>).MakeGenericType(relatedType),
                new Type[0]);

            propertyBuilder.SetSetMethod(GetSetMethod(typeBuilder, propertyBuilder, fieldBuilder));
            propertyBuilder.SetGetMethod(GetGetMethod(typeBuilder, propertyBuilder, fieldBuilder));
        }

        private static MethodBuilder GetSetMethod(TypeBuilder typeBuilder, PropertyInfo property, FieldInfo field)
        {
            var setMethod = typeBuilder.DefineMethod(
                $"set_{property.Name}",
                VmMethodAttributes,
                null,
                new[] { property.PropertyType });

            var ilGenerator = setMethod.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Ldarg_1);
            ilGenerator.Emit(OpCodes.Stfld, field);
            ilGenerator.Emit(OpCodes.Ret);

            return setMethod;
        }

        private static MethodBuilder GetGetMethod(TypeBuilder typeBuilder, PropertyInfo property, FieldInfo field)
        {
            var getMethod = typeBuilder.DefineMethod(
                $"get_{property.Name}",
                VmMethodAttributes,
                property.PropertyType,
                Type.EmptyTypes);

            var ilGenerator = getMethod.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Ldfld, field);
            ilGenerator.Emit(OpCodes.Ret);

            return getMethod;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
div.ScreenfulUser {position: relative;}
div.ScreenfulUser div.clickable { color: #666666; cursor: pointer;}
div.ScreenfulUser div.clickable:hover {color: var(--link); }
div.ScreenfulUser div.clickable span.arrow {color: #666666; font-size: 85%; position: relative; top: -2px; margin-left: 5px; }
div.ScreenfulUser div.clickable:hover span.arrow {color: var(--link); }

div.ScreenfulUser div.menu {border: 1px solid var(--border); background-color: #ffffff; border-radius: 4px; box-shadow: 0px 0px 4px #666666; position: absolute; right: -5px; margin-top: 10px; z-index: 1; white-space: nowrap;}
div.ScreenfulUser div.menu a {display: block; padding: 10px 20px; text-decoration: none; color: #333333; border-top: 1px solid #dddddd;}
div.ScreenfulUser div.menu a:first-child {border-top-left-radius: 4px; border-top-right-radius: 4px; border-top: 0px;}
div.ScreenfulUser div.menu a:last-child {border-bottom-left-radius: 4px; border-bottom-right-radius: 4px;}
div.ScreenfulUser div.menu a:hover {background-color: #f7f9ea; }


text:
from django.conf import settings

import olympia.core.logger

from olympia.constants.search import SEARCH_LANGUAGE_TO_ANALYZER

from .utils import to_language

log = olympia.core.logger.getLogger('z.es')

class BaseSearchIndexer(object):
    """
    Base Indexer class for all search-related things (as opposed to
    stats-related things).

    Intended to be inherited from every document type that we want to put in
    ElasticSearch for search-related purposes. A class inheriting from
    BaseSearchIndexer should implement at least the following classmethods:

    - get_model(cls)
    - get_mapping(cls)
    - extract_document(cls, obj)
    - create_new_index(cls, index_name)
    - reindex_tasks_group(cls, index_name)
    """

    @classmethod
    def get_index_alias(cls):
        return settings.ES_INDEXES.get(cls.get_model().ES_ALIAS_KEY)

    @classmethod
    def get_doctype_name(cls):
        """Return the document type name for this indexer. We default to simply
        use the db table from the corresponding model."""
        return cls.get_model()._meta.db_table

    @classmethod
    def attach_translation_mappings(cls, mapping, field_names):
        """
        For each field in field_names, attach a dict to the ES mapping
        properties making "<field_name>_translations" an object containing
        "string" and "lang" as non-indexed strings.

        Used to store non-indexed, non-analyzed translations in ES that will be
        sent back by the API for each item. It does not take care of the
        indexed content for search, it's there only to store and return
        raw translations.
        """
        doc_name = cls.get_doctype_name()

        for field_name in field_names:
            # _translations is the suffix in TranslationSerializer.
            mapping[doc_name]['properties'][
                '%s_translations' % field_name
            ] = cls.get_translations_definition()

    @classmethod
    def get_translations_definition(cls):
        """
        Return the mapping to use for raw translations (to be returned directly
        by the API, not used for analysis).
        See attach_translation_mappings() for more information.
        """
        return {
            'type': 'object',
            'properties': {
                'lang': {'type': 'text', 'index': False},
                'string': {'type': 'text', 'index': False},
            },
        }

    @classmethod
    def get_raw_field_definition(cls):
        """
        Return the mapping to use for the "raw" version of a field. Meant to be
        used as part of a 'fields': {'raw': ... } definition in the mapping of
        an existing field.

        Used for exact matches and sorting
        """
        # It needs to be a keyword to turnoff all analysis ; that means we
        # don't get the lowercase filter applied by the standard &
        # language-specific analyzers, so we need to do that ourselves through
        # a custom normalizer for exact matches to work in a case-insensitive
        # way.
        return {
            'type': 'keyword',
            'normalizer': 'lowercase_keyword_normalizer',
        }

    @classmethod
    def attach_language_specific_analyzers(cls, mapping, field_names):
        """
        For each field in field_names, attach language-specific mappings that
        will use specific analyzers for these fields in every language that we
        support.

        These mappings are used by the search filtering code if they exist.
        """
        doc_name = cls.get_doctype_name()

        for lang, analyzer in SEARCH_LANGUAGE_TO_ANALYZER.items():
            for field in field_names:
                property_name = '%s_l10n_%s' % (field, lang)
                mapping[doc_name]['properties'][property_name] = {
                    'type': 'text',
                    'analyzer': analyzer,
                }

    @classmethod
    def attach_language_specific_analyzers_with_raw_variant(cls, mapping, field_names):
        """
        Like attach_language_specific_analyzers() but with an extra field to
        storethe "raw" variant of the value, for exact matches.
        """
        doc_name = cls.get_doctype_name()

        for lang, analyzer in SEARCH_LANGUAGE_TO_ANALYZER.items():
            for field in field_names:
                property_name = '%s_l10n_%s' % (field, lang)
                mapping[doc_name]['properties'][property_name] = {
                    'type': 'text',
                    'analyzer': analyzer,
                    'fields': {
                        'raw': cls.get_raw_field_definition(),
                    },
                }

    @classmethod
    def extract_field_api_translations(cls, obj, field, db_field=None):
        """
        Returns a dict containing translations that we need to store for
        the API. Empty translations are skipped entirely.
        """
        if db_field is None:
            db_field = '%s_id' % field

        extend_with_me = {
            '%s_translations'
            % field: [
                {'lang': to_language(lang), 'string': str(string)}
                for lang, string in obj.translations[getattr(obj, db_field)]
                if string
            ]
        }
        return extend_with_me

    @classmethod
    def extract_field_search_translation(cls, obj, field, default_locale):
        """
        Returns the translation for this field in the object's default locale,
        in the form a dict with one entry (the field being the key and the
        translation being the value, or an empty string if none was found).

        That field will be analyzed and indexed by ES *without*
        language-specific analyzers.
        """
        translations = dict(obj.translations[getattr(obj, '%s_id' % field)])
        default_locale = default_locale.lower() if default_locale else None
        value = translations.get(default_locale, getattr(obj, field))

        return {field: str(value) if value else ''}

    @classmethod
    def extract_field_analyzed_translations(cls, obj, field, db_field=None):
        """
        Returns a dict containing translations for each language that we have
        an analyzer for, for the given field.

        When no translation exist for a given language+field combo, the value
        returned is an empty string, to avoid storing the word "None" as the
        field does not understand null values.
        """
        if db_field is None:
            db_field = '%s_id' % field

        translations = dict(obj.translations[getattr(obj, db_field)])

        return {
            '%s_l10n_%s' % (field, lang): translations.get(lang) or ''
            for lang in SEARCH_LANGUAGE_TO_ANALYZER
        }


text:
package net.sourceforge.marathon.javafxagent.components;

import java.util.ArrayList;
import java.util.List;

import org.testng.AssertJUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import javafx.application.Platform;
import javafx.scene.layout.Pane;
import javafx.scene.web.HTMLEditor;
import net.sourceforge.marathon.javafx.tests.HTMLEditorSample;
import net.sourceforge.marathon.javafxagent.IJavaFXElement;
import net.sourceforge.marathon.javafxagent.JavaFXAgent;
import net.sourceforge.marathon.javafxagent.Wait;

public class JavaFXHTMLEditorTest extends JavaFXElementTest {

    private JavaFXAgent driver;
    private IJavaFXElement htmlEditor;

    @BeforeMethod
    public void initializeDriver() {
        driver = new JavaFXAgent();
        htmlEditor = driver.findElementByTagName("html-editor");
    }

    @Test
    public void select() {
        HTMLEditor htmlEditorNode = (HTMLEditor) getPrimaryStage().getScene().getRoot().lookup(".html-editor");
        Platform.runLater(() -> {
            htmlEditor.marathon_select("This html editor test");
        });
        try {
            new Wait("Waiting for html text to be set.") {
                @Override
                public boolean until() {
                    String htmlText = htmlEditorNode.getHtmlText();
                    return htmlText.equals(
                            "This html editor test");
                }
            };
        } catch (Throwable t) {
        }
        AssertJUnit.assertEquals(
                "This html editor test",
                htmlEditor.getText());
        AssertJUnit.assertEquals(
                "This html editor test",
                htmlEditorNode.getHtmlText());
    }

    @Test
    public void getText() {
        List<String> text = new ArrayList<>();
        Platform.runLater(() -> {
            htmlEditor.marathon_select("This html editor test");
            text.add(htmlEditor.getAttribute("text"));
        });
        try {
            new Wait("Waiting for html text to be set.") {
                @Override
                public boolean until() {
                    return htmlEditor.getAttribute("text").equals(
                            "This html editor test");
                }
            };
        } catch (Throwable t) {
        }
        AssertJUnit.assertEquals(
                "This html editor test",
                htmlEditor.getAttribute("text"));
    }

    @Override
    protected Pane getMainPane() {
        return new HTMLEditorSample();
    }

}


text:
package io.skysail.client.testsupport;

import io.skysail.api.links.Link;

import org.restlet.data.Header;
import org.restlet.util.Series;

public class LinkTitlePredicate extends LinkPredicate {

    private String title;

    public LinkTitlePredicate(String title, Series<Header> series) {
        super(series);
        this.title = title;
    }

    @Override
    public boolean test(Link l) {
        return l.getTitle().equals(title);
    }

    @Override
    public String toString() {
        return new StringBuilder("LinkTitlePredicate(title='").append(title).append("', available links: \n")
                .append(super.toString()).toString();
    }

}


text:
/*
 * Based on enforcer-ng/src/db/db_clause.h header file from the OpenDNSSEC
 * project.
 *
 * Copyright (c) 2014 .SE (The Internet Infrastructure Foundation).
 * Copyright (c) 2014 OpenDNSSEC AB (svb)
 * All rights reserved.
 */

/** \file libdbo/clause.h */
/** \defgroup libdbo_clause libdbo_clause
 * Database Clause.
 * These are the functions and container for handling a database clause.
 */
/** \defgroup libdbo_clause_list libdbo_clause_list
 * Database Clause List.
 * These are the functions and container for handling database clauses.
 */

#ifndef libdbo_clause_h
#define libdbo_clause_h

#ifdef __cplusplus
extern "C" {
#endif

/** \addtogroup libdbo_clause */
/** \{ */

/**
 * The clause operation to make on the value.
 */
typedef enum {
    /**
     * Empty, not set or unknown.
     */
    LIBDBO_CLAUSE_UNKNOWN,
    /**
     * ==
     */
    LIBDBO_CLAUSE_EQUAL,
    /**
     * !=
     */
    LIBDBO_CLAUSE_NOT_EQUAL,
    /**
     * <
     */
    LIBDBO_CLAUSE_LESS_THEN,
    /**
     * <=
     */
    LIBDBO_CLAUSE_LESS_OR_EQUAL,
    /**
     * >=
     */
    LIBDBO_CLAUSE_GREATER_OR_EQUAL,
    /**
     * >
     */
    LIBDBO_CLAUSE_GREATER_THEN,
    /**
     * Is null.
     */
    LIBDBO_CLAUSE_IS_NULL,
    /**
     * Is not null.
     */
    LIBDBO_CLAUSE_IS_NOT_NULL,
    /**
     * This adds a nested clause as in wrapping the content with ( ).
     */
    LIBDBO_CLAUSE_NESTED
} libdbo_clause_type_t;

/**
 * Short for LIBDBO_CLAUSE_EQUAL.
 */
#define LIBDBO_CLAUSE_EQ LIBDBO_CLAUSE_EQUAL
/**
 * Short for LIBDBO_CLAUSE_NOT_EQUAL.
 */
#define LIBDBO_CLAUSE_NE LIBDBO_CLAUSE_NOT_EQUAL
/**
 * Short for LIBDBO_CLAUSE_LESS_THEN.
 */
#define LIBDBO_CLAUSE_LT LIBDBO_CLAUSE_LESS_THEN
/**
 * Short for LIBDBO_CLAUSE_LESS_OR_EQUAL.
 */
#define LIBDBO_CLAUSE_LE LIBDBO_CLAUSE_LESS_OR_EQUAL
/**
 * Short for LIBDBO_CLAUSE_GREATER_OR_EQUAL.
 */
#define LIBDBO_CLAUSE_GE LIBDBO_CLAUSE_GREATER_OR_EQUAL
/**
 * Short for LIBDBO_CLAUSE_GREATER_THEN.
 */
#define LIBDBO_CLAUSE_GT LIBDBO_CLAUSE_GREATER_THEN

/**
 * The operator to do between the previous clause and this one.
 */
typedef enum {
    /**
     * Empty, not set or unknown.
     */
    LIBDBO_CLAUSE_OPERATOR_UNKNOWN,
    /**
     * ||
     */
    LIBDBO_CLAUSE_OPERATOR_AND,
    /**
     * &&
     */
    LIBDBO_CLAUSE_OPERATOR_OR
} libdbo_clause_operator_t;

/**
 * Short for LIBDBO_CLAUSE_OPERATOR_AND.
 */
#define LIBDBO_CLAUSE_OP_AND LIBDBO_CLAUSE_OPERATOR_AND
/**
 * Short for LIBDBO_CLAUSE_OPERATOR_OR.
 */
#define LIBDBO_CLAUSE_OP_OR  LIBDBO_CLAUSE_OPERATOR_OR

#ifndef DOXYGEN_SHOULD_SKIP_THIS
struct libdbo_clause;
struct libdbo_clause_list;
#endif

/**
 * A database clause, describes the comparison of a database object field and a
 * value.
 */
typedef struct libdbo_clause libdbo_clause_t;
/** \} */

/** \addtogroup libdbo_clause_list */
/** \{ */
/**
 * A list of database clauses.
 */
typedef struct libdbo_clause_list libdbo_clause_list_t;
/** \} */

#ifdef __cplusplus
}
#endif

#include <libdbo/value.h>

#ifdef __cplusplus
extern "C" {
#endif

#ifndef DOXYGEN_SHOULD_SKIP_THIS
struct libdbo_clause {
    libdbo_clause_t* next;
    char* table;
    char* field;
    libdbo_clause_type_t type;
    libdbo_value_t value;
    libdbo_clause_operator_t clause_operator;
    libdbo_clause_list_t* clause_list;
};
#endif

/** \addtogroup libdbo_clause */
/** \{ */

/**
 * Create a new database clause.
 * \return a libdbo_clause_t pointer or NULL on error.
 */
libdbo_clause_t* libdbo_clause_new(void);

/**
 * Delete a database clause.
 * \param[in] clause a libdbo_clause_t pointer.
 */
void libdbo_clause_free(libdbo_clause_t* clause);

/**
 * Get the table name of a database clause.
 * \param[in] clause a libdbo_clause_t pointer.
 * \return a character pointer or NULL on error or if no table name has been set.
 */
const char* libdbo_clause_table(const libdbo_clause_t* clause);

/**
 * Get the field name of a database clause.
 * \param[in] clause a libdbo_clause_t pointer.
 * \return a character pointer or NULL on error or if no field name has been set.
 */
const char* libdbo_clause_field(const libdbo_clause_t* clause);

/**
 * Get the database clause type of a database clause.
 * \param[in] clause a libdbo_clause_t pointer.
 * \return a libdbo_clause_type_t.
 */
libdbo_clause_type_t libdbo_clause_type(const libdbo_clause_t* clause);

/**
 * Get the database value of a database value.
 * \param[in] clause a libdbo_clause_t pointer.
 * \return a libdbo_value_t pointer or NULL on error.
 */
const libdbo_value_t* libdbo_clause_value(const libdbo_clause_t* clause);

/**
 * Get the database clause operator of a database clause.
 * \param[in] clause a libdbo_clause_t pointer.
 * \return a libdbo_clause_operator_t.
 */
libdbo_clause_operator_t libdbo_clause_operator(const libdbo_clause_t* clause);

/**
 * Get the database clause list of a database clause, this is used for nested
 * database clauses.
 * \param[in] clause a libdbo_clause_t pointer.
 * \return a libdbo_clause_list_t pointer or NULL on error or if no database clause
 * list has been set.
 */
const libdbo_clause_list_t* libdbo_clause_list(const libdbo_clause_t* clause);

/**
 * Set the table name of a database clause.
 * \param[in] clause a libdbo_clause_t pointer.
 * \param[in] table a character pointer.
 * \return LIBDBO_ERROR_* on failure, otherwise LIBDBO_OK.
 */
int libdbo_clause_set_table(libdbo_clause_t* clause, const char* table);

/**
 * Set the field name of a database clause.
 * \param[in] clause a libdbo_clause_t pointer.
 * \param[in] field a character pointer.
 * \return LIBDBO_ERROR_* on failure, otherwise LIBDBO_OK.
 */
int libdbo_clause_set_field(libdbo_clause_t* clause, const char* field);

/**
 * Set the database clause type of a database clause.
 * \param[in] clause a libdbo_clause_t pointer.
 * \param[in] type a libdbo_clause_type_t.
 * \return LIBDBO_ERROR_* on failure, otherwise LIBDBO_OK.
 */
int libdbo_clause_set_type(libdbo_clause_t* clause, libdbo_clause_type_t type);

/**
 * Set the database clause operator of a database clause.
 * \param[in] clause a libdbo_clause_t pointer.
 * \param[in] clause_operator a libdbo_clause_operator_t.
 * \return LIBDBO_ERROR_* on failure, otherwise LIBDBO_OK.
 */
int libdbo_clause_set_operator(libdbo_clause_t* clause, libdbo_clause_operator_t clause_operator);

/**
 * Set the database clause list of a database clause, this is used for nested
 * database clauses. The ownership of the database clause list it taken.
 * \param[in] clause a libdbo_clause_t pointer.
 * \param[in] clause_list a libdbo_clause_list_t pointer.
 * \return LIBDBO_ERROR_* on failure, otherwise LIBDBO_OK.
 */
int libdbo_clause_set_list(libdbo_clause_t* clause, libdbo_clause_list_t* clause_list);

/**
 * Check if the database clause is not empty.
 * \param[in] clause a libdbo_clause_t pointer.
 * \return LIBDBO_ERROR_* if empty, otherwise LIBDBO_OK.
 */
int libdbo_clause_not_empty(const libdbo_clause_t* clause);

/**
 * Return the next database clause connected in a database clause list.
 * \param[in] clause a libdbo_clause_t pointer.
 * \return a libdbo_clause_t pointer or NULL on error or if there are no more
 * database clauses in the list.
 */
const libdbo_clause_t* libdbo_clause_next(const libdbo_clause_t* clause);

/**
 * Get the writable database value of a database clause.
 * \param[in] clause a libdbo_clause_t pointer.
 * \return a libdbo_value_t pointer or NULL on error.
 */
libdbo_value_t* libdbo_clause_get_value(libdbo_clause_t* clause);

/** \} */

#ifndef DOXYGEN_SHOULD_SKIP_THIS
struct libdbo_clause_list {
    libdbo_clause_t* begin;
    libdbo_clause_t* end;
};
#endif

/** \addtogroup libdbo_clause_list */
/** \{ */

/**
 * Create a new database clause list.
 * \return a libdbo_clause_list_t pointer or NULL on error.
 */
libdbo_clause_list_t* libdbo_clause_list_new(void);

/**
 * Delete a database clause list and all database clauses in the list.
 * \param[in] clause_list a libdbo_clause_list_t pointer.
 */
void libdbo_clause_list_free(libdbo_clause_list_t* clause_list);

/**
 * Add a database clause to a database clause list, this takes over the
 * ownership of the database clause.
 * \param[in] clause_list a libdbo_clause_list_t pointer.
 * \param[in] clause a libdbo_clause_t pointer.
 * \return LIBDBO_ERROR_* on failure, otherwise LIBDBO_OK.
 */
int libdbo_clause_list_add(libdbo_clause_list_t* clause_list, libdbo_clause_t* clause);

/**
 * Return the first database clause of a database clause list.
 * \param[in] clause_list a libdbo_clause_list_t pointer.
 * \return a libdbo_clause_t pointer or NULL on error or if the list is empty.
 */
const libdbo_clause_t* libdbo_clause_list_begin(const libdbo_clause_list_t* clause_list);

/** \} */

#ifdef __cplusplus
}
#endif

#ifndef DOXYGEN_SHOULD_SKIP_THIS
#ifdef LIBDBO_SHORT_NAMES
#define DB_CLAUSE_UNKNOWN LIBDBO_CLAUSE_UNKNOWN
#define DB_CLAUSE_EQUAL LIBDBO_CLAUSE_EQUAL
#define DB_CLAUSE_NOT_EQUAL LIBDBO_CLAUSE_NOT_EQUAL
#define DB_CLAUSE_LESS_THEN LIBDBO_CLAUSE_LESS_THEN
#define DB_CLAUSE_LESS_OR_EQUAL LIBDBO_CLAUSE_LESS_OR_EQUAL
#define DB_CLAUSE_GREATER_OR_EQUAL LIBDBO_CLAUSE_GREATER_OR_EQUAL
#define DB_CLAUSE_GREATER_THEN LIBDBO_CLAUSE_GREATER_THEN
#define DB_CLAUSE_IS_NULL LIBDBO_CLAUSE_IS_NULL
#define DB_CLAUSE_IS_NOT_NULL LIBDBO_CLAUSE_IS_NOT_NULL
#define DB_CLAUSE_NESTED LIBDBO_CLAUSE_NESTED
#define DB_CLAUSE_OPERATOR_UNKNOWN LIBDBO_CLAUSE_OPERATOR_UNKNOWN
#define DB_CLAUSE_OPERATOR_AND LIBDBO_CLAUSE_OPERATOR_AND
#define DB_CLAUSE_OPERATOR_OR LIBDBO_CLAUSE_OPERATOR_OR
#define db_clause_t libdbo_clause_t
#define db_clause_list_t libdbo_clause_list_t
#define db_clause_new(...) libdbo_clause_new(__VA_ARGS__)
#define db_clause_free(...) libdbo_clause_free(__VA_ARGS__)
#define db_clause_table(...) libdbo_clause_table(__VA_ARGS__)
#define db_clause_field(...) libdbo_clause_field(__VA_ARGS__)
#define db_clause_type(...) libdbo_clause_type(__VA_ARGS__)
#define db_clause_value(...) libdbo_clause_value(__VA_ARGS__)
#define db_clause_operator(...) libdbo_clause_operator(__VA_ARGS__)
#define db_clause_list(...) libdbo_clause_list(__VA_ARGS__)
#define db_clause_set_table(...) libdbo_clause_set_table(__VA_ARGS__)
#define db_clause_set_field(...) libdbo_clause_set_field(__VA_ARGS__)
#define db_clause_set_type(...) libdbo_clause_set_type(__VA_ARGS__)
#define db_clause_set_operator(...) libdbo_clause_set_operator(__VA_ARGS__)
#define db_clause_set_list(...) libdbo_clause_set_list(__VA_ARGS__)
#define db_clause_not_empty(...) libdbo_clause_not_empty(__VA_ARGS__)
#define db_clause_next(...) libdbo_clause_next(__VA_ARGS__)
#define db_clause_get_value(...) libdbo_clause_get_value(__VA_ARGS__)
#define db_clause_list_new(...) libdbo_clause_list_new(__VA_ARGS__)
#define db_clause_list_free(...) libdbo_clause_list_free(__VA_ARGS__)
#define db_clause_list_add(...) libdbo_clause_list_add(__VA_ARGS__)
#define db_clause_list_begin(...) libdbo_clause_list_begin(__VA_ARGS__)
#endif
#endif

#endif


text:
class Java::ComGoogleGdataDataCalendar::CalendarEventEntry
  alias_method :extended_properties, :extended_property
end


text:
import os
import shutil
from pprint import pprint

import pytest
import browsers
from webdriver_manager.core.constants import DEFAULT_PROJECT_ROOT_CACHE_PATH, DEFAULT_USER_HOME_CACHE_PATH
from webdriver_manager.core.logger import log

@pytest.fixture(scope="session", autouse=True)
def list_browsers():
    pprint(list(browsers.browsers()))

@pytest.fixture()
def delete_drivers_dir():
    try:
        if os.path.exists(DEFAULT_USER_HOME_CACHE_PATH):
            log(f"Delete {DEFAULT_USER_HOME_CACHE_PATH} folder")
            shutil.rmtree(DEFAULT_USER_HOME_CACHE_PATH)
        if os.path.exists(DEFAULT_PROJECT_ROOT_CACHE_PATH):
            log(f"Delete {DEFAULT_PROJECT_ROOT_CACHE_PATH} folder")
            shutil.rmtree(DEFAULT_PROJECT_ROOT_CACHE_PATH)
    except PermissionError as e:
        print(f"Can not delete folder {e}")

@pytest.fixture(scope='function')
def ssl_verify_enable():
    yield
    os.environ['WDM_SSL_VERIFY'] = ''


text:
// IsTransient property added in .NET 5
// Some providers implement it for other runtimes (e.g. MySqlConnector), but we don't handle them here (could be added on request)
#if NET6_0_OR_GREATER
using System;
using System.Collections.Generic;

namespace LinqToDB.Data.RetryPolicy
{
	using Common;
	using Data.RetryPolicy;

	/// <summary>
	/// Retry policy handles exceptions with <c>DbException.IsTransient == true</c> (requires provider support and .NET 6 or greater).
	/// </summary>
	public sealed class TransientRetryPolicy : RetryPolicyBase
	{
		/// <summary>
		/// Creates a new instance of <see cref="TransientRetryPolicy" />.
		/// </summary>
		public TransientRetryPolicy()
			: this(Configuration.RetryPolicy.DefaultMaxRetryCount)
		{ }

		/// <summary>
		/// Creates a new instance of <see cref="TransientRetryPolicy" />.
		/// </summary>
		/// <param name="maxRetryCount"> The maximum number of retry attempts. </param>
		public TransientRetryPolicy(int maxRetryCount)
			: this(maxRetryCount, Configuration.RetryPolicy.DefaultMaxDelay)
		{ }

		/// <summary>
		/// Creates a new instance of <see cref="TransientRetryPolicy" />.
		/// </summary>
		/// <param name="maxRetryCount">The maximum number of retry attempts.</param>
		/// <param name="maxRetryDelay">The maximum delay in milliseconds between retries.</param>
		public TransientRetryPolicy(
			int      maxRetryCount,
			TimeSpan maxRetryDelay)
			: base(maxRetryCount, maxRetryDelay)
		{
		}

		protected override bool ShouldRetryOn(Exception exception) => DbExceptionTransientExceptionDetector.ShouldRetryOn(exception);
	}
}
#endif


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>play.cache Class Hierarchy (playframework)</title>
<meta name="date" content="2013-04-02">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package play.cache

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

play.cache.Cache

play.mvc.Results

play.mvc.Action<T>

play.cache.CachedAction

Annotation Type Hierarchy

play.cache.Cached (implements java.lang.annotation.Annotation)

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
using namespace std;
using namespace Tizen::ArtikCloud;

GithubOrganization::GithubOrganization()
{
	//__init();
}

GithubOrganization::~GithubOrganization()
{
	//__cleanup();
}

void
GithubOrganization::__init()
{
	//_class = std::string();
	//_links = new GithubOrganizationlinks();
	//jenkinsOrganizationPipeline = bool(false);
	//name = std::string();
}

void
GithubOrganization::__cleanup()
{
	//if(_class != NULL) {
	//
	//delete _class;
	//_class = NULL;
	//}
	//if(_links != NULL) {
	//
	//delete _links;
	//_links = NULL;
	//}
	//if(jenkinsOrganizationPipeline != NULL) {
	//
	//delete jenkinsOrganizationPipeline;
	//jenkinsOrganizationPipeline = NULL;
	//}
	//if(name != NULL) {
	//
	//delete name;
	//name = NULL;
	//}
	//
}

void
GithubOrganization::fromJson(char* jsonStr)
{
	JsonObject *pJsonObject = json_node_get_object(json_from_string(jsonStr,NULL));
	JsonNode *node;
	const gchar *_classKey = "_class";
	node = json_object_get_member(pJsonObject, _classKey);
	if (node !=NULL) {

		if (isprimitive("std::string")) {
			jsonToValue(&_class, node, "std::string", "");
		} else {

		}
	}
	const gchar *_linksKey = "_links";
	node = json_object_get_member(pJsonObject, _linksKey);
	if (node !=NULL) {

		if (isprimitive("GithubOrganizationlinks")) {
			jsonToValue(&_links, node, "GithubOrganizationlinks", "GithubOrganizationlinks");
		} else {

			GithubOrganizationlinks* obj = static_cast<GithubOrganizationlinks*> (&_links);
			obj->fromJson(json_to_string(node, false));

		}
	}
	const gchar *jenkinsOrganizationPipelineKey = "jenkinsOrganizationPipeline";
	node = json_object_get_member(pJsonObject, jenkinsOrganizationPipelineKey);
	if (node !=NULL) {

		if (isprimitive("bool")) {
			jsonToValue(&jenkinsOrganizationPipeline, node, "bool", "");
		} else {

		}
	}
	const gchar *nameKey = "name";
	node = json_object_get_member(pJsonObject, nameKey);
	if (node !=NULL) {

		if (isprimitive("std::string")) {
			jsonToValue(&name, node, "std::string", "");
		} else {

		}
	}
}

GithubOrganization::GithubOrganization(char* json)
{
	this->fromJson(json);
}

char*
GithubOrganization::toJson()
{
	JsonObject *pJsonObject = json_object_new();
	JsonNode *node;
	if (isprimitive("std::string")) {
		std::string obj = getClass();
		node = converttoJson(&obj, "std::string", "");
	}
	else {

	}
	const gchar *_classKey = "_class";
	json_object_set_member(pJsonObject, _classKey, node);
	if (isprimitive("GithubOrganizationlinks")) {
		GithubOrganizationlinks obj = getLinks();
		node = converttoJson(&obj, "GithubOrganizationlinks", "");
	}
	else {

		GithubOrganizationlinks obj = static_cast<GithubOrganizationlinks> (getLinks());
		GError *mygerror;
		mygerror = NULL;
		node = json_from_string(obj.toJson(), &mygerror);

	}
	const gchar *_linksKey = "_links";
	json_object_set_member(pJsonObject, _linksKey, node);
	if (isprimitive("bool")) {
		bool obj = getJenkinsOrganizationPipeline();
		node = converttoJson(&obj, "bool", "");
	}
	else {

	}
	const gchar *jenkinsOrganizationPipelineKey = "jenkinsOrganizationPipeline";
	json_object_set_member(pJsonObject, jenkinsOrganizationPipelineKey, node);
	if (isprimitive("std::string")) {
		std::string obj = getName();
		node = converttoJson(&obj, "std::string", "");
	}
	else {

	}
	const gchar *nameKey = "name";
	json_object_set_member(pJsonObject, nameKey, node);
	node = json_node_alloc();
	json_node_init(node, JSON_NODE_OBJECT);
	json_node_take_object(node, pJsonObject);
	char * ret = json_to_string(node, false);
	json_node_free(node);
	return ret;
}

std::string
GithubOrganization::getClass()
{
	return _class;
}

void
GithubOrganization::setClass(std::string  _class)
{
	this->_class = _class;
}

GithubOrganizationlinks
GithubOrganization::getLinks()
{
	return _links;
}

void
GithubOrganization::setLinks(GithubOrganizationlinks  _links)
{
	this->_links = _links;
}

bool
GithubOrganization::getJenkinsOrganizationPipeline()
{
	return jenkinsOrganizationPipeline;
}

void
GithubOrganization::setJenkinsOrganizationPipeline(bool  jenkinsOrganizationPipeline)
{
	this->jenkinsOrganizationPipeline = jenkinsOrganizationPipeline;
}

std::string
GithubOrganization::getName()
{
	return name;
}

void
GithubOrganization::setName(std::string  name)
{
	this->name = name;
}


text:
package org.apache.ignite.internal.processors.cache;

import java.nio.ByteBuffer;
import java.util.UUID;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.GridDirectTransient;
import org.apache.ignite.internal.util.typedef.internal.CU;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;

/**
 *
 */
public class GridChangeGlobalStateMessageResponse extends GridCacheMessage {
    /** */
    private static final long serialVersionUID = 0L;

    /** Request id. */
    private UUID requestId;

    /** Activation error. */
    @GridDirectTransient
    private Throwable err;

    /** Serialized activation error. */
    private byte[] errBytes;

    /**
     * Default constructor.
     */
    public GridChangeGlobalStateMessageResponse() {
         /* No-op. */
    }

    /**
     *
     */
    public GridChangeGlobalStateMessageResponse(UUID requestId, Throwable err) {
        this.requestId = requestId;
        this.err = err;
    }

    /** {@inheritDoc} */
    @Override public boolean cacheGroupMessage() {
        return false;
    }

    /** {@inheritDoc} */
    @Override public int handlerId() {
        return 0;
    }

    /**
     *
     */
    public UUID getRequestId() {
        return requestId;
    }

    /**
     *
     */
    public Throwable getError() {
        return err;
    }

    /** {@inheritDoc} */
    @Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
        super.prepareMarshal(ctx);

        if (err != null && errBytes == null)
            errBytes = CU.marshal(ctx, false, err);

    }

    /** {@inheritDoc} */
    @Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
        super.finishUnmarshal(ctx, ldr);

        if (errBytes != null && err == null)
            err = ctx.marshaller().unmarshal(errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));

    }

    /** {@inheritDoc} */
    @Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
        writer.setBuffer(buf);

        if (!super.writeTo(buf, writer))
            return false;

        if (!writer.isHeaderWritten()) {
            if (!writer.writeHeader(directType(), fieldsCount()))
                return false;

            writer.onHeaderWritten();
        }

        switch (writer.state()) {
            case 3:
                if (!writer.writeByteArray("errBytes", errBytes))
                    return false;

                writer.incrementState();

            case 4:
                if (!writer.writeUuid("requestId", requestId))
                    return false;

                writer.incrementState();

        }

        return true;
    }

    /** {@inheritDoc} */
    @Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
        reader.setBuffer(buf);

        if (!reader.beforeMessageRead())
            return false;

        if (!super.readFrom(buf, reader))
            return false;

        switch (reader.state()) {
            case 3:
                errBytes = reader.readByteArray("errBytes");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

            case 4:
                requestId = reader.readUuid("requestId");

                if (!reader.isLastRead())
                    return false;

                reader.incrementState();

        }

        return reader.afterMessageRead(GridChangeGlobalStateMessageResponse.class);
    }

    /** {@inheritDoc} */
    @Override public short directType() {
        return -45;
    }

    /** {@inheritDoc} */
    @Override public byte fieldsCount() {
        return 5;
    }

    /** {@inheritDoc} */
    @Override public boolean addDeploymentInfo() {
        return false;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(GridChangeGlobalStateMessageResponse.class, this, super.toString());
    }
}


text:
package com.neustar.ultraservice.schema.v01;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for RedirectType.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="RedirectType">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="Framed"/>
 *     <enumeration value="HTTP_301_REDIRECT"/>
 *     <enumeration value="HTTP_302_REDIRECT"/>
 *     <enumeration value="HTTP_303_REDIRECT"/>
 *     <enumeration value="HTTP_307_REDIRECT"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "RedirectType")
@XmlEnum
public enum RedirectType {

    @XmlEnumValue("Framed")
    FRAMED("Framed"),
    HTTP_301_REDIRECT("HTTP_301_REDIRECT"),
    HTTP_302_REDIRECT("HTTP_302_REDIRECT"),
    HTTP_303_REDIRECT("HTTP_303_REDIRECT"),
    HTTP_307_REDIRECT("HTTP_307_REDIRECT");
    private final String value;

    RedirectType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static RedirectType fromValue(String v) {
        for (RedirectType c: RedirectType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

}


text:
FORMAT: 1A

# Grouping Resources API
This API example demonstrates how to group resources and form **groups of
resources**. You can create as many or as few groups as you like. If you do not
create any group all your resources will be part of an "unnamed" group.

## API Blueprint
+ [Previous: Named Resource and Actions](03.%20Named%20Resource%20and%20Actions.md)
+ [This: Raw API Blueprint](https://raw.github.com/apiaryio/api-blueprint/master/examples/04.%20Grouping%20Resources.md)
+ [Next: Responses](05.%20Responses.md)

# Group Messages
Group of all messages-related resources.

This is the first group of resources in this document. It is **recognized** by
the **keyword `group`** and its name is `Messages`.

Any following resource definition is considered to be a part of this group
until another group is defined. It is **customary** to increase header level of
resources (and actions) nested under a resource.

## My Message [/message]

### Retrieve a Message [GET]

+ Response 200 (text/plain)

        Hello World!

### Update a Message [PUT]

+ Request (text/plain)

        All your base are belong to us.

+ Response 204

# Group Users
Group of all user-related resources.

This is the second group in this blueprint. For now, no resources were defined
here and as such we will omit it from the next installment of this course.


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /var/www/html/SymJobeet/src/KK/JobeetBundle/DependencyInjection/Configuration.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/var/www/html/SymJobeet/src/KK/JobeetBundle /

DependencyInjection /

Configuration.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

100.00%

1 / 1

100.00%

1 / 1

      CRAP

100.00%

3 / 3

      Configuration

100.00%

1 / 1

100.00%

1 / 1

      1

100.00%

3 / 3

       getConfigTreeBuilder()

100.00%

1 / 1

      1

100.00%

3 / 3

1
	<?php

2

3
	namespace KK\JobeetBundle\DependencyInjection;

4

5
	use Symfony\Component\Config\Definition\Builder\TreeBuilder;

6
	use Symfony\Component\Config\Definition\ConfigurationInterface;

7

8
	/**

9
	 * This is the class that validates and merges configuration from your app/config files

10
	 *

11
	 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}

12
	 */

13
	class Configuration implements ConfigurationInterface

14
	{

15
	    /**

16
	     * {@inheritDoc}

17
	     */

18
	    public function getConfigTreeBuilder()

19
	    {

     <tr class="success popin" data-title="4 tests cover line 20" data-content="<ul><li class="danger">KK\JobeetBundle\Test\Repository\CategoryRepositoryTest::testGetWithJobs</li><li class="danger">KK\JobeetBundle\Tests\Repository\JobRepositoryTest::testCountActiveJobs</li><li class="danger">KK\JobeetBundle\Tests\Repository\JobRepositoryTest::testGetActiveJobs</li><li class="danger">KK\JobeetBundle\Tests\Repository\JobRepositoryTest::testGetActiveJob</li></ul>" data-placement="bottom" data-html="true">
20
	        $treeBuilder = new TreeBuilder();

     <tr class="success popin" data-title="4 tests cover line 21" data-content="<ul><li class="danger">KK\JobeetBundle\Test\Repository\CategoryRepositoryTest::testGetWithJobs</li><li class="danger">KK\JobeetBundle\Tests\Repository\JobRepositoryTest::testCountActiveJobs</li><li class="danger">KK\JobeetBundle\Tests\Repository\JobRepositoryTest::testGetActiveJobs</li><li class="danger">KK\JobeetBundle\Tests\Repository\JobRepositoryTest::testGetActiveJob</li></ul>" data-placement="bottom" data-html="true">
21
	        $rootNode = $treeBuilder->root('kk_jobeet');

22

23
	        // Here you should define the parameters that are allowed to

24
	        // configure your bundle. See the documentation linked above for

25
	        // more information on that topic.

26

     <tr class="success popin" data-title="4 tests cover line 27" data-content="<ul><li class="danger">KK\JobeetBundle\Test\Repository\CategoryRepositoryTest::testGetWithJobs</li><li class="danger">KK\JobeetBundle\Tests\Repository\JobRepositoryTest::testCountActiveJobs</li><li class="danger">KK\JobeetBundle\Tests\Repository\JobRepositoryTest::testGetActiveJobs</li><li class="danger">KK\JobeetBundle\Tests\Repository\JobRepositoryTest::testGetActiveJob</li></ul>" data-placement="bottom" data-html="true">
27
	        return $treeBuilder;

28
	    }

29
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.16 using PHP 5.5.9-1+sury.org~precise+1 and PHPUnit 3.7.32 at Thu Mar 6 16:04:27 MST 2014.


text:
'''
Defining the design matrix
'''
from __future__ import print_function

import numpy as np
import logging
import sys

def getsimpledesignmat(n):
  '''
  For a two smaple case, get a design matrix
  '''
  x1=np.identity(n)
  x2=np.zeros(n)
  x3=np.ones(n)
  c1=np.column_stack((x1,x2))
  c2=np.column_stack((x1,x3))
  c3=np.vstack((c1,c2))
  return np.matrix(c3)

def getextenddesignmat(nsg,nsample,designmat,includebase=False):
  '''
  Get an extended design matrix from an arbitrily design matrix
  Parameters:
    nsg
        number of sgRNAs
    nsample
        number of samples (excluding baseline samples)
    includebase
        whether to include further nsgrna*nsample rows at the end
  Return value:
    extended design matrix

  the matrix size:
    (nsg* (nsample+1))*(nbeta) if includebase = False
    (nsg* (2*nsample+1))*(nbeta) if includebase = True
  '''
  if designmat.shape[0] !=nsample:
    raise ValueError('The row of design matrix does match the number of samples.')

  sgiden=np.identity(nsg)
  matright=np.matrix([[0]*designmat.shape[1]]*nsg)
  c3_top=np.column_stack((sgiden,matright))
  c3=c3_top.copy()
  for ns in range(nsample):
    # expand the ns-th row of design mat
    matright=np.matrix(designmat[ns].tolist()*nsg)
    px=np.column_stack((sgiden,matright))
    c3=np.vstack((c3,px))
  if includebase:
    for ns in range(nsample):
      c3=np.vstack((c3,c3_top))
  return c3

def analyze_designmat(design_mat):
  '''
  analyze the design matrix
  Return value:
    the index of baseline samples
    the new design matrix
  '''
  init_design_mat=design_mat
  init_design_mat_rowsum=[x[0] for x in np.sum(init_design_mat,axis=1).tolist()]
  for i in range(len(init_design_mat_rowsum)):
    if init_design_mat_rowsum[i]==0:
      print('Error parsing the design matrix: 0 row sums for some samples.')
  init_design_basesample=[t for t in range(init_design_mat.shape[0]) if init_design_mat_rowsum[t]==1]
  init_design_othersample=[t for t in range(init_design_mat.shape[0]) if init_design_mat_rowsum[t]>1]
  new_design_matrix=design_mat[init_design_othersample,1:]
  return (init_design_basesample,new_design_matrix)

def parse_designmat_from_day0(args):
  '''
  Parse the design matrix from a string.
  Parameters
  ----------
  args
    An argparse object where day0_label and count_table will be used

  Return values
  ----------
  ndesm
    The design matrix object
  samples
    Sample id (rows of design matrix)
  beta_label
    Beta label (columns of design matrix)
  '''
  # first, get the labels in the count table
  if args.count_table.upper().endswith('.CSV'):
    splitter=','
  else:
    splitter=None
  with open(args.count_table) as f:
    firstline=f.readline()
  field=firstline.strip().split(splitter)
  samples=field[2:]

  # check day0 label
  args.day0_label=args.day0_label.split(',')
  for dl in args.day0_label:
    if dl not in samples:
      logging.error('Label '+dl+' specified in the --day0-label option does not match count table. Please double check.')
      sys.exit(-1)
  # check day0s
  nsample=len(samples)
  nonday0sample=[x for x in samples if x not in args.day0_label]
  n_nond0=len(nonday0sample)
  if n_nond0 == nsample:
    logging.error('Cannot find day0 sample.')
    sys.exit(-1)
  sample_order=args.day0_label+nonday0sample
  # dessplit=[ [1 ] + [(lambda t:1 if t in nonday0sample else 0)(tlb) for tlb in sample_order]]
  dessplit=[ [1]+ [  (nd==tlb)*1 for nd in nonday0sample ]   for tlb in sample_order ]
  desmat=np.matrix(dessplit)
  return (desmat,sample_order,['baseline']+nonday0sample)

def parse_designmat(designmatstr):
  '''
  Parse the design matrix from a string.
  Parameters
  ----------
  designmatstr
    A string of design matrix, either specifying the matrix elements directly, or a file containing the design matrix. See explanations below.

  Return values
  ----------
  ndesm
    The design matrix object
  samples
    Sample id (rows of design matrix)
  beta_label
    Beta label (columns of design matrix)
  ----------
  Two different values are specified: a file name containing the design matrix, or a string of design matrix.

  If designmatstr is a string, use ";" to separate rows and "," to separate columns.
  For example, if a design matrix is as follows:

  1 0 0
  1 0 0
  1 1 0
  1 0 1

  Then the design matrix string should be:

  1,0,0;1,0,0;1,1,0;1,0,1

  Otherwise if a file is specified, the file should be a tab-delimited file containing the design matrix. Row and column names are required:
  sample b0 b1 b2
  s1     1  0  0
  s2     1  0  0
  s3     1  1  0
  s4     1  0  1
  '''
  #
  (nret,ndesm)=parse_designmat_str(designmatstr)
  if nret==0:
    return (ndesm,None,None)
  else:
    logging.info('Cannot parse design matrix as a string; try to parse it as a file name ...')
    (nret2,ndesm2,rows,columns)=parse_designmat_file(designmatstr)
    if nret2==0:
      return (ndesm2,rows,columns)
    else:
      raise ValueError('parsing the design matrix from file '+designmatstr)
  return (None,None,None)

def parse_designmat_str(designmatstr):
  '''
  Parse the design matrix from a string
  For explanations, see parse_designmat()
  Return value:
    (x, design_mat)
    x:
      0 if success, -1 if not
    designmat:
      design matrix if success, None if not
  '''
  desfield=designmatstr.split(';')
  try:
    dessplit=[ [float(x) for x in fx.split(',')] for fx in desfield]
    dessplitmat=np.matrix(dessplit)
    return (0, dessplitmat)
  except ValueError:
    return (-1, None)

def parse_designmat_file(designmatstr):
  '''
  Parse the design matrix from a file
  For explanations, see parse_designmat()
  Return value:
  ------------
    (x, design_mat,rows,columns)
    x:
      0 if success, -1 if not
    designmat:
      design matrix if success, None if not
    rows:
      labels for rows (i.e., sample labels)
    columns:
      labels for columns (i.e., sample columns)
  '''
  filefield=[x.strip().split() for x in open(designmatstr,'r')]
  try:
    dessplit=[ [float(x) for x in fx[1:]] for fx in filefield[1:]]
    dessplitmat=np.matrix(dessplit)
    collabels=filefield[0][1:]
    rowlabels=[ fx[0] for fx in filefield[1:] if len(fx)>0]
    return (0, dessplitmat,rowlabels,collabels)
  except ValueError:
    return (-1, None,None,None)

class DesignMatCache:
  '''
  Store the design matrix and relevant information of different # sgRNAs, so we don't have to construct it every time
  '''
  cache={}
  @staticmethod
  def save_record(orig_design_mat,n):
    '''
    Save the design mat of sgRNA n to cache
    '''
    # calculate the number of base line samples
    #
    nsample=orig_design_mat.shape[0]-1 # the number of samples excluding the 1st base sample
    (basesampleid,_new_designmat)=analyze_designmat(orig_design_mat)
    design_mat=orig_design_mat[1:,1:] # assuming the 1st column must be the baseline condition, and the 1st row is the base line condition; they are removed.
    extdesign_mat=getextenddesignmat(n,nsample,design_mat,includebase=True)
    extdesignmat_residule=extdesign_mat[0:(nsample+1)*n,n:] # this is the design matrix containing only non-baseline betas and first (nsample+1) samples
    # save
    save_tuple=(basesampleid,design_mat,extdesign_mat,extdesignmat_residule)
    DesignMatCache.cache[n]=save_tuple

  @staticmethod
  def has_record(n):
    '''
    If the cache has the record of design matrix of sgRNA n
    '''
    if n in DesignMatCache.cache:
      return True
    else:
      return False
  @staticmethod
  def get_record(n):
    '''
    Get the record in design matrix
    '''
    return DesignMatCache.cache[n]


text:
var Helper = {

    getScreenSize: function() {
        var height = window.innerHeight;
        var width = window.innerWidth;

        return {
            width: width,
            height: height
        };
    },

    getViewSize: function() {
        if(this.isLandscape()) {
            return {
                width: 1280,
                height: 720
            };
        }
        else {
            return {
                width: 720,
                height: 1280
            };
        }
    },

    isLandscape: function() {
        return (window.orientation == 90)||(window.orientation == -90);
    },

    show: function( id, visible ) {

        var element = document.getElementById( id );
        if ( element == null ) {
            return;
        }

        var className = element.className;
        if ( className == null )
            className = "";

        if ( visible ) {
            className = className.replace( / ?hidden/, "" );
        } else {
            if ( className.indexOf( "hidden") == -1 ) {
                if ( className.length > 0 )
                    className += " ";

                className += "hidden";
            }
        }
        element.className = className;
    },

    sortByPriorty: function (todos) {
        var a = new Array();
        $.each(todos, function() {
            a.push(this);
        });

        for (var i = 0; i < a.length; i++) {
            var swapped;
            do {
                swapped = false;
                for (var i=0; i < a.length-1; i++) {
                    if ( a[i].priority < a[i+1].priority ) {
                        var temp = a[i];
                        a[i] = a[i+1];
                        a[i+1] = temp;
                        swapped = true;
                    }
                }
            } while (swapped);
        }
        return a;
    },

    sortByTime: function (todos) {
        var sortedArray = [];
        var morningItems = [];
        var afternoonItems = [];
        var eveningItems = [];
        $.each(todos, function() {
            if(this.period == TodoItem.PeriodEnum.MORNING)
                morningItems.push(this);
            if(this.period == TodoItem.PeriodEnum.AFTERNOON)
                afternoonItems.push(this);
            if(this.period == TodoItem.PeriodEnum.EVENING)
                eveningItems.push(this);
        });
        sortedArray.push.apply(sortedArray, morningItems);
        sortedArray.push.apply(sortedArray, afternoonItems);
        sortedArray.push.apply(sortedArray, eveningItems);

        return sortedArray;
    },

    printObjectectProperties: function(object) {
        for (var i in object) {
            console.log('object[\''+i+'\'] is ' + object[i]);
        }
    }
};


text:
define([
  'jquery',
  'underscore',
  'backbone',
	'vm'
], function ($, _, Backbone, Vm) {
  var AppRouter = Backbone.Router.extend({
    routes: {
      // Pages
      '/:owner/:name': 'project',

      // Default - catch all
      '*actions': 'defaultAction'
    }
  });

  var initialize = function(options){
		var appView = options.appView;
    var router = new AppRouter(options);
    router.on('route:project', function (owner, name) {
      require(['views/project/page'], function (Project) {
        var projectPage = Vm.create(appView, 'Project', Project);
        projectPage.render(owner, name);
      });
    });
		router.on('route:defaultAction', function (actions) {
			require(['views/dashboard/page'], function (DashboardPage) {
        var dashboardPage = Vm.create(appView, 'DashboardPage', DashboardPage);
        dashboardPage.render();
      });
		});
    Backbone.history.start();
  };
  return {
    initialize: initialize
  };
});


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 org.activiti.app.service.editor;

import org.activiti.app.domain.editor.Model;
import org.activiti.app.service.api.AppDefinitionService;
import org.activiti.app.service.api.DeploymentService;
import org.activiti.app.service.api.ModelService;
import org.activiti.engine.identity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Can't merge this with {@link AppDefinitionService}, as it doesn't have visibility of domain models needed to do the publication.
 *
 * @author jbarrez
 */
@Service
@Transactional
public class AppDefinitionPublishService {

  private static final Logger logger = LoggerFactory.getLogger(AppDefinitionPublishService.class);

  @Autowired
  protected ModelService modelService;

  @Autowired
  protected DeploymentService deploymentService;

  public void publishAppDefinition(String comment, Model appDefinitionModel, User user) {

    // Create new version of the app model
    modelService.createNewModelVersion(appDefinitionModel, comment, user);

    // Deploy the app model to be executable
    deploymentService.updateAppDefinition(appDefinitionModel, user);
  }

}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.role;

/**
 * A {@link Role} with an unlimited {@link Context}.
 *
 * @author jonmv
 */
public class UnboundRole extends Role {

    UnboundRole(RoleDefinition roleDefinition) {
        super(roleDefinition, Context.unlimited());
    }

    @Override
    public String toString() {
        return "role '" + definition() + "'";
    }

}


text:
"""Service calling related helpers."""
import asyncio
import logging
from os import path

import voluptuous as vol

from homeassistant.auth.permissions.const import POLICY_CONTROL
from homeassistant.const import ATTR_ENTITY_ID, ENTITY_MATCH_ALL
import homeassistant.core as ha
from homeassistant.exceptions import TemplateError, Unauthorized, UnknownUser
from homeassistant.helpers import template
from homeassistant.loader import get_component, bind_hass
from homeassistant.util.yaml import load_yaml
import homeassistant.helpers.config_validation as cv
from homeassistant.util.async_ import run_coroutine_threadsafe

CONF_SERVICE = 'service'
CONF_SERVICE_TEMPLATE = 'service_template'
CONF_SERVICE_ENTITY_ID = 'entity_id'
CONF_SERVICE_DATA = 'data'
CONF_SERVICE_DATA_TEMPLATE = 'data_template'

_LOGGER = logging.getLogger(__name__)

SERVICE_DESCRIPTION_CACHE = 'service_description_cache'

@bind_hass
def call_from_config(hass, config, blocking=False, variables=None,
                     validate_config=True):
    """Call a service based on a config hash."""
    run_coroutine_threadsafe(
        async_call_from_config(hass, config, blocking, variables,
                               validate_config), hass.loop).result()

@bind_hass
async def async_call_from_config(hass, config, blocking=False, variables=None,
                                 validate_config=True, context=None):
    """Call a service based on a config hash."""
    if validate_config:
        try:
            config = cv.SERVICE_SCHEMA(config)
        except vol.Invalid as ex:
            _LOGGER.error("Invalid config for calling service: %s", ex)
            return

    if CONF_SERVICE in config:
        domain_service = config[CONF_SERVICE]
    else:
        try:
            config[CONF_SERVICE_TEMPLATE].hass = hass
            domain_service = config[CONF_SERVICE_TEMPLATE].async_render(
                variables)
            domain_service = cv.service(domain_service)
        except TemplateError as ex:
            if blocking:
                raise
            _LOGGER.error('Error rendering service name template: %s', ex)
            return
        except vol.Invalid:
            if blocking:
                raise
            _LOGGER.error('Template rendered invalid service: %s',
                          domain_service)
            return

    domain, service_name = domain_service.split('.', 1)
    service_data = dict(config.get(CONF_SERVICE_DATA, {}))

    if CONF_SERVICE_DATA_TEMPLATE in config:
        try:
            template.attach(hass, config[CONF_SERVICE_DATA_TEMPLATE])
            service_data.update(template.render_complex(
                config[CONF_SERVICE_DATA_TEMPLATE], variables))
        except TemplateError as ex:
            _LOGGER.error('Error rendering data template: %s', ex)
            return

    if CONF_SERVICE_ENTITY_ID in config:
        service_data[ATTR_ENTITY_ID] = config[CONF_SERVICE_ENTITY_ID]

    await hass.services.async_call(
        domain, service_name, service_data, blocking=blocking, context=context)

@bind_hass
def extract_entity_ids(hass, service_call, expand_group=True):
    """Extract a list of entity ids from a service call.

    Will convert group entity ids to the entity ids it represents.

    Async friendly.
    """
    if not (service_call.data and ATTR_ENTITY_ID in service_call.data):
        return []

    group = hass.components.group

    # Entity ID attr can be a list or a string
    service_ent_id = service_call.data[ATTR_ENTITY_ID]

    if expand_group:

        if isinstance(service_ent_id, str):
            return group.expand_entity_ids([service_ent_id])

        return [ent_id for ent_id in
                group.expand_entity_ids(service_ent_id)]

    if isinstance(service_ent_id, str):
        return [service_ent_id]

    return service_ent_id

@bind_hass
async def async_get_all_descriptions(hass):
    """Return descriptions (i.e. user documentation) for all service calls."""
    if SERVICE_DESCRIPTION_CACHE not in hass.data:
        hass.data[SERVICE_DESCRIPTION_CACHE] = {}
    description_cache = hass.data[SERVICE_DESCRIPTION_CACHE]

    format_cache_key = '{}.{}'.format

    def domain_yaml_file(domain):
        """Return the services.yaml location for a domain."""
        if domain == ha.DOMAIN:
            from homeassistant import components
            component_path = path.dirname(components.__file__)
        else:
            component_path = path.dirname(get_component(hass, domain).__file__)
        return path.join(component_path, 'services.yaml')

    def load_services_files(yaml_files):
        """Load and parse services.yaml files."""
        loaded = {}
        for yaml_file in yaml_files:
            try:
                loaded[yaml_file] = load_yaml(yaml_file)
            except FileNotFoundError:
                loaded[yaml_file] = {}

        return loaded

    services = hass.services.async_services()

    # Load missing files
    missing = set()
    for domain in services:
        for service in services[domain]:
            if format_cache_key(domain, service) not in description_cache:
                missing.add(domain_yaml_file(domain))
                break

    if missing:
        loaded = await hass.async_add_job(load_services_files, missing)

    # Build response
    catch_all_yaml_file = domain_yaml_file(ha.DOMAIN)
    descriptions = {}
    for domain in services:
        descriptions[domain] = {}
        yaml_file = domain_yaml_file(domain)

        for service in services[domain]:
            cache_key = format_cache_key(domain, service)
            description = description_cache.get(cache_key)

            # Cache missing descriptions
            if description is None:
                if yaml_file == catch_all_yaml_file:
                    yaml_services = loaded[yaml_file].get(domain, {})
                else:
                    yaml_services = loaded[yaml_file]
                yaml_description = yaml_services.get(service, {})

                description = description_cache[cache_key] = {
                    'description': yaml_description.get('description', ''),
                    'fields': yaml_description.get('fields', {})
                }

            descriptions[domain][service] = description

    return descriptions

@bind_hass
async def entity_service_call(hass, platforms, func, call):
    """Handle an entity service call.

    Calls all platforms simultaneously.
    """
    if call.context.user_id:
        user = await hass.auth.async_get_user(call.context.user_id)
        if user is None:
            raise UnknownUser(context=call.context)
        entity_perms = user.permissions.check_entity
    else:
        entity_perms = None

    # Are we trying to target all entities
    if ATTR_ENTITY_ID in call.data:
        target_all_entities = call.data[ATTR_ENTITY_ID] == ENTITY_MATCH_ALL
    else:
        _LOGGER.warning('Not passing an entity ID to a service to target all '
                        'entities is deprecated. Use instead: entity_id: "*"')
        target_all_entities = True

    if not target_all_entities:
        # A set of entities we're trying to target.
        entity_ids = set(
            extract_entity_ids(hass, call, True))

    # If the service function is a string, we'll pass it the service call data
    if isinstance(func, str):
        data = {key: val for key, val in call.data.items()
                if key != ATTR_ENTITY_ID}
    # If the service function is not a string, we pass the service call
    else:
        data = call

    # Check the permissions

    # A list with for each platform in platforms a list of entities to call
    # the service on.
    platforms_entities = []

    if entity_perms is None:
        for platform in platforms:
            if target_all_entities:
                platforms_entities.append(list(platform.entities.values()))
            else:
                platforms_entities.append([
                    entity for entity in platform.entities.values()
                    if entity.entity_id in entity_ids
                ])

    elif target_all_entities:
        # If we target all entities, we will select all entities the user
        # is allowed to control.
        for platform in platforms:
            platforms_entities.append([
                entity for entity in platform.entities.values()
                if entity_perms(entity.entity_id, POLICY_CONTROL)])

    else:
        for platform in platforms:
            platform_entities = []
            for entity in platform.entities.values():
                if entity.entity_id not in entity_ids:
                    continue

                if not entity_perms(entity.entity_id, POLICY_CONTROL):
                    raise Unauthorized(
                        context=call.context,
                        entity_id=entity.entity_id,
                        permission=POLICY_CONTROL
                    )

                platform_entities.append(entity)

            platforms_entities.append(platform_entities)

    tasks = [
        _handle_service_platform_call(func, data, entities, call.context)
        for platform, entities in zip(platforms, platforms_entities)
    ]

    if tasks:
        await asyncio.wait(tasks)

async def _handle_service_platform_call(func, data, entities, context):
    """Handle a function call."""
    tasks = []

    for entity in entities:
        if not entity.available:
            continue

        entity.async_set_context(context)

        if isinstance(func, str):
            await getattr(entity, func)(**data)
        else:
            await func(entity, data)

        if entity.should_poll:
            tasks.append(entity.async_update_ha_state(True))

    if tasks:
        await asyncio.wait(tasks)


text:
Server::Server(std::string ip, int port){
    // prepares the socket descriptor and the relevant structs
    ip_addr = ip;
    port = port;

    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(server_fd == -1){
        perror("Could not create server socket");
        exit(1);
    }

    //this will avoid the socket already in use if server is restarted and the socket
    // is still lying around in te kernel

    int opt = 1;
    if(setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR,&opt, sizeof(opt)) != 0){
        perror("Could not reuse socket");
        exit(1);
    }
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);
    if(inet_pton(AF_INET, ip_addr.c_str(), &(server_addr.sin_addr)) <= 0){
        perror("Could not translate IP ");
        exit(1);
    } // lets work with IPV4 for now

    if(bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) != 0 ){
        perror("Could not bind to socket");
        exit(1);
    }
}

void Server::start(){
    // binds the socket and then listens for incoming connections from clients
    // this is the beginning of the client server exchange

    if(listen(server_fd, LISTEN_QUEUE) !=0 ){
        perror("Server could not listen for connections");
        close(server_fd);
        exit(1);
    }

}


text:
/**
 * 创建日期:  2017年08月21日 19:07
 * 创建作者:  杨 强  <281455776@qq.com>
 */
package com.yangqiang.api.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.function.Predicate;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * class文件工具 查找指定包下的满足要求的类
 *
 * @author 杨 强
 */
public class ClassFileUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClassFileUtil.class);

    /**
     * 获取指定包下所有满足要求的类
     *
     * @param packageName
     * @param predicate
     * @return
     */
    public static Set<Class> getClasses(String packageName, Predicate<Class> predicate) {
        return getClasses(packageName, true, predicate);
    }

    /**
     * 获取指定包下满足要求的类
     *
     * @param packageName 包名
     * @param recursive 是否递归查找
     * @param predicate 判定条件
     * @return
     */
    public static Set<Class> getClasses(String packageName, boolean recursive, Predicate<Class> predicate) {
        Set<Class> ret = new LinkedHashSet<>();
        String packageDirName = packageName.replace('.', '/');
        try {
            Enumeration<URL> dirs = ClassFileUtil.class.getClassLoader().getResources(packageDirName);
            while (dirs.hasMoreElements()) {
                URL url = dirs.nextElement();
                String protocol = url.getProtocol();
                if ("file".equals(protocol)) {
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    ret.addAll(findSubClassFromFile(packageName, filePath, recursive, predicate));
                } else if ("jar".equals(protocol)) {
                    JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
                    ret.addAll(findSubClassFromJar(jar, packageName, recursive, predicate));
                }
            }
        } catch (Exception e) {
            LOGGER.error("读取Class文件出错", e);
        }

        return ret;
    }

    private static Set<Class> findSubClassFromJar(JarFile jar, String packageName, boolean recursive, Predicate<Class> predicate) {
        Set<Class> ret = new LinkedHashSet<>();
        Enumeration<JarEntry> entries = jar.entries();

        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            String name = entry.getName();
            if (!name.endsWith(".class")) {
                continue;
            }
            if (name.charAt(0) == '/') {
                name = name.substring(1);
            }

            // 去掉后缀后的类完整名
            String className = name.replace('/', '.').substring(0, name.length() - 6);

            String newPackageName = null;
            int idx = className.lastIndexOf('.');
            if (idx != -1) {
                newPackageName = className.substring(0, idx);
            }
            if (newPackageName == null) {
                continue;
            }
            // 不是指定包的类并且不满足子包的类
            if ((!newPackageName.equals(packageName)) && !(recursive && newPackageName.startsWith(packageName))) {
                continue;
            }
            try {
                Class clazz = Class.forName(className, false, ClassFileUtil.class.getClassLoader());
                if (predicate.test(clazz)) {
                    ret.add(clazz);
                }
            } catch (Throwable e) {
                LOGGER.error("读取Jar中的Class文件出错", e);
            }
        }
        return ret;
    }

    private static Set<Class> findSubClassFromFile(String packageName, String packagePath, boolean recursive, Predicate<Class> predicate) {
        Set<Class> ret = new LinkedHashSet<>();
        File dir = new File(packagePath);
        if (!dir.exists() || !dir.isDirectory()) {
            return ret;
        }
        File[] files = dir.listFiles(file -> (file.getName().endsWith(".class")) || (recursive && file.isDirectory()));
        if (files == null) {
            return ret;
        }
        for (File file : files) {
            String fileName = file.getName();
            if (file.isDirectory()) {
                ret.addAll(findSubClassFromFile(packageName + "." + fileName, file.getAbsolutePath(), recursive, predicate));
                continue;
            }
            String className = packageName + '.' + fileName.substring(0, fileName.length() - 6);
            try {
                Class clazz = Class.forName(className, false, ClassFileUtil.class.getClassLoader());
                if (predicate.test(clazz)) {
                    ret.add(clazz);
                }
            } catch (Exception e) {
                LOGGER.error("读取文件夹中的Class文件出错", e);
            }
        }

        return ret;
    }
}


text:
using System.Resources;
using System.Runtime.CompilerServices;

namespace System
{
    internal partial class SR
    {
        // This method is used to decide if we need to append the exception message parameters to the message when calling SR.Format.
        // by default it returns false.
        // Native code generators can replace the value this returns based on user input at the time of native code generation.
        // Marked as NoInlining because if this is used in an AoT compiled app that is not compiled into a single file, the user
        // could compile each module with a different setting for this. We want to make sure there's a consistent behavior
        // that doesn't depend on which native module this method got inlined into.
        [MethodImpl(MethodImplOptions.NoInlining)]
        private static bool UsingResourceKeys() => false;

        internal static string GetResourceString(string resourceKey, string defaultString = null)
        {
            if (UsingResourceKeys())
            {
                return defaultString ?? resourceKey;
            }

            string resourceString = null;
            try
            {
                resourceString = ResourceManager.GetString(resourceKey);
            }
            catch (MissingManifestResourceException) { }

            if (defaultString != null && resourceKey.Equals(resourceString))
            {
                return defaultString;
            }

            return resourceString;
        }

        internal static string Format(string resourceFormat, object p1)
        {
            if (UsingResourceKeys())
            {
                return string.Join(", ", resourceFormat, p1);
            }

            return string.Format(resourceFormat, p1);
        }

        internal static string Format(string resourceFormat, object p1, object p2)
        {
            if (UsingResourceKeys())
            {
                return string.Join(", ", resourceFormat, p1, p2);
            }

            return string.Format(resourceFormat, p1, p2);
        }

        internal static string Format(string resourceFormat, object p1, object p2, object p3)
        {
            if (UsingResourceKeys())
            {
                return string.Join(", ", resourceFormat, p1, p2, p3);
            }

            return string.Format(resourceFormat, p1, p2, p3);
        }

        internal static string Format(string resourceFormat, params object[] args)
        {
            if (args != null)
            {
                if (UsingResourceKeys())
                {
                    return resourceFormat + ", " + string.Join(", ", args);
                }

                return string.Format(resourceFormat, args);
            }

            return resourceFormat;
        }

        internal static string Format(IFormatProvider provider, string resourceFormat, object p1)
        {
            if (UsingResourceKeys())
            {
                return string.Join(", ", resourceFormat, p1);
            }

            return string.Format(provider, resourceFormat, p1);
        }

        internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2)
        {
            if (UsingResourceKeys())
            {
                return string.Join(", ", resourceFormat, p1, p2);
            }

            return string.Format(provider, resourceFormat, p1, p2);
        }

        internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3)
        {
            if (UsingResourceKeys())
            {
                return string.Join(", ", resourceFormat, p1, p2, p3);
            }

            return string.Format(provider, resourceFormat, p1, p2, p3);
        }

        internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
        {
            if (args != null)
            {
                if (UsingResourceKeys())
                {
                    return resourceFormat + ", " + string.Join(", ", args);
                }

                return string.Format(provider, resourceFormat, args);
            }

            return resourceFormat;
        }
    }
}


text:
        <wicket:head>

        </wicket:head>

        <wicket:extend>

            <menu wicket:id="menu" class="navIntraTool">[menu]</menu>

	                    <wicket:message key="reportres_printversion">[reportres_printversion]</wicket:message>

	                    <wicket:message key="reportres_print">[reportres_print]</wicket:message>

                                    <wicket:message key="reportres_summ_description">[reportres_summ_description]</wicket:message>

                                    <wicket:message key="reportres_summ_site">[reportres_summ_site]</wicket:message>

                                    <wicket:message key="reportres_summ_act_basedon">[reportres_summ_act_basedon]</wicket:message>

                                    [reportResourceActionTitle]

                                    [reportActivitySelectionTitle]

                                    <wicket:message key="reportres_summ_timeperiod">[reportres_summ_timeperiod]</wicket:message>

                                    <wicket:message key="reportres_summ_usr_selectiontype">[reportres_summ_usr_selectiontype]</wicket:message>

                                    [reportUserSelectionTitle]

                                    <wicket:message key="reportres_summ_generatedon">[reportres_summ_generatedon]</wicket:message>

	            <form wicket:id="form">

[table]

		                <input type="submit" wicket:id="back" wicket:message="value:report_back" class="active"/>
		                <input type="submit" wicket:id="export" wicket:message="value:bt_export" onclick="showExportButtons();return false;" class="export"/>

		                <input type="submit" wicket:id="exportXls" wicket:message="value:bt_export_excel" class="exportButtons" style="display:none;"/>
		                <input type="submit" wicket:id="exportCsv" wicket:message="value:bt_export_csv" class="exportButtons" style="display:none;"/>
		                <input type="submit" wicket:id="exportPdf" wicket:message="value:bt_export_pdf" class="exportButtons" style="display:none;"/>

	            </form>

        </wicket:extend>


text:
define(["require", "exports", "tslib", "aurelia-dependency-injection", "../designs/material-design"], function (require, exports, tslib_1, aurelia_dependency_injection_1, material_design_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Android = void 0;
    var Android = /** @class */ (function () {
        function Android(design) {
            this.design = design;
            this.type = 'android';
        }
        Android = tslib_1.__decorate([
            aurelia_dependency_injection_1.inject(material_design_1.MaterialDesign)
        ], Android);
        return Android;
    }());
    exports.Android = Android;
});
//# sourceMappingURL=android.js.map


text:
namespace ZooSystem.BLL.Entities.Animals.Mammals
{
    using System;

    public class Goat : Animal
    {

        private const byte averageLifeSpan = 13;

        private const string GoatSpeech = "BEEEEEEE!";

        /// <summary>
        /// Initializes a new instance of the <see cref="Goat"/> class.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="age"></param>
        public Goat(int id, string name, int age)
            :base(id, name, age, averageLifeSpan)
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Goat"/> class.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="age"></param>
        /// <param name="birthDay"></param>
        public Goat(int id, string name, int age, DateTime birthDay)
            :base(id, name, age, averageLifeSpan, birthDay)
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Goat"/> class.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="age"></param>
        /// <param name="stamina"></param>
        /// <param name="birthDay"></param>
        public Goat(int id, string name, int age, int stamina, DateTime birthDay)
            :base(id, name, age, stamina, averageLifeSpan, birthDay)
        {

        }

        public override Species Specie
        {
            get { return Species.Mammal; }
        }

        /// <summary>
        /// Feeds the goat.
        /// </summary>
        /// <param name="food"></param>
        public override void Eat(AnimalFood food)
        {
            if (food.Type != FoodType.Milk)
            {
                Console.WriteLine("Feed the goats only with milk.");
                return;

            }

            Console.WriteLine(
                    "Goat {0} drunk milk and increased its stamina with {1}.",
                    this.Name, food.RegenerateStamina());

            this.IncreaseStamina(food.RegenerateStamina());
        }

        /// <summary>
        /// Introduces goat.
        /// </summary>
        /// <returns></returns>
        public override string Speak()
        {
            return string.Format("Goat {0} says {1}:", this.Name, GoatSpeech);
        }
    }
}


text:
package gw.lang.reflect.java;

import java.io.Serializable;

public interface IJavaClassAnnotation extends Serializable {
  String annotationTypeName();

  Object getValue(String name);
}


text:
package com.facebook.buck.cxx.toolchain;

import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.rules.ToolProvider;
import com.facebook.buck.util.environment.Platform;
import com.google.common.collect.ImmutableList;

public interface ArchiverProvider {

  Archiver resolve(BuildRuleResolver resolver);

  Iterable<BuildTarget> getParseTimeDeps();

  static ArchiverProvider from(Archiver archiver) {
    return new ArchiverProvider() {

      @Override
      public Archiver resolve(BuildRuleResolver resolver) {
        return archiver;
      }

      @Override
      public Iterable<BuildTarget> getParseTimeDeps() {
        return ImmutableList.of();
      }
    };
  }

  static ArchiverProvider from(ToolProvider toolProvider, Platform platform) {
    return new ArchiverProvider() {
      @Override
      public Archiver resolve(BuildRuleResolver resolver) {
        Tool archiver = toolProvider.resolve(resolver);
        switch (platform) {
          case MACOS:
          case FREEBSD:
            return new BsdArchiver(archiver);
          case LINUX:
            return new GnuArchiver(archiver);
          case WINDOWS:
            return new WindowsArchiver(archiver);
          case UNKNOWN:
          default:
            throw new RuntimeException(
                "Invalid platform for archiver. Must be one of {MACOS, LINUX, WINDOWS}");
        }
      }

      @Override
      public Iterable<BuildTarget> getParseTimeDeps() {
        return toolProvider.getParseTimeDeps();
      }
    };
  }
}


text:
use 5.008;
use strict;
use warnings;

package MongoDB;
# ABSTRACT: Official MongoDB Driver for Perl

use version;
our $VERSION = 'v0.707.2.0';

# regexp_pattern was unavailable before 5.10, had to be exported to load the
# function implementation on 5.10, and was automatically available in 5.10.1
use if ($] eq '5.010000'), 're', 'regexp_pattern';

use XSLoader;
use MongoDB::Connection;
use MongoDB::MongoClient;
use MongoDB::Database;
use MongoDB::Collection;
use MongoDB::DBRef;
use MongoDB::OID;
use MongoDB::Timestamp;
use MongoDB::BSON::Binary;
use MongoDB::BSON::Regexp;
use MongoDB::BulkWrite;

XSLoader::load(__PACKAGE__, $MongoDB::VERSION);

*read_documents = \&MongoDB::BSON::decode_bson;

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

MongoDB - Official MongoDB Driver for Perl

=head1 VERSION

version v0.707.2.0

=head1 SYNOPSIS

    use MongoDB;

    my $client     = MongoDB::MongoClient->new(host => 'localhost', port => 27017);
    my $database   = $client->get_database( 'foo' );
    my $collection = $database->get_collection( 'bar' );
    my $id         = $collection->insert({ some => 'data' });
    my $data       = $collection->find_one({ _id => $id });

=head1 DESCRIPTION

This is the official Perl driver for MongoDB.  MongoDB is an open-source
document database that provides high performance, high availability, and easy
scalability.

A MongoDB server (or cluster) hosts a number of databases. A database holds a
set of collections. A collection holds a set of documents. A document is a set
of key-value pairs. Documents have dynamic schema. Dynamic schema means that
documents in the same collection do not need to have the same set of fields or
structure, and common fields in a collection's documents may hold different
types of data.

Here are some resources for learning more about MongoDB:

=over 4

=item *

L<MongoDB Manual|http://docs.mongodb.org/manual/contents/>

=item *

L<MongoDB CRUD Introduction|http://docs.mongodb.org/manual/core/crud-introduction/>

=item *

L<MongoDB Data Modeling Introductions|http://docs.mongodb.org/manual/core/data-modeling-introduction/>

=back

For getting started with the Perl driver, see these pages:

=over 4

=item *

L<MongoDB Perl Driver Tutorial|MongoDB::Tutorial>

=item *

L<MongoDB Perl Driver Examples|MongoDB::Examples>

=back

Extensive documentation and support resources are available via the
L<MongoDB community website|http://www.mongodb.org/>.

=head1 USAGE

The MongoDB driver is organized into a set of classes representing different
levels of abstraction and functionality.

As a user, you first create and configure a L<MongoDB::MongoClient> object to
connect to a MongoDB server (or cluster).  From that client object, you can get
a L<MongoDB::Database> object for interacting with a specific database.

From a database object you can get a L<MongoDB::Collection> object for CRUD
operations on that specific collection, or a L<MongoDB::GridFS> object for
working with an abstract file system hosted on the database.  Each of those
classes may return other objects for specific features or functions.

See the documentation of those classes for more details or the
L<MongoDB Perl Driver Tutorial|MongoDB::Tutorial> for an example.

=head1 FUNCTIONS (DEPRECATED)

The following low-level functions are deprecated and will be removed in a
future release.

=over 4

=item *

write_insert

=item *

write_query

=item *

write_update

=item *

write_remove

=item *

read_documents

=back

=head1 SEMANTIC VERSIONING SCHEME

Starting with MongoDB v0.704.0.0, the driver will be using a modified
L<semantic versioning|http://semver.org/> scheme.

Versions will have a C<vX.Y.Z.N> tuple scheme with the following properties:

=over 4

=item *

C<X> will be incremented for incompatible API changes

=item *

C<Y> will be incremented for new functionality that is backwards compatible

=item *

C<Z> will be incremented for backwards-compatible bug fixes

=item *

C<N> will be zero for a stable release; C<N> will be non-zero for development releases

=back

We use C<N> because CPAN does not support pre-release version labels (e.g.
"-alpha1") and requires non-decreasing version numbers for releases.

When C<N> is non-zero, C<X>, C<Y>, and C<Z> have no semantic meaning except to
indicate the last stable release.

For example, v0.704.0.1 is merely the first development release after
v0.704.0.0.  The next stable release could be a bug fix (v0.704.1.0), a feature
enhancement (v0.705.0.0), or an API change (v1.0.0.0).

See the Changes file included with development releases for an indication of
the nature of changes involved.

=head1 AUTHORS

=over 4

=item *

David Golden <david.golden@mongodb.org>

=item *

Mike Friedman <friedo@mongodb.com>

=item *

Kristina Chodorow <kristina@mongodb.org>

=item *

Florian Ragwitz <rafl@debian.org>

=back

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2014 by MongoDB, Inc..

This is free software, licensed under:

  The Apache License, Version 2.0, January 2004

=cut


text:
=================================================================

Read the documentation at: [herschel.sussex.ac.uk/XID_plus](http://herschel.sussex.ac.uk/XID_plus)

## Contributors

This code is being developed by [Peter Hurley](http://www.sussex.ac.uk/profiles/188689).

## [License](Licence.md)