text:
package com.boya.kites.liberator.domain;

import com.mongodb.BasicDBObject;
import org.bson.BasicBSONObject;
import org.bson.types.BasicBSONList;
import org.canedata.field.Fields;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created  IN BOYA by lz on 15-8-26.
 */
public class ClassifyCustomization implements Serializable, Base<ClassifyCustomization> {

    private static final long serialVersionUID;

    static {
        serialVersionUID = -5809782578272943999L;
    }

    private String id;
    private String name;
    private Clazz r;
    private Clazz s;
    private int copyright;
    private int catalog;
    private long crtAt;
    private long updAt;
    private int order;
    private String operator;
    private String tid;
    private String summary;
    private Display display;
    private int status;
    private List<Data> data;

    public static class Data implements Serializable {

        private static final long serialVersionUID;

        static {
            serialVersionUID = -5809782578272943999L;
        }

        private String id;
        private int order;
        private int type;
        private String title;
        private String summary;
        private String content;
        private String url;
        private String icon;
        private List<String> covers;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public int getOrder() {
            return order;
        }

        public void setOrder(int order) {
            this.order = order;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getSummary() {
            return summary;
        }

        public void setSummary(String summary) {
            this.summary = summary;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getIcon() {
            return icon;
        }

        public void setIcon(String icon) {
            this.icon = icon;
        }

        public List<String> getCovers() {
            return covers;
        }

        public void setCovers(List<String> covers) {
            this.covers = covers;
        }
    }

    public static class Display implements Serializable {

        private static final long serialVersionUID;

        static {
            serialVersionUID = -5809782578272943999L;
        }

        private int style;
        private int type;

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        public int getStyle() {
            return style;
        }

        public void setStyle(int style) {
            this.style = style;
        }
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Clazz getR() {
        return r;
    }

    public void setR(Clazz r) {
        this.r = r;
    }

    public Clazz getS() {
        return s;
    }

    public void setS(Clazz s) {
        this.s = s;
    }

    public int getCopyright() {
        return copyright;
    }

    public void setCopyright(int copyright) {
        this.copyright = copyright;
    }

    public int getCatalog() {
        return catalog;
    }

    public void setCatalog(int catalog) {
        this.catalog = catalog;
    }

    public long getCrtAt() {
        return crtAt;
    }

    public void setCrtAt(long crtAt) {
        this.crtAt = crtAt;
    }

    public long getUpdAt() {
        return updAt;
    }

    public void setUpdAt(long updAt) {
        this.updAt = updAt;
    }

    public String getOperator() {
        return operator;
    }

    public void setOperator(String operator) {
        this.operator = operator;
    }

    public String getTid() {
        return tid;
    }

    public void setTid(String tid) {
        this.tid = tid;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public Display getDisplay() {
        return display;
    }

    public void setDisplay(Display display) {
        this.display = display;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public List<Data> getData() {
        return data;
    }

    public void setData(List<Data> data) {
        this.data = data;
    }

    public int getOrder() {
        return order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    /**
     * 这里获取全部数据
     *
     * @param field
     * @return
     */
    @Override
    public ClassifyCustomization fill(Fields field) {
        ClassifyCustomization tc = null;
        if (null != field) {
            tc = new ClassifyCustomization();
            tc.setId(field.getString("_" + Meta.ID));
            if (null != field.get(Meta.NAME))
                tc.setName(field.getString(Meta.NAME));
            BasicDBObject c = field.get("c");
            BasicDBObject r = (BasicDBObject) c.get("r");
            BasicDBObject s = (BasicDBObject) c.get("s");
            Clazz rootc = new Clazz();
            rootc.setId(r.getString("id"));
            tc.setR(rootc);
            Clazz roots = new Clazz();
            roots.setId(s.getString("id"));
            tc.setS(roots);
            if (null != field.get(Meta.COPYRIGHT))
                tc.setCopyright(field.getInt(Meta.COPYRIGHT));
            if (null != field.get(Meta.CATALOG))
                tc.setCatalog(field.getInt(Meta.CATALOG));
            if (null != field.get(Meta.CRTAT))
                tc.setCrtAt(field.getLong(Meta.CRTAT));
            if (null != field.get(Meta.UPDAT))
                tc.setUpdAt(field.getLong(Meta.UPDAT));
            if (null != field.get(Meta.OPERATOR))
                tc.setOperator(field.getString(Meta.OPERATOR));
            if (null != field.get(Meta.TID))
                tc.setTid(field.getString(Meta.TID));
            if (null != field.get(Meta.SUMMARY))
                tc.setSummary(field.getString(Meta.SUMMARY));
            if (null != field.get(Meta.STATUS))
                tc.setStatus(field.getInt(Meta.STATUS));
            if (null != field.get(Meta.ORDER))
                tc.setOrder(field.getInt(Meta.ORDER));
            if (null != field.get(Meta.DISPLAY)) {
                Display display1 = new Display();
                BasicDBObject bdis = field.get(Meta.DISPLAY);
                display1.setStyle(bdis.getInt(Meta.STYLE));
                display1.setType(bdis.getInt(Meta.TYPE));
                tc.setDisplay(display1);
            }
            BasicBSONList dataCover = (BasicBSONList) field.get(Meta.DATA);
            List<Data> datas = new ArrayList<>();
            if (null != dataCover) {
                for (int j = 0; dataCover.size() > j; j++) {
                    BasicBSONObject bb = (BasicBSONObject) dataCover.get(j);
                    Data d = new Data();
                    d.setId(bb.getString(Meta.ID));
                    d.setOrder(bb.getInt(Meta.ORDER));
                    d.setType(bb.getInt(Meta.TYPE));
                    d.setTitle(bb.getString(Meta.TITLE));
                    d.setSummary(bb.getString(Meta.SUMMARY));
                    d.setContent(bb.getString(Meta.CONTENT));
                    d.setUrl(bb.getString(Meta.URL));
                    d.setIcon(bb.getString(Meta.ICON));
                    BasicBSONList Coverbb = (BasicBSONList) bb.get(Meta.COVERS);
                    List<String> listCover = new ArrayList<>();
                    if (null != Coverbb) {
                        for (int i = 0; Coverbb.size() > i; i++) {
                            listCover.add((String) Coverbb.get(i));
                        }
                        d.setCovers(listCover);
                    }
                    datas.add(d);
                }
            }
            tc.setData(datas);
        }
        return tc;
    }

    public static final class Meta {
        public static final String TABLENAME = "classifyCustomization";
        public static final String ID = "id";
        public static final String NAME = "name";
        public static final String C = "c";
        public static final String R = "r";
        public static final String S = "s";
        public static final String COPYRIGHT = "copyright";
        public static final String CATALOG = "catalog";
        public static final String CRTAT = "crtAt";
        public static final String UPDAT = "updAt";
        public static final String OPERATOR = "operator";
        public static final String TID = "tid";
        public static final String SUMMARY = "summary";
        public static final String DISPLAY = "display";
        public static final String TYPE = "type";
        public static final String STYLE = "style";
        public static final String STATUS = "status";
        public static final String DATA = "data";
        public static final String ORDER = "order";
        public static final String TITLE = "title";
        public static final String CONTENT = "content";
        public static final String URL = "url";
        public static final String ICON = "icon";
        public static final String COVERS = "covers";
        //状态定义
        public static final int STAUTS_OPEN = 1;
        public static final int STAUTS_EDIT = 2;
        public static final int STAUTS_CLOSE = 9;
    }
}


text:
//===-- sanitizer/asan_interface.h ------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file is a part of HWAddressSanitizer.
//
// Public interface header.
//===----------------------------------------------------------------------===//
#ifndef SANITIZER_HWASAN_INTERFACE_H
#define SANITIZER_HWASAN_INTERFACE_H

#include <sanitizer/common_interface_defs.h>

#ifdef __cplusplus
extern "C" {
#endif
  // Libc hook for program startup in statically linked executables.
  // Initializes enough of the runtime to run instrumented code. This function
  // should only be called in statically linked executables because it modifies
  // the GOT, which won't work in regular binaries because RELRO will already
  // have been applied by the time the function is called. This also means that
  // the function should be called before libc applies RELRO.
  // Does not call libc unless there is an error.
  // Can be called multiple times.
  void __hwasan_init_static(void);

  // This function may be optionally provided by user and should return
  // a string containing HWASan runtime options. See asan_flags.h for details.
  const char* __hwasan_default_options(void);

  void __hwasan_enable_allocator_tagging(void);
  void __hwasan_disable_allocator_tagging(void);

  // Mark region of memory with the given tag. Both address and size need to be
  // 16-byte aligned.
  void __hwasan_tag_memory(const volatile void *p, unsigned char tag,
                           size_t size);

  /// Set pointer tag. Previous tag is lost.
  void *__hwasan_tag_pointer(const volatile void *p, unsigned char tag);

  // Set memory tag from the current SP address to the given address to zero.
  // This is meant to annotate longjmp and other non-local jumps.
  // This function needs to know the (almost) exact destination frame address;
  // clearing shadow for the entire thread stack like __asan_handle_no_return
  // does would cause false reports.
  void __hwasan_handle_longjmp(const void *sp_dst);

  // Set memory tag for the part of the current thread stack below sp_dst to
  // zero. Call this in vfork() before returning in the parent process.
  void __hwasan_handle_vfork(const void *sp_dst);

  // Libc hook for thread creation. Should be called in the child thread before
  // any instrumented code.
  void __hwasan_thread_enter();

  // Libc hook for thread destruction. No instrumented code should run after
  // this call.
  void __hwasan_thread_exit();

  // Print shadow and origin for the memory range to stderr in a human-readable
  // format.
  void __hwasan_print_shadow(const volatile void *x, size_t size);

  // Print one-line report about the memory usage of the current process.
  void __hwasan_print_memory_usage();

  /* Returns the offset of the first byte in the memory range that can not be
   * accessed through the pointer in x, or -1 if the whole range is good. */
  intptr_t __hwasan_test_shadow(const volatile void *x, size_t size);

  int __sanitizer_posix_memalign(void **memptr, size_t alignment, size_t size);
  void * __sanitizer_memalign(size_t alignment, size_t size);
  void * __sanitizer_aligned_alloc(size_t alignment, size_t size);
  void * __sanitizer___libc_memalign(size_t alignment, size_t size);
  void * __sanitizer_valloc(size_t size);
  void * __sanitizer_pvalloc(size_t size);
  void __sanitizer_free(void *ptr);
  void __sanitizer_cfree(void *ptr);
  size_t __sanitizer_malloc_usable_size(const void *ptr);
  struct mallinfo __sanitizer_mallinfo();
  int __sanitizer_mallopt(int cmd, int value);
  void __sanitizer_malloc_stats(void);
  void * __sanitizer_calloc(size_t nmemb, size_t size);
  void * __sanitizer_realloc(void *ptr, size_t size);
  void * __sanitizer_reallocarray(void *ptr, size_t nmemb, size_t size);
  void * __sanitizer_malloc(size_t size);
#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // SANITIZER_HWASAN_INTERFACE_H

redpajama_set_name: RedPajamaGithub


text:
package com.md_5.fondue.protocol.packet;

import com.md_5.fondue.protocol.PacketHandler;
import io.netty.buffer.ByteBuf;
import lombok.EqualsAndHashCode;
import lombok.ToString;

@ToString
@EqualsAndHashCode(callSuper = false)
public class Packet16CollectItem extends Packet {

    private int collected;
    private int collector;

    public Packet16CollectItem() {
    }

    @Override
    public void read(ByteBuf in) {
        collected = in.readInt();
        collector = in.readInt();
    }

    @Override
    public void write(ByteBuf out) {
        out.writeInt(collected);
        out.writeInt(collector);
    }

    @Override
    public void handle(PacketHandler handler) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}


text:
/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/

var N = parseInt(readline());

var strengths = [];

// Fill array of strengths
for (var i = 0; i < N; i++) {
    var Pi = parseInt(readline());
    strengths.push(Pi);
}

// Sort it
strengths.sort(function(a,b) {
    return a - b;
});

// Find the smallest difference
var diff = Math.pow(2, 54);

for(i = 1; i < N && diff > 0; i++) {
    var innerDiff = strengths[i] - strengths[i-1];

    if (diff > innerDiff) {
        diff = innerDiff
    }
}

print(diff);


text:
namespace armnn
{

void Gather(const TensorInfo& paramsInfo,
            const TensorInfo& indicesInfo,
            const TensorInfo& outputInfo,
            Decoder<float>& params,
            const int32_t* indices,
            Encoder<float>& output,
            const int32_t = 0);

} //namespace armnn


text:
package com.trilead.ssh2.transport;

import java.io.IOException;

/**
 * MessageHandler.
 *
 * @author Christian Plattner, plattner@trilead.com
 * @version $Id: MessageHandler.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
 */
public interface MessageHandler
{
	public void handleMessage(byte[] msg, int msglen) throws IOException;
}


text:
namespace mediapipe {
namespace time_series_util {
namespace {

TEST(TimeSeriesUtilTest, LogWarningIfTimestampIsInconsistent) {
  // "Special" timestamps aren't considered consistent.
  EXPECT_FALSE(LogWarningIfTimestampIsInconsistent(Timestamp::Unset(),
                                                   Timestamp(0), 0, 1));

  EXPECT_TRUE(LogWarningIfTimestampIsInconsistent(
      Timestamp(2 * Timestamp::kTimestampUnitsPerSecond),
      Timestamp(1 * Timestamp::kTimestampUnitsPerSecond), 10000, 10000.0));
  EXPECT_FALSE(LogWarningIfTimestampIsInconsistent(
      Timestamp(2 * Timestamp::kTimestampUnitsPerSecond),
      Timestamp(1 * Timestamp::kTimestampUnitsPerSecond), 10001, 10000.0));
}

TEST(TimeSeriesUtilTest, FillTimeSeriesHeaderIfValid) {
  {
    Packet empty_packet;
    TimeSeriesHeader header;
    EXPECT_FALSE(FillTimeSeriesHeaderIfValid(empty_packet, &header).ok());
  }

  {
    std::unique_ptr<TimeSeriesHeader> valid_header(new TimeSeriesHeader);
    valid_header->set_sample_rate(1234.5);
    valid_header->set_num_channels(3);
    Packet valid_packet = Adopt(valid_header.release());
    TimeSeriesHeader packet_header;
    MP_EXPECT_OK(FillTimeSeriesHeaderIfValid(valid_packet, &packet_header));
    EXPECT_EQ(packet_header.sample_rate(), 1234.5);
    EXPECT_EQ(packet_header.num_channels(), 3);
  }

  {
    std::unique_ptr<TimeSeriesHeader> missing_num_channels_header(
        new TimeSeriesHeader);
    missing_num_channels_header->set_sample_rate(1234.5);
    Packet packet_with_missing_num_channel =
        Adopt(missing_num_channels_header.release());
    TimeSeriesHeader header;
    EXPECT_FALSE(
        FillTimeSeriesHeaderIfValid(packet_with_missing_num_channel, &header)
            .ok());
  }

  {
    std::unique_ptr<TimeSeriesHeader> missing_sample_rate_header(
        new TimeSeriesHeader);
    missing_sample_rate_header->set_num_channels(3);
    Packet packet_with_missing_sample_rate =
        Adopt(missing_sample_rate_header.release());
    TimeSeriesHeader header;
    EXPECT_FALSE(
        FillTimeSeriesHeaderIfValid(packet_with_missing_sample_rate, &header)
            .ok());
  }
}

TEST(TimeSeriesUtilTest, FillMultiStreamTimeSeriesHeaderIfValid) {
  {
    Packet empty_packet;
    MultiStreamTimeSeriesHeader header;
    EXPECT_FALSE(
        FillMultiStreamTimeSeriesHeaderIfValid(empty_packet, &header).ok());
  }

  {
    Packet packet_with_empty_header = Adopt(new MultiStreamTimeSeriesHeader());
    MultiStreamTimeSeriesHeader header;
    EXPECT_FALSE(FillMultiStreamTimeSeriesHeaderIfValid(
                     packet_with_empty_header, &header)
                     .ok());
  }

  {
    std::unique_ptr<MultiStreamTimeSeriesHeader> valid_header(
        new MultiStreamTimeSeriesHeader);
    valid_header->mutable_time_series_header()->set_sample_rate(1234.5);
    valid_header->mutable_time_series_header()->set_num_channels(3);
    Packet valid_packet = Adopt(valid_header.release());
    MultiStreamTimeSeriesHeader packet_header;
    MP_EXPECT_OK(
        FillMultiStreamTimeSeriesHeaderIfValid(valid_packet, &packet_header));
    EXPECT_EQ(packet_header.time_series_header().sample_rate(), 1234.5);
    EXPECT_EQ(packet_header.time_series_header().num_channels(), 3);
  }

  {
    TimeSeriesHeader missing_num_channels_header;
    std::unique_ptr<MultiStreamTimeSeriesHeader>
        header_with_invalid_time_series_header(new MultiStreamTimeSeriesHeader);
    header_with_invalid_time_series_header->mutable_time_series_header()
        ->set_sample_rate(1234.5);
    Packet packet_with_invalid_time_series_header =
        Adopt(header_with_invalid_time_series_header.release());
    MultiStreamTimeSeriesHeader header;
    EXPECT_FALSE(FillMultiStreamTimeSeriesHeaderIfValid(
                     packet_with_invalid_time_series_header, &header)
                     .ok());
  }
}

TEST(IsMatrixShapeConsistentWithHeaderTest, BasicOperation) {
  TimeSeriesHeader header;
  header.set_num_samples(2);
  header.set_num_channels(3);

  EXPECT_TRUE(
      IsMatrixShapeConsistentWithHeader(Matrix::Zero(3, 2), header).ok());
  EXPECT_FALSE(
      IsMatrixShapeConsistentWithHeader(Matrix::Zero(0, 0), header).ok());
  // Transposed Matrix.
  EXPECT_FALSE(
      IsMatrixShapeConsistentWithHeader(Matrix::Zero(2, 3), header).ok());
}

TEST(IsMatrixShapeConsistentWithHeaderTest,
     EmptyHeaderConsistentWithAnyMatrix) {
  TimeSeriesHeader empty_header;
  EXPECT_TRUE(
      IsMatrixShapeConsistentWithHeader(Matrix::Zero(0, 0), empty_header).ok());
  EXPECT_TRUE(
      IsMatrixShapeConsistentWithHeader(Matrix::Zero(3, 2), empty_header).ok());
}

TEST(IsMatrixShapeConsistentWithHeaderTest,
     NumChannelsUnsetConsistentWithAnyNumRows) {
  TimeSeriesHeader header;
  header.set_num_channels(2);
  for (int num_cols : {1, 2, 5, 9}) {
    EXPECT_TRUE(
        IsMatrixShapeConsistentWithHeader(Matrix::Zero(2, num_cols), header)
            .ok());
  }
}

TEST(IsMatrixShapeConsistentWithHeaderTest,
     NumSamplesUnsetConsistentWithAnyNumColumns) {
  TimeSeriesHeader header;
  header.set_num_samples(2);
  for (int num_rows : {1, 2, 5, 9}) {
    EXPECT_TRUE(
        IsMatrixShapeConsistentWithHeader(Matrix::Zero(num_rows, 2), header)
            .ok());
  }
}

TEST(TimeSeriesUtilTest, SecondsToSamples) {
  // If the time is an integer multiple of the sampling period, we
  // should get an exact result.
  double sample_rate = 10.0;
  double integer_multiple_time = 5;
  EXPECT_EQ(integer_multiple_time * sample_rate,
            SecondsToSamples(integer_multiple_time, sample_rate));

  // Otherwise we should be within one sample.
  double arbitrary_time = 5.01;
  EXPECT_NEAR(arbitrary_time * sample_rate,
              SecondsToSamples(arbitrary_time, sample_rate), 1);
}

TEST(TimeSeriesUtilTest, SamplesToSeconds) {
  double sample_rate = 32.5;
  int64 num_samples = 128;
  EXPECT_EQ(num_samples / sample_rate,
            SamplesToSeconds(num_samples, sample_rate));
}

}  // namespace
}  // namespace time_series_util
}  // namespace mediapipe


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/label_device_address"
            android:textSize="18sp" />

        <Space
            android:layout_width="5dp"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/device_address"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/label_state"
            android:textSize="18sp" />

        <Space
            android:layout_width="5dp"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/connection_state"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/disconnected"
            android:textSize="18sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/bettery_"
            android:textSize="18sp" />

        <Space
            android:layout_width="5dp"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/data_battery"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/disconnected"
            android:textSize="18sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/label_data"
            android:textSize="18sp" />

        <Space
            android:layout_width="5dp"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/data_value"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/no_data"
            android:textSize="18sp" />
    </LinearLayout>

    <com.androidplot.xy.XYPlot
        android:id="@+id/degreedisp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        androidPlot.domainLabel="t"
        androidPlot.domainLabelWidget.labelPaint.textSize="@dimen/domain_label_font_size"
        androidPlot.graphWidget.domainLabelPaint.textSize="@dimen/domain_tick_label_font_size"
        androidPlot.graphWidget.domainOriginLabelPaint.textSize="@dimen/domain_tick_label_font_size"
        androidPlot.graphWidget.gridLinePaint.color="#000000"
        androidPlot.graphWidget.marginBottom="25dp"
        androidPlot.graphWidget.marginLeft="22dp"
        androidPlot.graphWidget.marginRight="10dp"
        androidPlot.graphWidget.marginTop="20dp"
        androidPlot.graphWidget.rangeLabelPaint.textSize="@dimen/range_tick_label_font_size"
        androidPlot.graphWidget.rangeOriginLabelPaint.textSize="@dimen/range_tick_label_font_size"
        androidPlot.legendWidget.heightMetric.value="25dp"
        androidPlot.legendWidget.iconSizeMetrics.heightMetric.value="15dp"
        androidPlot.legendWidget.iconSizeMetrics.widthMetric.value="15dp"
        androidPlot.legendWidget.positionMetrics.anchor="right_bottom"
        androidPlot.legendWidget.textPaint.textSize="@dimen/legend_text_font_size"
        androidPlot.rangeLabel="degree"
        androidPlot.rangeLabelWidget.labelPaint.textSize="@dimen/range_label_font_size"
        androidPlot.title="Gas Measurement"
        androidPlot.titleWidget.labelPaint.textSize="@dimen/title_font_size" />
</LinearLayout>


text:
package org.kuali.rice.kew.lookup.valuefinder;

import org.kuali.rice.core.api.util.ConcreteKeyValue;
import org.kuali.rice.core.api.util.KeyValue;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.krad.keyvalues.KeyValuesBase;

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

/**
 * This is a description of what this class does - chris don't forget to fill this in.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 *
 */
public class DocumentRouteStatusValuesFinder extends KeyValuesBase {

	private static
	<T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
	  List<T> list = new ArrayList<T>(c);
	  java.util.Collections.sort(list);
	  return list;
	}

	/**
	 * @see org.kuali.rice.krad.keyvalues.KeyValuesFinder#getKeyValues()
	 */
	@Override
	public List<KeyValue> getKeyValues() {
		List<KeyValue> keyValues = new ArrayList<KeyValue>();
		List<String> docStatusParentKeys = asSortedList(KewApiConstants.DOCUMENT_STATUS_PARENT_TYPES.keySet());

		for (String parentKey : docStatusParentKeys) {
			KeyValue keyLabel = new ConcreteKeyValue(parentKey,parentKey + " Statuses");
			keyValues.add(keyLabel);

			// each parent key, pending, successful, unsuccessful each has a sub list of real document statuses
			List<String> docStatusCodes = KewApiConstants.DOCUMENT_STATUS_PARENT_TYPES.get(parentKey);
			for(String docStatusCode : docStatusCodes){
				KeyValue docStat = new ConcreteKeyValue(docStatusCode, "- "+ KewApiConstants.DOCUMENT_STATUSES.get(docStatusCode));
				keyValues.add(docStat);
			}
		}
		return keyValues;
	}

}


text:
namespace talg
{

}


text:
'use strict';
/**
 * Dime - application.js
 *
 * Initialize the javascript application
 */
(function ($, Backbone, _, moment, window) {

    // Initialize namespace Dime with collection, model and views object
    var Dime = window.Dime || function () {
        var store = {
            routes:{},
            templates:{}
        };

        var storedTemplate = function(name, data) {
            if (store.templates[name]) {
                var item = store.templates[name];

                if (item.type) {
                    if (item.type === 'html') {
                        return item.data;
                    } else if (item.type === 'func'){
                        return (data) ? item.data(data) : item.data;
                    }
                }
                return item;
            }

            Dime.throw('Template name [' + name + '] was not found in store.', Dime);
        }

        // Return Dime object
        return {
            Collection:{},
            Helper:{},
            Model:{},
            Views:{},
            Route:{
                Activities:'api/activities',
                Customers:'api/customers',
                Parser:'api/process',
                Projects:'api/projects',
                Services:'api/services',
                Settings:'api/settings',
                Timeslices:'api/timeslices',
                Tags:'api/tags',
                Users:'api/users'
            },
            /**
             * Log a message if a logger exists
             *
             * @param msg message to log
             * @param level optional, [INFO|WARN|ERROR]
             * @return Dime
             */
            log:function (msg, level) {
                if (console && console.log) {
                    var content = [];
                    if (level) {
                        content.push(level);
                    }
                    content.push(moment().format('HH:mm:ss'));
                    content.push(msg);
                    console.log(content);
                }
                return this;
            },
            /**
             * add notification to area-header
             *
             * @param message message of notification
             * @param type, if undefined will be warning style [info|success|error]
             * @param delay, default: 2000
             */
            notify:function (message, type, delay) {
                var template = this.render("#tpl-application-notification");
                if (delay === undefined) {
                    delay = 2000;
                }

                if (template) {
                    var header = $('#area-header');
                    if (header) {
                        var data = {message: message, type: ' alert-info'};
                        if (type !== undefined) {
                            data.type = ' alert-' + type;
                        }
                        var $el = $(template(data));
                        if (delay) {
                            $el.delay(2000).promise().done(function () {
                                $el.fadeOut('slow', function() {
                                    $el.detach().remove();
                                });
                            });
                        }
                        header.append($el);
                    }
                }
            },
            /**
             * Create namespace object if needed in Dime splitted by dot (.).
             * Example:
             *   Dime.provide('Views.Service') -> create Service in Views
             *
             * @param name Namspace items splitted by dot (.)
             * @param obj optional, set to the last item in path
             * @param force optinal, force set of object
             * @return parent object
             */
            provide:function (name, obj, force) {
                if (!name) {
                    throw "Give a name for Dime.provide(name)";
                }
                var parent = this;

                var parts = name.split('.');
                if (parts) {
                    for (var i = 0; i < parts.length; i++) {
                        if (!parent[parts[i]]) {
                            if (i >= parts.length - 1 && obj) {
                                parent[parts[i]] = obj;
                            } else {
                                parent[parts[i]] = {};
                            }
                        }
                        parent = parent[parts[i]];
                    }

                    if (force) {
                        parent = obj;
                    }
                }

                return parent;
            },
            /**
             * Render template
             *
             * @param name Name of Symfony2 template (e.g. DimeTimetrackerFrontedBundle:Activity:form)
             * @param data Object will be pushed into template function
             * @param cache disable cache if you want
             * @return {*} undefined if nothing was found
             */
            render: function(name, data, cache) {
                if (!name) {
                    this.throw("Give a name for Dime.render(name)", this);
                }
                if (cache === undefined) {
                    cache = true;
                }
                if (data && !data.App) {
                    data.App = this;
                }
                if (cache && store.templates[name]) {
                    return storedTemplate(name, data);
                }

                if (name.search(/:/) !== -1) {
                    $.ajax({
                        async:false,
                        url:'template/' + name,
                        dataType:'html',
                        success:function (data) {
                            store.templates[name] = { data: data, type: 'html' };
                        }
                    });
                } else {
                    var html = $(name).html();
                    if (html) {
                        var temp = _.template(html);
                        if (cache) {
                            store.templates[name] = { data: temp, type: 'func' };
                        }
                        return (data) ? temp(data) : temp;
                    }
                    this.throw('Selector[' + name + '] not found', this);
                }

                return storedTemplate(name, data);
            },
            /**
             * Initialize the whole app
             *
             * @return Dime
             */
            run:function () {
                this.log('Starting application', 'INFO');

                // Initialize
                var initialize = this.hook.where({scope: 'initialize'});
                if (initialize.length > 0) {
                    for (var i = 0; i < initialize.length; i++) {
                        var model = initialize[i],
                            callback = model.get('callback');

                        if (callback) {
                            this.log('Initialize ' + model.id, 'DEBUG');
                            callback();
                        }
                    }
                }

                return this;
            },
            'throw': function(message, source) {
                throw { message: message, source: source };
            }
        };
    }();

    var ApplicationRouter = Backbone.Router.extend({
        el:undefined,
        $el:undefined,
        currentRoute:undefined,
        currentView:undefined,
        navigate:function (fragment, options) {
            this.currentRoute = fragment;
            return Backbone.Router.prototype.navigate.call(this, fragment, options);
        },
        route: function(route, name, callback) {
            Dime.log("Add route [" + route + "]");
            return Backbone.Router.prototype.route.call(this, route, name, callback);
        },
        setElement:function (el) {
            this.el = el;
            this.$el = $(this.el);
        },
        switchView:function (view) {
            if (this.currentView) {
                // Detach the old view
                this.currentView.remove();
                this.$el.addClass('loading');
            }
            // fetch template
            view.$el.html(Dime.render(view.template));
            this.$el.html(view.el);
            view.render();
            this.currentView = view;
            this.$el.removeClass('loading');

            return view;
        }
    });
    Dime.provide('router', new ApplicationRouter());

    // Expose Dime to the global object
    if (!window.Dime) {
        window.Dime = Dime;
    }

    $(function () {
        Dime.run();
    });
})(jQuery, Backbone, _, moment, window);


text:
package com.dfyy.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dfyy.bussiness.Blacklist;
import com.dfyy.bussiness.Message;
import com.dfyy.bussiness.SUser;
import com.dfyy.dao.BlacklistDao;
import com.dfyy.dao.SUserDao;

@Service
@Transactional
public class BlacklistService {

	@Autowired
	private BlacklistDao dao;

	@Autowired
	private SUserDao userDao;

	public List<Blacklist> getByPage(int page, Integer size) {
		return dao.getByPage(new PageRequest(page, size));
	}

	public int getCount() {
		return dao.getCount();
	}

	public Blacklist getByUid(String uid) {
		return dao.getByUid(uid, 0);
	}

	public Blacklist getByUid(String uid, Integer module) {
		return dao.getByUid(uid, module);
	}

	public Blacklist addToBlackList(String phone, Integer module, String reason, String operator) {
		SUser user = userDao.getUserByPhone(phone);
		if (user == null) {
			throw new RuntimeException("手机号为" + phone + "的用户不存在");
		}
		if (dao.getByUid(user.getId(), module) != null) {
			throw new RuntimeException("手机号为" + phone + "的用户已加入黑名单");
		}

		Blacklist bl = new Blacklist();
		bl.setStatus(0);
		bl.setTime(new Date());
		bl.setUser(user);
		bl.setModule(module);
		bl.setReason(reason);
		bl.setOperator(operator);
		dao.save(bl);
		return bl;
	}

	public void delete(Integer bid) {
		Blacklist bl = dao.findOne(bid);
		bl.setStatus(-1);
		dao.save(bl);
	}

}


text:
using System.Net;
using System.Web;
using System.Xml.XPath;
using ClickToCall.Web.Controllers;
using ClickToCall.Web.Services;
using ClickToCall.Web.Tests.Extensions;
using Moq;
using NUnit.Framework;
using TestStack.FluentMVCTesting;

namespace ClickToCall.Web.Tests.Controllers
{
    [TestFixture]
    public class CallControllerTests
    {
        private Mock<IRequestValidationService> _mockValidatorService;

        [SetUp]
        public void Init()
        {
            _mockValidatorService = new Mock<IRequestValidationService>();
        }

        [Test]
        public void ShouldRespondUnauthorizedOnInvalidRequest()
        {
            _mockValidatorService
                .Setup(service => service.IsValidRequest(It.IsAny<HttpContext>(), It.IsAny<string>()))
                .Returns(false);

            var controller = new CallController(_mockValidatorService.Object);
            controller
                .WithCallTo(c => c.Connect("sales-number"))
                .ShouldGiveHttpStatus(HttpStatusCode.Unauthorized);
        }

        [Test]
        public void ShouldRespondWithTwiMLOnValidRequest()
        {
            _mockValidatorService
                .Setup(service => service.IsValidRequest(It.IsAny<HttpContext>(), It.IsAny<string>()))
                .Returns(true);

            var controller = new CallController(_mockValidatorService.Object);
            controller
                .WithCallTo(c => c.Connect("sales-number"))
                .ShouldReturnTwiMLResult(data =>
                {
                    StringAssert.Contains(
                        "Thanks for contacting", data.XPathSelectElement("Response/Say").Value);
                    Assert.That(data.XPathSelectElement("Response/Dial").Value, Is.EqualTo("sales-number"));
                });
        }
    }
}


text:
/*************************************************************************/
/*                                                                       */
/*                Centre for Speech Technology Research                  */
/*                     University of Edinburgh, UK                       */
/*                         Copyright (c) 1996                            */
/*                        All Rights Reserved.                           */
/*                                                                       */
/*  Permission is hereby granted, free of charge, to use and distribute  */
/*  this software and its documentation without restriction, including   */
/*  without limitation the rights to use, copy, modify, merge, publish,  */
/*  distribute, sublicense, and/or sell copies of this work, and to      */
/*  permit persons to whom this work is furnished to do so, subject to   */
/*  the following conditions:                                            */
/*   1. The code must retain the above copyright notice, this list of    */
/*      conditions and the following disclaimer.                         */
/*   2. Any modifications must be clearly marked as such.                */
/*   3. Original authors' names are not deleted.                         */
/*   4. The authors' names are not used to endorse or promote products   */
/*      derived from this software without specific prior written        */
/*      permission.                                                      */
/*                                                                       */
/*  THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK        */
/*  DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING      */
/*  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT   */
/*  SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE     */
/*  FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES    */
/*  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN   */
/*  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,          */
/*  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF       */
/*  THIS SOFTWARE.                                                       */
/*                                                                       */
/*************************************************************************/

#include "EST_unix.h"
#include "EST_ling_class.h"

/** @name Feature and Val Classes Example Code
  */
//@{

int main(void)
{

  /** @name Adding basic information to an EST_Item
  *
  * An item such as
  * <graphic fileref="../arch_doc/eq01.gif" format="gif"></graphic>
  * is constructed as follows: (note that
  * the attributes are in capitals by linguistic convention only:
  * attribute names are case sensitive and can be upper or lower
  * case).
  */
  //@{

  //@{ code
  EST_Item p;

  p.set("POS", "Noun");
  p.set("NAME", "example");
  p.set("FOCUS", "+");
  p.set("DURATION", 2.76);
  p.set("STRESS", 2);

  //@} code

  /** The type of the values in features is a
  * <classname>EST_Val</classname> class, which is a union which can
  * store ints, floats, EST_Strings, void pointers, and
  * <classname>EST_Features</classname>. The overloaded function
  * facility of C++ means that the <function>set()</function> can be
  * used for all of these.
  */

  //@}

  /** @name Accessing basic information in an Item
    *
    * When accessing the features, the type must be
    * specified. This is done most easily by using of a series of
    * functions whose type is coded by a capital letter:
    * </para>
    * <formalpara><title><function>F()</function></title><para> return value as a
    * float</para></formalpara>
    * <formalpara><title><function>I()</function></title><para> return value as a
    *	    integer</para></formalpara>
    * <formalpara><title><function>S()</function></title><para> return value as a
    * <formalpara><title><function>A()</function></title><para> return value as a
    *       EST_Features</para></formalpara>
    * <para>
    */

  //@{

  //@{ code
  cout << "Part of speech for p is " << p.S("POS") << endl;
  cout << "Duration for p is " << p.F("DURATION") << endl;
  cout << "Stress value for p is " << p.I("STRESS") << endl;
  //@} code

  /** </para>
    * <SIDEBAR>
    * <TITLE>Output</TITLE>
    * <screen>
    * "Noun"
    * 2.75
    * 1
    * </screen>
    * </SIDEBAR>
    * <para>
    * A optional default value can be given if a result is always desired
    */

  //@{ code
  cout << "Part of speech for p is "
      << p.S("POS") << endl;
  cout << "Syntactic Category for p is "
      << p.S("CAT", "Noun") << endl; // noerror
  //@} code

  //@}

  /** @name Nested feature structures in items
    *
    * Nested feature structures such as <xref linkend="eq11">
    * <example ID="eq11">
    *   <title>Example eq11</title>
    * <graphic fileref="../arch_doc/eq05.gif" format="gif"></graphic>
    * </example>
    * can be created in a number of ways:
    */
  //@{

  //@{ code

  p.set("NAME", "d");
  p.set("VOICE", "+");
  p.set("CONTINUANT", "-");
  p.set("SONORANT", "-");

  EST_Features f;
  p.set("PLACE OF ARTICULATION", f); // copy in empty feature set here

  p.A("PLACE OF ARTICULATION").set("CORONAL", "+");
  p.A("PLACE OF ARTICULATION").set("ANTERIOR", "+");
  //@} code

  /** or by filling the values in an EST_Features object and
    * copying it in:
    */

  //@{ code
  EST_Features f2;

  f2.set("CORONAL", "+");
  f2.set("ANTERIOR", "+");

  p.set("PLACE OF ARTICULATION", f2);
  //@} code

  /** Nested features can be accessed by multiple calls to the
    * accessing commands:
    */

  //@{ code
  cout << "Anterior value is: " << p.A("PLACE OF ARTICULATION").S("ANTERIOR");
  cout << "Coronal value is: " << p.A("PLACE OF ARTICULATION").S("CORONAL");
  //@} code

  /** The first command is <function>A()</function> because PLACE is a
    * feature structure, and the second command is
    * <function>S()</function> because it returns a string (the
    * value or ANTRIOR or CORONAL). A shorthand is provided to
    * extract the value in a single statement:
    */

  //@{ code
  cout << "Anterior value is: " << p.S("PLACE OF ARTICULATION.ANTERIOR");
  cout << "Coronal value is: " << p.S("PLACE OF ARTICULATION.CORONAL");
  //@} code

  /** Again, as the last value to be returned is a string
    * <function>S()</function> must be used. This shorthand can also be used
    * to set the features:
    */

  //@{ code

  p.set("PLACE OF ARTICULATION.CORONAL", "+");
  p.set("PLACE OF ARTICULATION.ANTERIOR", "+");
  //@} code

  /** this is the easiest and most commonly used method. */

  //@}

  /** @name Utility functions for items
    *
    * The presence of a attribute can be checked using
    * <function>f_present()</function>, which returns true if the
    *  attribute is in the item:
    */
  //@{

  //@{ code
  cout << "This is true: " << p.f_present("PLACE OF ARTICULATION");
  cout << "This is false: " << p.f_present("MANNER");
  //@} code

  /** A attribute can be removed by <function>f_remove</function>
    */

  //@{ code
  p.f_remove("PLACE OF ARTICULATION");
  //@} code

  //@}

  exit(0);

}
//@}


text:
package com.google.errorprone.refaster;

import com.google.common.testing.EqualsTester;
import com.google.common.testing.SerializableTester;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests for {@link ULocalVarIdent}.
 *
 * @author lowasser@google.com (Louis Wasserman)
 */
@RunWith(JUnit4.class)
public class ULocalVarIdentTest {
  @Test
  public void equality() {
    new EqualsTester()
        .addEqualityGroup(ULocalVarIdent.create("foo"))
        .addEqualityGroup(ULocalVarIdent.create("bar"))
        .testEquals();
  }

  @Test
  public void serialization() {
    SerializableTester.reserializeAndAssert(ULocalVarIdent.create("foo"));
  }
}


text:
#!/usr/bin/env node

const shell = require('shelljs');
const path = require('path');
const fs = require('fs');
const ROOT = path.join(__dirname, '..', '..');

function updateSubprojectHelp () {
    console.log('Updates the subproject path of the CordovaLib entry to point to this script\'s version of Cordova.');
    console.log('Usage: CordovaVersion/bin/update_cordova_project path/to/your/app.xcodeproj [path/to/CordovaLib.xcodeproj]');
}

function setShellFatal (value, func) {
    const oldVal = shell.config.fatal;
    shell.config.fatal = value;
    func();
    shell.config.fatal = oldVal;
}

function copyJsAndCordovaLib (projectPath, projectName, use_shared) {
    shell.cp('-f', path.join(ROOT, 'CordovaLib', 'cordova.js'), path.join(projectPath, 'www'));
    shell.cp('-rf', path.join(ROOT, 'cordova-js-src'), path.join(projectPath, 'platform_www'));
    shell.cp('-f', path.join(ROOT, 'CordovaLib', 'cordova.js'), path.join(projectPath, 'platform_www'));

    fs.lstat(path.join(projectPath, 'CordovaLib'), function (err, stats) {
        if (!err) {
            if (stats.isSymbolicLink()) {
                fs.unlinkSync(path.join(projectPath, 'CordovaLib'));
            } else {
                shell.rm('-rf', path.join(projectPath, 'CordovaLib'));
            }
        }

        if (use_shared) {
            update_cordova_subproject([path.join(projectPath, projectName + '.xcodeproj', 'project.pbxproj')]);
            // Symlink not used in project file, but is currently required for plugman because
            // it reads the VERSION file from it (instead of using the cordova/version script
            // like it should).
            fs.symlinkSync(path.join(ROOT, 'CordovaLib'), path.join(projectPath, 'CordovaLib'));
        } else {
            const r = path.join(projectPath, projectName);
            const srcLib = path.join(ROOT, 'CordovaLib');
            const dstLib = path.join(projectPath, 'CordovaLib');
            shell.mkdir('-p', path.join(dstLib, 'CordovaLib.xcodeproj'));
            shell.cp('-f', path.join(r, '.gitignore'), projectPath);
            shell.cp('-rf', path.join(srcLib, 'CordovaLib'), dstLib);
            shell.cp('-f', path.join(srcLib, 'VERSION'), dstLib);
            shell.cp('-f', path.join(srcLib, 'cordova.js'), dstLib);
            shell.cp('-f', path.join(srcLib, 'CordovaLib', 'CordovaLib-Prefix.pch'), path.join(dstLib, 'CordovaLib'));
            shell.cp('-f', path.join(srcLib, 'CordovaLib.xcodeproj', 'project.pbxproj'), path.join(dstLib, 'CordovaLib.xcodeproj'));
            update_cordova_subproject([path.join(r + '.xcodeproj', 'project.pbxproj'), path.join(dstLib, 'CordovaLib.xcodeproj', 'project.pbxproj')]);
        }
    });
}

function copyScripts (projectPath) {
    const srcScriptsDir = path.join(ROOT, 'bin', 'templates', 'scripts', 'cordova');
    const destScriptsDir = path.join(projectPath, 'cordova');

    // Delete old scripts directory.
    shell.rm('-rf', destScriptsDir);

    // Copy in the new ones.
    const binDir = path.join(ROOT, 'bin');
    shell.cp('-r', srcScriptsDir, projectPath);

    const nodeModulesDir = path.join(ROOT, 'node_modules');
    if (fs.existsSync(nodeModulesDir)) shell.cp('-r', nodeModulesDir, destScriptsDir);

    // Copy the check_reqs script
    shell.cp(path.join(binDir, 'check_reqs*'), destScriptsDir);
    shell.cp(path.join(binDir, 'lib', 'check_reqs.js'), path.join(destScriptsDir, 'lib'));

    // Copy the version scripts
    shell.cp(path.join(binDir, 'apple_osx_version'), destScriptsDir);
    shell.cp(path.join(binDir, 'apple_xcode_version'), destScriptsDir);
    shell.cp(path.join(binDir, 'lib', 'versions.js'), path.join(destScriptsDir, 'lib'));

    // Make sure they are executable (sometimes zipping them can remove executable bit)
    shell.find(destScriptsDir).forEach(function (entry) {
        shell.chmod(755, entry);
    });
}

function detectProjectName (projectDir) {
    const files = fs.readdirSync(projectDir);
    for (let i = 0; i < files.length; ++i) {
        const m = /(.*)\.xcodeproj$/.exec(files[i]);
        if (m) {
            return m[1];
        }
    }
    throw new Error('Could not find an .xcodeproj directory within ' + projectDir);
}

function AbsParentPath (_path) {
    return path.resolve(path.dirname(_path));
}

function AbsProjectPath (relative_path) {
    let absolute_path = path.resolve(relative_path);
    if (/.pbxproj$/.test(absolute_path)) {
        absolute_path = AbsParentPath(absolute_path);
    } else if (!(/.xcodeproj$/.test(absolute_path))) {
        throw new Error('The following is not a valid path to an Xcode project' + absolute_path);
    }
    return absolute_path;
}

function relpath (_path, start) {
    start = start || process.cwd();
    return path.relative(path.resolve(start), path.resolve(_path));
}

/*
 * Creates a new OSX project with the following options:
 *
 * - --link (optional): Link directly against the shared copy of the CordovaLib instead of a copy of it
 * - --cli (optional): Use the CLI-project template
 * - <path_to_new_project>: Path to your new Cordova OSX project
 * - <package_name>: Package name, following reverse-domain style convention
 * - <project_name>: Project name
 * - <project_template_dir>: Path to a project template (override)
 *
 */
exports.createProject = function (project_path, package_name, project_name, opts, events) {
    package_name = package_name || 'my.cordova.project';
    project_name = project_name || 'CordovaExample';
    const use_shared = !!opts.link;
    const bin_dir = path.join(ROOT, 'bin');
    const project_parent = path.dirname(project_path);
    const project_template_dir = opts.customTemplate || path.join(bin_dir, 'templates', 'project');

    // check that project path doesn't exist
    if (fs.existsSync(project_path)) {
        return Promise.reject('Project already exists');
    }

    // check that parent directory does exist so cp -r will not fail
    if (!fs.existsSync(project_parent)) {
        return Promise.reject(project_parent + ' does not exist. Please specify an existing parent folder');
    }

    // create the project directory and copy over files
    shell.mkdir(project_path);
    shell.cp('-rf', path.join(project_template_dir, 'www'), project_path);
    shell.cp('-rf', path.join(project_template_dir, '__PROJECT_NAME__.xcodeproj'), project_path);
    shell.mv(path.join(project_path, '__PROJECT_NAME__.xcodeproj'), path.join(project_path, project_name + '.xcodeproj'));
    shell.cp('-rf', path.join(project_template_dir, '__PROJECT_NAME__'), project_path);
    shell.mv(path.join(project_path, '__PROJECT_NAME__'), path.join(project_path, project_name));

    const r = path.join(project_path, project_name);
    shell.mv(path.join(r, '__PROJECT_NAME__-Info.plist'), path.join(r, project_name + '-Info.plist'));
    shell.mv(path.join(r, '__PROJECT_NAME__-Prefix.pch'), path.join(r, project_name + '-Prefix.pch'));
    shell.mv(path.join(r, 'gitignore'), path.join(r, '.gitignore'));

    const project_name_esc = project_name.replace(/&/g, '\\&');
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r + '.xcodeproj', 'project.pbxproj'));
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r, 'Classes', 'AppDelegate.h'));
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r, 'Classes', 'AppDelegate.m'));
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r, 'Classes', 'MainViewController.h'));
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r, 'Classes', 'MainViewController.m'));
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r, 'MainViewController.xib'));
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r, 'en.lproj/MainViewController.strings'));
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r, 'main.m'));
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r, project_name + '-Info.plist'));
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r, project_name + '-Prefix.pch'));
    shell.sed('-i', /__PROJECT_NAME__/g, project_name_esc, path.join(r, 'config.xml'));
    shell.sed('-i', /--ID--/g, package_name, path.join(r, project_name + '-Info.plist'));

    // CordovaLib stuff
    copyJsAndCordovaLib(project_path, project_name, use_shared);
    copyScripts(project_path);

    events.emit('log', generateDoneMessage('create', use_shared));
    return Promise.resolve();
};

exports.updateProject = function (projectPath, opts, events) {
    const projectName = detectProjectName(projectPath);
    setShellFatal(true, function () {
        copyJsAndCordovaLib(projectPath, projectName, opts.link);
        copyScripts(projectPath);
        events.emit('log', generateDoneMessage('update', opts.link));
    });
    return Promise.resolve();
};

function generateDoneMessage (type, link) {
    const pkg = require('../../package');
    let msg = 'OS X project ' + (type === 'update' ? 'updated ' : 'created ') + 'with ' + pkg.name + '@' + pkg.version;
    if (link) {
        msg += ' and has a linked CordovaLib';
    }
    return msg;
}

function update_cordova_subproject (argv) {
    if (argv.length < 1 || argv.length > 2) {
        updateSubprojectHelp();
        throw new Error('Usage error for update_cordova_subproject');
    }

    const projectPath = AbsProjectPath(argv[0]);
    let cordovaLibXcodePath;
    if (argv.length < 2) {
        cordovaLibXcodePath = path.join(ROOT, 'CordovaLib', 'CordovaLib.xcodeproj');
    } else {
        cordovaLibXcodePath = AbsProjectPath(argv[1]);
    }

    const parentProjectPath = AbsParentPath(projectPath);
    let subprojectPath = relpath(cordovaLibXcodePath, parentProjectPath);
    const REGEX = /(.+PBXFileReference.+wrapper.pb-project.+)(path = .+?;)(.*)(sourceTree.+;)(.+)/;
    let newLine;
    let lines = shell.grep('CordovaLib.xcodeproj', path.join(projectPath, 'project.pbxproj'));
    let found = false;

    subprojectPath = subprojectPath.replace(/\\/g, '/');
    lines = lines.split('\n');
    for (let i = 0; i < lines.length; ++i) {
        if (lines[i].match(REGEX)) {
            found = true;
            /* eslint-disable no-useless-escape */
            newLine = lines[i].replace(/path = .+?;/, 'path = ' + subprojectPath + ';');
            newLine = newLine.replace(/sourceTree.+?;/, 'sourceTree = \"<group>\";');
            if (!newLine.match('name')) {
                newLine = newLine.replace('path = ', 'name = CordovaLib.xcodeproj; path = ');
            }
            shell.sed('-i', lines[i], newLine, path.join(projectPath, 'project.pbxproj'));
        }
    }

    // Patching pbxproj to replace copy www shell script with nodejs
    // Don't forget to duplicate this in templates/__CLI__.xcodeproj/project.pbxproj and templates/__PROJECT_NAME__.xcodeproj/project.pbxproj on later changes
    const copyWwwSh = 'cordova\/lib\/copy-www-build-step\.sh';
    const copyWwwJs = 'NODEJS_PATH=\/usr\/local\/bin; NVM_NODE_PATH=~\/\.nvm\/versions\/node\/`nvm version 2>\/dev\/null`\/bin; N_NODE_PATH=`find \/usr\/local\/n\/versions\/node\/\* -maxdepth 0 -type d 2>\/dev\/null \| tail -1`\/bin; XCODE_NODE_PATH=`xcode-select --print-path`\/usr\/share\/xcs\/Node\/bin; PATH=\$NODEJS_PATH:\$NVM_NODE_PATH:\$N_NODE_PATH:\$XCODE_NODE_PATH:\$PATH && node cordova\/lib\/copy-www-build-step\.js';
    shell.sed('-i', copyWwwSh, copyWwwJs, path.join(projectPath, 'project.pbxproj'));

    /* eslint-enable no-useless-escape */

    if (!found) {
        throw new Error('Subproject: ' + subprojectPath + ' entry not found in project file');
    }
}

exports.updateSubprojectHelp = updateSubprojectHelp;
exports.update_cordova_subproject = update_cordova_subproject;


text:
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace Apricot.Shared
{
    /// <summary>
    ///     Classe de notification entre la vue et le vue-modèle.
    /// </summary>
    public abstract class NotifyPropertyChanged : INotifyPropertyChanged
    {
        #region Members.

        /// <summary>
        ///     Raises when a property value is updated.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion Members.

        #region Methods.

        /// <summary>
        ///     Notify a update by the component name.
        /// </summary>
        /// <param name="propertyName">The property name. This parameter is optional: the name is obtained if this method is called in a property.</param>
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            if (propertyName == null)
            {
                throw new ArgumentNullException("propertyName", "The parameter is null or empty.");
            }

            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        ///     Notify a update by a component object.
        /// </summary>
        /// <param name="args">The component.</param>
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
        {
            try
            {
                if (PropertyChanged != null)
                {
                    Debug.WriteLine("Update notification on the property: {0}", args.PropertyName);
                    PropertyChanged(this, args);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("The property has couldn't be notified: {0} following an error: {1}", args.PropertyName, e.Message);
            }
        }

        /// <summary>
        ///     Update and notify a value.
        /// </summary>
        /// <typeparam name="T">The generic type.</typeparam>
        /// <param name="property">The property value.</param>
        /// <param name="value">The new value of the property.</param>
        /// <param name="propertyName">The property name. This parameter is optional: the name is obtained if this method is called in a property.</param>
        /// <returns>True if the property is update and notified, otherwise, False.</returns>
        protected bool SetValueProperty<T>(ref T property, T value, [CallerMemberName] string propertyName = null)
        {
            if (propertyName == null)
            {
                throw new ArgumentNullException("propertyName", "The parameter is null or empty.");
            }
            if (Equals(property, value) && (propertyName != null))
            {
                Debug.WriteLine("The property has couldn't be notified: {0} because the previous value is identical to the new value.", propertyName);
                return false;
            }

            property = value;
            OnPropertyChanged(propertyName);
            return true;
        }

        #endregion Methods.
    }
}


text:
layout: post
title: Installing and configuring Squid and DansGuardian on FreeBSD
tags: freebsd squid dansguardian
---
In the following handbook we will show you how to install and
configure Squid acting as a transparent proxy server and DansGuardian
for content filtering on a FreeBSD system.

Squid is a caching proxy server, which is used for reducing network
bandwidth usage and accelerating the web content.

From the [official site of Squid](http://www.squid-cache.org/):

*Squid is a caching proxy for the Web supporting HTTP, HTTPS, FTP, and
 more. It reduces bandwidth and improves response times by caching and
 reusing frequently-requested web pages. Squid has extensive access
 controls and makes a great server accelerator. It runs on most
 available operating systems, including Windows and is licensed under
 the GNU GPL.*

For more information about Squid, please [visit the official website
of Squid](http://www.squid-cache.org/).

In the second part of the handbook we will see how to install and
configure DansGuardian - a web content filtering system.

From the [official site of DansGuardian](http://dansguardian.org/):

*DansGuardian is an award winning Open Source web content filter which
 currently runs on Linux, FreeBSD, OpenBSD, NetBSD, Mac OS X, HP-UX,
 and Solaris. It filters the actual content of pages based on many
 methods including phrase matching, PICS filtering and URL
 filtering. It does not purely filter based on a banned list of sites
 like lesser totally commercial filters.*

For more information about DansGuardian, please visit the [official
site of DanGuardian](http://dansguardian.org/).

This setup has been tested and confirmed to be running successfully on
a FreeBSD 8.2 system.

The important thing about our setup is that our firewall and gateway
are running on the same machine as Squid and DansGuardian are, in
order to have transparent proxy capabilities.

## Requirements

* root access or sudo rights
* Basic understand of the [OpenBSD Packet
* Filter](http://www.openbsd.org/faq/pf/)
* Your machine is configured and works as the gateway and firewall for
* your network. Please have a look at the [Gateways and Routes chapter
* of the FreeBSD
* Handbook](http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/network-routing.html)
* for more information.

## Installation of Squid
The first part of the handbook covers the installation and
configuration of Squid.

In order to install Squid we will use the [FreeBSD Ports
Collection](http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/ports.html).

Let's start with the installation of Squid:

```bash
$ cd /usr/ports/www/squid && sudo make install clean
```

![_config.yml]({{ site.baseurl }}/images/squid-config.jpg)

* SQUID_LDAP_AUTH
* SQUID_DELAY_POOLS
* SQUID_CARP
* SQUID_WCCP
* SQUID_IDENT
* SQUID_ARP_ACL
* SQUID_PF
* SQUID_FOLLOW_XFF
* SQUID_KQUEUE
* SQUID_SSL
* SQUID_REFERER_LOG
* SQUID_USERAGENT_LOG
* SQUID_ARP_ACL
* SQUID_LARGEFILE

Once the installation of Squid is over you should see something
similar:

```bash
===> post-installation information for squid-2.7.9_1:

     o You can find the configuration files for this package in the
       directory /usr/local/etc/squid.

     o The default cache directory is /var/squid/cache.
       The default log directory is /var/squid/logs.

       Note:
       You must initialize new cache directories before you can start
       squid.  Do this by running "squid -z" as 'root' or 'squid'.
       If your cache directories are already initialized (e.g. after an
       upgrade of squid) you do not need to initialize them again.

     o The default configuration will deny everyone but local networks
       as defined in RFC 1918 access to the proxy service.
       Edit the "http_access allow/deny" directives in
       /usr/local/etc/squid/squid.conf to suit your needs.

     To enable Squid, set squid_enable=yes in either
     /etc/rc.conf, /etc/rc.conf.local or /etc/rc.conf.d/squid
     Please see /usr/local/etc/rc.d/squid for further details.

     Note:
     If you just updated your Squid installation from 2.6 or earlier,
     make sure to check your Squid configuration against the 2.7 default
     configuration file /usr/local/etc/squid/squid.conf.default.

     Additionally, you should check your configuration by calling
     'squid -f /path/to/squid.conf -k parse' before starting Squid.

===>   Compressing manual pages for squid-2.7.9_1
===>   Registering installation for squid-2.7.9_1
===> SECURITY REPORT:
      This port has installed the following files which may act as network
      servers and may therefore pose a remote security risk to the system.
/usr/local/sbin/squid

      This port has installed the following startup scripts which may cause
      these network services to be started at boot time.
/usr/local/etc/rc.d/squid

      If there are vulnerabilities in these programs there may be a security
      risk to the system. FreeBSD makes no guarantee about the security of
      ports included in the Ports Collection. Please type 'make deinstall'
      to deinstall the port if this is a concern.

      For more information, and contact details about the security
      status of this software, see the following webpage:
http://www.squid-cache.org/
===>  Cleaning for squid-2.7.9_1
```

## Configuration of Squid

Squid's main configuration file resides in
*/usr/local/etc/squid/squid.conf*.

Open */usr/local/etc/squid/squid.conf* file for editing and do the
necessary changes. Most options are self explanatory.

Below you will find a fully working *squid.conf* file. Please consult
the Squid man pages and the example
*/usr/local/etc/squid/squid.conf.default* file for more information
about the different options - the file is pretty well documented.

```text
#
# ACL lists
#

acl all src all
acl manager proto cache_object
acl localhost src 127.0.0.1/32
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32

acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http

acl CONNECT method CONNECT
acl PURGE   method PURGE

acl intranet_subnet src 10.1.16.0/20
acl openvpn_subnet  src 10.1.32.0/20

#
# General options
#

http_port <firewall-ip-address>:3128 transparent

visible_hostname <firewall-fqdn>

cache_mgr admin@example.org
ftp_user  squid@example.org

minimum_object_size 0 KB
maximum_object_size 1024 MB

request_body_max_size 0

hierarchy_stoplist cgi-bin ?

always_direct allow all

access_log /var/squid/logs/access.log squid

coredump_dir /var/squid/cache

#
# Permissions order - 1st comes, 1st served
#

icp_access  allow all
miss_access allow all

http_access allow PURGE             localhost
http_access allow manager           localhost
http_access allow intranet_subnet
http_access allow openvpn_subnet
http_access deny all
```

The most important things from the above configuration that you need
to change for your setup are the ones listed below:

* *http_port <firewall-ip-address>:3128 transparent* - change
   *<firewall-ip-address>* with your firewall's IP address
* *visible_hostname <firewall-fqdn>* - change *<firewall-fqdn>*
   *with your firewall's FQDN name.
* *cache_mgr* *admin@example.org* - put your administrator's email
   *address here
* *intranet_subnet* and *openvpn_subnet* are two subnets that we
  *allow access to our proxy server.

Again, please consult the example *squid.conf.default* configuration
file for more explanation of the options used above.

# Fine tuning FreeBSD to meet Squid's requirements

To fine tune FreeBSD in order to be able to open more files and
processes, add the below lines to your */boot/loader.conf* file.

```text
kern.maxfiles="12328"
kern.maxfilesperproc="11095"
kern.maxproc="6164"
kern.maxprocperuid="5547"
kern.maxusers="256"
```

You might want to play a bit with these settings, if they do not match
your requirements and raise the values.

## Enabling Squid during boot-time.

In order to enable Squid during boot-time add the following lines to
your */etc/rc.conf* file:

```bash
# Enable Squid
squid_enable="YES"
```

## Firewall configuration in PF

In order to be able to pass connections transparently to the proxy
server we need to add some rules to our */etc/pf.conf* file.

Below is an example configuration of a */etc/pf.conf* file for our
transparent Squid proxy setup.

```text
ext_if = "<external-interface>"
int_if = "<internal-interface>"

# --- IP given by the ISP ---
ip_addr = "x.x.x.x"

# --- squid server ip address (usually the localhost) ---
SQUID_SERVER = "x.x.x.x"

# --- squid port ---
SQUID_PORT = "3128"

# --- hosts with internet access from the private network ---
table <allowed> { 10.1.16.0/20 }

# --- openvpn clients subnet ---
table <openvpn_clients> { 10.1.32.0/20 }

# --- OPTIONS section ---
set skip on lo0
set block-policy return

# --- SCRUB section ---
scrub in all

# --- TRANSLATION (NAT/RDR) section ---
nat on $ext_if from <allowed> to any -> $ip_addr
nat on $ext_if from <openvpn_clients> to any -> $ip_addr

# --- redirect HTTP traffic to the Squid server on the firewall ---
rdr on $int_if inet proto tcp from any to any port www ->
$SQUID_SERVER port $SQUID_PORT

# --- FILTER RULES ---

# --- default policy ---
block log all

# --- antispoof protection ---
antispoof quick for $ext_if inet
antispoof quick for $int_if inet

# --- INTERNAL interface ---

pass in quick on $int_if inet from <allowed> to any keep state
pass in quick on $int_if inet from <openvpn_clients> to any keep state
pass out quick on $int_if inet from any to any keep state

# --- EXTERNAL interface ---

pass out quick on $ext_if inet from any to any keep state
```

Reload *pf(4)* rules using *pfctl(8)*.

```bash
$ sudo pfctl -f /etc/pf.conf
```

## Starting Squid

The first thing we need to do before starting Squid is to check our
configuration if it contains any errors:

```bash
$ sudo squid -f /usr/local/etc/squid/squid.conf -k parse
```

If everything is OK we can proceed, otherwise you will need to check
your *squid.conf* file and fix the reported errors.

Now we need to initialize the cache directories of Squid. To do this
simply execute the command below:

```bash
$ sudo squid -z
```

**NOTE:** If you are doing an upgrade of Squid you do not need to
  initialize the cache directories as they should be initialized
  already.

And now let's start Squid:

```bash
$ sudo /usr/local/etc/rc.d/squid start
```

If you have followed the handbook by this step you should have a fully
working Squid transparent proxy server.

In the next chapters of this handbook we will have a look at
DansGuardian and how to integrate it with Squid.

In this chapter of the handbook we will cover the installation and
basic configuration of DansGuardian.

## Installing Dansguardian

In order to install DansGuardian on your FreeBSD system you will need
first to fetch the distribution tarball from the [DansGuardian web
site](http://dansguardian.org/) and place it in your
*/usr/ports/distfiles* directory.

Once you do that we can continue with the installation of DansGuardian
using the FreeBSD Ports Collection.

```bash
$ cd /usr/ports/www/dansguardian && sudo make install clean
```

![_config.yml]({{ site.baseurl }}/images/dansguardian.jpg)

Once the installation of DansGuardian is over you should see something
similiar:

```bash
===> Installing rc.d startup script(s)
===>   Please Note:

*******************************************************************************
       This port has created a log file named dansguardian.log that can get
       quite large.  Please read the newsyslog(8) man page for instructions
       on configuring log rotation and compression.

       This port has been converted to the new RC framework and should work
       correctly via rcorder.  Please read the comments in the startup script
       for instructions on enabling the daemon.

       WITH_CLAMAV, WITH_ICAP, WITH_KASP, WITH_NTLM are all experimental
       options that I am not currently able to test.  Let me know how these
       work (or not) for you.  (Patches always welcome.)
*******************************************************************************
===>   Compressing manual pages for dansguardian-2.10.1.1_1
===>   Registering installation for dansguardian-2.10.1.1_1
===> SECURITY REPORT:
      This port has installed the following files which may act as network
      servers and may therefore pose a remote security risk to the system.
/usr/local/sbin/dansguardian

      This port has installed the following startup scripts which may cause
      these network services to be started at boot time.
/usr/local/etc/rc.d/dansguardian

      If there are vulnerabilities in these programs there may be a security
      risk to the system. FreeBSD makes no guarantee about the security of
      ports included in the Ports Collection. Please type 'make deinstall'
      to deinstall the port if this is a concern.

      For more information, and contact details about the security
      status of this software, see the following webpage:
http://dansguardian.org
===>  Cleaning for dansguardian-2.10.1.1_1
```

Now that DansGuardian has been installed we can continue with it's
configuration in the next chapter of the handbook.

## Configuration of Dansguardian

In this section we only cover the basic configuration of
DansGuardian.

You are also advised to [check the documentation of the DansGuardian
web site](http://dansguardian.org/?page=documentation) for more
information about DansGuardian.

The main DansGuardian configuration file resides in
*/usr/local/etc/dansguardian/dansguardian.conf*. The file is pretty
well documented and in this handbook we will only change a few options
in order to match our setup.

So open the */usr/local/etc/dansguardian/dansguardian.conf* file for
editing and do the needed changes.

In this example we change only the following options.

```text
filterip = <dansguardian-ip-address>
filterport = 8080 # dansguardian port
proxyip = <squid-ip-address>
proxyport = 3128 # Squid's port
accessdeniedaddress = 'http://<dansguardian-fqdn>/cgi-bin/dansguardian.pl'
forwardedfor = on
loglocation = '/var/log/dansguardian/access.log'
```

Create the DansGuardian log file and give it proper permissions:

```bash
$ sudo mkdir /var/log/dansguardian
$ sudo touch /var/log/dansguardian/access.log
$ sudo chown -R nobody:nobody /var/log/dansguardian
$ sudo chmod -R 0600 /var/log/dansguardian
```

## Enabling DansGuardian during boot-time

In order to enable DansGuardian during boot-time add the following
lines to your */etc/rc.conf* file:

```bash
# Enable DansGuardian
dansguardian_enable="YES"
```

## Firewall configuration in PF for DansGuardian

Just like we did in the Squid configuration chapter of this handbook
where we did modifications to our */etc/pf.conf* file for transparent
proxy, in this chapter of the handbook we will modify again
*/etc/pf.conf* so that all HTTP requests are going through
DansGuardian instead.

Below is an example configuration of */etc/pf.conf* file for our
Squid and DansGuardian setup:

```text
ext_if = "<external-interface>"
int_if = "<internal-interface>"

# --- IP given by the ISP ---
ip_addr = "x.x.x.x"

# --- squid server ip address (usually the localhost) ---
SQUID_SERVER = "x.x.x.x"

# --- squid port ---
SQUID_PORT = "3128"

# --- dansguardian port ---
DG_PORT = "8080"

# --- hosts with internet access from the private network ---
table <allowed> { 10.1.16.0/20 }

# --- openvpn clients subnet ---
table <openvpn_clients> { 10.1.32.0/20 }

# --- OPTIONS section ---
set skip on lo0
set block-policy return

# --- SCRUB section ---
scrub in all

# --- TRANSLATION (NAT/RDR) section ---
nat on $ext_if from <allowed> to any -> $ip_addr
nat on $ext_if from <openvpn_clients> to any -> $ip_addr

# --- redirect HTTP traffic to the Squid server on the firewall ---
rdr on $int_if inet proto tcp from any to any port www -> $SQUID_SERVER port $DG_PORT

# --- FILTER RULES ---

# --- default policy ---
block log all

# --- antispoof protection ---
antispoof quick for $ext_if inet
antispoof quick for $int_if inet

# --- INTERNAL interface ---

pass in quick on $int_if inet from <allowed> to any keep state
pass in quick on $int_if inet from <openvpn_clients> to any keep state
pass out quick on $int_if inet from any to any keep state

# --- EXTERNAL interface ---

pass out quick on $ext_if inet from any to any keep state
```

The only difference here is that now we are redirecting all HTTP
traffic to DansGuardian first which in turn passes it to Squid.

This way DansGuardian is taking care of the content filtering first.

Reload *pf(4)* rules using *pfctl(8)*.

```bash
$ sudo pfctl -f /etc/pf.conf
```

## Staring DansGuardian

In order to start DansGuardian execute the command below:

```bash
$ sudo /usr/local/etc/rc.d/dansguardian start
```

And that was it! By now you should have a fully working setup with
Squid transparent proxy and DansGuardian content filter.