text:
"""
Testing utilities for ``flocker.node``.
"""

import os
import pwd
import socket
from unittest import skipIf
from contextlib import closing
from uuid import uuid4

from zope.interface import implementer

from characteristic import attributes

from twisted.trial.unittest import TestCase
from twisted.internet.defer import succeed

from zope.interface.verify import verifyObject

from eliot import Logger, ActionType

from ._docker import BASE_DOCKER_API_URL
from . import IDeployer, IStateChange, sequentially
from ..testtools import loop_until
from ..control import (
    IClusterStateChange, Node, NodeState, Deployment, DeploymentState)
from ..control._model import ip_to_uuid

DOCKER_SOCKET_PATH = BASE_DOCKER_API_URL.split(':/')[-1]

def docker_accessible():
    """
    Attempt to connect to the Docker control socket.

    This may address https://clusterhq.atlassian.net/browse/FLOC-85.

    :return: A ``bytes`` string describing the reason Docker is not
        accessible or ``None`` if it appears to be accessible.
    """
    try:
        with closing(socket.socket(family=socket.AF_UNIX)) as docker_socket:
            docker_socket.connect(DOCKER_SOCKET_PATH)
    except socket.error as e:
        return os.strerror(e.errno)
    return None

_docker_reason = docker_accessible()

if_docker_configured = skipIf(
    _docker_reason,
    "User {!r} cannot access Docker via {!r}: {}".format(
        pwd.getpwuid(os.geteuid()).pw_name,
        DOCKER_SOCKET_PATH,
        _docker_reason,
    ))

def wait_for_unit_state(docker_client, unit_name, expected_activation_states):
    """
    Wait until a unit is in the requested state.

    :param docker_client: A ``DockerClient`` instance.
    :param unicode unit_name: The name of the unit.
    :param expected_activation_states: Activation states to wait for.

    :return: ``Deferred`` that fires when required state has been reached.
    """
    def is_in_states(units):
        for unit in units:
            if unit.name == unit_name:
                if unit.activation_state in expected_activation_states:
                    return True

    def check_if_in_states():
        responded = docker_client.list()
        responded.addCallback(is_in_states)
        return responded

    return loop_until(check_if_in_states)

CONTROLLABLE_ACTION_TYPE = ActionType(u"test:controllableaction", [], [])

@implementer(IStateChange)
@attributes(['result'])
class ControllableAction(object):
    """
    ``IStateChange`` whose results can be controlled.
    """
    called = False
    deployer = None

    _logger = Logger()

    @property
    def eliot_action(self):
        return CONTROLLABLE_ACTION_TYPE(self._logger)

    def run(self, deployer):
        self.called = True
        self.deployer = deployer
        return self.result

@implementer(IDeployer)
class DummyDeployer(object):
    """
    A non-implementation of ``IDeployer``.
    """
    hostname = u"127.0.0.1"
    node_uuid = uuid4()

    def discover_state(self, node_stat):
        return succeed(())

    def calculate_changes(self, desired_configuration, cluster_state):
        return sequentially(changes=[])

@implementer(IDeployer)
class ControllableDeployer(object):
    """
    ``IDeployer`` whose results can be controlled.
    """
    def __init__(self, hostname, local_states, calculated_actions):
        self.node_uuid = ip_to_uuid(hostname)
        self.hostname = hostname
        self.local_states = local_states
        self.calculated_actions = calculated_actions
        self.calculate_inputs = []

    def discover_state(self, node_state):
        return self.local_states.pop(0).addCallback(lambda val: (val,))

    def calculate_changes(self, desired_configuration, cluster_state):
        self.calculate_inputs.append(
            (cluster_state.get_node(uuid=self.node_uuid,
                                    hostname=self.hostname),
             desired_configuration, cluster_state))
        return self.calculated_actions.pop(0)

# A deployment with no information:
EMPTY = Deployment(nodes=[])
EMPTY_STATE = DeploymentState()

def ideployer_tests_factory(fixture):
    """
    Create test case for IDeployer implementation.

    :param fixture: Callable that takes ``TestCase`` instance and returns
         a ``IDeployer`` provider.

    :return: ``TestCase`` subclass that will test the given fixture.
    """
    class IDeployerTests(TestCase):
        """
        Tests for ``IDeployer``.
        """
        def test_interface(self):
            """
            The object claims to provide the interface.
            """
            self.assertTrue(verifyObject(IDeployer, fixture(self)))

        def _discover_state(self):
            """
            Create a deployer using the fixture and ask it to discover state.

            :return: The return value of the object's ``discover_state``
                method.
            """
            deployer = fixture(self)
            result = deployer.discover_state(NodeState(hostname=b"10.0.0.1"))
            return result

        def test_discover_state_list_result(self):
            """
            The object's ``discover_state`` method returns a ``Deferred`` that
            fires with a ``list``.
            """
            def discovered(changes):
                self.assertEqual(tuple, type(changes))
            return self._discover_state().addCallback(discovered)

        def test_discover_state_iclusterstatechange(self):
            """
            The elements of the ``list`` that ``discover_state``\ 's
            ``Deferred`` fires with provide ``IClusterStateChange``.
            """
            def discovered(changes):
                wrong = []
                for obj in changes:
                    if not IClusterStateChange.providedBy(obj):
                        wrong.append(obj)
                if wrong:
                    template = (
                        "Some elements did not provide IClusterStateChange: {}"
                    )
                    self.fail(template.format(wrong))
            return self._discover_state().addCallback(discovered)

        def test_calculate_necessary_state_changes(self):
            """
            The object's ``calculate_necessary_state_changes`` method returns a
            ``IStateChange`` provider.
            """
            deployer = fixture(self)
            result = deployer.calculate_changes(EMPTY, EMPTY_STATE)
            self.assertTrue(verifyObject(IStateChange, result))

    return IDeployerTests

def to_node(node_state):
    """
    Convert a ``NodeState`` to a corresponding ``Node``.

    :param NodeState node_state: Object to convert.
    :return Node: Equivalent node.
    """
    return Node(uuid=node_state.uuid, hostname=node_state.hostname,
                applications=node_state.applications or [],
                manifestations=node_state.manifestations or {})

def assert_calculated_changes_for_deployer(
        case, deployer, node_state, node_config, nonmanifest_datasets,
        additional_node_states, additional_node_config, expected_changes
):
    """
    Assert that ``calculate_changes`` returns certain changes when it is
    invoked with the given state and configuration.

    :param TestCase case: The ``TestCase`` to use to make assertions (typically
        the one being run at the moment).
    :param IDeployer deployer: The deployer provider which will be asked to
        calculate the changes.
    :param NodeState node_state: The deployer will be asked to calculate
        changes for a node that has this state.
    :param Node node_config: The deployer will be asked to calculate changes
        for a node with this desired configuration.
    :param set nonmanifest_datasets: Datasets which will be presented as part
        of the cluster state without manifestations on any node.
    :param set additional_node_states: A set of ``NodeState`` for other nodes.
    :param set additional_node_config: A set of ``Node`` for other nodes.
    :param expected_changes: The ``IStateChange`` expected to be returned.
    """
    cluster_state = DeploymentState(
        nodes={node_state} | additional_node_states,
        nonmanifest_datasets={
            dataset.dataset_id: dataset
            for dataset in nonmanifest_datasets
        },
    )
    cluster_configuration = Deployment(
        nodes={node_config} | additional_node_config,
    )
    changes = deployer.calculate_changes(
        cluster_configuration, cluster_state,
    )
    case.assertEqual(expected_changes, changes)


text:
package org.motechproject.nms.imi.service.impl;

import org.motechproject.nms.imi.exception.ExecException;
import org.motechproject.server.config.SettingsFacade;

public class SortHelper {

    private static final String SORT_BINARY_SETTING = "imi.sort.binary";
    private static final String SORT_BINARY_DEFAULT = "/usr/bin/sort";
    private static final String SORT_TIMEOUT_SETTING = "imi.sort.timeout";
    private static final Long SORT_TIMEOUT_DEFAULT = 60000L;
    private static final String SORTED_SUFFIX = ".sorted";
    private static final String LOCAL_CDR_DIR = "imi.local_cdr_dir";

    private SettingsFacade settingsFacade;

    public SortHelper(SettingsFacade settingsFacade) {
        this.settingsFacade = settingsFacade;
    }

    private String getSettingWithDefault(String setting, String defaultValue) {
        String s = settingsFacade.getProperty(setting);
        if (s == null) {
            return  defaultValue;
        }
        return s;
    }

    private String getSortBinary() {
        return getSettingWithDefault(SORT_BINARY_SETTING, SORT_BINARY_DEFAULT);
    }

    private Long getSortTimeout() {
        try {
            return Long.parseLong(settingsFacade.getProperty(SORT_TIMEOUT_SETTING));
        } catch (NumberFormatException e) {
            return SORT_TIMEOUT_DEFAULT;
        }
    }

    public String localCdrFile(String file) {
        String localFile = settingsFacade.getProperty(LOCAL_CDR_DIR);
        localFile += localFile.endsWith("/") ? "" : "/";
        localFile += file;
        return localFile;
    }

    public String localSortedCdrFile(String file) {
        String localFile = settingsFacade.getProperty(LOCAL_CDR_DIR);
        localFile += localFile.endsWith("/") ? "" : "/";
        localFile += file;
        localFile += SORTED_SUFFIX;
        return localFile;
    }

    /**
     * Sorts the provided source CDR file on requestId (col1, text) and attempt (col4, int) into the destination
     * file
     */
    void sort(String file) throws ExecException {
        String command = String.format("%s -t , -k 1,1r -k 4,4n -o %s %s", getSortBinary(),
                localSortedCdrFile(file), localCdrFile(file));
        ExecHelper execHelper = new ExecHelper();
        execHelper.exec(command, getSortTimeout());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.sapphirine.rf.MovieRecommender.model;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import au.com.bytecode.opencsv.CSVReader;

public class DemographicModel {

	private String path;
	private Map<Long, YearAndSex> modelData;

	public DemographicModel(String path) throws IOException
	{
		File file = new File(path);
		if(!file.exists() || file.isDirectory())
		{
		    throw new FileNotFoundException(file.toString());
		}
		else
		{
			this.path = path;
		}
		modelData = new HashMap<Long, YearAndSex>();
		buildModel();
	}

	private void buildModel() throws IOException
	{
		try(CSVReader reader = new CSVReader(new FileReader(path), '\t'))
		{
		String[] line;
			while ((line = reader.readNext()) != null) {
				if (line.length >= 3) {
					if (!line[0].contains("undef")) {
						long id = Integer.parseInt(line[0]);
						int year = -1;
						String sex = "undef";
						if (!line[1].contains("undef")) {
							year = Integer.parseInt(line[1]);
						}
						if (!line[2].contains("undef")) {
							if (line[2].equalsIgnoreCase("m")
									|| line[2].equalsIgnoreCase("f")) {
								sex = line[2];
							} else {
								sex = "undef";
							}
						} else {
							sex = line[2];
						}
						modelData.put(id, new YearAndSex(year, sex));
					}
				}
			}
		}
	}

	public int getBirthYearByUserID(long id)
	{
		if(modelData.containsKey(id))
		{
			return modelData.get(id).getYear();
		}
		return -1;
	}

	public String getSexTypeByUserID(long id)
	{
		if(modelData.containsKey(id))
		{
			return modelData.get(id).getSex();
		}
		return "undef";
	}

	private class YearAndSex
	{
		private int year;
		private String sex;
		public YearAndSex(int year, String sex)
		{
			this.year = year;
			this.sex = sex;
		}

		public int getYear() {
			return year;
		}
		public void setYear(int year) {
			this.year = year;
		}
		public String getSex() {
			return sex;
		}
		public void setSex(String sex) {
			this.sex = sex;
		}
	}

}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;

namespace DeviceHive.Client
{
    internal class JsonContractResolver : CamelCasePropertyNamesContractResolver
    {
        #region DefaultContractResolver Members

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var property = base.CreateProperty(member, memberSerialization);
            if (property.DeclaringType == typeof(Notification) && property.PropertyName == "name")
            {
                property.PropertyName = "notification";
            }
            if (property.DeclaringType == typeof(Command) && property.PropertyName == "name")
            {
                property.PropertyName = "command";
            }
            return property;
        }
        #endregion
    }
}


text:
<?xml version="1.0" standalone="yes"?>
<!--

    Copyright (c) 2004, 2021 Oracle and/or its affiliates. All rights reserved.

    This program and the accompanying materials are made available under the
    terms of the Eclipse Distribution License v. 1.0, which is available at
    http://www.eclipse.org/org/documents/edl-v10.php.

    SPDX-License-Identifier: BSD-3-Clause

-->

<project basedir="." default="run">
  <description>
      This sample app demonstrates how a pull-parser can
      be used with JAXB to increase the flexibility of processing.
  </description>

  <property name="jaxb.home" value="../.." />
  <mkdir dir="lib"/>
  <path id="classpath">
    <pathelement path="src" />
    <pathelement path="classes" />
    <pathelement path="schemas" />
    <!--additional jar files for this sample-->
    <fileset dir="lib" includes="*.jar" />
    <fileset dir="${jaxb.home}" includes="mod/*.jar" />
  </path>
  <taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
    <classpath refid="classpath" />
  </taskdef>

  <!--
    Check if the necessary jar files are properly installed.
  -->
  <target name="jar-check">
    <available file="lib/sjsxp.jar" property="sjsxp.jar-present" />
    <fail unless="sjsxp.jar-present">
Please download sjsxp.jar from the web and place it in the lib directory.

Alternatively download from maven central:
mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get -DremoteRepositories=http://download.java.net/maven/2 \
-Dartifact=com.sun.xml.stream:sjsxp:LATEST -Ddest=./lib/sjsxp.jar

    </fail>
  </target>

  <!--compile Java source files-->
  <target name="compile" description="Compile all Java source files" depends="jar-check">
    <echo message="Compiling the schema..." />
    <mkdir dir="gen-src" />
    <xjc schema="contact.xsd" package="contact" destdir="gen-src">
      <produces dir="gen-src/contact" includes="**/*.java" />
    </xjc>
    <echo message="Compiling the java source files..." />
    <mkdir dir="classes" />
    <javac destdir="classes" debug="on">
      <src path="src" />
      <src path="gen-src" />
      <classpath refid="classpath" />
    </javac>
  </target>

  <target name="run" depends="compile" description="Run the sample app">
    <echo message="Running the sample application..." />
    <java classname="Main" fork="true">
      <classpath refid="classpath" />
      <arg value="Jane Smith" />
    </java>
  </target>

  <target name="javadoc" description="Generates javadoc" depends="compile">
    <echo message="Generating javadoc..." />
    <mkdir dir="docs/api" />
    <javadoc sourcepath="gen-src" destdir="docs/api" windowtitle="pull parser based unmarshalling" useexternalfile="yes">
      <fileset dir="." includes="gen-src/**/*.java" excludes="**/impl/**/*.java" />
    </javadoc>
  </target>

  <target name="clean" description="Deletes all the generated artifacts.">
    <delete dir="docs/api" />
    <delete dir="gen-src" />
    <delete dir="schemas" />
    <delete dir="classes" />
  </target>
</project>


text:
using System.Text;

namespace ACBr.Net.Core
{
    /// <summary>
    /// Classe com enconding para facilitar o uso.
    /// </summary>
    public static class ACBrEncoding
    {
        #region Fields

        private static Encoding iso88591;
        private static Encoding ibm850;
        private static Encoding ibm860;
        private static Encoding windows1252;

        #endregion Fields

        #region Properties

        /// <summary>
        /// Retorna o enconding ISO-8859-1
        /// </summary>
        public static Encoding ISO88591 => iso88591 ?? (iso88591 = Encoding.GetEncoding("ISO-8859-1"));

        /// <summary>
        /// Retorna o enconding IBM850
        /// </summary>
        public static Encoding IBM850 => ibm850 ?? (ibm850 = Encoding.GetEncoding("IBM850"));

        /// <summary>
        /// Retorna o enconding IBM860
        /// </summary>
        public static Encoding IBM860 => ibm860 ?? (ibm860 = Encoding.GetEncoding("IBM860"));

        /// <summary>
        /// Retorna o enconding CP1252
        /// </summary>
        public static Encoding CP1252 => Windows1252;

        /// <summary>
        /// Retorna o enconding Windows-1252
        /// </summary>
        public static Encoding Windows1252 => windows1252 ?? (windows1252 = Encoding.GetEncoding("Windows-1252"));

        #endregion Properties
    }
}


text:
typedef struct DriveStats DriveStats;
typedef struct CPUStats CPUStats;

enum {
	NDRIVE = 16,
	NAMELEN = 31
};

struct DriveStats {
	char name[NAMELEN+1];
	int64_t size;
	int64_t blocksize;

	int64_t read;
	int64_t written;
	int64_t nread;
	int64_t nwrite;
	int64_t readtime;
	int64_t writetime;
	int64_t readlat;
	int64_t writelat;
	int64_t readerrs;
	int64_t writeerrs;
	int64_t readretries;
	int64_t writeretries;
};

struct CPUStats {
	natural_t user;
	natural_t nice;
	natural_t sys;
	natural_t idle;
};

extern int readdrivestat(DriveStats a[], int n);
extern int readcpustat(CPUStats *cpu);


text:
package org.factcast.core.subscription;

import static org.junit.jupiter.api.Assertions.*;

import java.util.Arrays;
import java.util.Collection;

import org.factcast.core.TestHelper;
import org.factcast.core.spec.FactSpec;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class SubscriptionRequestTest {

    @Test
    void testCatchupNullSpec() {
        Assertions.assertThrows(NullPointerException.class, () -> {
            SubscriptionRequest.catchup((FactSpec) null);
        });
    }

    @Test
    void testFollowNullSpec() {
        Assertions.assertThrows(NullPointerException.class, () -> {
            SubscriptionRequest.follow((FactSpec) null);
        });
    }

    @Test
    void testFollowDelayNullSpec() {
        Assertions.assertThrows(NullPointerException.class, () -> {
            SubscriptionRequest.follow(1, null);
        });
    }

    @Test
    void testCatchup() {
        FactSpec s = FactSpec.ns("xx");
        final SubscriptionRequest r = SubscriptionRequest.catchup(s).fromScratch();
        assertTrue(r.specs().contains(s));
        assertEquals(1, r.specs().size());
    }

    @Test
    void testCatchupCollection() {
        FactSpec ns1 = FactSpec.ns("ns1");
        FactSpec ns2 = FactSpec.ns("ns2");
        final SubscriptionRequest r = SubscriptionRequest.catchup(Arrays.asList(ns1, ns2))
                .fromScratch();
        assertTrue(r.specs().contains(ns1));
        assertTrue(r.specs().contains(ns2));
        assertEquals(2, r.specs().size());
        assertFalse(r.continuous());
    }

    @Test
    void testFollowCollection() {
        FactSpec ns1 = FactSpec.ns("ns1");
        FactSpec ns2 = FactSpec.ns("ns2");
        final SubscriptionRequest r = SubscriptionRequest.follow(Arrays.asList(ns1, ns2))
                .fromScratch();
        assertTrue(r.specs().contains(ns1));
        assertTrue(r.specs().contains(ns2));
        assertEquals(2, r.specs().size());
        assertTrue(r.continuous());
    }

    @Test
    void testCatchupCollectionNullParameters() {
        TestHelper.expectNPE(() -> {
            SubscriptionRequest.catchup((Collection<FactSpec>) null);
        });
    }

    @Test
    void testFollowCollectionNullParameters() {
        TestHelper.expectNPE(() -> {
            SubscriptionRequest.follow((Collection<FactSpec>) null);
        });
    }

    @Test
    void testFollow() {
        FactSpec s = FactSpec.ns("xx");
        final SubscriptionRequest r = SubscriptionRequest.follow(s).fromScratch();
        assertTrue(r.specs().contains(s));
        assertEquals(1, r.specs().size());
    }

    @Test
    void testFollowMaxDelay() {
        FactSpec s = FactSpec.ns("xx");
        final SubscriptionRequest r = SubscriptionRequest.follow(7, s).fromScratch();
        assertTrue(r.specs().contains(s));
        assertEquals(1, r.specs().size());
        assertEquals(7, r.maxBatchDelayInMs());
    }
}


text:
<?php /* Smarty version Smarty-3.1.18, created on 2014-10-16 03:56:46
         compiled from "/srv/www/server.com/public_html/design/themes/responsive/templates/addons/seo/hooks/index/title.post.tpl" */ ?>
<?php /*%%SmartyHeaderCode:1640327488543f09be813286-22064892%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
  'file_dependency' =>
  array (
    'e7a93dc3f8cb8e6e31b5a39d8df29d4cf9d95276' =>
    array (
      0 => '/srv/www/server.com/public_html/design/themes/responsive/templates/addons/seo/hooks/index/title.post.tpl',
      1 => 1413417022,
      2 => 'tygh',
    ),
  ),
  'nocache_hash' => '1640327488543f09be813286-22064892',
  'function' =>
  array (
  ),
  'variables' =>
  array (
    'runtime' => 0,
    'search' => 0,
    'auth' => 0,
  ),
  'has_nocache_code' => false,
  'version' => 'Smarty-3.1.18',
  'unifunc' => 'content_543f09be860e79_52594425',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_543f09be860e79_52594425')) {function content_543f09be860e79_52594425($_smarty_tpl) {?><?php if (!is_callable('smarty_function_set_id')) include '/srv/www/server.com/public_html/app/functions/smarty_plugins/function.set_id.php';
?><?php if ($_smarty_tpl->tpl_vars['runtime']->value['customization_mode']['design']=="Y"&&@constant('AREA')=="C") {?><?php $_smarty_tpl->_capture_stack[0][] = array("template_content", null, null); ob_start(); ?><?php if ($_smarty_tpl->tpl_vars['search']->value) {?><?php echo htmlspecialchars(fn_get_seo_page_title($_smarty_tpl->tpl_vars['search']->value), ENT_QUOTES, 'UTF-8');?>
<?php }?><?php list($_capture_buffer, $_capture_assign, $_capture_append) = array_pop($_smarty_tpl->_capture_stack[0]);
if (!empty($_capture_buffer)) {
 if (isset($_capture_assign)) $_smarty_tpl->assign($_capture_assign, ob_get_contents());
 if (isset( $_capture_append)) $_smarty_tpl->append( $_capture_append, ob_get_contents());
 Smarty::$_smarty_vars['capture'][$_capture_buffer]=ob_get_clean();
} else $_smarty_tpl->capture_error();?><?php if (trim(Smarty::$_smarty_vars['capture']['template_content'])) {?><?php if ($_smarty_tpl->tpl_vars['auth']->value['area']=="A") {?><span class="cm-template-box template-box" data-ca-te-template="addons/seo/hooks/index/title.post.tpl" id="<?php echo smarty_function_set_id(array('name'=>"addons/seo/hooks/index/title.post.tpl"),$_smarty_tpl);?>
">

<?php echo Smarty::$_smarty_vars['capture']['template_content'];?>
<?php } else { ?><?php echo Smarty::$_smarty_vars['capture']['template_content'];?>
<?php }?><?php }?><?php } else { ?><?php if ($_smarty_tpl->tpl_vars['search']->value) {?><?php echo htmlspecialchars(fn_get_seo_page_title($_smarty_tpl->tpl_vars['search']->value), ENT_QUOTES, 'UTF-8');?>
<?php }?><?php }?><?php }} ?>


text:
#pragma once

#include "../Scene/Animatable.h"

namespace Urho3D
{

class DebugRenderer;
class Node;
class Scene;

struct ComponentReplicationState;

/// Autoremove is used by some components for automatic removal from the scene hierarchy upon completion of an action, for example sound or particle effect.
enum AutoRemoveMode
{
    REMOVE_DISABLED = 0,
    REMOVE_COMPONENT,
    REMOVE_NODE
};

/// Base class for components. Components can be created to scene nodes.
class URHO3D_API Component : public Animatable
{
    URHO3D_OBJECT(Component, Animatable);

    friend class Node;
    friend class Scene;

public:
    /// Construct.
    Component(Context* context);
    /// Destruct.
    virtual ~Component() override;

    /// Handle enabled/disabled state change.
    virtual void OnSetEnabled() { }

    /// Save as binary data. Return true if successful.
    virtual bool Save(Serializer& dest) const override;
    /// Save as XML data. Return true if successful.
    virtual bool SaveXML(XMLElement& dest) const override;
    /// Save as JSON data. Return true if successful.
    virtual bool SaveJSON(JSONValue& dest) const override;
    /// Mark for attribute check on the next network update.
    virtual void MarkNetworkUpdate() override;
    /// Return the depended on nodes to order network updates.
    virtual void GetDependencyNodes(PODVector<Node*>& dest);
    /// Visualize the component as debug geometry.
    virtual void DrawDebugGeometry(DebugRenderer* debug, bool depthTest);

    /// Set enabled/disabled state.
    void SetEnabled(bool enable);
    /// Remove from the scene node. If no other shared pointer references exist, causes immediate deletion.
    void Remove();

    /// Return ID.
    unsigned GetID() const { return id_; }

    /// Return scene node.
    Node* GetNode() const { return node_; }

    /// Return the scene the node belongs to.
    Scene* GetScene() const;

    /// Return whether is enabled.
    bool IsEnabled() const { return enabled_; }

    /// Return whether is effectively enabled (node is also enabled.)
    bool IsEnabledEffective() const;
    /// Return component in the same scene node by type. If there are several, returns the first.
    Component* GetComponent(StringHash type) const;
    /// Return components in the same scene node by type.
    void GetComponents(PODVector<Component*>& dest, StringHash type) const;
    /// Template version of returning a component in the same scene node by type.
    template <class T> T* GetComponent() const;
    /// Template version of returning components in the same scene node by type.
    template <class T> void GetComponents(PODVector<T*>& dest) const;

    /// Add a replication state that is tracking this component.
    void AddReplicationState(ComponentReplicationState* state);
    /// Prepare network update by comparing attributes and marking replication states dirty as necessary.
    void PrepareNetworkUpdate();
    /// Clean up all references to a network connection that is about to be removed.
    void CleanupConnection(Connection* connection);

protected:
    /// Handle attribute animation added.
    virtual void OnAttributeAnimationAdded() override;
    /// Handle attribute animation removed.
    virtual void OnAttributeAnimationRemoved() override;
    /// Handle scene node being assigned at creation.
    virtual void OnNodeSet(Node* node);
    /// Handle scene being assigned. This may happen several times during the component's lifetime. Scene-wide subsystems and events are subscribed to here.
    virtual void OnSceneSet(Scene* scene);
    /// Handle scene node transform dirtied.
    virtual void OnMarkedDirty(Node* node);
    /// Handle scene node enabled status changing.
    virtual void OnNodeSetEnabled(Node* node);
    /// Set ID. Called by Scene.
    void SetID(unsigned id);
    /// Set scene node. Called by Node when creating the component.
    void SetNode(Node* node);
    /// Handle scene attribute animation update event.
    void HandleAttributeAnimationUpdate(StringHash eventType, VariantMap& eventData);
    /// Return a component from the scene root that sends out fixed update events (either PhysicsWorld or PhysicsWorld2D). Return null if neither exists.
    Component* GetFixedUpdateSource();
    /// Perform autoremove. Called by subclasses. Caller should keep a weak pointer to itself to check whether was actually removed, and return immediately without further member operations in that case.
    void DoAutoRemove(AutoRemoveMode mode);

    /// Scene node.
    Node* node_;
    /// Unique ID within the scene.
    unsigned id_;
    /// Network update queued flag.
    bool networkUpdate_;
    /// Enabled flag.
    bool enabled_;
};

template <class T> T* Component::GetComponent() const { return static_cast<T*>(GetComponent(T::GetTypeStatic())); }

template <class T> void Component::GetComponents(PODVector<T*>& dest) const
{
    GetComponents(reinterpret_cast<PODVector<Component*>&>(dest), T::GetTypeStatic());
}

}


text:
package instance

import (
	"github.com/kubernetes-incubator/service-catalog/cmd/svcat/command"
	"github.com/kubernetes-incubator/service-catalog/cmd/svcat/output"
	"github.com/spf13/cobra"
)

type getCmd struct {
	*command.Context
	ns   string
	name string
}

// NewGetCmd builds a "svcat get instances" command
func NewGetCmd(cxt *command.Context) *cobra.Command {
	getCmd := &getCmd{Context: cxt}
	cmd := &cobra.Command{
		Use:     "instances [name]",
		Aliases: []string{"instance", "inst"},
		Short:   "List instances, optionally filtered by name",
		Example: `
  svcat get instances
  svcat get instance wordpress-mysql-instance
  svcat get instance -n ci concourse-postgres-instance
`,
		PreRunE: command.PreRunE(getCmd),
		RunE:    command.RunE(getCmd),
	}
	cmd.Flags().StringVarP(
		&getCmd.ns,
		"namespace",
		"n",
		"default",
		"The namespace in which to get the ServiceInstance",
	)
	return cmd
}

func (c *getCmd) Validate(args []string) error {
	if len(args) > 0 {
		c.name = args[0]
	}

	return nil
}

func (c *getCmd) Run() error {
	if c.name == "" {
		return c.getAll()
	}

	return c.get()
}

func (c *getCmd) getAll() error {
	instances, err := c.App.RetrieveInstances(c.ns)
	if err != nil {
		return err
	}

	output.WriteInstanceList(c.Output, instances.Items...)
	return nil
}

func (c *getCmd) get() error {
	instance, err := c.App.RetrieveInstance(c.ns, c.name)
	if err != nil {
		return err
	}

	output.WriteInstanceList(c.Output, *instance)
	return nil
}


text:
"""841. Keys and Rooms
https://leetcode.com/problems/keys-and-rooms/

There are N rooms and you start in room 0.
Each room has a distinct number in 0, 1, 2, ..., N-1,
and each room may have some keys to access the next room.

Formally, each room i has a list of keys rooms[i],
and each key rooms[i][j] is an integer in [0, 1, ..., N-1]
where N = rooms.length.  A key rooms[i][j] = v opens the room with number v.

Initially, all the rooms start locked (except for room 0).
You can walk back and forth between rooms freely.
Return true if and only if you can enter every room.

Example 1:

Input: [[1],[2],[3],[]]
Output: true
Explanation:
We start in room 0, and pick up key 1.
We then go to room 1, and pick up key 2.
We then go to room 2, and pick up key 3.
We then go to room 3.  Since we were able to go to every room, we return true.

Example 2:

Input: [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can't enter the room with number 2.

Note:

1 <= rooms.length <= 1000
0 <= rooms[i].length <= 1000
The number of keys in all rooms combined is at most 3000.
"""
from typing import List

class Solution:
    def can_visit_all_rooms(self, rooms: List[List[int]]) -> bool:
        def dfs(key: int):
            nonlocal count
            count += 1
            opened.add(key)
            for k in rooms[key]:
                if k not in opened:
                    dfs(k)

        opened = set()
        count = 0
        dfs(0)
        return count == len(rooms)

    def can_visit_all_rooms_1(self, rooms: List[List[int]]) -> bool:
        opened = [0]
        queue = [0]
        count = 0
        while queue:
            count += 1
            i = queue.pop(0)
            for key in rooms[i]:
                if key not in opened:
                    opened.append(key)
                    queue.append(key)
        return count == len(rooms)

    def can_visit_all_rooms_2(self, rooms: List[List[int]]) -> bool:
        opened = [0]
        keys = rooms[0]
        while keys:
            new_keys = []
            for key in keys:
                if key not in opened:
                    new_keys.extend(rooms[key])
                    opened.append(key)
                keys = new_keys

        return len(opened) == len(rooms)


text:
/***********************************************************************************************************************************
Execute Process
***********************************************************************************************************************************/
#include "build.auto.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include "common/debug.h"
#include "common/log.h"
#include "common/exec.h"
#include "common/fork.h"
#include "common/io/fdRead.h"
#include "common/io/fdWrite.h"
#include "common/io/io.h"
#include "common/io/read.h"
#include "common/io/write.h"
#include "common/wait.h"

/***********************************************************************************************************************************
Object type
***********************************************************************************************************************************/
struct Exec
{
    ExecPub pub;                                                    // Publicly accessible variables
    String *command;                                                // Command to execute
    StringList *param;                                              // List of parameters to pass to command
    const String *name;                                             // Name to display in log/error messages
    TimeMSec timeout;                                               // Timeout for any i/o operation (read, write, etc.)

    pid_t processId;                                                // Process id of the child process

    int fdRead;                                                     // Read file descriptor
    int fdWrite;                                                    // Write file descriptor
    int fdError;                                                    // Error file descriptor

    IoRead *ioReadFd;                                               // File descriptor read interface
    IoWrite *ioWriteFd;                                             // File descriptor write interface
};

/***********************************************************************************************************************************
Macro to close file descriptors after dup2() in the child process

If the parent process is daemomized and has closed stdout, stdin, and stderr or some combination of them, then the newly created
descriptors might overlap stdout, stdin, or stderr.  In that case we don't want to accidentally close the descriptor that we have
just copied.

Note that this is pretty specific to the way that file descriptors are handled in this module and may not be generally applicable in
other code.
***********************************************************************************************************************************/
#define PIPE_DUP2(pipe, pipeIdx, fd)                                                                                \
    do                                                                                \
    {                                                                                \
        dup2(pipe[pipeIdx], fd);                                                                                \
                                                                                \
        if (pipe[0] != fd)                                                                                \
            close(pipe[0]);                                                                                \
                                                                                \
        if (pipe[1] != fd)                                                                                \
            close(pipe[1]);                                                                                \
    }                                                                                \
    while (0);

/***********************************************************************************************************************************
Free exec file descriptors and ensure process is shut down
***********************************************************************************************************************************/
static void
execFreeResource(THIS_VOID)
{
    THIS(Exec);

    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(EXEC, this);
    FUNCTION_LOG_END();

    ASSERT(this != NULL);

    // Close file descriptors
    close(this->fdRead);
    close(this->fdWrite);
    close(this->fdError);

    // Wait for the child to exit. We don't really care how it exits as long as it does.
    if (this->processId != 0)
    {
        MEM_CONTEXT_TEMP_BEGIN()
        {
            int processResult = 0;
            Wait *wait = waitNew(this->timeout);

            do
            {
                THROW_ON_SYS_ERROR(
                    (processResult = waitpid(this->processId, NULL, WNOHANG)) == -1, ExecuteError,
                    "unable to wait on child process");
            }
            while (processResult == 0 && waitMore(wait));

            // If the process did not exit then error -- else we may end up with a collection of zombie processes
            if (processResult == 0)
                THROW_FMT(ExecuteError, "%s did not exit when expected", strZ(this->name));
        }
        MEM_CONTEXT_TEMP_END();
    }

    FUNCTION_LOG_RETURN_VOID();
}

/**********************************************************************************************************************************/
Exec *
execNew(const String *command, const StringList *param, const String *name, TimeMSec timeout)
{
    FUNCTION_LOG_BEGIN(logLevelDebug)
        FUNCTION_LOG_PARAM(STRING, command);
        FUNCTION_LOG_PARAM(STRING_LIST, param);
        FUNCTION_LOG_PARAM(STRING, name);
        FUNCTION_LOG_PARAM(TIME_MSEC, timeout);
    FUNCTION_LOG_END();

    ASSERT(command != NULL);
    ASSERT(name != NULL);
    ASSERT(timeout > 0);

    Exec *this = NULL;

    OBJ_NEW_BEGIN(Exec)
    {
        this = OBJ_NEW_ALLOC();

        *this = (Exec)
        {
            .command = strDup(command),
            .name = strDup(name),
            .timeout = timeout,

            // Parameter list is optional but if not specified we need to build one with the command
            .param = param == NULL ? strLstNew() : strLstDup(param),
        };

        // The first parameter must be the command
        strLstInsert(this->param, 0, this->command);
    }
    OBJ_NEW_END();

    FUNCTION_LOG_RETURN(EXEC, this);
}

/***********************************************************************************************************************************
Check if the process is still running

This should be called when anything unexpected happens while reading or writing, including errors and eof.  If this function returns
then the original error should be rethrown.
***********************************************************************************************************************************/
static void
execCheck(Exec *this)
{
    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(EXEC, this);
    FUNCTION_LOG_END();

    ASSERT(this != NULL);

    int processStatus;
    int processResult;

    THROW_ON_SYS_ERROR(
        (processResult = waitpid(this->processId, &processStatus, WNOHANG)) == -1, ExecuteError, "unable to wait on child process");

    if (processResult != 0)
    {
        // Clear the process id so we don't try to wait for this process on free
        this->processId = 0;

        // If the process exited normally
        if (WIFEXITED(processStatus))
        {
            // Get data from stderr to help diagnose the problem
            String *errorStr = strTrim(
                strNewBuf(ioReadBuf(ioFdReadNewOpen(strNewFmt("%s error", strZ(this->name)), this->fdError, 0))));

            // Throw the error with as much information as is available
            THROWP_FMT(
                errorTypeFromCode(WEXITSTATUS(processStatus)), "%s terminated unexpectedly [%d]%s%s", strZ(this->name),
                WEXITSTATUS(processStatus), strSize(errorStr) > 0 ? ": " : "", strSize(errorStr) > 0 ? strZ(errorStr) : "");
        }

        // If the process did not exit normally then it must have been a signal
        THROW_FMT(ExecuteError, "%s terminated unexpectedly on signal %d", strZ(this->name), WTERMSIG(processStatus));
    }

    FUNCTION_LOG_RETURN_VOID();
}

/***********************************************************************************************************************************
Read from the process
***********************************************************************************************************************************/
static size_t
execRead(THIS_VOID, Buffer *buffer, bool block)
{
    THIS(Exec);

    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(EXEC, this);
        FUNCTION_LOG_PARAM(BUFFER, buffer);
        FUNCTION_LOG_PARAM(BOOL, block);
    FUNCTION_LOG_END();

    ASSERT(this != NULL);
    ASSERT(buffer != NULL);

    size_t result = 0;

    TRY_BEGIN()
    {
        result = ioReadInterface(this->ioReadFd)->read(ioReadDriver(this->ioReadFd), buffer, block);
    }
    CATCH_ANY()
    {
        execCheck(this);
        RETHROW();
    }
    TRY_END();

    FUNCTION_LOG_RETURN(SIZE, result);
}

/***********************************************************************************************************************************
Write to the process
***********************************************************************************************************************************/
static void
execWrite(THIS_VOID, const Buffer *buffer)
{
    THIS(Exec);

    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(EXEC, this);
        FUNCTION_LOG_PARAM(BUFFER, buffer);
    FUNCTION_LOG_END();

    ASSERT(this != NULL);
    ASSERT(buffer != NULL);

    TRY_BEGIN()
    {
        ioWrite(this->ioWriteFd, buffer);
        ioWriteFlush(this->ioWriteFd);
    }
    CATCH_ANY()
    {
        execCheck(this);
        RETHROW();
    }
    TRY_END();

    FUNCTION_LOG_RETURN_VOID();
}

/***********************************************************************************************************************************
Is the process eof?
***********************************************************************************************************************************/
static bool
execEof(THIS_VOID)
{
    THIS(Exec);

    FUNCTION_LOG_BEGIN(logLevelTrace);
        FUNCTION_LOG_PARAM(EXEC, this);
    FUNCTION_LOG_END();

    ASSERT(this != NULL);

    // Check if the process is still running on eof
    if (ioReadInterface(this->ioReadFd)->eof(ioReadDriver(this->ioReadFd)))
        execCheck(this);

    FUNCTION_LOG_RETURN(BOOL, false);
}

/***********************************************************************************************************************************
Get the read file descriptor
***********************************************************************************************************************************/
static int
execFdRead(const THIS_VOID)
{
    THIS(const Exec);

    FUNCTION_TEST_BEGIN();
        FUNCTION_TEST_PARAM(EXEC, this);
    FUNCTION_TEST_END();

    ASSERT(this != NULL);

    FUNCTION_TEST_RETURN(this->fdRead);
}

/**********************************************************************************************************************************/
void
execOpen(Exec *this)
{
    FUNCTION_LOG_BEGIN(logLevelDebug)
        FUNCTION_LOG_PARAM(EXEC, this);
    FUNCTION_LOG_END();

    ASSERT(this != NULL);

    // Create pipes to communicate with the subprocess.  The names of the pipes are from the perspective of the parent process since
    // the child process will use them only briefly before exec'ing.
    int pipeRead[2];
    int pipeWrite[2];
    int pipeError[2];

    THROW_ON_SYS_ERROR(pipe(pipeRead) == -1, KernelError, "unable to create read pipe");
    THROW_ON_SYS_ERROR(pipe(pipeWrite) == -1, KernelError, "unable to create write pipe");
    THROW_ON_SYS_ERROR(pipe(pipeError) == -1, KernelError, "unable to create error pipe");

    // Fork the subprocess
    this->processId = forkSafe();

    // Exec command in the child process
    if (this->processId == 0)
    {
        // Disable logging and close log file
        logClose();

        // Assign stdout to the input side of the read pipe
        PIPE_DUP2(pipeRead, 1, STDOUT_FILENO);

        // Assign stdin to the output side of the write pipe
        PIPE_DUP2(pipeWrite, 0, STDIN_FILENO);

        // Assign stderr to the input side of the error pipe
        PIPE_DUP2(pipeError, 1, STDERR_FILENO);

        // Execute the binary.  This statement will not return if it is successful
        execvp(strZ(this->command), (char ** const)strLstPtr(this->param));

        // If we got here then there was an error.  We can't use a throw as we normally would because we have already shutdown
        // logging and we don't want to execute exit paths that might free parent resources which we still have references to.
        fprintf(stderr, "unable to execute '%s': [%d] %s\n", strZ(this->command), errno, strerror(errno));
        exit(errorTypeCode(&ExecuteError));
    }

    // Close the unused file descriptors
    close(pipeRead[1]);
    close(pipeWrite[0]);
    close(pipeError[1]);

    // Store the file descriptors we'll use and need to close when the process terminates
    this->fdRead = pipeRead[0];
    this->fdWrite = pipeWrite[1];
    this->fdError = pipeError[0];

    // Assign file descriptors to io interfaces
    this->ioReadFd = ioFdReadNew(strNewFmt("%s read", strZ(this->name)), this->fdRead, this->timeout);
    this->ioWriteFd = ioFdWriteNewOpen(strNewFmt("%s write", strZ(this->name)), this->fdWrite, this->timeout);

    // Create wrapper interfaces that check process state
    this->pub.ioReadExec = ioReadNewP(this, .block = true, .read = execRead, .eof = execEof, .fd = execFdRead);
    ioReadOpen(execIoRead(this));
    this->pub.ioWriteExec = ioWriteNewP(this, .write = execWrite);
    ioWriteOpen(execIoWrite(this));

    // Set a callback so the file descriptors will get freed
    memContextCallbackSet(objMemContext(this), execFreeResource, this);

    FUNCTION_LOG_RETURN_VOID();
}


text:
package org.jetbrains.plugins.groovy.refactoring.inline;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.usageView.BaseUsageViewDescriptor;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils;
import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrClassInitializer;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrVariableDeclarationOwner;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction;
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ControlFlowBuilder;
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringBundle;
import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceHandlerBase;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.List;

/**
 * @author Max Medvedev
 */
public class GroovyInlineLocalProcessor extends BaseRefactoringProcessor {
  private static final Logger LOG = Logger.getInstance(GroovyInlineLocalProcessor.class);

  private final InlineLocalVarSettings mySettings;
  private final GrVariable myLocal;

  public GroovyInlineLocalProcessor(Project project, InlineLocalVarSettings settings, GrVariable local) {
    super(project);
    this.mySettings = settings;
    this.myLocal = local;
  }

  @NotNull
  @Override
  protected UsageViewDescriptor createUsageViewDescriptor(@NotNull UsageInfo[] usages) {
    return new BaseUsageViewDescriptor(myLocal);
  }

  @Override
  protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) {
    final MultiMap<PsiElement, String> conflicts = new MultiMap<>();
    final UsageInfo[] usages = refUsages.get();
    for (UsageInfo usage : usages) {
      collectConflicts(usage.getReference(), conflicts);
    }

    return showConflicts(conflicts, usages);
  }

  @Override
  protected boolean isPreviewUsages(@NotNull UsageInfo[] usages) {
    for (UsageInfo usage : usages) {
      if (usage instanceof ClosureUsage) return true;
    }
    return false;
  }

  private void collectConflicts(final PsiReference reference, final MultiMap<PsiElement, String> conflicts) {
    GrExpression expr = (GrExpression)reference.getElement();
    if (PsiUtil.isAccessedForWriting(expr)) {
      conflicts.putValue(expr, GroovyRefactoringBundle.message("variable.is.accessed.for.writing", myLocal.getName()));
    }
  }

  @NotNull
  @Override
  protected UsageInfo[] findUsages() {
    final Instruction[] controlFlow = mySettings.getFlow();
    final List<BitSet> writes = ControlFlowUtils.inferWriteAccessMap(controlFlow, myLocal);

    ArrayList<UsageInfo> toInline = new ArrayList<>();
    collectRefs(myLocal, controlFlow, writes, mySettings.getWriteInstructionNumber(), toInline);

    return toInline.toArray(new UsageInfo[toInline.size()]);
  }

  /**
   * ClosureUsage represents usage of local var inside closure
   */
  private static class ClosureUsage extends UsageInfo {
    private ClosureUsage(@NotNull PsiReference reference) {
      super(reference);
    }
  }

  private static void collectRefs(final GrVariable variable,
                                  Instruction[] flow,
                                  final List<BitSet> writes,
                                  final int writeInstructionNumber,
                                  final ArrayList<UsageInfo> toInline) {
    for (Instruction instruction : flow) {
      final PsiElement element = instruction.getElement();
      if (instruction instanceof ReadWriteVariableInstruction) {
        if (((ReadWriteVariableInstruction)instruction).isWrite()) continue;

        if (element instanceof GrVariable && element != variable) continue;
        if (!(element instanceof GrReferenceExpression)) continue;

        final GrReferenceExpression ref = (GrReferenceExpression)element;
        if (ref.isQualified() || ref.resolve() != variable) continue;

        final BitSet prev = writes.get(instruction.num());
        if (writeInstructionNumber >= 0 && prev.cardinality() == 1 && prev.get(writeInstructionNumber)) {
          toInline.add(new UsageInfo(ref));
        }
        else if (writeInstructionNumber == -1 && prev.cardinality() == 0) {
          toInline.add(new ClosureUsage(ref));
        }
      }
      else if (element instanceof GrClosableBlock) {
        final BitSet prev = writes.get(instruction.num());
        if (writeInstructionNumber >= 0 && prev.cardinality() == 1 && prev.get(writeInstructionNumber) ||
            writeInstructionNumber == -1 && prev.cardinality() == 0) {
          final Instruction[] closureFlow = ((GrClosableBlock)element).getControlFlow();
          collectRefs(variable, closureFlow, ControlFlowUtils.inferWriteAccessMap(closureFlow, variable), -1, toInline);
        }
      }
      else if (element instanceof GrAnonymousClassDefinition) {
        final BitSet prev = writes.get(instruction.num());
        if (writeInstructionNumber >= 0 && prev.cardinality() == 1 && prev.get(writeInstructionNumber) ||
            writeInstructionNumber == -1 && prev.cardinality() == 0) {
          ((GrAnonymousClassDefinition)element).acceptChildren(new GroovyRecursiveElementVisitor() {
            @Override
            public void visitField(@NotNull GrField field) {
              GrExpression initializer = field.getInitializerGroovy();
              if (initializer != null) {
                Instruction[] flow = new ControlFlowBuilder(field.getProject()).buildControlFlow(initializer);
                collectRefs(variable, flow, ControlFlowUtils.inferWriteAccessMap(flow, variable), -1, toInline);
              }
            }

            @Override
            public void visitMethod(@NotNull GrMethod method) {
              GrOpenBlock block = method.getBlock();
              if (block != null) {
                Instruction[] flow = block.getControlFlow();
                collectRefs(variable, flow, ControlFlowUtils.inferWriteAccessMap(flow, variable), -1, toInline);
              }
            }

            @Override
            public void visitClassInitializer(@NotNull GrClassInitializer initializer) {
              GrOpenBlock block = initializer.getBlock();
              Instruction[] flow = block.getControlFlow();
              collectRefs(variable, flow, ControlFlowUtils.inferWriteAccessMap(flow, variable), -1, toInline);
            }
          });
        }
      }
    }
  }

  @Override
  protected void performRefactoring(@NotNull UsageInfo[] usages) {
    CommonRefactoringUtil.sortDepthFirstRightLeftOrder(usages);

    final GrExpression initializer = mySettings.getInitializer();

    GrExpression initializerToUse = GrIntroduceHandlerBase.insertExplicitCastIfNeeded(myLocal, mySettings.getInitializer());

    for (UsageInfo usage : usages) {
      GrVariableInliner.inlineReference(usage, myLocal, initializerToUse);
    }

    final PsiElement initializerParent = initializer.getParent();

    if (initializerParent instanceof GrAssignmentExpression) {
      initializerParent.delete();
      return;
    }

    if (initializerParent instanceof GrVariable) {
      final Collection<PsiReference> all = ReferencesSearch.search(myLocal).findAll();
      if (!all.isEmpty()) {
        initializer.delete();
        return;
      }
    }

    final PsiElement owner = myLocal.getParent().getParent();
    if (owner instanceof GrVariableDeclarationOwner) {
      ((GrVariableDeclarationOwner)owner).removeVariable(myLocal);
    }
    else {
      myLocal.delete();
    }
  }

  @Override
  protected String getCommandName() {
    return RefactoringBundle.message("inline.command", myLocal.getName());
  }
}


text:
  1. install Node (v11.10.0 will work) on your machine or "N" or "nvm"
  2. run $(npm install) inside package.json folder
  3. run $(npm start) inside package.json folder
  4. gulp automaticaly watches for .scss changes and compiles children scss-files of scss-folder to css now
  5. Find a plugin for your code-editor to get use of .jsbeautifyrc as second instance for more rules that sass-lint-auto-fix doesn't support. (for vscode: "Beautify")

## Keep package versions up to date if possible. check with $(npm outdated) inside package.json folder


text:
package consulo.ui.web.internal;

import consulo.ui.ListBox;
import consulo.ui.model.ListModel;

import javax.annotation.Nonnull;

/**
 * @author VISTALL
 * @since 2019-02-19
 */
public class WebListBoxImpl<E> extends WebSingleListComponentBase<E, WebListBoxImpl.Vaadin<E>> implements ListBox<E> {
  public static class Vaadin<J> extends VaadinSingleListComponentBase<J> {
    @Override
    protected boolean needRenderNullValue() {
      return false;
    }
  }

  public WebListBoxImpl(ListModel<E> model) {
    super(model);
  }

  @Nonnull
  @Override
  public Vaadin<E> createVaadinComponent() {
    return new Vaadin<>();
  }
}


text:
#pragma once

#include "envoy/api/api.h"
#include "envoy/common/exception.h"
#include "envoy/common/optref.h"
#include "envoy/common/pure.h"
#include "envoy/config/subscription.h"
#include "envoy/config/typed_config.h"
#include "envoy/protobuf/message_validator.h"
#include "envoy/service/discovery/v3/discovery.pb.h"

#include "absl/container/flat_hash_set.h"
#include "absl/types/optional.h"

namespace Envoy {
namespace Config {

/*
 * An abstract class that represents an xDS source. The toKey() function provides a unique
 * identifier for the source for a group of xDS resources in a DiscoveryResponse.
 */
class XdsSourceId {
public:
  virtual ~XdsSourceId() = default;

  /**
   * Returns a unique string representation of the source. The string can be used as an identifier
   * for the source (e.g. as a key in a hash map).
   * @return string representation of the source.
   */
  virtual std::string toKey() const PURE;
};

/**
 * An interface for hooking into xDS resource fetch and update events.
 * Currently, this interface only supports the SotW (state-of-the-world) xDS protocol.
 *
 * Instances of this interface get invoked on the main Envoy thread. Thus, it is important for
 * implementations of this interface to not execute any blocking operations on the same thread.
 * Any blocking operations (e.g. flushing config to disk) should be handed off to a separate thread
 * so we don't block the main thread.
 */
class XdsResourcesDelegate {
public:
  virtual ~XdsResourcesDelegate() = default;

  /**
   * Returns a list of xDS resources for the given source and names. The implementation is not
   * required to return all (or any) of the requested resources, but the resources it does return
   * are required to be in the set of requested resources. An empty resource name set will return
   * all known resources from the given xDS source (i.e. the "wildcard").
   *
   * This function is intended to only be called on xDS fetch startup, and allows the
   * implementation to return a set of resources to be loaded and used by the Envoy instance
   * (e.g. persisted resources in local storage).
   *
   * @param source_id The xDS source for the requested resources.
   * @param resource_names The names of the requested resources.
   * @return A list of xDS resources for the given source.
   */
  virtual std::vector<envoy::service::discovery::v3::Resource>
  getResources(const XdsSourceId& source_id,
               const absl::flat_hash_set<std::string>& resource_names) const PURE;

  /**
   * Invoked when SotW xDS configuration updates have been received from an xDS authority, have been
   * applied on the Envoy instance, and are about to be ACK'ed.
   *
   * @param source_id The xDS source for the requested resources.
   * @param resources The resources for the given source received on the DiscoveryResponse.
   */
  virtual void onConfigUpdated(const XdsSourceId& source_id,
                               const std::vector<DecodedResourceRef>& resources) PURE;

  /**
   * Invoked when loading a resource obtained from the getResources() call resulted in a failure.
   * This would typically happen when there is a parsing or validation error on the xDS resource
   * protocol buffer.
   *
   * @param source_id The xDS source for the requested resource.
   * @param resource_name The name of the resource.
   * @param exception The exception that occurred, if any.
   */
  virtual void onResourceLoadFailed(const XdsSourceId& source_id, const std::string& resource_name,
                                    const absl::optional<EnvoyException>& exception) PURE;
};

using XdsResourcesDelegatePtr = std::unique_ptr<XdsResourcesDelegate>;
using XdsResourcesDelegateOptRef = OptRef<XdsResourcesDelegate>;

/**
 * A factory abstract class for creating instances of XdsResourcesDelegate.
 */
class XdsResourcesDelegateFactory : public Config::TypedFactory {
public:
  ~XdsResourcesDelegateFactory() override = default;

  /**
   * Creates a XdsResourcesDelegate using the given configuration.
   * @param config Configuration of the XdsResourcesDelegate to create.
   * @param validation_visitor Validates the configuration.
   * @param api The APIs that can be used by the delegate.
   * @param dispatcher The dispatcher for the thread.
   * @return The created XdsResourcesDelegate instance
   */
  virtual XdsResourcesDelegatePtr
  createXdsResourcesDelegate(const ProtobufWkt::Any& config,
                             ProtobufMessage::ValidationVisitor& validation_visitor, Api::Api& api,
                             Event::Dispatcher& dispatcher) PURE;

  std::string category() const override { return "envoy.xds_delegates"; }
};

} // namespace Config
} // namespace Envoy


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.util;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

/**
 * Non thread safe version of {@link UserDataHolderBase}.
 */
public class UnprotectedUserDataHolder implements UserDataHolder, UserDataHolderUnprotected {

  private Map<Key, Object> myUserData;

  @Nullable
  @Override
  public <T> T getUserData(@NotNull Key<T> key) {
    //noinspection unchecked
    T value = myUserData != null ? (T)myUserData.get(key) : null;
    if (value == null && key instanceof KeyWithDefaultValue) {
      value = ((KeyWithDefaultValue<T>)key).getDefaultValue();
      putUserData(key, value);
    }
    return value;
  }

  @Override
  public <T> void putUserData(@NotNull Key<T> key, @Nullable T value) {
    if (myUserData == null) myUserData = new HashMap<>();
    myUserData.put(key, value);
  }

  @Nullable
  @Override
  public <T> T getUserDataUnprotected(@NotNull Key<T> key) {
    return getUserData(key);
  }

  @Override
  public <T> void putUserDataUnprotected(@NotNull Key<T> key, @Nullable T value) {
    putUserData(key, value);
  }
}


text:
layout: post
title: "Records - Antiga Nova Tecnologia"
date: 2018-10-22
permalink: /:title
description:
  O tipo Record pode ter métodos e até mesmo campos privados. Seria isso considerado uma abominação para um código Orientado a Objetos?
image: /images/2018/alvaro-reyes-517391-unsplash.jpg
tags:
  - Object Pascal
keywords:
  - freepascal
  - fpc
  - delphi
  - lazarus
  - pascal
  - object pascal
  - object-oriented
  - oop
  - mdbs99
  - records
---

O tipo Record pode ter métodos e até mesmo campos privados. Seria isso considerado uma abominação para um código Orientado a Objetos?

![Unsplash image]({{ page.image }})

Photo by Alvaro Reyes on Unsplash

Na programação Orientada a Objetos, utilizamos objetos.

Se você precisasse de um objeto para representar os *dados* de um usuário, apenas login, password e nome, como seria a definição da classe?

Vamos tentar:

    TUserData = class
    private
      fLogin: string;
      fPassword: string;
      fName: string;
    public
      property Login: string read fLogin write fLogin;
      property Password: string read fPassword write fPassword;
      property Name: string read fName write fName;
    end;

Esse seria um estilo de implementação que podemos ver em muitos sistemas que se dizem ser Orientados a Objetos.

No entanto, essa classe irá gerar "objetos" que são mais conhecidos como DTO (Data Transfer Object) o que, por definição, é um conceito errado.

Objetos não são ["baldes de dados"]({% post_url 2015-12-29-o-que-e-orientacao-a-objetos %}#objeto-nao-e-um-balde-de-funcoes-e-dados).

Objetos verdadeiros possuem comportamento e [encapsulam]({% post_url 2018-04-16-encapsulamento %}) dados e/ou outros objetos em seu interior. O que está encapsulado não deveria ser visível ou acessado diretamente por outro objeto externo.

Essa é a *teoria*.

Mas, e se no contexto do seu sistema você realmente não necessitasse de nenhum método para representar os dados de um usuário?

Por muito tempo eu tenho utilizado objetos para tudo, até mesmo para representar dados, mas sem utilizar objetos anêmicos como esse, no entanto.

Para representar os dados acima, eu utilizaria a técnica do [Método About()]({% post_url 2016-11-14-diga-me-algo-sobre-voce %}#metodo-about), que iria retornar um XML ou JSON, conforme explicado em 2016...

Há vantagens nessa técnica como ter uma única interface que qualquer classe possa implementar para retornar um XML/JSON. Mas também há desvantagens, como não haver checagem estática do compilador e o *overhead* em "montar/desmontar" o *stream* se houver a necessidade de repassar a informação por uma cadeia de objetos.

Nesses ~2 anos, eu diria que muita coisa mudou.

Estou trabalhando em alguns projetos que necessitam de extrema velocidade de processamento, mas nem por isso eles são menos Orientados a Objetos.

Como?

Redescobrindo o tipo Record.

Mas antes eu quero lhe contar por quê eu neglicenciei os Records por muito tempo.

Bem, Records existem desde o Turbo Pascal. Eles representam uma estrutura de dados. Você define uma estrutura e depois define *procedures* e *functions* para trabalhar com as estruturas — como ainda fazemos na linguagem C.

Na Orientação a Objetos, nós unimos comportamento aos dados num único artefato chamado objeto.

Então, a ideia de ter um Record com todos os seus dados públicos e funções "soltas" que o utilizam, implementadas muitas vezes em Unidades diferentes, me soa muito "anti-objeto", muito anti-encapsulamento.

Records, dessa forma, são estruturas para programas procedurais.

Mas, já faz uns anos que os arquitetos da linguagem Object Pascal introduziram métodos em Records.

Sim, métodos, em Records.

Quando eu li isso pela primeira vez, achei que os arquitetos tinham ficado loucos. Métodos em Records? Qual o sentido? Já temos objetos, não precisamos de Records com métodos. Isso não faz o menor sentido! — eu pensava.

Entretanto, hoje em dia, Records podem ter métodos e eles podem ser até mesmo privados, assim como ter *fields* privados!

Ora, não é isso um objeto?

Não.

Então, não seria melhor utilizar um objeto?

Depende.

Records são estruturas de dados — mesmo que eles tenham métodos — e deveria ser utilizados como tal.

Records são alocados automaticamente pelo compilador na área de memória *stack*, ao invés da área de memória *heap*, como fazem os objetos. Utilizar o *stack* é mais rápido e mais simples para o compilador gerenciar a memória.

Então, se você necessita representar *apenas* dados, Record é a melhor opção.

Records não podem utilizar herança e muito menos implementar uma interface, então não há polimorfismo — lembre-se, são apenas dados.

Então, se você necessita de polimorfismo e comportamento, objeto é a melhor opção.

Dito isso, por quê métodos em Records pode mudar a maneira em como utilizamos Records em programas Orientados a Objetos?

Quando declaramos um Record, seus campos não são inicializados, como acontece com os atributos de um objeto. Então, podemos definir um método para iniciá-lo, sem ter que fazer isso externamente — mesmo que seus campos sejam públicos — encapsulando a inicialização dos campos na própria estrutura de dados:

    TUserData = record
      login: string;
      password: string;
      name: string;
      procedure Init;
    end;

    procedure TUserData.Init;
    begin
      login := '';
      password := '';
      name := '';
    end;

    var
      u: TUserData;
    begin
      u.Init;
    end;

Outra opção é utilizar a função [Default()](https://www.freepascal.org/docs-html/rtl/system/default.html) mas o importante é que você tem a opção de fazer o que quiser no procedimento que será como um construtor:

    procedure TUserData.Init;
    begin
      Default(self);
    end;

Se o *password* precisar ser criptografado/descriptografado, você não precisa de funções externas para isso:

    function TUserData.EncryptedPassword: string;
    begin
      result := '<using some algorithm to encrypt>';
    end;

    function TUserData.DecryptedPassword: string;
    begin
      result := '<using some algorithm to decrypt>';
    end;

Existem algumas regras a seguir:

1. Não implemente métodos que se comportem como objetos, ou seja, trabalhe *apenas* com os dados do Record, transformando-os;
1. Não retorne instâncias de objetos em seus métodos, com exceção de instâncias de interfaces, mas evite a todo custo;
1. Só utilize campos com tipos primitivos ou gerenciados (ex: strings, Variant, etc), nunca instâncias de objetos;

Faça isso e você estará seguro.

Seu código não será considerado menos Orientado a Objetos por estar utilizando estruturas de dados que representam dados. Records foram criados exatamente para isso e a implementação de métodos apenas facilitaram seu uso.

Até logo.


text:
using System;
using System.Data;
using System.Diagnostics;
using FluidDbClient.Sql;

namespace FluidDbClient.Sandbox.Demos.ScriptCompilation
{
    public static class DemoScriptCompilationSimple
    {
        /*------------------------------------------------------------------------------------------------
            The script below is obviously not SQL.
            The point is to show how DbScriptCompiler works to build a dynamically parameterized script.

            The type parameter <TDatabase> can be dropped if targeting the default database.

            The resultant DbScriptDocument object can be applied to a query or command like this:

            DbManagedQuery.IncludeScriptDoc(doc);
            DbManagedCommand.IncludeScriptDoc(doc);

        --------------------------------------------------------------------------------------------------*/
        public static void Start()
        {
            var doc =
                new DbScriptCompiler<AcmeDb>()
                .Append("This is a parameter: {0}.", "Hello")
                .Append("Here are two more parameters: {0} and {1}.", DateTime.Now, true)
                .Append("This is a literal: {{0}}.", Guid.NewGuid())
                .Append("Here's a combination: {0} with some {{1}}, add a little {2} and a touch of {{3}}.", 5, 10.6, "Wow", "Ain't it nice")
                .Append("Notice how the db provider is consulted so that parameter prefixes and literal values are as they should be!")
                .Append("Need some comma-separated parameters? Here ya go: {0}", new { name1 = "Thing1", name2 = "Thing2" })
                .Append("Watch DBNulls appear before your eyes: {0} {1}", null, null)
                .Append("Just make sure not to send in a null as a single parameter. That won't compute!")
                .Append("But (with Sql Provider) you can do this: {0}. No value specified = DBNull;", new SqlParamDef(SqlDbType.Date))
                .Compile();

            Debug.WriteLine(doc.Text);

            foreach (var p in doc.Parameters)
            {
                Debug.WriteLine(DbRegistry.GetDatabase<AcmeDb>().Provider.Interpreter.GetDiagnosticString(p));
            }
        }
    }
}


text:
layout: single
author_profile: false
author: mark
title: "Submit Your Bach Bracket Picks"
permalink: /bachelor-submit-s18/
---

		Drag the contestants in the order you think they will be told "thanks but no thanks".

Top of the list = contestant who makes it to the end

Bottom of the list = contestant you think will go home first

		Good luck!

($10 USD / entry. Entries are due no later than Monday Jan 8 @ 8PM PST/EST)

	<form id="bracket-form">

💍 Winner

	    	Annaliese (32, California, Event Designer)

	    	Ashley (25, Florida, Realtor)

	    	Becca K. (27, Minnesota, Publicist)

	    	Bekah M. (Age Unknown, California, Nanny)

	    	Bibiana (30, Florida, Exec Assistant)

	    	Brittany T. (30, South Carolina, Tech Recruiter)

	    	Caroline (26, Massachusetts, Realtor)

	    	Chelsea (29, Maine, Exec Assistant)

	    	Jacqueline (26, West Virginia, Research Coordinator)

	    	Jenna (28, Indiana, Social Media Manager)

	    	Jenny (25, Illinois, Graphic Designer)

	    	Kendall (26, California, Creative Designer)

	    	Krystal (30, Montana, Fitness Coach)

	    	Lauren B. (25, Virginia, Tech Salesperson)

	    	Lauren G. (26, Indiana, Exec Recruiter)

	    	Lauren S. (31, Texas, Social Media Manager)

	    	Maquel
(23, Utah, Photographer)

	    	Marikh
(27, Utah, Restaurant Owner)

	    	Seinne
(27, California, Realtor)

	    	Tia
(26, Arkansas, Physical Therapist)

	    	Valerie
(25, Tennessee, Server)

😢 First to go home

		Your Name
		<input id="name" name="name" type="text" value=""/>

		Your Email
		<input id="email" name="email" type="text" value=""/>

	<input id="ranking" name="ranking" type="hidden" value=""/>

	<input class="btn-primary" type="submit" value="SUBMIT PICKS"/>

This is it

	</form>

  {% include form-drag-sort.html %}

  {% include gsheet.html %}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="トップエスイー">
    <link rel="shortcut icon" href="../images/logo.png" type="image/png">
    <link rel="icon" href="../images/logo.png" type="image/png">
    <title>トップ エスイー</title>
    <link rel="stylesheet" href="../lib/css/bootstrap-sandstone.min.css" media="screen">
    <link rel="stylesheet" href="../lib/css/style.css" media="screen">

        If you see this, (1)the page is generating now, or (2)your browser has any issues.
        In case of (1), the page is going to show just for a while.
        If you see this in a long period, it might be (2) and you must use any supported web browser with Javascript
        enabled.

        この表示が見えている場合,(1)ページ生成中であるか,(2)Webブラウザーに問題があります.
        (1)の場合はしらばく待つとページが表示されます.長時間表示されていれば(2)の可能性が高く,
        その場合は対応ブラウザーを使用しJavaScriptを有効にした上でお使い下さい.

講師一覧(2022年度)

                    プロフィール

担当講義:

所属・役職:

研究分野:

ひとこと:


text:
/* Extras modul */
var extras = function (tools) {
  /* Private methods */

  /* Public API */
  return {
    // Retrieve information about current command rate
    rate: function () {
      return tools._wrapper(function (callback) {
        tools._head('images', function (err, data) {
          if (err) return callback(err)
          callback(null, {'ratelimit-limit': data['ratelimit-limit'],
                          'ratelimit-remaining': data['ratelimit-remaining'],
                          'ratelimit-reset': data['ratelimit-reset']})
        })
      })
    }
  }
}

module.exports = extras


text:
<?xml version="1.0" encoding="utf-8"?>
<migration name="Add rhodes grass">
  <item-creation item="varieties#chloris" parent="poaceae"/>
  <item-creation item="varieties#chloris_gayana" parent="chloris" itis_tsn="41565"/>
</migration>


text:
/*
 * Translated default messages for bootstrap-select.
 * Locale: IT (Italian; italiano)
 * Region: IT (Italy; Italia)
 * Author: Michele Beltrame <mb@cattlegrid.info>
 */
(function ($) {
  $.fn.selectpicker.defaults = {
    noneSelectedText: 'Nessuna selezione',
    noneResultsText: 'Nessun risultato per {0}',
    countSelectedText: 'Selezionati {0} di {1}',
    maxOptionsText: ['Limite raggiunto ({n} {var} max)', 'Limite del gruppo raggiunto ({n} {var} max)', ['elementi', 'elemento']],
    multipleSeparator: ', '
  };
})(jQuery);


text:
package com.gilt.handlebars.scala.binding

trait BindingFactory[T] {
  def apply(model: T): Binding[T]
  def bindPrimitive(s: String): Binding[T]
  def bindPrimitive(s: Int): Binding[T]
  def bindPrimitive(s: Boolean): Binding[T]
  def bindPrimitiveDynamic(v: Any) = {
    v match {
      case i: Int => bindPrimitive(i)
      case b: Boolean => bindPrimitive(b)
      case s => bindPrimitive(s.toString)
    }
  }
}


text:
__author__ = "Timothy McFadden"
__date__ = "06/02/2015"
__copyright__ = "Timothy McFadden, 2015"
__license__ = "MIT"
"""
This is the unit test for storcli-check.py
"""
import os
import sys
import logging
import zipfile
import tempfile
import unittest

THIS_DIR = os.path.abspath(os.path.dirname(__file__))
DATA_DIR = os.path.join(THIS_DIR, "data")

sys.path.insert(0, os.path.abspath(os.path.join(THIS_DIR, '..', 'src')))
import storcli_check

class TestMain(unittest.TestCase):
    def setUp(self):
        self.logger = storcli_check.get_logger()
        self.logger.setLevel(logging.CRITICAL)

    def test_find_storcli(self):
        if "win" in sys.platform:
            fh = open("storcli.exe", "wb")
            fh.close()
            fh = open("storcli64.exe", "wb")
            fh.close()

            self.assertTrue("storcli" in storcli_check.find_storcli(self.logger))
            os.unlink("storcli.exe")
            os.unlink("storcli64.exe")
        else:
            self.assertTrue(storcli_check.find_storcli(self.logger))

        self.assertRaises(Exception, storcli_check.find_storcli, self.logger, ["storcli-doesnt-exist"])

    def test_get_logger(self):
        l = storcli_check.get_logger(logfile_path="tmplog.txt", logfile_mode="wb")
        l.debug("testing")
        logging.shutdown()

        self.assertTrue(os.path.exists("tmplog.txt"))
        os.unlink("tmplog.txt")

    def test_flush_logfile(self):
        storcli_check.get_logger(logfile_path="tmplog.txt", logfile_mode="wb")
        storcli_check.flush_logfile(self.logger)

    def test_remove_directory(self):
        newdir = tempfile.mkdtemp()
        subdir = os.path.join(newdir, "test-dir")
        os.makedirs(subdir)

        files = [os.path.join(x, "test.txt") for x in [newdir, subdir]]

        for file_ in files:
            fh = open(file_, "wb")
            fh.close()

        self.assertTrue(os.path.isdir(newdir))
        self.assertTrue(os.path.isdir(subdir))

        for file_ in files:
            self.assertTrue(os.path.isfile(file_))

        storcli_check.remove_directory(newdir)

        self.assertFalse(os.path.isdir(newdir))
        self.assertFalse(os.path.isdir(subdir))

        for file_ in files:
            self.assertFalse(os.path.isfile(file_))

    def test_zip(self):
        newdir = tempfile.mkdtemp()
        subdir = os.path.join(newdir, "test-dir")
        os.makedirs(subdir)

        files = [os.path.join(x, "test.txt") for x in [newdir, subdir]]

        for file_ in files:
            fh = open(file_, "wb")
            fh.close()

        zip_dest_dir = tempfile.mkdtemp()
        zip_dest = os.path.join(zip_dest_dir, "test.zip")

        fd, other_file = tempfile.mkstemp(dir=zip_dest_dir)
        os.close(fd)
        os.rename(other_file, other_file + "-test.txt")
        other_file += "-test.txt"

        storcli_check.zip([newdir, other_file], zip_dest)

        self.assertTrue(os.path.isfile(zip_dest))

        zf = zipfile.ZipFile(zip_dest, 'r')
        zipped_files = zf.infolist()
        zf.close()

        self.assertTrue(len(zipped_files) == 3)
        self.assertTrue(zipped_files[0].filename.endswith("test.txt"))
        self.assertTrue(zipped_files[1].filename.endswith("test.txt"))
        self.assertTrue(zipped_files[2].filename.endswith("test.txt"))

        storcli_check.remove_directory(newdir)
        storcli_check.remove_directory(zip_dest_dir)

    def test_sendmail(self):
        newdir = tempfile.mkdtemp()
        filename = os.path.join(newdir, "test.txt")
        fh = open(filename, "wb")
        fh.write("Hello, World!\n")
        fh.close()

        # This should raise an exception since the mailserver doesn't really exist
        self.assertRaises(
            Exception, storcli_check.sendmail,
            subject="test", to="nobody@example.com,nobody@example.com",
            sender="me@nowhere.com", body="Hello, World!",
            mailserver="mailhost@asdf123.net",
            attachments=[filename],
            cc="nobody@example.com,nobody@example.com")

        # Cover the case were cc is empty (branch coverage)
        self.assertRaises(
            Exception, storcli_check.sendmail,
            subject="test", to="nobody@example.com,nobody@example.com",
            sender="me@nowhere.com", body="Hello, World!",
            mailserver="mailhost@asdf123.net",
            attachments=[filename],
            cc=None)
        storcli_check.remove_directory(newdir)

    def test_parse_arumgnents(self):
        parser_ = storcli_check.init_parser()

        self.assertRaises(SystemExit, storcli_check.parse_arguments, parser_, self.logger, ["--af346tg"])

        args = ["--mailto", "test@example.com", "--mailserver", "mailhost.example.com"]
        (options, args) = storcli_check.parse_arguments(parser_, self.logger, args)
        self.assertTrue(len(args) == 0)
        self.assertTrue(options.mailto == "test@example.com")
        self.assertTrue(options.mailserver == "mailhost.example.com")
        self.assertTrue(options.attachments)

        args = ["--no-attachments"]
        (options, args) = storcli_check.parse_arguments(parser_, self.logger, args)
        self.assertFalse(options.attachments)

if __name__ == '__main__':
    unittest.main()


text:
using System;

namespace Platform.Events.EventsGameRelated
{
    public class GameLoadedEventArgs
    {
        public Byte[] GameBytes { get; set; }
    }
}


text:
package org.kohsuke.stapler.beanutils;

import org.apache.commons.jelly.DynaTag;
import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.jelly.MissingAttributeException;
import org.apache.commons.jelly.TagSupport;
import org.apache.commons.jelly.XMLOutput;
import org.xml.sax.SAXException;

public class DynaTagWithStringProperty extends TagSupport implements DynaTag {
    private String clazz;

    public void setClass(String clazz) {
        this.clazz = clazz;
    }

    @Override
    public void doTag(XMLOutput output) throws MissingAttributeException, JellyTagException {
        try {
            output.writeComment("Tag with string property\n");
            output.writeCDATA(getClass().getName() + ":" + clazz);
        } catch (SAXException e) {
            // ignore
        }
        invokeBody(output);
    }

    @Override
    public void setAttribute(String name, Object value) throws JellyTagException {
        if ("class".equals(name)) {
            this.setClass((String) value);
        }
    }

    @Override
    public Class getAttributeType(String name) throws JellyTagException {
        if ("class".equals(name)) {
            return String.class;
        }
        return null;
    }
}


text:
package ru.r2cloud.jradio.is1;

public enum UhfFeedback {

	N(0), B(1), T(2), UNKNOWN(255);

	private final int code;

	private UhfFeedback(int code) {
		this.code = code;
	}

	public static UhfFeedback valueOfCode(int code) {
		for (UhfFeedback cur : values()) {
			if (cur.code == code) {
				return cur;
			}
		}
		return UNKNOWN;
	}
}


text:
require File.expand_path(File.join(File.dirname(__FILE__), "spec_helper"))
require 'java' if RUBY_PLATFORM =~ /java/

describe "Managed Struct" do
  include FFI
  module ManagedStructTestLib
    extend FFI::Library
    ffi_lib TestLibrary::PATH
    attach_function :ptr_from_address, [ FFI::Platform::ADDRESS_SIZE == 32 ? :uint : :ulong_long ], :pointer
  end
  it "should raise an error if release() is not defined" do
    class NoRelease < FFI::ManagedStruct ; layout :i, :int; end
    lambda { NoRelease.new(ManagedStructTestLib.ptr_from_address(0x12345678)) }.should raise_error(NoMethodError)
  end

  it "should be the right class" do
    class WhatClassAmI < FFI::ManagedStruct
      layout :i, :int
      def self.release
      end
    end

    WhatClassAmI.new(ManagedStructTestLib.ptr_from_address(0x12345678)).class.should eq WhatClassAmI
  end

  it "should release memory properly" do
    class PleaseReleaseMe < FFI::ManagedStruct
      layout :i, :int
      @@count = 0
      def self.release
        @@count += 1
      end
      def self.wait_gc(count)
        loop = 5
        while loop > 0 && @@count < count
          loop -= 1
          if RUBY_PLATFORM =~ /java/
            java.lang.System.gc
          else
            GC.start
          end
          sleep 0.05 if @@count < count
        end
      end
    end

    loop_count = 30
    wiggle_room = 5

    PleaseReleaseMe.should_receive(:release).at_least(loop_count-wiggle_room).times
    loop_count.times do
      PleaseReleaseMe.new(ManagedStructTestLib.ptr_from_address(0x12345678))
    end
    PleaseReleaseMe.wait_gc loop_count
  end
end


text:
require 'spec_helper'

describe 'Indenting strings' do
  it "bulk indenting strings" do
    expect(<<~EOF).to be_elixir_indentation
    defp sql do
      """
      SELECT *
        FROM table
       WHERE column = 123
         AND another_column = 456
      """
    end
    EOF
  end
end


text:
package travel.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.social.twitter.api.Twitter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;

@Controller
public class HelloController {

    private UsersConnectionRepository usersConnectionRepository;

    @Autowired
    public HelloController(UsersConnectionRepository usersConnectionRepository)
    {
        this.usersConnectionRepository=usersConnectionRepository;
    }

    @RequestMapping("/")
    public String index() {
        if( SecurityContextHolder.getContext().getAuthentication() != null &&
            SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
            //when Anonymous Authentication is enabled
            !(SecurityContextHolder.getContext().getAuthentication()
                instanceof AnonymousAuthenticationToken) )
        {
          return "redirect:/user/home/";

        }
        return "index";
    }

    @RequestMapping("/ownerror")
    public String error() {

        return "error";
    }
}


text:
_AdMob currently supports these three types of Ads, as does this plugin_

## Enabling AdMob

### Android
> ⚠ Important! Plugin version 7.4.0+ requires you to do this - or your app will crash on start-up! ⚠

Open your App_Resources/Android/AndroidManifest.xml file and add this `meta-data` line at [the right spot](https://github.com/EddyVerbruggen/nativescript-plugin-firebase/blob/3fe3f6b4b9d1b83b048b10472bec923f64e08c75/demo/app_resources/Android/src/main/AndroidManifest.xml#L28-L30) (and replace the value by the actual App ID of [your app](https://apps.admob.com/)!):

```xml
<application>
  <!-- this line needs to be added (replace the value!) -->
  <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-3940256099942544~3347511713" />

  <activity></activity>
</application>
```

### iOS

> ⚠ Important! Plugin version 8.2.0+ requires you to do this - or your app will crash on start-up! ⚠

As can be read [here](https://developers.google.com/admob/ios/quick-start#update_your_infoplist) you should open your
App_Resources/iOS/Info.plist file and add this `GADApplicationIdentifier` key and replace the value by the actual App ID of [your app](https://apps.admob.com/)!:

```xml
  <key>GADApplicationIdentifier</key>
  <string>ca-app-pub-9517346003011652~2508636525</string>
```

#### App Transport Security
Open `app/App_Resources/iOS/Info.plist` and add this to the bottom:

```xml
<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
  <key>NSAllowsArbitraryLoadsForMedia</key>
  <true/>
  <key>NSAllowsArbitraryLoadsInWebContent</key>
  <true/>
</dict>
```

[More info on this subject.](https://firebase.google.com/docs/admob/ios/app-transport-security)

## Functions
> Note that it may take up to 24 hours after adding an Ad to your [AdMob console](https://apps.admob.com) before it's available for your app. Until then you'll see a ⚠ warning about an unknown Ad ID.

### admob.showBanner
Go [manage your AdMob app](https://apps.admob.com) and grab the banner, then show it in your app:

```js
  firebase.admob.showBanner({
    size: firebase.admob.AD_SIZE.SMART_BANNER, // see firebase.admob.AD_SIZE for all options
    margins: { // optional nr of device independent pixels from the top or bottom (don't set both)
      bottom: 10,
      top: -1
    },
    androidBannerId: "ca-app-pub-9517346003011652/7749101329",
    iosBannerId: "ca-app-pub-9517346003011652/3985369721",
    testing: true, // when not running in production set this to true, Google doesn't like it any other way
    iosTestDeviceIds: [ //Android automatically adds the connected device as test device with testing:true, iOS does not
        "45d77bf513dfabc2949ba053da83c0c7b7e87715", // Eddy's iPhone 6s
        "fee4cf319a242eab4701543e4c16db89c722731f"  // Eddy's iPad Pro
    ],
    keywords: ["keyword1", "keyword2"], // add keywords for ad targeting
    onOpened: () => console.log("Ad opened"),
    onClicked: () => console.log("Ad clicked"),
    onLeftApplication: () => console.log("Ad left application")
  }).then(
      function () {
        console.log("AdMob banner showing");
      },
      function (errorMessage) {
        dialogs.alert({
          title: "AdMob error",
          message: errorMessage,
          okButtonText: "Hmmkay"
        });
      }
  );
```

### admob.hideBanner
Easy peasy:

```js
  firebase.admob.hideBanner().then(
      function () {
        console.log("AdMob banner hidden");
      },
      function (errorMessage) {
        dialogs.alert({
          title: "AdMob error",
          message: errorMessage,
          okButtonText: "Hmmkay"
        });
      }
  );
```

### admob.showInterstitial
This is a fullscreen ad, so you can earn extra credit on the eternal ladder of annoyance.

Note that an interstitial is supposed to be hidden by clicking the close button, so there's no function to do it programmatically.

If you want to get notified when an interstitial is closed, provide an `onAdClosed` callback as shown below.

There's two ways how you can use this function:

* **RECOMMENDED**: without arguments, and after the Promise of `preloadInterstitial` resolves. This will show the interstitial immediately.
* **DEPRECATED**: with arguments (same as `preloadInterstitial`). This will preload and *then* show the interstitial, so a delay will be noticable by the user, which is against Google's policies.

```js
  firebase.admob.preloadInterstitial({
    iosInterstitialId: "ca-app-pub-9517346003011652/6938836122",
    androidInterstitialId: "ca-app-pub-9517346003011652/6938836122",
    testing: true, // when not running in production set this to true, Google doesn't like it any other way
    iosTestDeviceIds: [ // Android automatically adds the connected device as test device with testing:true, iOS does not
        "45d77bf513dfabc2949ba053da83c0c7b7e87715", // Eddy's iPhone 6s
        "fee4cf319a242eab4701543e4c16db89c722731f"  // Eddy's iPad Pro
    ],
    onClosed: () => console.log("Interstitial closed"),
    onClicked: () => console.log("Interstitial clicked"),
    onOpened: () => console.log("Interstitial opened"),
    onLeftApplication: () => console.log("Interstitial left application")
  }).then(
      function () {
        console.log("AdMob interstitial preloaded, you can now call 'showInterstitial' at any time to show it without delay.");
      },
      function (errorMessage) {
        dialogs.alert({
          title: "AdMob error",
          message: errorMessage,
          okButtonText: "Hmmkay"
        });
      }
  );
```

After the preload Promise resolved successfully, you can show the interstitial at any time you want:

```js
  firebase.admob.showInterstitial().then(
      function () {
        console.log("AdMob interstitial showing.");
      },
      function (errorMessage) {
        dialogs.alert({
          title: "AdMob error",
          message: errorMessage,
          okButtonText: "Hmmkay"
        });
      }
  );
```

### preloadRewardedVideoAd
Use this for instance while loading your view, so it's ready for the moment you want to actually show it (by calling `showRewardedVideoAd`).

```js
firebase.admob.preloadRewardedVideoAd({
    testing: true,
    iosAdPlacementId: "ca-app-pub-XXXXXX/YYYYY2", // add your own
    androidAdPlacementId: "ca-app-pub-AAAAAAAA/BBBBBB2", // add your own
    keywords: ["keyword1", "keyword2"], // add keywords for ad targeting
  }).then(
      function() {
        console.log("RewardedVideoAd preloaded - you can now call 'showRewardedVideoAd' whenever you're ready to do so");
      },
      function(error) {
        console.log("admob preloadRewardedVideoAd error: " + error);
      }
)
```

### showRewardedVideoAd
At any moment after `preloadRewardedVideoAd` successfully resolves, you can call `showRewardedVideoAd`.

Note that when you want to use `showRewardedVideoAd` again, you also have to use `preloadRewardedVideoAd` again because those ads can't be reused.

`onRewarded` is probably the only callback you need to worry about.

```js
firebase.admob.showRewardedVideoAd({
  onRewarded: (reward) => {
    // the properties 'amount' and 'type' correlate to the values set at https://apps.admob.com
    console.log("onRewarded called with amount " + reward.amount);
    console.log("onRewarded called with type " + reward.type);
  },
  onOpened: () => console.log("onOpened"),
  onClosed: () => console.log("onClosed"),
  onStarted: () => console.log("onStarted"),
  onCompleted: () => console.log("onCompleted"),
  onLeftApplication: () => console.log("onLeftApplication")
}).then(
      function() {
        console.log("RewardedVideoAd showing");
      },
      function(error) {
        console.log("showRewardedVideoAd error: " + error);
      }
)
```

## What about the nativescript-admob plugin?
There's no functional difference between the AdMob features in the Firebase plugin and
[nativescript-admob](https://github.com/EddyVerbruggen/nativescript-admob).

The main advantage of using the version in the Firebase plugin is to avoid a gradle build conflict
in the Android build you may encounter when including both plugins in your app.


text:
import { MigrationInterface, QueryRunner } from "typeorm"

export class RemoveStarredCharts1646815966637 implements MigrationInterface {
    name = "RemoveStarredCharts1646815966637"

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`ALTER TABLE charts DROP COLUMN starred;`)
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(
            `ALTER TABLE charts ADD starred TINYINT NOT NULL;`
        )
    }
}