text:
package facade

import (
	"github.com/control-center/serviced/domain/addressassignment"
	"github.com/control-center/serviced/domain/host"
	"github.com/control-center/serviced/domain/pool"
	"github.com/control-center/serviced/domain/service"
	"github.com/control-center/serviced/domain/servicedefinition"
	. "gopkg.in/check.v1"
)

func (ft *FacadeIntegrationTest) TestGetServiceAddressAssignmentDetails(c *C) {
	// add a pool
	p := &pool.ResourcePool{
		ID: "poolid",
	}
	c.Assert(ft.Facade.AddResourcePool(ft.CTX, p), IsNil)

	// add a host
	h := &host.Host{
		ID:      "deadb11f",
		PoolID:  "poolid",
		Name:    "h1",
		IPAddr:  "12.27.36.45",
		RPCPort: 65535,
		IPs: []host.HostIPResource{
			{
				HostID:    "deadb11f",
				IPAddress: "12.27.36.45",
			},
		},
	}
	_, err := ft.Facade.AddHost(ft.CTX, h)
	c.Assert(err, IsNil)

	// add a service with an address assignment
	svcA := service.Service{
		ID:           "serviceid1",
		Name:         "svcA",
		DeploymentID: "depid",
		PoolID:       "poolid",
		Launch:       "auto",
		DesiredState: 0,
		Endpoints: []service.ServiceEndpoint{
			{
				Name:        "ep1",
				Application: "ep1",
				Purpose:     "export",
				Protocol:    "tcp",
				PortNumber:  1234,
				AddressConfig: servicedefinition.AddressResourceConfig{
					Port:     1234,
					Protocol: "tcp",
				},
			},
		},
	}
	c.Assert(ft.Facade.AddService(ft.CTX, svcA), IsNil)

	// add two child services, with and without address assignments
	svcB := service.Service{
		ID:              "serviceid2",
		Name:            "svcB",
		ParentServiceID: "serviceid1",
		DeploymentID:    "depid",
		PoolID:          "poolid",
		Launch:          "auto",
		DesiredState:    0,
		Endpoints: []service.ServiceEndpoint{
			{
				Name:        "ep2a",
				Application: "ep2a",
				Purpose:     "export",
				Protocol:    "tcp",
				PortNumber:  2123,
				AddressConfig: servicedefinition.AddressResourceConfig{
					Port:     2123,
					Protocol: "tcp",
				},
			},
			{
				Name:        "ep2b",
				Application: "ep2b",
				Purpose:     "export",
				Protocol:    "tcp",
				PortNumber:  2124,
				AddressConfig: servicedefinition.AddressResourceConfig{
					Port:     2124,
					Protocol: "tcp",
				},
			},
		},
	}
	c.Assert(ft.Facade.AddService(ft.CTX, svcB), IsNil)

	svcC := service.Service{
		ID:              "serviceid3",
		Name:            "svcC",
		ParentServiceID: "serviceid1",
		DeploymentID:    "depid",
		PoolID:          "poolid",
		Launch:          "auto",
		DesiredState:    0,
	}
	c.Assert(ft.Facade.AddService(ft.CTX, svcC), IsNil)

	// assign the ips
	req := addressassignment.AssignmentRequest{
		ServiceID:      "serviceid1",
		IPAddress:      "12.27.36.45",
		AutoAssignment: false,
	}
	c.Assert(ft.Facade.AssignIPs(ft.CTX, req), IsNil)

	addrs, err := ft.Facade.GetServiceAddressAssignmentDetails(ft.CTX, "serviceid1", false)
	c.Assert(err, IsNil)
	c.Assert(addrs, HasLen, 1)
	expected := []service.IPAssignment{
		{
			BaseIPAssignment: service.BaseIPAssignment{
				ServiceID:       "serviceid1",
				ParentServiceID: "",
				ServiceName:     "svcA",
				PoolID:          "poolid",
				Port:            1234,
				Application:     "ep1",
				EndpointName:    "ep1",
			},
			Type:      "static",
			HostID:    "deadb11f",
			HostName:  "h1",
			IPAddress: "12.27.36.45",
		},
	}
	c.Assert(addrs, DeepEquals, expected)

	addrs, err = ft.Facade.GetServiceAddressAssignmentDetails(ft.CTX, "serviceid1", true)
	c.Assert(err, IsNil)
	c.Assert(addrs, HasLen, 3)
	expected = append(expected, service.IPAssignment{
		BaseIPAssignment: service.BaseIPAssignment{
			ServiceID:       "serviceid2",
			ParentServiceID: "serviceid1",
			ServiceName:     "svcB",
			PoolID:          "poolid",
			Port:            2123,
			Application:     "ep2a",
			EndpointName:    "ep2a",
		},
		Type:      "static",
		HostID:    "deadb11f",
		HostName:  "h1",
		IPAddress: "12.27.36.45",
	})
	expected = append(expected, service.IPAssignment{
		BaseIPAssignment: service.BaseIPAssignment{
			ServiceID:       "serviceid2",
			ParentServiceID: "serviceid1",
			ServiceName:     "svcB",
			PoolID:          "poolid",
			Port:            2124,
			Application:     "ep2b",
			EndpointName:    "ep2b",
		},
		Type:      "static",
		HostID:    "deadb11f",
		HostName:  "h1",
		IPAddress: "12.27.36.45",
	})
	for _, assign := range addrs {
		verified := false
		for _, exp := range expected {
			if assign.ServiceID == exp.ServiceID && assign.Application == exp.Application {
				verified = true
				c.Assert(assign, Equals, exp)
				break
			}
		}

		if !verified {
			c.Errorf("Results did not have assignment for %s-%s", assign.ServiceID, assign.Application)
		}
	}

	addrs, err = ft.Facade.GetServiceAddressAssignmentDetails(ft.CTX, "serviceid3", false)
	c.Assert(err, IsNil)
	c.Assert(addrs, HasLen, 0)

	addrs, err = ft.Facade.GetServiceAddressAssignmentDetails(ft.CTX, "serviceid3", true)
	c.Assert(err, IsNil)
	c.Assert(addrs, HasLen, 0)

	// Remove one of the address assignments and verify that the expected number for the
	// service hasn't changed
	var assign *addressassignment.AddressAssignment
	assign, err = ft.Facade.FindAssignmentByServiceEndpoint(ft.CTX, "serviceid2", "ep2a")
	c.Assert(err, IsNil)
	err = ft.Facade.RemoveAddressAssignment(ft.CTX, assign.ID)
	c.Assert(err, IsNil)

	addrs, err = ft.Facade.GetServiceAddressAssignmentDetails(ft.CTX, "serviceid2", true)
	c.Assert(err, IsNil)
	c.Assert(addrs, HasLen, 2)

	verified := false
	for _, addr := range addrs {
		if addr.EndpointName == "ep2a" {
			verified = true
			c.Assert(addr.Type, Equals, "")
			c.Assert(addr.HostID, Equals, "")
			c.Assert(addr.HostName, Equals, "")
			c.Assert(addr.IPAddress, Equals, "")
		} else {
			c.Assert(addr, DeepEquals, expected[2])
		}
	}
	if !verified {
		c.Errorf("Results did not have empty assignment for serviceid2-ep2b ")
	}
}


text:
    	<title>Il tuo bambino</title>

Il tuo bambino

Alla 26ª settimana il feto possiede unghie, ciglia e sopracciglia e gli occhi sono completamente formati.

La spina dorsale si è rafforzata: è più robusta ed elastica e può sostenere il suo corpo in accrescimento. I polmoni del bambino si stanno ancora sviluppando e ci vorrà ancora del tempo prima che siano completi.

Il bimbo reagisce al tocco e ai suoni. Il suo cuore accelera, aumenta il ritmo, quando sente dei rumori tanto che in alcuni casi il bambino si muove al ritmo della musica.

Continua a leggere

redpajama_set_name: RedPajamaGithub


text:
package org.semanticweb.elk.owl.filters;

import org.semanticweb.elk.owl.interfaces.ElkDataOneOf;
import org.semanticweb.elk.owl.visitors.ElkDataOneOfVisitor;

/**
 * A filter producing objects in {@link ElkDataOneOf} from objects of this type.
 *
 * @author "Yevgeny Kazakov"
 *
 */
public interface ElkDataOneOfFilter extends ElkDataOneOfVisitor<ElkDataOneOf> {

	// nothing else

}


text:
function NLSProvider () {

}

NLSProvider.prototype.minZoom = 12;
NLSProvider.prototype.maxZoom = 14;

NLSProvider.prototype.crsSupported = [ 'EPSG:3857' ];

NLSProvider.prototype.coverage = {
	minX: -8,
	minY: 50,
	maxX: 2,
	maxY: 62
};

NLSProvider.prototype.getUrl = function ( x, y, z ) {

	return NLSTileUrlOS( x, y, z );

};

NLSProvider.prototype.getAttribution = function () {

	var a = document.createElement( 'a' );

	a.href = 'http://maps.nls.uk';
	a.textContent = 'map overlay by National Library of Scotland';

	return a;

};


text:
package io.cdap.wrangler.codec;

import com.google.gson.Gson;
import io.cdap.wrangler.api.Row;
import org.apache.avro.AvroTypeException;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.util.Utf8;

import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * This class {@link BinaryAvroDecoder} decodes a byte array of AVRO Json Records into the {@link Row} structure.
 */
public class BinaryAvroDecoder extends AbstractAvroDecoder {
  private final Gson gson;

  public BinaryAvroDecoder(Schema schema) {
    super(schema);
    this.gson = new Gson();
  }

  /**
   * Decodes byte array of binary encoded AVRO into list of {@link Row}.
   * This method will iterate through each of the AVRO schema fields and translate
   * them into columns within the {@link Row}.
   *
   * If the field is instance of {@link List} or {@link Map} it is converted into JSON
   * representation. In order to flatten or expand such columns other directives need
   * to be used.
   *
   * @param bytes array of bytes that contains binary encoded AVRO record.
   * @return list of {@link Row} that are converted from AVRO encoded binary messages.
   */
  @Override
  public List<Row> decode(byte[] bytes) throws DecoderException {
    List<Row> rows = new ArrayList<>();
    BinaryDecoder decoder = null;
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    try {
      decoder = DecoderFactory.get().binaryDecoder(in, null);
      while (true) {
        try {
          GenericRecord gRecord = getReader().read(null, decoder);
          List<Schema.Field> fields = getSchema().getFields();
          Row r = new Row();
          for (Schema.Field field : fields) {
            Object object = gRecord.get(field.name());
            if (object instanceof Utf8) {
              Utf8 o = (Utf8) object;
              object = o.toString();
            } else if (object instanceof Map || object instanceof List) {
              object = gson.toJson(object);
            }
            r.add(field.name(), object);
          }
          rows.add(r);
        } catch (EOFException e) {
          break; // Reached end of buffer.
        }
      }
    } catch (AvroTypeException e) {
      throw new DecoderException(e.getMessage());
    } catch (IOException e) {
      throw new DecoderException("Issue creating AVRO binary decoder. Verify the schema.");
    } finally {
      try {
        in.close();
      } catch (IOException e) {
        // Can't do anything.
      }
    }
    return rows;
  }
}


text:
<?php
$GLOBALS['HACKLIB_ROOT'] = '/opt/hack/usr/share/hhvm/hack/hacklib/hacklib.php';
require(__DIR__ . '/../../../vendor/autoload.php');


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.impala.analysis;

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

import org.apache.impala.analysis.Path.PathType;
import org.apache.impala.catalog.Table;
import org.apache.impala.catalog.TableLoadingException;
import org.apache.impala.catalog.Type;
import org.apache.impala.common.AnalysisException;
import org.apache.impala.thrift.TExprNode;
import org.apache.impala.thrift.TExprNodeType;
import org.apache.impala.thrift.TSlotRef;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;

public class SlotRef extends Expr {
  private final List<String> rawPath_;
  private final String label_;  // printed in toSql()

  // Results of analysis.
  private SlotDescriptor desc_;

  public SlotRef(ArrayList<String> rawPath) {
    super();
    rawPath_ = rawPath;
    label_ = ToSqlUtils.getPathSql(rawPath_);
  }

  /**
   * C'tor for a "dummy" SlotRef used in substitution maps.
   */
  public SlotRef(String alias) {
    super();
    rawPath_ = null;
    // Relies on the label_ being compared in equals().
    label_ = ToSqlUtils.getIdentSql(alias.toLowerCase());
  }

  /**
   * C'tor for a "pre-analyzed" ref to a slot.
   */
  public SlotRef(SlotDescriptor desc) {
    super();
    if (desc.isScanSlot()) {
      rawPath_ = desc.getPath().getRawPath();
    } else {
      rawPath_ = null;
    }
    desc_ = desc;
    type_ = desc.getType();
    evalCost_ = SLOT_REF_COST;
    String alias = desc.getParent().getAlias();
    label_ = (alias != null ? alias + "." : "") + desc.getLabel();
    numDistinctValues_ = desc.getStats().getNumDistinctValues();
    analysisDone();
  }

  /**
   * C'tor for cloning.
   */
  private SlotRef(SlotRef other) {
    super(other);
    rawPath_ = other.rawPath_;
    label_ = other.label_;
    desc_ = other.desc_;
    type_ = other.type_;
  }

  @Override
  protected void analyzeImpl(Analyzer analyzer) throws AnalysisException {
    Path resolvedPath = null;
    try {
      resolvedPath = analyzer.resolvePath(rawPath_, PathType.SLOT_REF);
    } catch (TableLoadingException e) {
      // Should never happen because we only check registered table aliases.
      Preconditions.checkState(false);
    }
    Preconditions.checkNotNull(resolvedPath);
    desc_ = analyzer.registerSlotRef(resolvedPath);
    type_ = desc_.getType();
    if (!type_.isSupported()) {
      throw new AnalysisException("Unsupported type '"
          + type_.toSql() + "' in '" + toSql() + "'.");
    }
    if (type_.isInvalid()) {
      // In this case, the metastore contained a string we can't parse at all
      // e.g. map. We could report a better error if we stored the original
      // HMS string.
      throw new AnalysisException("Unsupported type in '" + toSql() + "'.");
    }
    evalCost_ = SLOT_REF_COST;

    numDistinctValues_ = desc_.getStats().getNumDistinctValues();
    Table rootTable = resolvedPath.getRootTable();
    if (rootTable != null && rootTable.getNumRows() > 0) {
      // The NDV cannot exceed the #rows in the table.
      numDistinctValues_ = Math.min(numDistinctValues_, rootTable.getNumRows());
    }
  }

  @Override
  protected boolean isConstantImpl() { return false; }

  public SlotDescriptor getDesc() {
    Preconditions.checkState(isAnalyzed());
    Preconditions.checkNotNull(desc_);
    return desc_;
  }

  public SlotId getSlotId() {
    Preconditions.checkState(isAnalyzed());
    Preconditions.checkNotNull(desc_);
    return desc_.getId();
  }

  public Path getResolvedPath() {
    Preconditions.checkState(isAnalyzed());
    return desc_.getPath();
  }

  @Override
  public String toSqlImpl() {
    if (label_ != null) return label_;
    if (rawPath_ != null) return ToSqlUtils.getPathSql(rawPath_);
    return "<slot " + Integer.toString(desc_.getId().asInt()) + ">";
  }

  @Override
  protected void toThrift(TExprNode msg) {
    msg.node_type = TExprNodeType.SLOT_REF;
    msg.slot_ref = new TSlotRef(desc_.getId().asInt());
    // we shouldn't be sending exprs over non-materialized slots
    Preconditions.checkState(desc_.isMaterialized(), String.format(
        "Illegal reference to non-materialized slot: tid=%s sid=%s",
        desc_.getParent().getId(), desc_.getId()));
    // check that the tuples associated with this slot are executable
    desc_.getParent().checkIsExecutable();
    if (desc_.getItemTupleDesc() != null) desc_.getItemTupleDesc().checkIsExecutable();
  }

  @Override
  public String debugString() {
    Objects.ToStringHelper toStrHelper = Objects.toStringHelper(this);
    if (rawPath_ != null) toStrHelper.add("path", Joiner.on('.').join(rawPath_));
    toStrHelper.add("type", type_.toSql());
    String idStr = (desc_ == null ? "null" : Integer.toString(desc_.getId().asInt()));
    toStrHelper.add("id", idStr);
    return toStrHelper.toString();
  }

  @Override
  public int hashCode() {
    if (desc_ != null) return desc_.getId().hashCode();
    return Objects.hashCode(Joiner.on('.').join(rawPath_).toLowerCase());
  }

  @Override
  public boolean equals(Object obj) {
    if (!super.equals(obj)) return false;
    SlotRef other = (SlotRef) obj;
    // check slot ids first; if they're both set we only need to compare those
    // (regardless of how the ref was constructed)
    if (desc_ != null && other.desc_ != null) {
      return desc_.getId().equals(other.desc_.getId());
    }
    if ((label_ == null) != (other.label_ == null)) return false;
    if (!label_.equalsIgnoreCase(other.label_)) return false;
    return true;
  }

  @Override
  public boolean isBoundByTupleIds(List<TupleId> tids) {
    Preconditions.checkState(desc_ != null);
    for (TupleId tid: tids) {
      if (tid.equals(desc_.getParent().getId())) return true;
    }
    return false;
  }

  @Override
  public boolean isBoundBySlotIds(List<SlotId> slotIds) {
    Preconditions.checkState(isAnalyzed());
    return slotIds.contains(desc_.getId());
  }

  @Override
  public void getIdsHelper(Set<TupleId> tupleIds, Set<SlotId> slotIds) {
    Preconditions.checkState(type_.isValid());
    Preconditions.checkState(desc_ != null);
    if (slotIds != null) slotIds.add(desc_.getId());
    if (tupleIds != null) tupleIds.add(desc_.getParent().getId());
  }

  @Override
  public Expr clone() { return new SlotRef(this); }

  @Override
  public String toString() {
    if (desc_ != null) {
      return "tid=" + desc_.getParent().getId() + " sid=" + desc_.getId();
    }
    return "no desc set";
  }

  @Override
  protected Expr uncheckedCastTo(Type targetType) throws AnalysisException {
    if (type_.isNull()) {
      // Hack to prevent null SlotRefs in the BE
      return NullLiteral.create(targetType);
    } else {
      return super.uncheckedCastTo(targetType);
    }
  }
}


text:
class CreatePurchases < ActiveRecord::Migration
  def self.up
    create_table :purchases do |t|
       t.column :user_id,    :integer
       t.column :photo_id,   :integer
       t.column :journal_id, :integer
       t.column :value,      :float
       t.column :sale,       :boolean, :default => 0
       t.column :created_at, :datetime
    end
    add_index(:purchases, :user_id)
    add_index(:purchases, :photo_id)
    add_index(:purchases, :journal_id)
  end

  def self.down
    drop_table :purchases
  end
end


text:
$hostname = "navex-basic-securepwd"

# Create AES key to encrypt the password:
$KeyFile = ".\my\myAES.key"
$Key = New-Object Byte[] 16   # You can use 16, 24, or 32 for AES
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | out-file $KeyFile

$passsec = Read-Host 'Input the user`s password' -AsSecureString
$passsec = ConvertFrom-SecureString $passsec -Key $Key

docker run `
    -m 2G `
    --name $hostname `
    --hostname $hostname `
    -v $PSScriptRoot\my:c:\run\my `
    -e Accept_eula=Y `
    -e Auth=Windows `
    -e username=$env:USERNAME `
    -e securePassword=$passsec `
    -e passwordKeyFile='c:\run\my\myAES.key' `
    -e clickonce=Y `
    ${NAV_DOCKER_IMAGE}


text:
package br.com.caelum.vraptor.converter;

import static com.google.common.base.Strings.isNullOrEmpty;

import javax.annotation.Priority;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Alternative;
import javax.interceptor.Interceptor;

import br.com.caelum.vraptor.Convert;

/**
 * VRaptor's Integer converter.
 *
 * @author Guilherme Silveira
 */
@Convert(Integer.class)
@ApplicationScoped
@Alternative
@Priority(Interceptor.Priority.LIBRARY_BEFORE)
public class IntegerConverter implements Converter<Integer> {

	public static final String INVALID_MESSAGE_KEY = "is_not_a_valid_number";

	@Override
	public Integer convert(String value, Class<? extends Integer> type) {
		if (isNullOrEmpty(value)) {
			return null;
		}

		try {
			return Integer.valueOf(value);
		} catch (NumberFormatException e) {
			throw new ConversionException(new ConversionMessage(INVALID_MESSAGE_KEY, value));
		}
	}

}


text:
from . import importer

importer.install(check_options=True)

from django.core.management import (execute_from_command_line,  # noqa
                                    call_command)


text:
namespace Microsoft.Azure.Management.DataFactory
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Extension methods for TriggersOperations.
    /// </summary>
    public static partial class TriggersOperationsExtensions
    {
            /// <summary>
            /// Lists triggers.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            public static IPage<TriggerResource> ListByFactory(this ITriggersOperations operations, string resourceGroupName, string factoryName)
            {
                return operations.ListByFactoryAsync(resourceGroupName, factoryName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Lists triggers.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<TriggerResource>> ListByFactoryAsync(this ITriggersOperations operations, string resourceGroupName, string factoryName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListByFactoryWithHttpMessagesAsync(resourceGroupName, factoryName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Creates or updates a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            /// <param name='trigger'>
            /// Trigger resource definition.
            /// </param>
            /// <param name='ifMatch'>
            /// ETag of the trigger entity.  Should only be specified for update, for which
            /// it should match existing entity or can be * for unconditional update.
            /// </param>
            public static TriggerResource CreateOrUpdate(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName, TriggerResource trigger, string ifMatch = default(string))
            {
                return operations.CreateOrUpdateAsync(resourceGroupName, factoryName, triggerName, trigger, ifMatch).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Creates or updates a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            /// <param name='trigger'>
            /// Trigger resource definition.
            /// </param>
            /// <param name='ifMatch'>
            /// ETag of the trigger entity.  Should only be specified for update, for which
            /// it should match existing entity or can be * for unconditional update.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<TriggerResource> CreateOrUpdateAsync(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName, TriggerResource trigger, string ifMatch = default(string), CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, factoryName, triggerName, trigger, ifMatch, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Gets a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            public static TriggerResource Get(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName)
            {
                return operations.GetAsync(resourceGroupName, factoryName, triggerName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Gets a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<TriggerResource> GetAsync(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, factoryName, triggerName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Deletes a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            public static void Delete(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName)
            {
                operations.DeleteAsync(resourceGroupName, factoryName, triggerName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Deletes a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task DeleteAsync(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, factoryName, triggerName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Starts a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            public static void Start(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName)
            {
                operations.StartAsync(resourceGroupName, factoryName, triggerName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Starts a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task StartAsync(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.StartWithHttpMessagesAsync(resourceGroupName, factoryName, triggerName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Stops a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            public static void Stop(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName)
            {
                operations.StopAsync(resourceGroupName, factoryName, triggerName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Stops a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task StopAsync(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.StopWithHttpMessagesAsync(resourceGroupName, factoryName, triggerName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// List trigger runs.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            /// <param name='startTime'>
            /// Start time for trigger runs.
            /// </param>
            /// <param name='endTime'>
            /// End time for trigger runs.
            /// </param>
            public static IPage<TriggerRun> ListRuns(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName, System.DateTime startTime, System.DateTime endTime)
            {
                return operations.ListRunsAsync(resourceGroupName, factoryName, triggerName, startTime, endTime).GetAwaiter().GetResult();
            }

            /// <summary>
            /// List trigger runs.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            /// <param name='startTime'>
            /// Start time for trigger runs.
            /// </param>
            /// <param name='endTime'>
            /// End time for trigger runs.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<TriggerRun>> ListRunsAsync(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName, System.DateTime startTime, System.DateTime endTime, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListRunsWithHttpMessagesAsync(resourceGroupName, factoryName, triggerName, startTime, endTime, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Starts a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            public static void BeginStart(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName)
            {
                operations.BeginStartAsync(resourceGroupName, factoryName, triggerName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Starts a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task BeginStartAsync(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.BeginStartWithHttpMessagesAsync(resourceGroupName, factoryName, triggerName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Stops a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            public static void BeginStop(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName)
            {
                operations.BeginStopAsync(resourceGroupName, factoryName, triggerName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Stops a trigger.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The resource group name.
            /// </param>
            /// <param name='factoryName'>
            /// The factory name.
            /// </param>
            /// <param name='triggerName'>
            /// The trigger name.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task BeginStopAsync(this ITriggersOperations operations, string resourceGroupName, string factoryName, string triggerName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.BeginStopWithHttpMessagesAsync(resourceGroupName, factoryName, triggerName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Lists triggers.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            public static IPage<TriggerResource> ListByFactoryNext(this ITriggersOperations operations, string nextPageLink)
            {
                return operations.ListByFactoryNextAsync(nextPageLink).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Lists triggers.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<TriggerResource>> ListByFactoryNextAsync(this ITriggersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListByFactoryNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// List trigger runs.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            public static IPage<TriggerRun> ListRunsNext(this ITriggersOperations operations, string nextPageLink)
            {
                return operations.ListRunsNextAsync(nextPageLink).GetAwaiter().GetResult();
            }

            /// <summary>
            /// List trigger runs.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<TriggerRun>> ListRunsNextAsync(this ITriggersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListRunsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}


text:
<?php

namespace Admingenerator\GeneratorBundle\QueryFilter;

use Doctrine\ORM\QueryBuilder;

class DoctrineQueryFilter extends BaseQueryFilter
{
    /**
     * @var QueryBuilder
     */
    protected $query;

    /**
     * @var array
     */
    protected $joins = array();

    /**
     * @var integer
     */
    protected $paramNumber = 0;

    /**
     * @param string $field Table field name.
     * @return string Parameter name with unique key.
     */
    public function getParamName($field)
    {
        return $field.'_'.$this->paramNumber++;
    }

    public function addDefaultFilter($field, $value)
    {
        list($tableAlias, $filteredField) = $this->addTablePathToField($field);

        if (!is_array($value)) {
            $paramName = $this->getParamName($tableAlias.'_'.$filteredField);
            $this->query->andWhere(sprintf('%s.%s = :%s', $tableAlias, $filteredField, $paramName));
            $this->query->setParameter($paramName, $value);
        } elseif (count($value) > 0) {
            $paramName = $this->getParamName($tableAlias.'_'.$filteredField);
            $this->query->andWhere(sprintf('%s.%s IN (:%s)', $tableAlias, $filteredField, $paramName));
            $this->query->setParameter($paramName, $value);
        }
    }

    /**
     * @param string $field
     * @param boolean $value
     */
    public function addBooleanFilter($field, $value)
    {
        if ("" !== $value) {
            list($tableAlias, $filteredField) = $this->addTablePathToField($field);

            $paramName = $this->getParamName($tableAlias.'_'.$filteredField);
            $this->query->andWhere(sprintf('%s.%s = :%s', $tableAlias, $filteredField, $paramName));
            $this->query->setParameter($paramName, !!$value);
        }
    }

    /**
     * @param string $field
     * @param string $value
     */
    public function addStringFilter($field, $value)
    {

        list($tableAlias, $filteredField) = $this->addTablePathToField($field);

        $paramName = $this->getParamName($tableAlias.'_'.$filteredField);
        $this->query->andWhere(sprintf('%s.%s LIKE :%s', $tableAlias, $filteredField, $paramName));
        if ($value === '') {
            $this->query->setParameter($paramName, '');
        } else {
            $this->query->setParameter($paramName, '%' . $value . '%');
        }
    }

    /**
     * @param string $field
     * @param string $value
     */
    public function addTextFilter($field, $value)
    {
        $this->addStringFilter($field, $value);
    }

    public function addCollectionFilter($field, $value, $manyToMany = false)
    {
        list($tableAlias, $filteredField) = $this->addTablePathToField($field);
        if (!is_array($value)) {
            $value = array($value->getId());
        }

        $paramName = $this->getParamName($tableAlias.'_'.$filteredField);

        if ($manyToMany) {
            if (!in_array($filteredField, $this->joins)) {
                $this->query->join($tableAlias . '.' . $filteredField, $filteredField . '_table_filter_join');
            }
            $this->query->andWhere(sprintf('%s.%s IN (:%s)', $filteredField . '_table_filter_join', 'id', $paramName));
        } else {
            $this->query->andWhere(sprintf('%s.%s IN (:%s)', $tableAlias, $filteredField, $paramName));
        }
        $this->query->groupBy('q');
        $this->query->setParameter($paramName, $value);

    }

    public function addDateFilter($field, $value, $format = 'Y-m-d')
    {
        list($tableAlias, $filteredField) = $this->addTablePathToField($field);

        if (is_array($value)) {
            if (array_key_exists('from', $value)) {
                if (false !== $from = $this->formatDate($value['from'], $format)) {
                    $paramName = $this->getParamName($tableAlias.'_'.$filteredField.'_from');
                    $this->query->andWhere(sprintf('%s.%s >= :%s', $tableAlias, $filteredField, $paramName));
                    $this->query->setParameter($paramName, $from);
                }
            }

            if (array_key_exists('to', $value)) {
                if (false !== $to = $this->formatDate($value['to'], $format)) {
                    $paramName = $this->getParamName($tableAlias.'_'.$filteredField.'_to');
                    $this->query->andWhere(sprintf('%s.%s <= :%s',$tableAlias, $filteredField, $paramName));
                    $this->query->setParameter($paramName, $to);
                }
            }

        } else {
            if (false !== $date = $this->formatDate($value, $format)) {
                $paramName = $this->getParamName($tableAlias.'_'.$filteredField);
                $this->query->andWhere(sprintf('%s.%s = :%s', $tableAlias, $filteredField, $paramName));
                $this->query->setParameter($paramName, $date);
            }
        }
    }

    public function addDatetimeFilter($field, $value, $format = 'Y-m-d H:i:s')
    {
        $this->addDateFilter($field, $value, $format);
    }

    public function addNullFilter($field, $value = null)
    {
        list($tableAlias, $filteredField) = $this->addTablePathToField($field);

        $this->query->andWhere(sprintf('%s.%s IS NULL', $tableAlias, $filteredField));
    }

    public function addNotNullFilter($field, $value = null)
    {
        list($tableAlias, $filteredField) = $this->addTablePathToField($field);

        $this->query->andWhere(sprintf('%s.%s IS NOT NULL', $tableAlias, $filteredField));
    }

    protected function addTablePathToField($field)
    {
        if (!strpos($field, '.')) {
            return array('q', $field);
        }

        $fieldParts = explode('.', $field);
        $filteredField = array_pop($fieldParts);
        $parentTableAlias = 'q';

        foreach ($fieldParts as $field) {
            $joinAlias = $field . '_table_filter_join';
            if (!in_array($joinAlias, $this->joins)) {
                $this->query->join($parentTableAlias . '.' . $field, $joinAlias);
                $this->joins[] = $joinAlias;
            }
            $parentTableAlias = $joinAlias;
        }

        return array($parentTableAlias, $filteredField);
    }
}


text:
<template name="home">

Nueva factura

Historial

Grupos

</template>

<template name="createType">
    {{#autoForm collection="Types" id="createType" type="method" meteormethod="addType"}}
        <fieldset>
          <legend>Type</legend>
          {{> afQuickField name='name' placeholder="Write here the name"}}
        </fieldset>
        <button type="submit" class="btn btn-primary">Insert</button>
    {{/autoForm}}
</template>

<template name="createBrand">
    {{#autoForm collection="Brands" id="createBrand" type="method" meteormethod="addBrand"}}
        <fieldset>
          <legend>Brand</legend>
          {{> afQuickField name='name' placeholder="Write here the name"}}
        </fieldset>
        <button type="submit" class="btn btn-primary">Insert</button>
    {{/autoForm}}
</template>

<template name="createProduct">
    {{#autoForm collection="Products" id="createProduct" type="method" meteormethod="addProduct"}}
        <fieldset>
          <legend>Product</legend>
          {{> afQuickField name='name' placeholder="Write here the name"}}
          {{> afFormGroup name='brand' options=brands}}
          {{> afFormGroup name='type' options=types}}
        </fieldset>
        <button type="submit" class="btn btn-primary">Insert</button>
    {{/autoForm}}
</template>

<template name="createCurrency">
    {{#autoForm collection="Currencies" id="createCurrency" type="method" meteormethod="addCurrency"}}
        <fieldset>
          <legend>Currency</legend>
          {{> afQuickField name='name' placeholder="Write here the name"}}
          {{> afQuickField name='symbol' placeholder="Write the symbol"}}
        </fieldset>
        <button type="submit" class="btn btn-primary">Insert</button>
    {{/autoForm}}
</template>


text:
class CreateEventCategories < ActiveRecord::Migration
  def change
    create_table :event_categories do |t|
      t.string :title
      t.string :abbrv
      t.integer :sort_order
      t.string :color

      t.timestamps
    end
  end
end


text:
package com.chanlapp.westtabs.autofeedback;

/**
 * Created by bubu on 9/20/15.
 */
public class FeedbackException extends Exception {

    public FeedbackException(String detailMessage) {
        super(detailMessage);
    }

    public FeedbackException() {
    }
}


text:
"""
setup file for python project.
"""

from setuptools import setup, find_packages

SRC_DIR = 'simplecfs'
VERSION = '0.1'
README = ''

with open('README.md') as f:
    README = f.read()

setup(
    name='SimpleCFS',
    version=VERSION,
    description="Simple Coded File System",
    long_description=README,
    author="lijian",
    author_email="hustlijian@gmail.com",
    license="Apache License 2.0",
    url="TODO",
    keywords=' '.join([
        'python',
        'filesystem',
        'distributed',
        'erasure code',
    ]),
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: Apache Software License',
        'Natural Language :: English',
        'Operating System :: POSIX :: Linux',
        'Operating System :: MacOS :: MacOS X',
        'Programming Language :: Python',
        'Programming Language :: C',
        'Topic :: System :: Filesystems',
    ],
    package_dir={'': SRC_DIR},
    packages=find_packages(SRC_DIR),
    package_data={'': ['ext/*', ]},
    include_package_data=True,
    test_suite='nose.collector',
)


text:
import os
import tempfile
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.models import CreationDateTimeField
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.utils.hashcompat import sha_constructor, md5_constructor
from django.conf import settings
from django.core.files.images import ImageFile
from django.utils.encoding import smart_str
from django.contrib.auth.models import User
from attachments.utils import antivirus, detect_mime, create_thumbnail, humanize_filesize

FILE_STANDING = 0
FILE_VIRUS_NOT_FOUND = 1
FILE_VIRUS_FOUND = 2

FILE_STATUS_CHOICES = (
        (FILE_STANDING,        _('Standing')),
        (FILE_VIRUS_NOT_FOUND, _('Virus not found')),
        (FILE_VIRUS_FOUND,     _('Virus found')),
)

class AttachmentManager(models.Manager):
    def attachments_for_object(self, obj):
        object_type = ContentType.objects.get_for_model(obj)
        return self.filter(content_type__pk=object_type.id,
                           object_id=obj.id)

class Attachment(models.Model):
    """
    Attachment model
    """
    def file_upload_to(instance, filename):
        if not instance.hash:
            instance.make_hash()
        return 'attachments/{hash_byte[0]}/{hash_byte[1]}/{hash_byte[2]}/{user_id}_{hash}'.format(
            hash=instance.hash,
            hash_byte=instance.get_hash_3(),
            user_id=instance.user.id,
        )

    objects = AttachmentManager()

    content_type = models.ForeignKey(ContentType, verbose_name=_('Content Type'), help_text=_('relation to model wich instance is own this attachment'))
    object_id = models.PositiveIntegerField(_('Object ID'), help_text=_('ID of object row'))
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    hash = models.CharField(_('search hash'), max_length=40, unique=True, db_index=True)
    user = models.ForeignKey(User, related_name='attachments', verbose_name=_('user'))
    name = models.CharField(_('real file name'), max_length=255)
    description = models.TextField(_('description'), blank=True, help_text=_('attachment description'))
    mime_type = models.CharField(_('MIME type'), max_length=128, default='application/octet-stream')
    file = models.FileField(_('attachment'), upload_to=file_upload_to)
    size = models.PositiveIntegerField(_('file size'), blank=True, default=0)
    download_count = models.PositiveIntegerField(_('download count'), default=0)
    created = CreationDateTimeField(_('Created'), editable=True)

    av_state = models.PositiveIntegerField(_('avntivirus state'), default=FILE_STANDING, choices=FILE_STATUS_CHOICES)
    av_result = models.TextField(_('antivirus report'), blank=True)

    checksum = models.CharField(_('checksum'), max_length=40, blank=True, help_text=_('SHA1 checksum'))
    thumbnail = models.BooleanField(_('can generate thumbnails'), default=True)

    class Meta:
        ordering = ['-created']
        verbose_name = _('attachment')
        verbose_name_plural = _('attachments')
        permissions = (
            ('delete_foreign_attachment', 'Can delete foreign attachment'),
            ('change_foreign_attachment', 'Can change foreign attachment'),
            ('download_attachment', 'Can download attachment'),
        )

    class ChecksumDoesNotExist(Exception):
        pass

    def __unicode__(self):
        return u'{self.name} uloaded by {self.user.username}'.format(self=self)

    def save(self, *args, **kvargs):
        if not self.id:
            self.set_file(self.file)
        super(Attachment, self).save(*args, **kvargs)

    @models.permalink
    def get_absolute_url(self):
        return ('attachments:download', [self.id])

    def make_hash(self):
        self.hash = md5_constructor(smart_str(self.name) +
                                    smart_str(self.created.strftime('%s')) +
                                    smart_str(self.user.username)).hexdigest()

    def get_hash_3(self):
        """return tuple of first three bytes of search hash"""
        return self.hash[0:2], self.hash[2:4], self.hash[4:6]

    def set_file(self, fl):
        self.name = os.path.basename(fl.name)
        self.size = fl.size
        self.file = fl
        self.make_hash()

    def make_checksum(self):
        self.checksum = sha_constructor(self.file.read()).hexdigest()

    def check_file(self):
        if self.checksum:
            csum = sha_constructor(self.file.read()).hexdigest()
            return self.checksum == csum
        else:
            raise self.ChecksumDoesNotExist('for row {self.id} file {self.file}'.format(self=self))

    def make_check_av(self):
        res, val = antivirus.scan_file(self.file.path)
        if res:
            self.av_state = FILE_VIRUS_FOUND
            self.av_result = val
        else:
            self.av_state = FILE_VIRUS_NOT_FOUND
        return res

    def detect_mime(self):
        """detect mime using system `file` program"""
        return detect_mime(self.file.path)

    def get_size_display(self):
        return humanize_filesize(self.size)

class ThumbnailManager(models.Manager):
    def get_or_create(self, attachment, width, height):
        try:
            th = self.get(attachment=attachment, width=width, height=height)
        except self.model.DoesNotExist:
            th = self.create_for_attachment(attachment, width, height)
        return th

    def create_for_attachment(self, attachment, width, height):
        """
        Create Thumbnail object and save it if thumbnailer backend can generate thumbnail for this file.
        If not — return None.
        """
        if not attachment.thumbnail:
            return None

        th = self.model(attachment=attachment, width=width, height=height)
        with tempfile.NamedTemporaryFile(suffix='.thumb') as tfd:
            tfd.file.close()
            status, mime_type = create_thumbnail(attachment.file.path,
                                                 tfd.name,
                                                 width, height,
                                                 attachment.mime_type)
            if status:
                th.mime_type = mime_type
                th.file = ImageFile(open(tfd.name))
                th.save()
            else:
                attachment.thumbnail = False
                attachment.save()
                return None

        return th

class Thumbnail(models.Model):
    def file_upload_to(instance, filename):
        return 'attachments/thumb/{hash_byte[0]}/{hash_byte[1]}/{hash_byte[2]}/{user_id}_{width}x{height}_{hash}'.format(
            hash=instance.attachment.hash,
            hash_byte=instance.attachment.get_hash_3(),
            user_id=instance.attachment.user.id,
            width=instance.width,
            height=instance.height,
        )

    objects = ThumbnailManager()

    created = CreationDateTimeField(_('created'), blank=True, editable=True)
    attachment = models.ForeignKey(Attachment, related_name='thumbnails', verbose_name=_('attachment'), help_text=_('thumbnail for this attachment'))
    width = models.PositiveIntegerField(_('width'), db_index=True)
    height = models.PositiveIntegerField(_('height'), db_index=True)
    file = models.ImageField(_('thumbnail'), upload_to=file_upload_to)
    mime_type = models.CharField(_('MIME type'), max_length=128, default='image/jpeg')

    class Meta:
        ordering = ('-created', 'attachment__id')
        verbose_name = _('thumbnail')
        verbose_name_plural = _('thumbnails')
        unique_together = ('attachment', 'width', 'height')

    def __unicode__(self):
        return u'for {self.attachment.name} {self.width}x{self.height}'.format(self=self)

    @models.permalink
    def get_absolute_url(self):
        return ('attachments:thumbnail', (self.attachment_id, self.width, self.height))

from attachments import signals


text:
<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "feedback".
 *
 * @property integer $id
 * @property string $message
 * @property string $from
 */
class Feedback extends \yii\db\ActiveRecord
{
    public $messageForm;
    public $fromUser;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'feedback';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['messageForm', 'fromUser'], 'required'],
            [['message', 'from'], 'string'],
            ['created_at', 'string'],
        ];
    }

    public function behaviors()
    {
        return [
            'class' => TimestampBehavior::className()
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'message' => 'Message',
            'from' => 'From',
        ];
    }

    /**
     * @param $model Feedback;
     * @return mixed
     */
    public function leaveFeedback($model)
    {
        $model->message = $this->messageForm;
        $model->from = $this->fromUser;
        return $model->save() ? true : false;
    }
}


text:
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module      :  Graphics.GL.KHR.ParallelShaderCompile
-- Copyright   :  (c) Sven Panne 2019
-- License     :  BSD3
--
-- Maintainer  :  Sven Panne <svenpanne@gmail.com>
-- Stability   :  stable
-- Portability :  portable
--
--------------------------------------------------------------------------------

module Graphics.GL.KHR.ParallelShaderCompile (
  -- * Extension Support
  glGetKHRParallelShaderCompile,
  gl_KHR_parallel_shader_compile,
  -- * Enums
  pattern GL_COMPLETION_STATUS_KHR,
  pattern GL_MAX_SHADER_COMPILER_THREADS_KHR,
  -- * Functions
  glMaxShaderCompilerThreadsKHR
) where

import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions


text:
.. blogpost::
    :title: pandas, groupby, nan values
    :keywords:
    :date: 2016-11-20
    :categories: pandas

    La fonction `groupby <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html>`_
    ne considère pas (plus) les valeurs manquantes ou
    `NaN <https://docs.scipy.org/doc/numpy/reference/generated/numpy.isnan.html>`_.
    Le notebook :ref:`pandasgroupbyrst` illustre ce fait et montre comment les corriger.


text:
START_ATF_NAMESPACE
    struct _trunk_hint_answer_request_clzo
    {
        char wszAnswer[17];
    };
END_ATF_NAMESPACE


text:
// .NAME vtkBMPWriter - Writes Windows BMP files.
// .SECTION Description
// vtkBMPWriter writes BMP files. The data type
// of the file is unsigned char regardless of the input type.

// .SECTION See Also
// vtkBMPReader

#ifndef __vtkBMPWriter_h
#define __vtkBMPWriter_h

#include "vtkIOImageExport.h" // For export macro
#include "vtkImageWriter.h"

class VTKIOIMAGE_EXPORT vtkBMPWriter : public vtkImageWriter
{
public:
  static vtkBMPWriter *New();
  vtkTypeMacro(vtkBMPWriter,vtkImageWriter);
  virtual void PrintSelf(ostream& os, vtkIndent indent);

protected:
  vtkBMPWriter();
  ~vtkBMPWriter() {};

  virtual void WriteFile(ofstream *file, vtkImageData *data, int ext[6], int wExt[6]);
  virtual void WriteFileHeader(ofstream *, vtkImageData *, int wExt[6]);
private:
  vtkBMPWriter(const vtkBMPWriter&);  // Not implemented.
  void operator=(const vtkBMPWriter&);  // Not implemented.
};

#endif


text:
path=$(dirname $(dirname $0))
source $path/scripts/xwalk_common.sh
if [ $# != 1 ];then
    echo "Please add parameter packagename!"
    exit 1
fi
PACKAGENAME="$path/$1"
p_name=$1
APP_NAME=${p_name%%.wgt}
find_app $APP_NAME
pkgnum=`echo "$pkgids"|wc -w`
if [ $pkgnum -ge 1 ]; then
then
  uninstall_app $APP_NAME
  find_app $APP_NAME
  pkgnum=`echo "$pkgids"|wc -w`
  if [ $pkgnum -ge 1 ]; then
  then
    echo -e  "Fail to uninstall the existed widget!"
    exit 1
  fi
fi
install_app $PACKAGENAME
find_app $APP_NAME
pkgnum=`echo "$pkgids"|wc -w`
if [ $pkgnum -lt 1 ]; then
then
  echo -e  "Fail to install the widget!"
  exit 0
else
  uninstall_app $APP_NAME
  echo -e  "The widget is installed successfully!"
  exit 1
fi


text:
from clld.web import datatables
from clld.web.datatables.base import Col, LinkCol, IntegerIdCol

from tsezacp import models

class Texts(datatables.Contributions):
    def col_defs(self):
        return [
            IntegerIdCol(self, 'id', sTitle='Number'),
            LinkCol(self, 'name', sTitle='Title'),
            Col(self, 'description', sTitle='English translation'),
        ]

class Glossary(datatables.Units):
    def col_defs(self):
        return [
            LinkCol(self, 'name', sTitle='Morpheme'),
            Col(self, 'pos', sTitle='Part of speech', model_col=models.Morpheme.pos),
            Col(self, 'description', sTitle='Glosses'),
        ]

class Lines(datatables.Sentences):
    def col_defs(self):
        res = datatables.Sentences.col_defs(self)
        return res[:-3] + res[-1:]

def includeme(config):
    config.register_datatable('contributions', Texts)
    config.register_datatable('sentences', Lines)
    config.register_datatable('units', Glossary)


text:
#pragma once

#include <aws/core/Core_EXPORTS.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <aws/core/utils/DateTime.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/threading/ReaderWriterLock.h>
#include <aws/core/internal/AWSHttpResourceClient.h>
#include <aws/core/auth/AWSCredentials.h>
#include <aws/core/config/AWSProfileConfigLoader.h>
#include <aws/core/client/RetryStrategy.h>
#include <memory>

namespace Aws
{
    namespace Auth
    {
        constexpr int REFRESH_THRESHOLD = 1000 * 60 * 5;

        /**
         * Returns the full path of the config file.
         */
        AWS_CORE_API Aws::String GetConfigProfileFilename(); //defaults to "config"

        /**
         * Returns the default profile name.
         * The value is the first non-empty value of the following:
         * 1. AWS_PROFILE environment variable
         * 2. AWS_DEFAULT_PROFILE environment variable
         * 3. The literal name "default"
         */
        AWS_CORE_API Aws::String GetConfigProfileName(); //defaults to "default"

        /*
         * Fetches credentials by executing the process in the parameter
         */
        AWS_CORE_API AWSCredentials GetCredentialsFromProcess(const Aws::String& process);

        /**
          * Abstract class for retrieving AWS credentials. Create a derived class from this to allow
          * various methods of storing and retrieving credentials. Examples would be cognito-identity, some encrypted store etc...
          */
        class AWS_CORE_API AWSCredentialsProvider
        {
        public:
            /**
             * Initializes provider. Sets last Loaded time count to 0, forcing a refresh on the
             * first call to GetAWSCredentials.
             */
            AWSCredentialsProvider() : m_lastLoadedMs(0)
            {
            }

            virtual ~AWSCredentialsProvider() = default;

            /**
             * The core of the credential provider interface. Override this method to control how credentials are retrieved.
             */
            virtual AWSCredentials GetAWSCredentials() = 0;

        protected:
            /**
             * The default implementation keeps up with the cache times and lets you know if it's time to refresh your internal caching
             *  to aid your implementation of GetAWSCredentials.
             */
            virtual bool IsTimeToRefresh(long reloadFrequency);
            virtual void Reload();
            mutable Aws::Utils::Threading::ReaderWriterLock m_reloadLock;
        private:
            long long m_lastLoadedMs;
        };

        /**
         * Simply a provider that always returns empty credentials. This is useful for a client that needs to make unsigned
         * calls.
         */
        class AWS_CORE_API AnonymousAWSCredentialsProvider : public AWSCredentialsProvider
        {
        public:
            /**
             * Returns empty credentials object.
             */
            inline AWSCredentials GetAWSCredentials() override { return AWSCredentials(); }
        };

        /**
          * A simple string provider. It takes the AccessKeyId and the SecretKey as constructor args and
          * provides them through the interface. This is the default class for AWSClients that take string
          * arguments for credentials.
          */
        class AWS_CORE_API SimpleAWSCredentialsProvider : public AWSCredentialsProvider
        {
        public:
            /**
             * Initializes object from awsAccessKeyId, awsSecretAccessKey, and sessionToken parameters. sessionToken parameter is defaulted to empty.
             */
            inline SimpleAWSCredentialsProvider(const Aws::String& awsAccessKeyId, const Aws::String& awsSecretAccessKey, const Aws::String& sessionToken = "")
                : m_credentials(awsAccessKeyId, awsSecretAccessKey, sessionToken)
            { }

            /**
            * Initializes object from credentials object. everything is copied.
            */
            inline SimpleAWSCredentialsProvider(const AWSCredentials& credentials)
                : m_credentials(credentials)
            { }

            /**
             * Returns the credentials this object was initialized with as an AWSCredentials object.
             */
            inline AWSCredentials GetAWSCredentials() override
            {
                return m_credentials;
            }

        private:
            AWSCredentials m_credentials;
        };

        /**
        * Reads AWS credentials from the Environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN if they exist. If they
        * are not found, empty credentials are returned.
        */
        class AWS_CORE_API EnvironmentAWSCredentialsProvider : public AWSCredentialsProvider
        {
        public:
            /**
            * Reads AWS credentials from the Environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN if they exist. If they
            * are not found, empty credentials are returned. Credentials are not cached.
            */
            AWSCredentials GetAWSCredentials() override;
        };

        /**
        * Reads credentials profile from the default Profile Config File. Refreshes at set interval for credential rotation.
        * Looks for environment variables AWS_SHARED_CREDENTIALS_FILE and AWS_PROFILE. If they aren't found, then it defaults
        * to the default profile in ~/.aws/credentials.
        * Optionally a user can specify the profile and it will override the environment variable
        * and defaults. To alter the file this pulls from, then the user should alter the AWS_SHARED_CREDENTIALS_FILE variable.
        */
        class AWS_CORE_API ProfileConfigFileAWSCredentialsProvider : public AWSCredentialsProvider
        {
        public:

            /**
            * Initializes with refreshRateMs as the frequency at which the file is reparsed in milliseconds. Defaults to 5 minutes.
            */
            ProfileConfigFileAWSCredentialsProvider(long refreshRateMs = REFRESH_THRESHOLD);

            /**
            * Initializes with a profile override and
            * refreshRateMs as the frequency at which the file is reparsed in milliseconds. Defaults to 5 minutes.
            */
            ProfileConfigFileAWSCredentialsProvider(const char* profile, long refreshRateMs = REFRESH_THRESHOLD);

            /**
            * Retrieves the credentials if found, otherwise returns empty credential set.
            */
            AWSCredentials GetAWSCredentials() override;

            /**
             * Returns the fullpath of the calculated credentials profile file
             */
            static Aws::String GetCredentialsProfileFilename();

            /**
             * Returns the directory storing the profile file.
             */
            static Aws::String GetProfileDirectory();

        protected:
            void Reload() override;
        private:

            /**
             * Checks to see if the refresh interval has expired and reparses the file if it has.
             */
            void RefreshIfExpired();

            Aws::String m_profileToUse;
            Aws::Config::AWSConfigFileProfileConfigLoader m_credentialsFileLoader;
            long m_loadFrequencyMs;
        };

        /**
        * Credentials provider implementation that loads credentials from the Amazon
        * EC2 Instance Metadata Service.
        */
        class AWS_CORE_API InstanceProfileCredentialsProvider : public AWSCredentialsProvider
        {
        public:
            /**
             * Initializes the provider to refresh credentials form the EC2 instance metadata service every 5 minutes.
             * Constructs an EC2MetadataClient using the default http stack (most likely what you want).
             */
            InstanceProfileCredentialsProvider(long refreshRateMs = REFRESH_THRESHOLD);

            /**
             * Initializes the provider to refresh credentials form the EC2 instance metadata service every 5 minutes,
             * uses a supplied EC2MetadataClient.
             */
            InstanceProfileCredentialsProvider(const std::shared_ptr<Aws::Config::EC2InstanceProfileConfigLoader>&, long refreshRateMs = REFRESH_THRESHOLD);

            /**
            * Retrieves the credentials if found, otherwise returns empty credential set.
            */
            AWSCredentials GetAWSCredentials() override;

        protected:
            void Reload() override;

        private:
            void RefreshIfExpired();

            std::shared_ptr<Aws::Config::AWSProfileConfigLoader> m_ec2MetadataConfigLoader;
            long m_loadFrequencyMs;
        };

        /**
        * ECS credentials provider implementation that loads credentials from the Amazon
        * ECS metadata service or an arbitrary endpoint.
        */
        class AWS_CORE_API TaskRoleCredentialsProvider : public AWSCredentialsProvider
        {
        public:
            /**
             * Initializes the provider to retrieve credentials from the ECS metadata service every 5 minutes,
             * or before it expires.
             * @param resourcePath A path appended to the metadata service endpoint.
             * @param refreshRateMs The number of milliseconds after which the credentials will be fetched again.
             */
            TaskRoleCredentialsProvider(const char* resourcePath, long refreshRateMs = REFRESH_THRESHOLD);

            /**
             * Initializes the provider to retrieve credentials from a provided endpoint every 5 minutes or before it
             * expires.
             * @param endpoint The full URI to resolve to get credentials.
             * @param token An optional authorization token passed to the URI via the 'Authorization' HTTP header.
             * @param refreshRateMs The number of milliseconds after which the credentials will be fetched again.
             */
            TaskRoleCredentialsProvider(const char* endpoint, const char* token, long refreshRateMs = REFRESH_THRESHOLD);

            /**
             * Initializes the provider to retrieve credentials using the provided client.
             * @param client The ECSCredentialsClient instance to use when retrieving credentials.
             * @param refreshRateMs The number of milliseconds after which the credentials will be fetched again.
             */
            TaskRoleCredentialsProvider(const std::shared_ptr<Aws::Internal::ECSCredentialsClient>& client,
                    long refreshRateMs = REFRESH_THRESHOLD);
            /**
            * Retrieves the credentials if found, otherwise returns empty credential set.
            */
            AWSCredentials GetAWSCredentials() override;

        protected:
            void Reload() override;
        private:
            bool ExpiresSoon() const;
            void RefreshIfExpired();

        private:
            std::shared_ptr<Aws::Internal::ECSCredentialsClient> m_ecsCredentialsClient;
            long m_loadFrequencyMs;
            Aws::Auth::AWSCredentials m_credentials;
        };

        /**
         * Process credentials provider that loads credentials by running another command (or program) configured in config file
         * The configuration format is as following:
         * credential_process = command_path <arguments_list>
         * Each time the credentials needs to be refreshed, this command will be executed with configured arguments.
         * The default profile name to look up this configuration is "default", same as normal aws credentials configuration and other configurations.
         * The expected valid output of the command is a Json doc output to stdout:
         * {"Version": 1, "AccessKeyId": "AccessKey123", "SecretAccessKey": "SecretKey321", "SessionToken": "Token123", "Expiration": "1970-01-01T00:00:01Z"}
         * The Version key specifies the version of the JSON payload and must be set to 1 for now (as an integer type).
         * If the Version key is bumped to 2, SDKs would support both versions of the returned payload.
         * Value of Expiration field should be an valid ISO8601 formatted date string as above example.
         * The expected error message of the command is a string to output to stderr.
         */
        class AWS_CORE_API ProcessCredentialsProvider : public AWSCredentialsProvider
        {
        public:
            /**
             * Initializes the provider by checking default profile
             */
            ProcessCredentialsProvider();

            /**
             * Initializes the provider by checking specified profile
             * @param profile which profile in config file to use.
             */
            ProcessCredentialsProvider(const Aws::String& profile);

            /**
             * Retrieves the credentials if found, otherwise returns empty credential set.
             */
            AWSCredentials GetAWSCredentials() override;

        protected:
            void Reload() override;
        private:
            void RefreshIfExpired();

        private:
            Aws::String m_profileToUse;
            Aws::Auth::AWSCredentials m_credentials;
        };
    } // namespace Auth
} // namespace Aws


text:
class Model;

class Character_Info{
	public:
		std::string f_name;
		std::string l_name;
		uint8_t stats[7];
		uint8_t in_squad;

		Character_Info();
		~Character_Info();
};

class Character{
	public:
		int x;
		int y;
		int speed;
		char c;
		int color;
		uint8_t *movement_map;
		int turns;
		Character_Info *info;

		Character(Character_Info*);
		~Character();
};

void update_valid_moves(Character**, uint8_t*, Character*);
int move_character(Model *, Character*, int, int);

#endif


text:
Puppet::Type.type(:line_in_file).provide :cat_grep_sed, :parent => Puppet::Provider do

    #
    # Module description
    #
    desc "Shell provider for file_in_line management."

    #
    # Create generic resource methods
    #
    mk_resource_methods

    #
    # Prerequisites
    #
    commands :echo => "echo"
    commands :cat  => "cat"
    commands :grep => "grep"
    commands :sed  => "sed"

    #
    # Check if line already exists in file
    #
    def exists?
	#notice('PROVIDER METHOD: ' + __method__.id2name)

	# Check for all required stuff
	if @resource[:file].nil?
	    raise Puppet::Error, "Parameter 'file' is not defined"
	end
	if @resource[:line_regex].nil?
	    raise Puppet::Error, "Parameter 'line_regex' is not defined"
	end

	if @resource[:ensure] == :present
	    if @resource[:line].nil?
		raise Puppet::Error, "Parameter 'line' is not defined"
	    end

	    # Check if line matches line_regex
	    unless @resource[:line] =~ /^#{@resource[:line_regex]}$/
		raise Puppet::Error, "Parameter 'line_regex' does not match 'line' property"
	    end
	end

	# Does file exist? If not, create it
	unless FileTest.exists?(@resource[:file])
	    FileUtils.touch(@resource[:file])
	else
	    if FileTest.directory?(@resource[:file])
		raise Puppet::Error, "File is a directory: #{@resource[:file]}"
	    end
	end

	# Construct command
	lineRegexSh = get_shell_regex_format(@resource[:line_regex])
	cmd = "grep -E -c '^#{lineRegexSh}$' #{@resource[:file]}"

	# Execute and evaluate
	cmdOutput = `#{cmd}`
	if $? != 0
	    if cmdOutput.strip! == '0'
		return false
	    else
		raise Puppet::Error, "Exit status from grep is non-zero, but return value is not zero: #{cmdOutput.strip!}"
	    end
	else
	    # Can return whatever, only bool false is considered real false,
	    # everything else evaluates to true
	    return true
	end
    end

    #
    # Ensure line in file
    #
    def create
	#notice('PROVIDER METHOD: ' + __method__.id2name)

	# Set initial stuff
	tmpFile  = @resource[:file] + '.puppet.' + Process.pid.to_s + '.tmp'

	# Remove entries if requested
	if @resource[:remove_regex]
	    rmRegexSh = get_shell_regex_format(@resource[:remove_regex])

	    # Remove all instances first
	    execSimple("cat '#{@resource[:file]}' | grep -E -v '^#{rmRegexSh}$' > #{tmpFile}")

	    # Add desired line
	    execSimple("echo '#{@resource[:line]}' >> #{tmpFile}")

	    # Move to original location
	    execSimple("mv #{tmpFile} #{@resource[:file]}")
	else

	    # Add desired line
	    execSimple("echo '#{@resource[:line]}' >> #{@resource[:file]}")
	end

	# Return success
	return :present
    end

    #
    # Dummy method, create method takes care of everything about line creation
    #
    def line
	#notice('PROVIDER METHOD: ' + __method__.id2name)

	return @resource[:line]
    end

    #
    # Dummy method, create method takes care of everything
    #
    def remove_regex
	#notice('PROVIDER METHOD: ' + __method__.id2name)

	# Check if remove regex matches our line
	if @resource[:line] =~ /^#{@resource[:remove_regex]}$/
	    lineMatchesRemoveRegex = true
	else
	    lineMatchesRemoveRegex = false
	end

	# Set initial stuff
	rmRegexSh = get_shell_regex_format(@resource[:remove_regex])
	tmpFile  = @resource[:file] + '.puppet.' + Process.pid.to_s + '.tmp'

	# If line matches removeRegex, count occurences
	if lineMatchesRemoveRegex
	    cmd = "grep -E -c '^#{rmRegexSh}$' #{@resource[:file]}"
	    cmd_output = `#{cmd}`
	    ocCount = cmd_output.strip.to_i
	    if $? != 0
		if ocCount == 0
		    raise Puppet::Error, "No entries matching #{shRegex} found, but our line should already be there"
		else
		    raise Puppet::Error, "Exit status from grep is non-zero, but return value is not zero: #{cmd_output.strip!}"
		end
	    else
		if ocCount == 1
		    # Single instance, excellent
		    return @resource[:remove_regex]
		else
		    # Remove all instances first
		    execSimple("cat '#{@resource[:file]}' | grep -E -v '^#{rmRegexSh}$' > #{tmpFile}")

		    # Add desired line
		    execSimple("echo '#{@resource[:line]}' >> #{tmpFile}")

		    # Move to original location
		    execSimple("mv #{tmpFile} #{@resource[:file]}")

		    return @resource[:remove_regex]
		end
	    end
	end

	if !lineMatchesRemoveRegex
	    # Remove all instances
	    execSimple("cat '#{@resource[:file]}' | grep -E -v '^#{rmRegexSh}$' > #{tmpFile}")

	    # Move to original location
	    execSimple("mv #{tmpFile} #{@resource[:file]}")

	    return @resource[:remove_regex]
	end
    end

    #
    # Remove existing line from file
    #
    def destroy
	#notice('PROVIDER METHOD: ' + __method__.id2name)

	# If there is remove_regex defined, signal error
	if @resource[:remove_regex]
	    raise Puppet::Error, "When destroying resource, only line_regex is permitted to exist, not remove_regex also"
	end

	# Construct and execute modification
	lineRegexSh = get_shell_regex_format(@resource[:line_regex])
	tmpFile     = @resource[:file] + '.puppet.' + Process.pid.to_s + '.tmp'
	execSimple("cat '#{@resource[:file]}' | grep -E -v '^#{lineRegexSh}$' > #{tmpFile}")

	# Move to original location
	execSimple("mv #{tmpFile} #{@resource[:file]}")

	return @resource[:ensure]
    end

    #
    # Format normal regex into shell-compatible one
    #
    def get_shell_regex_format (origRegex)

	shellRegex1 = origRegex.sub("+", "\+")
	shellRegex2 = shellRegex1.sub("(", "\(")
	shellRegex3 = shellRegex2.sub("|", "\|")
	shellRegex4 = shellRegex3.sub(")", "\)")
	shellRegex  = shellRegex4

	return shellRegex
    end

    #
    # Execute simple command
    #
    def execSimple (cmd)

	cmdOutput = `#{cmd}`
	if $? != 0
	    raise Puppet::Error, "Execution failed: #{cmd}   #{cmdOutput}"
	end

	return cmdOutput.strip!
    end
end


text:
enum RegNum : BYTE {
#define REGDAT(Name, Listing,    Encode,    Type,    BitVec)  Reg ## Name,
#include "RegList.h"
#undef REGDAT

    RegNumCount,  // Number of operations
};

#define FIRST_FLOAT_REG RegD0

#define FOREACH_REG(reg) \
        for (RegNum reg = (RegNum)(RegNOREG+1); reg != RegNumCount; reg = (RegNum)(reg+1))
#define NEXT_REG

#define FOREACH_INT_REG(reg) \
        for (RegNum reg = (RegNum)(RegNOREG+1); reg != FIRST_FLOAT_REG; reg = (RegNum)(reg+1))
#define NEXT_INT_REG

#define FOREACH_FLOAT_REG(reg) \
        for (RegNum reg = FIRST_FLOAT_REG; reg != RegNumCount; reg = (RegNum)(reg+1))
#define NEXT_FLOAT_REG


text:
title: "Count The Number Of Connected Components In A Graph"
excerpt: "In this post we are going to implement an algorithm that counts the number of connected components in a graph"
header:
  overlay_image: /images/code.jpeg
date: 2022-01-30
tags: [Data Structures, Graph]
---

In the [previous post]({{ site.baseurl}}/graph-shortest-path) we implemented an algorithm that finds the shortest path between two vertices in a graph. In this post we are going to solve a [LeetCode](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/) problem that requires us to count the total number of connected components in a graph. Using **Figure 1** below as an example, our graph has 3 connected components. All we need to do is write an algorithm that counts them.

Figure 1: Connected components

## Solution

To solve this problem we are going to do a combination of iterative and recursive functions. We need to iterate through all the vertices in the graph and for each vertex, recursively run through it's neighbors until we have visited every vertex in the connected component. We need to ensure we don't double-count our vertices so we should maintain a set of visited components. We return `false` if a vertex has already been visited and `true` after we have successfully traversed through a connected component. When our recursive function returns `true` we increment the our count of connected components. Here's the code:

```csharp
public int GetTotalConnectedComponents()
{
    int count = 0;
    HashSet<T> visited = new();
    foreach(var vertex in _adjacentList.Keys)
    {
        if (Traverse(vertex, ref visited))
        {
            count++;
        }
    }
    return count;
}

private bool Traverse(T vertex, ref HashSet<T> visited)
{
    if (visited.Contains(vertex))
    {
        return false;
    }

    visited.Add(vertex);

    foreach (var neighbor in _adjacentList[vertex])
    {
        Traverse(neighbor, ref visited);
    }

    return true;
}
```

In this post we spoke about an algorithm that counts the number of connected components in a graph. All the code is available on [GitHub](https://github.com/vince-nyanga/data-structures). Leave a comment if you have any questions and/or suggestions. Till next time, thanks so much for taking your time to read.


text:
import os
import sublime
import sublime_plugin
import traceback

if int(sublime.version()) >= 3000:
    from plistlib import readPlistFromBytes
else:
    from plistlib import readPlist

try:  # Python 3
    from .haxe_helper import HaxeComplete_inst
    from .haxe_format import format_statement
except (ValueError):  # Python 2
    from haxe_helper import HaxeComplete_inst
    from haxe_format import format_statement

class HaxeColorScheme(sublime_plugin.EventListener):

    inst = None

    def __init__(self):
        HaxeColorScheme.inst = self
        self.color_scheme = None
        self.styles = None
        self.color_map = None
        self.settings = None
        self.init()

    def init(self):
        if sublime.active_window() is None or \
                sublime.active_window().active_view() is None:
            sublime.set_timeout(self.init, 200)
            return

        self.parse_scheme()

    def get_color(self, name):
        if self.color_map is None or name not in self.color_map:
            return None
        return self.color_map[name]

    def get_styles(self):
        self.parse_scheme()

        if self.styles is None:
            if self.color_map is None:
                return ''

            colors = (
                self.get_color('popupBackground') or
                self.get_color('lineHighlight') or
                self.get_color('background'),
                self.get_color('popupForeground') or
                self.get_color('foreground'))
            self.styles = \
                '<style>html{background-color:%s;color:%s;}</style>' % colors

        return self.styles

    def parse_scheme(self):
        if sublime is None or \
                sublime.active_window() is None or \
                sublime.active_window().active_view() is None:
            return

        if self.settings is None:
            self.settings = sublime.load_settings(
                'Preferences.sublime-settings')
            self.settings.add_on_change(
                'color_scheme', lambda: self.parse_scheme())

        color_scheme = self.settings.get(
            'color_scheme', 'Packages/Color Scheme - Default/Monokai.tmTheme')

        if self.color_scheme == color_scheme and self.color_map is not None:
            return

        self.color_scheme = color_scheme
        self.styles = None
        self.color_map = None

        try:
            if int(sublime.version()) >= 3000:
                b = sublime.load_binary_resource(color_scheme)
                pl = readPlistFromBytes(b)
            else:
                pl = readPlist(os.path.join(os.path.abspath(
                    sublime.packages_path() + '/..'), color_scheme))
        except:
            print(traceback.print_exc())
            return

        def safe_update(fr, to):
            for k in fr.keys():
                if k not in to:
                    to[k] = fr[k]

        dct = {}
        for d in pl.settings:
            if 'settings' not in d:
                continue
            s = d['settings']
            if 'scope' not in d:
                safe_update(s, dct)
            else:
                scope = d['scope']
                scopes = [sc.strip() for sc in scope.split(',')]
                if 'text' in scopes or 'source' in scopes:
                    dct.update(d.settings)

        self.color_map = dct

class HaxeShowPopup(sublime_plugin.TextCommand):

    def run(self, edit, text=None):
        view = self.view
        if not text:
            return

        view.show_popup(
            HaxeColorScheme.inst.get_styles() + text, max_width=700)

class HaxeHint(sublime_plugin.TextCommand):

    def insert_snippet(self, hints):
        view = self.view
        snippet = ''
        i = 1
        for h in hints:
            var = '%d:%s' % (i, h)
            if snippet == '':
                snippet = var
            else:
                snippet += ',${%s}' % var
            i += 1

        snippet = format_statement(view, snippet)

        view.run_command('insert_snippet', {
            'contents': '${' + snippet + '}'
        })

    def run(self, edit, input=''):
        complete = HaxeComplete_inst()
        view = self.view

        if not input:
            if view.substr(view.sel()[0].end()) == '(':
                view.run_command('haxe_show_type')
                return

        if input == '(':
            sel = view.sel()
            emptySel = True
            for r in sel:
                if not r.empty():
                    emptySel = False
                    break

            autoMatch = view.settings().get('auto_match_enabled', False)

            if autoMatch:
                if emptySel:
                    view.run_command('insert_snippet', {
                        'contents': '($0)'
                    })
                else:
                    view.run_command('insert_snippet', {
                        'contents': '(${0:$SELECTION})'
                    })
            else:
                view.run_command('insert', {
                    'characters': '('
                })
        else:
            view.run_command('insert', {
                'characters': input
            })

        if input and not view.settings().get('haxe_auto_complete', True):
            return

        haxe_smart_snippets = view.settings().get('haxe_smart_snippets', False)
        haxe_use_popup = view.settings().get('haxe_use_popup', True) and \
            int(sublime.version()) >= 3070

        if not haxe_smart_snippets and not haxe_use_popup:
            return

        for r in view.sel():
            comps, hints = complete.get_haxe_completions(
                view, r.end(), ignoreTopLevel=True)

            if haxe_use_popup:
                self.show_popup(hints)
            elif haxe_smart_snippets and input:
                self.insert_snippet(hints)

    def show_popup(self, hints):
        view = self.view
        text = ''

        for h in hints:
            if not text:
                text = '{}%s{}' % h
            else:
                text += ',%s' % h

        text = format_statement(view, text)
        text = text.replace('<', '<')
        text = text.replace('>', '>')
        text = text.format('<b>', '</b>')

        view.run_command('haxe_show_popup', {
            'text': text
        })


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<artifactId>contentreview</artifactId>
		<groupId>org.sakaiproject.contentreview</groupId>
		<version>10.4</version>
		<relativePath>../../pom.xml</relativePath>
	</parent>
	<name>contentreview-model-api</name>
	<groupId>org.sakaiproject.contentreview</groupId>
	<artifactId>contentreview-model-api</artifactId>
	<description />
	<packaging>jar</packaging>
	<properties>
		<deploy.target>shared</deploy.target>
	</properties>
</project>


text:
<form class="application-modal-form" role="form" ng-submit="generateToken()">

    <button type="button" class="close" ng-click="cancel()">
      ×
      Close
    </button>

Generate Application Token

        <button type="button" class="close" data-dismiss="alert">
          ×
          Close
        </button>
        {{issue}}

    <button type="reset" class="btn btn-default"
            ng-click="cancel()" translate="global.form.no" ng-disabled="isGeneratingToken">No</button>

    <button type="submit" ng-hide="isGeneratingTokenSucceed"
            class="btn btn-primary" translate="global.form.generate" ng-disabled="isGeneratingToken">Generate</button>

    <button ng-show="isGeneratingTokenSucceed" ng-click="restart()"
            class="btn btn-primary" translate="global.form.restart">Restart</button>

</form>