text:
_[Baremetrics](https://baremetrics.com) provides one-click analytics & insights for Stripe. **[Get started today!](https://baremetrics.com)**_

---

The Baremetrics date range picker is a simplified solution for selecting both date ranges and single dates all from a single calender view. There aren't a billion options but the code is pretty basic and modular so feel free to edit however to meet your own needs.

Design by [Chris Meeks](https://dribbble.com/ChrisMeeks)
Code by [Tyler van der Hoeven](https://github.com/tyvdh)

[View a demo](http://baremetrics.github.io/calendar/)
[View in a live production app](https://demo.baremetrics.com/)

![](http://tyler.link/bqs5/Screen%20Shot%202015-07-02%20at%201.29.07%20PM.png)
![](http://tyler.link/br0F/Screen%20Shot%202015-07-02%20at%201.29.28%20PM.png)
![](http://tyler.link/bqV5/Screen%20Shot%202015-07-02%20at%201.32.15%20PM.png)

## Installing

Using the date picker is pretty simple, you've just got to make a couple choices and include a couple settings.
Create a div with a `daterange` class and then either the `daterange--double` or `daterange--single` classname for targeting the specific calendar you'd like to generate.

```html
<div class="daterange daterange--double"></div>
<div class="daterange daterange--single"></div>
```

Next you've just gotta create a `new Calendar` instance.

```js
new Calendar({
  element: $('.daterange--single'),
  current_date: 'June 15, 2015'
});

new Calendar({
  element: $('.daterange--double'),
  earliest_date: 'January 1, 2000',
  latest_date: new Date(),
  start_date: 'May 1, 2015',
  end_date: 'May 31, 2015',
  callback: function() {
    var start = moment(this.start_date).format('ll'),
        end = moment(this.end_date).format('ll');

    console.debug('Start Date: '+ start +'\nEnd Date: '+ end);
  }
});
```

### Base Calendar Params
- element _\*required_
  - jQuery DOM object of the calendar div you're working on
- earliest_date
  - The earliest date to show in the calendar
- latest_date
  - The latest date to show in the calendar
- callback
  - A function for whenever a new date is saved
  - Inside you have access to variables like `this.earliest_date`, `this.latest_date` and `this.current_date` for doing things with the new dates
- format
  - Object containing formatting strings for.. you guessed it.. formating your dates
  ```js
    format: {
      input: 'MMMM D, YYYY', // Format for the input fields
      jump_month: 'MMMM', // Format for the month switcher
      jump_year: 'YYYY' // Format for the year switcher
    }
  ```
- days_array
  - Array of the 7 strings you'd like to represent your days in the calendar
  ```js
    days_array: ['Su','Mo','Tu','We','Th','Fr','Sa']
  ```

### Single Calendar Params
- current_date
  - The date to start the calendar on

### Double Calendar Params
- callback
  - The double calendar includes access to `this.end_date` and `this.start_date`
- start_date
  - The date to start the selection on for the calendar
- end_date
  - The date to end the selection on for the calendar
- format
  - The double calendar adds the `preset` key to the format object for formatting the preset dates in the preset dropdown
- same_day_range
  - Allow a range selection of a single day
- preset_left
  - The preset button is left-aligned, default is false.

---

## Developing

I've included my signature gulpfile too so be sure and take a look at that as well.

```bash
$ cd <project directory>
$ npm install
$ gulp
```

I also use [pow](http://pow.cx/) and the [powder gem](https://github.com/Rodreegez/powder) to run my local dev environments but however you plan on wrangling that the gulpfile turns on a livereload server so as long as you have the files serving somehow any changes you make will show up instantly.

## Dependencies
- [jQuery](https://jquery.com/)
- [MomentJS](http://momentjs.com/)


text:
namespace url {
class Origin;
}

namespace content {

// Delegate interface for the FedCM implementation to query whether the FedCM
// API is enabled in Site Settings.
class CONTENT_EXPORT FederatedIdentityApiPermissionContextDelegate {
 public:
  enum class PermissionStatus {
    GRANTED,
    BLOCKED_VARIATIONS,
    BLOCKED_THIRD_PARTY_COOKIES_BLOCKED,
    BLOCKED_SETTINGS,
    BLOCKED_EMBARGO,
  };

  FederatedIdentityApiPermissionContextDelegate() = default;
  virtual ~FederatedIdentityApiPermissionContextDelegate() = default;

  // Returns the status of the FedCM API for the passed-in
  // |relying_party_embedder|.
  virtual PermissionStatus GetApiPermissionStatus(
      const url::Origin& relying_party_embedder) = 0;

  // Records that the FedCM prompt was explicitly dismissed and places the
  // permission under embargo for the passed-in |relying_party_embedder|.
  virtual void RecordDismissAndEmbargo(
      const url::Origin& relying_party_embedder) = 0;

  // Clears any existing embargo status for the FEDERATED_IDENTITY_API
  // permission for the passed-in |relying_party_embedder|. Clears the dismiss
  // and ignore counts.
  virtual void RemoveEmbargoAndResetCounts(
      const url::Origin& relying_party_embedder) = 0;

  // This function is so we can avoid the delay in tests. It does not really
  // belong on this delegate but we don't have a better one and it seems
  // wasteful to add one just for this one testing function.
  virtual bool ShouldCompleteRequestImmediately() const;
};

}  // namespace content

#endif  // CONTENT_PUBLIC_BROWSER_FEDERATED_IDENTITY_API_PERMISSION_CONTEXT_DELEGATE_H_

redpajama_set_name: RedPajamaGithub


text:
/**
 * Provides classes for TagSet exporting data models.
 * The content of these data models are populated from the persistence data model selecting
 * only needed attributes.
 */
package de.tudarmstadt.ukp.clarin.webanno.model.export;


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>
        <groupId>org.sonatype.oss</groupId>
        <artifactId>oss-parent</artifactId>
        <version>7</version>
    </parent>

    <groupId>org.fenixedu</groupId>
    <artifactId>fenixedu-canvas</artifactId>
    <name>FenixEdu Canvas</name>
    <version>1.1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <description>WebJar for FenixEdu Canvas</description>
    <url>http://fenixedu.org</url>

    <dependencies>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>2.1.1</version>
        </dependency>
    </dependencies>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <upstreamVersion>master</upstreamVersion>
        <sourceUrl>https://github.com/FenixEdu/fenixedu-canvas/archive</sourceUrl>
        <destDir>${project.build.outputDirectory}/META-INF/resources/webjars/${project.artifactId}</destDir>
        <requirejs>
            {
                "paths": {
                    "bootstrap": "js/bootstrap",
                    "bootstrap-css": "css/bootstrap"
                },
                "shim": {
                    "bootstrap": [ "jquery" ]
                }
            }
        </requirejs>
    </properties>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                        <phase>process-resources</phase>
                        <goals><goal>run</goal></goals>
                        <configuration>
                            <target>
                                <echo message="copy resources" />
                                <copy todir="${destDir}">
                                    <fileset dir="../dist" includes="js/,css/,fonts/,fancytree/" />
                                    <fileset dir=".." includes="less/" />
                                </copy>
                            </target>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <groupId>com.google.code.maven-replacer-plugin</groupId>
                <artifactId>replacer</artifactId>
                <version>1.5.3</version>
                <executions>
                    <execution>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>replace</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <includes>
                        <include>
                            ${project.build.directory}/classes/META-INF/resources/webjars/fenixedu-canvas/*/css/*.css
                        </include>
                    </includes>
                    <inputFilePattern>(.*).css</inputFilePattern>
                    <outputFilePattern>$1-jsf.css</outputFilePattern>
                    <replacements>
                        <replacement>
                            <token>url\('?+\.\.\/fonts\/([^\s\)?#']+)[\?#]{0,2}([^';]*)+?'?\)</token>
                            <value>url("#{resource['webjars:fenixedu-canvas/fonts/$1']}&v=${upstreamVersion}&#$2")</value>
                        </replacement>
                    </replacements>
                    <regex>true</regex>
                    <regexFlags>
                        <regexFlag>CASE_INSENSITIVE</regexFlag>
                    </regexFlags>
                    <unescape>true</unescape>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.5</version>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
                <targetPath>${destDir}</targetPath>
            </resource>
        </resources>
    </build>

    <distributionManagement>
        <repository>
            <id>fenixedu-releases</id>
            <url>https://repo.fenixedu.org/fenixedu-releases</url>
        </repository>
    </distributionManagement>

</project>


text:
package com.cscao.libs.gmswear.connectivity;

import static com.cscao.libs.gmswear.GmsWear.getInstance;

import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.cscao.libs.gmswear.GmsWear;
import com.cscao.libs.gmswear.consumer.DataConsumer;
import com.cscao.libs.gmswear.filter.NearbyFilter;
import com.cscao.libs.gmswear.util.Constants;
import com.cscao.libs.gmswear.util.WearUtil;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.wearable.Channel;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.WearableStatusCodes;

import java.io.File;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Set;
import java.util.UUID;

/**
 * A helper class to facilitate the transfer of a file or bytes across the wearable network. For
 * a pure file transfer, clients should use a pattern similar to the following:

 * On the sender side:
 *

 * FileTransfer fileTransfer = new FileTransfer.Builder(targetNode)
 *     .setTargetName(targetFileName)
 *     .setFile(fileToBeSent))
 *     .setOnFileTransferResultListener(myResultListener)
 *     .build();
 * fileTransfer.transfer();
 *

 * On the receiver end, the library handles the rest and saves the file in the private data storage
 * for the app, under the "targetFileName". If the receiver node wants to be notified that a file
 * has been received and saved successfully, they can register a DataConsumer listener and override
 * {@link DataConsumer#onFileReceivedResult(int, String, File, String)}
 * which includes the status, the unique requestId for the transfer, the File object pointing to
 * the
 * saved file and the original name of the file on the sender side:
 *

 * mWearConsumer = new AbstractDataConsumer() {
 *
 *     public void onFileReceivedResult(int statusCode, String requestId,
 *             File savedFile, String originalName) {
 *         Log.d(TAG, String.format(
 *             "File Received: status=%d, requestId=%s, savedLocation=%s, originalName=%s",
 *             statusCode, requestId, savedFile.getAbsolutePath(), originalName));
 *     }
 * }
 *

 * It is also possible to use low-level apis based on
 * {@link com.google.android.gms.wearable.ChannelApi} to open a channel and create an
 * {@link OutputStream} on the sender side and and {@link java.io.InputStream} on the other side to
 * transfer data. This can be done by following a pattern similar to this:
 *

 * On the sender side:
 *

 * FileTransfer fileTransfer = new FileTransfer.Builder(targetNode)
 *        .setOnChannelOutputStreamListener(listener)
 *        .build();
 * fileTransfer.requestOutputStream();
 *

 * The {@link DataConsumer#onOutputStreamForChannelReady(int, Channel, OutputStream)} listener will
 * receive a reference to the status for this request, a channel and an
 * {@link OutputStream} to write to. On the receiver side, the library can inform the client that a
 * channel has been opened and a callback will provide a reference to the channel and the
 * {@link java.io.InputStream} that the client can use to receive the data:
 *

 * mWearConsumer = new AbstractDataConsumer() {
 *
 *         public void onInputStreamForChannelOpened(int statusCode, String requestId,
 *             Channel channel, InputStream inputStream) {
 *                 //get the data from the inputStream ..
 *         }
 * }
 *

 */
public class FileTransfer {

    public static final String PARAM_NAME = "name";
    public static final String PARAM_SIZE = "size";
    public static final String PARAM_REQUEST_ID = "request-id";
    private static final String TAG = "FileTransfer";
    private static final String PATH_SEPARATOR = "/";
    private final File mFile;
    private final String mTargetName;
    private final Node mNode;
    private final String mRequestId;
    private final OnFileTransferRequestListener mFileTransferResultListener;
    private final OnChannelOutputStreamListener mOnChannelOutputStreamListener;

    private FileTransfer(Builder builder) {
        mFile = builder.mFile;
        mTargetName = builder.mTargetName;
        mNode = builder.mNode;
        mRequestId = builder.mRequestId;
        mFileTransferResultListener = builder.mFileTransferResultListener;
        mOnChannelOutputStreamListener = builder.mOnChannelOutputStreamListener;
    }

    /**
     * Initiates the transfer of a file to the target node. Using this method, a file can be
     * transferred without any additional work on the receiver end although the receiver can
     * register a {@link DataConsumer#onFileReceivedResult(int, String, File, String)}
     * to be notified when the transfer is completed or when it fails.
     * Using {@link DataConsumer#onSendFileResult(int, String)}, the sender node can also
     * learn about the status of the file transfer request.
     */
    public void startTransfer() {
        assertFileTransferParams();
        final Uri uri = Uri.fromFile(mFile);
        String path = buildPath(mTargetName, mRequestId, mFile.length());
        final GmsWear gmsWear = getInstance();
        if (mNode == null) {
            return;
        }

        gmsWear.openChannel(mNode, path, new OnChannelReadyListener() {
            @Override
            public void onChannelReady(int statusCode, Channel channel) {
                if (statusCode != WearableStatusCodes.SUCCESS) {
                    Log.e(TAG, "transfer(): Failed to open channel; status code= " + statusCode);
                    if (mFileTransferResultListener != null) {
                        mFileTransferResultListener.onFileTransferStatusResult(statusCode);
                    }
                    return;
                }

                gmsWear.sendFile(mRequestId, channel, uri, 0, -1, new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        if (status.getStatusCode() != WearableStatusCodes.SUCCESS) {
                            Log.e(TAG, "transfer(): Failed to send file; status code= " + status
                                    .getStatusCode());
                        }
                        if (mFileTransferResultListener != null) {
                            mFileTransferResultListener
                                    .onFileTransferStatusResult(status.getStatusCode());
                        }
                    }
                });
            }
        });
    }

    /**
     * Opens a channel and an {@link OutputStream} to transfer data. If the
     * intention is to transfer a file, it is recommended to use {@link #startTransfer()} method
     * instead. Using this api, the sender client needs to use
     * {@link DataConsumer#onInputStreamForChannelOpened} listener to receive an
     * {@link java.io.InputStream} for writing data to. On the receiver node, the client has to
     * register to {@link DataConsumer#onOutputStreamForChannelReady(int, Channel, OutputStream)}
     * to be notified when an {@link java.io.InputStream} is available to read the bytes from.
     */
    public void requestOutputStream() {
        assertStreamParams();
        String path = Constants.PATH_FILE_TRANSFER_TYPE_STREAM + mRequestId;
        if (mNode == null) {
            Log.e(TAG, "target node can't be null ");
            return;
        }
        GmsWear.getInstance().getOutputStreamViaChannel(mNode, path,
                mOnChannelOutputStreamListener);
    }

    private String buildPath(String name, String requestId, long size) {
        String encodedName = null;
        try {
            encodedName = URLEncoder.encode(name, "utf-8");
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "buildPath(): Failed to encode name " + name, e);
        }
        return Constants.PATH_FILE_TRANSFER_TYPE_FILE + encodedName + PATH_SEPARATOR + size
                + PATH_SEPARATOR + requestId;
    }

    private void assertStreamParams() {
        if (mOnChannelOutputStreamListener == null) {
            throw new IllegalArgumentException("An OnChannelOutputStreamListener should be set");
        }
    }

    private void assertFileTransferParams() {
        if (mFile == null) {
            throw new IllegalArgumentException("File to transfer is missing");
        }
    }

    /**
     * An interface to use when a request for opening an {@link OutputStream} is made. Clients need
     * to register an implementation of this interface when they make a request for an
     * {@link OutputStream} to be notified when one is available.
     */
    public interface OnChannelOutputStreamListener {

        /**
         * Is called when the request for opening an {@link OutputStream} is fulfilled.
         * {@code statusCode} shows the status code of the result and if successful, the fields
         * {@code channel} and {@code outputSteam} will, respectively, provide access to the
         * underlying {@link Channel} and the {@link OutputStream} that clients can use to write
         * data to. If the request fails, these two field will be {@code null}
         */
        void onOutputStreamForChannelReady(int statusCode, Channel channel,
                OutputStream outputStream);
    }

    /**
     * Internal only. An interface to provide feedback when the result for opening a channel is
     * available.
     */
    public interface OnChannelReadyListener {

        /**
         * Is called when the result of the request for opening a channel is ready. The
         * {@code statusCode} can be used to decide if the request was successful or not. If
         * successful, the {@code channel} will be the resulting channel, otherwise it will be
         * {@code null}.
         */
        void onChannelReady(int statusCode, Channel channel);
    }

    public interface OnFileTransferRequestListener {
        void onFileTransferStatusResult(int statusCode);
    }

    /**
     * A helper interface that clients can use to report the progress of a transfer.
     */
    public interface OnChannelTransferProgressListener {

        /**
         * Show the progress of data transfer. {@code progress} indicates the progress and
         * {@code max} shows the total (max) value.
         */
        void onProgressUpdated(long progress, long total);
    }

    /**
     * Builder for {@link FileTransfer}.
     */
    public static final class Builder {
        private File mFile;
        private String mTargetName;
        private Node mNode;
        private String mRequestId;
        private OnFileTransferRequestListener mFileTransferResultListener;
        private OnChannelOutputStreamListener mOnChannelOutputStreamListener;
        private GmsWear mGmsWear;

        /**
         * A Builder class to help with the construction of a {@link FileTransfer} object.
         *
         * @param targetNode The {@link Node} to send the file or bytes to.
         */
        public Builder(Node targetNode) {
            mNode = WearUtil.assertNotNull(targetNode, "targetNode");
        }

        /**
         * Builder for nearest node
         */
        public Builder() {
            mGmsWear = getInstance();
            Set<Node> nodes = new NearbyFilter().
                    filterNodes(mGmsWear.getConnectedNodes());
            if (!nodes.isEmpty()) {
                mNode = nodes.iterator().next();
            } else {
                Log.e(TAG, "no available nodes to send");
            }
        }

        /**
         * Sets the original file that should be transferred.
         */
        public Builder setFile(File file) {
            mFile = WearUtil.assertNotNull(file, "file");
            if (!file.exists()) {
                throw new IllegalArgumentException(
                        "The file to be transferred doesn't exist: " + file.getAbsolutePath());
            }
            return this;
        }

        /**
         * Sets the name of the transferred file at the destination. This is optional and if not
         * set, the name of the original file will be used.
         */
        public Builder setTargetName(@Nullable String targetName) {
            mTargetName = targetName;
            return this;
        }

        /**
         * Sets the listener {@link OnChannelOutputStreamListener} that should
         * be notified when an output stream is available. This is used when we are using
         * low-level apis to transfer data.
         */
        public Builder setOnChannelOutputStreamListener(
                OnChannelOutputStreamListener onChannelOutputStreamListener) {
            mOnChannelOutputStreamListener = WearUtil
                    .assertNotNull(onChannelOutputStreamListener,
                            "onChannelOutputStreamListener");
            return this;
        }

        /**
         * Sets the (optional) requestId. This will be used to correlate the request and its
         * corresponding results and responses. If not provided, a unique requestId will be created
         * automatically.
         */
        public Builder setRequestId(@Nullable String requestId) {
            mRequestId = requestId;
            return this;
        }

        /**
         * Sets an optional {@link OnFileTransferRequestListener} listener that will be notified
         * of the status of {@link #startTransfer()}.
         */
        public Builder setOnFileTransferResultListener(
                OnFileTransferRequestListener nFileTransferRequestListener) {
            mFileTransferResultListener = WearUtil
                    .assertNotNull(nFileTransferRequestListener, "nFileTransferRequestListener");
            return this;
        }

        /**
         * Builds the {@link FileTransfer} object.
         */
        public FileTransfer build() {
            if (TextUtils.isEmpty(mRequestId)) {
                mRequestId = UUID.randomUUID().toString();
            }
            if (TextUtils.isEmpty(mTargetName) && mFile != null) {
                mTargetName = mFile.getName();
            }
            return new FileTransfer(this);
        }

    }

}


text:
package dk.simplecontentprovider.demo.provider;

import android.net.Uri;
import android.provider.BaseColumns;

public final class DemoContract {
    public static final String SCHEME = "content://";
    public static final String AUTHORITY = "dk.simplecontentprovider.demo";

    public static final class Owners implements BaseColumns {
        protected static final String TABLE_NAME = "owners";

        public static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + "/" + TABLE_NAME);

        public static final String NAME = "name";
        public static final String ADDRESS = "address";
    }

    public static final class Pets implements BaseColumns {
        protected static final String TABLE_NAME = "pets";

        public static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + "/" + TABLE_NAME);

        public static final String NAME = "name";
        public static final String TYPE = "type";
        public static final String AGE = "age";
        public static final String OWNER_ID = "owner_id";
    }

    public static final class OwnersAndPetsView implements BaseColumns {
        protected static final String VIEW_NAME = "owners_and_pets";

        public static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + "/" + VIEW_NAME);

        public static final String NAME = "owner_name";
        public static final String ADDRESS = "owner_address";
        public static final String NUMBER_OF_PETS = "number_of_pets";
        public static final String PET_NAMES = "pet_names";
    }
}


text:
import pify from 'pify'
import humanlizePath from './utils/humanlize-path'
import { loadModule } from './utils/load-module'

/* eslint import/no-anonymous-default-export: [2, {"allowObject": true}] */
export default {
  name: 'less',
  test: /\.less$/,
  async process({ code }) {
    const less = loadModule('less')
    if (!less) {
      throw new Error('You need to install "less" packages in order to process Less files')
    }

    let { css, map, imports } = await pify(less.render.bind(less))(code, {
      ...this.options,
      sourceMap: this.sourceMap && {},
      filename: this.id
    })

    for (const dep of imports) {
      this.dependencies.add(dep)
    }

    if (map) {
      map = JSON.parse(map)
      map.sources = map.sources.map(source => humanlizePath(source))
    }

    return {
      code: css,
      map
    }
  }
}


text:
package com.orientechnologies.orient.core.serialization.compression.impl;

import java.util.Random;

import org.testng.Assert;

import com.orientechnologies.orient.core.serialization.compression.OCompression;
import com.orientechnologies.orient.core.serialization.compression.OCompressionFactory;

/**
 * @author Andrey Lomakin
 * @since 05.06.13
 */
public abstract class AbstractCompressionTest {
  protected void testCompression(String name) {
    long seed = System.currentTimeMillis();
    System.out.println("Compression seed " + seed);

    Random random = new Random(seed);
    final int iterationsCount = 1000;
    for (int i = 0; i < iterationsCount; i++) {
      int contentSize = random.nextInt(10 * 1024 - 100) + 100;
      byte[] content = new byte[contentSize];
      random.nextBytes(content);

      OCompression compression = OCompressionFactory.INSTANCE.getCompression(name);

      byte[] compressedContent = compression.compress(content);
      Assert.assertEquals(content, compression.uncompress(compressedContent));
    }
  }
}


text:
package org.apache.cassandra.avro;

import java.io.IOException;
import java.net.InetAddress;
import java.util.UUID;

import org.apache.avro.ipc.HttpServer;
import org.apache.avro.specific.SpecificResponder;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.CompactionManager;
import org.apache.cassandra.db.SystemTable;
import org.apache.cassandra.db.Table;
import org.apache.cassandra.db.commitlog.CommitLog;
import org.apache.cassandra.db.migration.Migration;
import org.apache.cassandra.service.MigrationManager;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Mx4jTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Avro analogue to org.apache.cassandra.service.CassandraDaemon.
 *
 */
public class CassandraDaemon extends org.apache.cassandra.service.AbstractCassandraDaemon {
    private static Logger logger = LoggerFactory.getLogger(CassandraDaemon.class);
    private HttpServer server;
    private InetAddress listenAddr;
    private int listenPort;

    protected void setup() throws IOException
    {
        FBUtilities.tryMlockall();

        listenPort = DatabaseDescriptor.getRpcPort();
        listenAddr = DatabaseDescriptor.getRpcAddress();

        /*
         * If ThriftAddress was left completely unconfigured, then assume
         * the same default as ListenAddress
         */
        if (listenAddr == null)
            listenAddr = FBUtilities.getLocalAddress();

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
        {
            public void uncaughtException(Thread t, Throwable e)
            {
                logger.error("Fatal exception in thread " + t, e);
                if (e instanceof OutOfMemoryError)
                {
                    System.exit(100);
                }
            }
        });

        // check the system table for mismatched partitioner.
        try
        {
            SystemTable.checkHealth();
        }
        catch (ConfigurationException e)
        {
            logger.error("Fatal exception during initialization", e);
            System.exit(100);
        }

        try
        {
            DatabaseDescriptor.loadSchemas();
        }
        catch (IOException e)
        {
            logger.error("Fatal exception during initialization", e);
            System.exit(100);
        }

        // initialize keyspaces
        for (String table : DatabaseDescriptor.getTables())
        {
            if (logger.isDebugEnabled())
                logger.debug("opening keyspace " + table);
            Table.open(table);
        }

        // replay the log if necessary and check for compaction candidates
        CommitLog.recover();
        CompactionManager.instance.checkAllColumnFamilies();

        // check to see if CL.recovery modified the lastMigrationId. if it did, we need to re apply migrations. this isn't
        // the same as merely reloading the schema (which wouldn't perform file deletion after a DROP). The solution
        // is to read those migrations from disk and apply them.
        UUID currentMigration = DatabaseDescriptor.getDefsVersion();
        UUID lastMigration = Migration.getLastMigrationId();
        if ((lastMigration != null) && (lastMigration.timestamp() > currentMigration.timestamp()))
        {
            MigrationManager.applyMigrations(currentMigration, lastMigration);
        }

        SystemTable.purgeIncompatibleHints();

        // start server internals
        StorageService.instance.initServer();

    }

    /** hook for JSVC */
    public void start() throws IOException
    {
        if (logger.isDebugEnabled())
            logger.debug(String.format("Binding avro service to %s:%s", listenAddr, listenPort));
        SpecificResponder responder = new SpecificResponder(Cassandra.class, new CassandraServer());

        logger.info("Listening for avro clients...");
        Mx4jTool.maybeLoad();
        // FIXME: This isn't actually binding to listenAddr (it should).
        server = new HttpServer(responder, listenPort);
        server.start();
    }

    /** hook for JSVC */
    public void stop()
    {
        logger.info("Cassandra shutting down...");
        server.close();
    }

    public static void main(String[] args) {
        new CassandraDaemon().activate();
    }

}


text:
require 'spec_helper'

describe Zoomus::Actions::Metrics do

  before :all do
    @zc = zoomus_client
    @args = {:type => 1,
             :from => '2013-04-05T15:50:47Z',
             :to => '2013-04-09T19:00:00Z'}
  end

  describe "#metrics_meetings action" do
    before :each do
      stub_request(
        :post,
        zoomus_url("/metrics/meetings")
      ).to_return(:body => json_response("metrics_meetings"))
    end

    it "requires a 'type' argument" do
      expect { @zc.metrics_meetings(filter_key(@args, :type)) }.to raise_error(ArgumentError)
    end

    it "requires a 'from' argument" do
      expect { @zc.metrics_meetings(filter_key(@args, :from)) }.to raise_error(ArgumentError)
    end

    it "requires a 'to' argument" do
      expect { @zc.metrics_meetings(filter_key(@args, :to)) }.to raise_error(ArgumentError)
    end

    it "returns a hash" do
      expect(@zc.metrics_meetings(@args)).to be_kind_of(Hash)
    end

    it "returns 'total_records'" do
      expect(@zc.metrics_meetings(@args)["total_records"]).to eq(1)
    end

    it "returns 'meetings' Array" do
      expect(@zc.metrics_meetings(@args)["meetings"]).to be_kind_of(Array)
    end
  end

  describe "#metrics_meetings! action" do
    before :each do
      stub_request(
        :post,
        zoomus_url("/metrics/meetings")
      ).to_return(:body => json_response("error"))
    end

    it "raises Zoomus::Error exception" do
      expect {
        @zc.metrics_meetings!(@args)
      }.to raise_error(Zoomus::Error)
    end
  end
end


text:
ETL == Extract, Transform and Load, or "log processing" in muggle world.

### Use case: session log

- Merge logs from clients and different servers, group by session-id
- Raw logs are dirty, do clean up filter, normalization --- tighly coupled to biz logic
- Assume 2h session window, provided aggregated detailed session data asap.

### Use case: dimensional metrics

- Use session data.
- Extract 10+ dimensions and 100+ event signals for each session
- Extraction logic can be complicated but limited to a single session.
- Populate to SQL DB (or Dremel / BigQuery) for interactive queries.

Typical query:

    SELECT sum/avg/quantile/...(signals)
    WHERE exp_id IN (...) AND dimension_x=..
    GROUP BY exp_id, dimension_y, dimension_z ...

### Use case: realtime spike detection

- Realtime hot topics, spam detection
- Directly streaming log data
- Find dimensions and signals, maintain an in-memory time series storage.

### What we have today

- Log ingestion tools
  - Heka, fluented etc.
  - Focus on convert / unfiy different log sources, configuration driven, coding not required in most cases.
  - Lack of aggregation support
- Data analysis platforms
  - New tools like Spark, Dataflow, focus on ease the task of constructing complex computation pipeline / fow with planner / compiler.
  - Functional programming model.
- Workflow management
  - DAG based MR pipeline management, Airflow etc.
- Time-series DB
  - Specific application (monitoring: prometheus)

### The gap

- Programming model for dirty data
  - Complexity is in processing single / small set (session) data, not overall computation model, facny distributed query planner doesn't help.
  - Complexity is in biz logic, not in converting one format to another, configurable generic modules doesn't help.
- Manageable computation model
  - Computation model of ETL pipelines tend to be simple, static.
  - But consider real-time streaming + small batch needs above, we want to do it in same framework.
  - +data dependencies and modules owned by different teams.
  - The pipeline must be predictable, easy monitor / debug / optimize, auto planner can harm.
- Pipeline Ops
  - Updating binary, changing protobuf.
  - Configurations shared between different modules / teams.
  - Monitoring, failure / overrun detection + data dependency management
  - Current tools not integrated well.

### Goal

- A programming framework for ETL job.
- Ops support as first class citizen, from framework to tools.
- Integrate with current tools, computation platforms, storages.
- CPU + IO efficiency

### Non-goal

- Another distributed computing framework.

## Saw, the programming model

### Main inspirations

- [Sawzall](http://static.googleusercontent.com/media/research.google.com/en//archive/sawzall-sciprog.pdf): table abstraction.
- [Millwheel](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/41378.pdf): generalized computation model.

### Saw

- A (possibly stateful) computation unit.
- `Emit(datum)`
  - Main interface, process a single input
  - Datum: a KV pair, where key is string and V can be anything (protobuf on wire)
  - Process data, send converted datums to any number of other saw, modify self state.
- `Result() -> Any`
  - Returns aggregated computation result based on all data received from `Emit()`
- Somewhat similar to Actor but
  - Message passing is synchronized.
  - Saw receives concurrent Emit unless otherwise noted.

### Table

- Is a framework container Saw.
- `table[sum]`: upon reciving datum `<kev, value>`, it group datum by key, and use aggregator `sum` to aggregate.
- sum is also a saw, for every datum emitted, it roughly do `self.curr += datum.value`
- Its `Result()` returns a map of `Result()` returned by aggregator for each key, and can optionally dump to persistent storage.
- Because the result is essentially a bunch of datum `<key, value>`, we can (in parallel) send its result to other saws, that's often called "re-saw"

Table is the main abstraction and power source of Saw, it takes care of:

- Data / computation parallelism and distribution
  - While table receives `Emit()` concurrently, it makes sure aggregator for each key gets data in sequence so normally aggregator implementor don't need to consider concurrency problem.
  - A distributed table is able to run aggregators in different nodes, using MR for example.
- Data persistentcy
  - As long as saw implements encoder / decoder, computation result (or even current state of aggregators) can be stored.

### Driver

- Gets data input from outside world.
  - Read input from local file / network storage, Kafka etc.
- Manage local runtime
  - Streaming or batch, parallelism.
- Detect data dependency and do remote excution
  - Provide tools to write complex workflow / pipeline

### Discussion

User-defined saws often falls in one of the two categories:

- Stateless "mapper"
- Stateful aggregator or "reducer"

Mapper only need to implement Emit. (`Result()` makes no sense to stateless component):

    func Emit(datum Datum) error {
      if !isValidData(datum) {
        return
      }
      userDimensions := extractDimensions(datum)
      metrics := normalzedMetrics(datum)
      // Store all data to session
      if isSessionEvent(datum) {
        sessionID := extractSessionID(datum)
        SessionTable.Emit(MakeDatum(sessionId, datum.Value))
      }
      // Event-specific aggregations
      if isQuery(datum) {
        for word := range strings.Split(data.Value.Query) {
          if isStopWord(word) {
            continue
          }
          QueryTable.Emit(makeQueryDatum(userDimensions, word, metrics))
        }
      } else isAdClick(datum) {
        ...
        adDimnesions := extractAdDimensions(datum)
        AdClickTable.Emit(makeAdClickDatum(Datum(userDimensions, adDimensions, metrics)))
      }
    }

Note the significant difference from MR framework: it sends data to different destination (represented as tables in Saw), with different key schema.

- In MR, the same semantic need be done using seperate mapper functions, resulting splitted code of closely related logics (dimension extraction and metric normalization etc.), and inefficient runtime.
- In MR, data flow is controlled by job configuration code that combines small piecies of mapper / reducer functions, in here, it's controlled within Emit(), well aligned with bussiness needs.

Comparing to Millwheel, one key differences is the absent of key extractor --- the data producer instead of consumer determine key schema. That sacrifice some flexibility but for good:

- Because of its static nature, consumer key extraction flexibility is not that valuable to ETL tasks.
- Data produced needed to be stored in specified structure to support common consumer needs,  key schema is part of this storage design --- same of computation distribution. You either get bad performance or sacrifice flexibility.
- If the flexibility is really needed, a simple in-memory, synchronized pubsub does the trick.

In writing reducer, a common pattern is to do mini-aggregation, by providing simple in-memory table (essentially memory map) and common standard aggregators, they can be done in a unified way.

TODO: code samples

## Implementation

### Early High-level decisions

- Go
  - It's not data analysis --- or I'd better use Python
  - Static type, code analysis tool, enable debugging and auditing at scale.
  - Acceptable performance at many-core architecture.
  - Easy deploy
- Optimize of single instance first
  - Single machine is powerful enough to cover 80% of needs today, Go uses multi-cores well.
  - They're very cheap on cloud --- 32 cores, 120G RAM preemptible instance costs < $0.5 / hr on [GCE](https://cloud.google.com/compute/pricing), and you can simply disable it when it's not actively used.
  - Familiar, flexible programming model from start, worry about horizontal scalability later.
- Optimize for Ops
  - Monitoring: critical for long running jobs.
  - Ease deployment --- single binary, different saw / driver configuration on different nodes, update and restart the whole thing in one shot.
  - Pipeline / data dependency management and scheduling.
- Cloud infrastructures
  - Cheap network storage like S3 or GCS can be as fast as local SSD. See also [Latency Numbers Every programmer Should Know](http://www.eecs.berkeley.edu/~rcs/research/interactive_latency.html)
  - Off-the-shelf haddop + spark cluster.
  - Computer instances can be start / stop within minutes, and even docker and kubernetes, oh my...
  - Saw won't re-invent the wheel for all these stuff already there.

### Local instance

### Tables

### Distributed computing

### Persistency / Storage

### Fault tolerence

## Example: session + dashboard


text:
using Microsoft.AspNetCore.Routing.Patterns;

namespace DeveloperExceptionPageSample;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddProblemDetails();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.Use((context, next) =>
        {
            context.Request.RouteValues = new RouteValueDictionary(new
            {
                routeValue1 = "Value1",
                routeValue2 = "Value2",
            });

            var endpoint = new RouteEndpoint(
                c => null,
                RoutePatternFactory.Parse("/"),
                0,
                new EndpointMetadataCollection(
                    new HttpMethodMetadata(new[] { "GET", "POST" })),
                "Endpoint display name");

            context.SetEndpoint(endpoint);
            return next(context);
        });
        app.UseDeveloperExceptionPage();
        app.Run(context =>
        {
            throw new Exception(string.Concat(
                "Demonstration exception. The list:", "\r\n",
                "New Line 1", "\n",
                "New Line 2", Environment.NewLine,
                "New Line 3"));
        });
    }

    public static Task Main(string[] args)
    {
        var host = new HostBuilder()
            .ConfigureWebHost(webHostBuilder =>
            {
                webHostBuilder
                .UseKestrel()
                .UseIISIntegration()
                .UseStartup<Startup>();
            })
            .Build();

        return host.RunAsync();
    }
}


text:
require "../module/AlchemyAPI.rb"

# Create an AlchemyAPI object.
alchemyObj = AlchemyAPI.new();

# Load the API key from disk.
alchemyObj.loadAPIKey("api_key.txt");

# Extract a ranked list of named entities from a web URL.
result = alchemyObj.URLGetRankedNamedEntities("http://www.techcrunch.com/");
puts result

# Extract a ranked list of named entities from a text string.
result = alchemyObj.TextGetRankedNamedEntities("Hello my name is Bob.  I am speaking to you at this very moment.  Are you listening to me, Bob?");
puts result

# Load a HTML document to analyze.
htmlFile = File.readlines('data/example.html').map {|l| l.rstrip}

# Extract a ranked list of named entities from a HTML document.
result = alchemyObj.HTMLGetRankedNamedEntities(htmlFile, "http://www.test.com/");
puts result


text:
"""
Problem Definition :

The cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.

Find the smallest cube for which exactly five permutations of its digits are cube.

"""

__author__ = 'vivek'

import time
from collections import Counter

def main():

    start_time = time.clock()

    cubes = [''.join(sorted(str(i**3))) for i in xrange(0, 10000)]

    perm_count = Counter(cubes)
    answer = 10000

    for key in perm_count:
        if perm_count[key] == 5:
            answer = min(answer, cubes.index(key))

    print(answer**3)

    print "Run time...{} secs \n".format(round(time.clock() - start_time, 4))

if __name__ == '__main__':
    main()


text:
require 'spec_helper'

describe 'ActiveRecord Integration' do

  let(:user){ User.create(:first_name => 'Mikey', :last_name => 'Foreman') }
  let(:admin){ Admin.create(:first_name => 'John', :last_name => 'Juniper') }
  let(:chair){ Chair.create(:name => 'Viking') }

  it 'should add scopes and cfinds to descendents' do
    User.should respond_to(:cached)
    User.should respond_to(:cfind)
  end

  it 'should propagate to child classes' do
    Admin.should respond_to(:cached)
    Admin.should respond_to(:cfind)
  end

  it 'should provide dv8 keys to descendents' do
    User.instance_methods.map(&:to_s).should include('dv8_keys')
  end

  it 'should find a record and only hit the cache once' do
    user
    ActiveRecord::Base.connection.should_receive(:select_all).once.and_return([user.attributes])
    User.cfind(user.id)
    User.cfind(user.id)
  end

  it 'should find a record when queried through a parent class' do
    admin
    ActiveRecord::Base.connection.should_receive(:select_all).once.and_return([admin.attributes])
    Admin.cfind(admin.id)
    User.cfind(admin.id).should be_a(Admin)
  end

  it 'should actually retrieve the user and instantiate a new object' do
    a = User.cfind(user.id)
    b = User.cfind(user.id)
    a.should eql(user)
    b.should eql(user)

    a.object_id.should_not eql(b.object_id)
    b.object_id.should_not eql(user.object_id)
    a.object_id.should_not eql(user.object_id)
  end

  it 'should behave normally when dv8 is not included' do
    c = chair
    u = user
    u.chair = chair
    u.save

    c.should_not respond_to(:cached_user)
    c.user.should eql(user)
  end

  context 'with dv8 models' do

    class FakeModel
      def self.after_update(*args); end
      def self.after_touch(*args); end
      def self.scope(*args, &block); Module.new(&block); end
      def self.table_name; 'fake_model'; end
      def self.reflect_on_association(*args); nil; end

      def initialize(options = {})
        options.reverse_merge(:friendly_id => nil, :id => nil, :to_param => nil, :slug => nil).each do |k,v|
          class_eval <<-EO
            def #{k}; #{v.inspect}; end
          EO
        end
      end

      include Dv8::Base
    end

    it 'should build dv8_keys properly' do
      keys(:id => 44, :friendly_id => '44').should eql([
        'fake_model-44'
      ])

      keys(:id => 50, :friendly_id => 'faker').should eql([
        'fake_model-50',
        'fake_model-faker'
      ])

      keys(:id => 60, :friendly_id => 'something', :to_param => 'test').should eql([
        'fake_model-60',
        'fake_model-something',
        'fake_model-test'
      ])

      keys(:id => 70, :friendly_id => 'other', :to_param => 'other').should eql([
        'fake_model-70',
        'fake_model-other'
      ])

      keys(:id => 80, :slug => 'anything').should eql([
        'fake_model-80',
        'fake_model-anything'
      ])
    end

    it 'should expire all dv8 keys' do
      Rails.cache.should_receive(:delete).with('fake_model-12').once
      Rails.cache.should_receive(:delete).with('fake_model-test').once
      Rails.cache.should_receive(:delete).with('fake_model-crazy').once
      mod(:id => 12, :friendly_id => 'test', :to_param => 'crazy').expire_dv8
    end

    def keys(fields)
      FakeModel.new(fields).dv8_keys
    end

    def mod(fields)
      FakeModel.new(fields)
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PetAdopt.Data.Repositories
{
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Linq;

    public class EFRepository<T> : IRepository<T> where T: class
    {
        protected DbContext context;
        private IDbSet<T> set;

        public EFRepository() : this(new PetAdoptDbContext())
        {
            this.context = context;
            this.set = context.Set<T>();
        }

        public EFRepository(DbContext context)
        {
            this.context = context;
            this.set = context.Set<T>();
        }

        public virtual IQueryable<T> All()
        {
            return this.set;
        }

        public T Find(object id)
        {
            return this.set.Find(id);
        }

        public void Add(T entity)
        {
            this.ChangeState(entity, EntityState.Added);
        }

        public void Update(T entity)
        {
            this.ChangeState(entity, EntityState.Modified);
        }

        public virtual T Delete(T entity)
        {
            this.ChangeState(entity, EntityState.Deleted);
            return entity;
        }

        public T Delete(object id)
        {
            var entity = this.Find(id);
            this.Delete(entity);
            return entity;
        }

        public int SaveChanges()
        {
            return this.context.SaveChanges();
        }

        private void ChangeState(T entity, EntityState state)
        {
            var entry = this.context.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                this.set.Attach(entity);
            }

            entry.State = state;
        }

        public virtual void Detach(T entity)
        {
            DbEntityEntry entry = this.context.Entry(entity);

            entry.State = EntityState.Detached;
        }
    }
}


text:
/* $OpenBSD: wscons_callbacks.h,v 1.2 2000/08/01 13:51:17 mickey Exp $ */
/* $NetBSD: wscons_callbacks.h,v 1.12 2000/03/06 21:37:16 thorpej Exp $ */

/*
 * Copyright (c) 1996, 1997 Christopher G. Demetriou.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Christopher G. Demetriou
 *	for the NetBSD Project.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Calls to the display interface from the glue code.
 */
struct device *wsdisplay_set_console_kbd __P((struct device *));

/*
 * Calls to the display interface from the keyboard interface.
 */
void	wsdisplay_kbdinput __P((struct device *v, keysym_t));
int	wsdisplay_switch __P((struct device *, int, int));
enum wsdisplay_resetops {
	WSDISPLAY_RESETEMUL,
	WSDISPLAY_RESETCLOSE
};
void	wsdisplay_reset __P((struct device *, enum wsdisplay_resetops));
void	wsdisplay_kbdholdscreen __P((struct device *v, int));

void	wsdisplay_set_cons_kbd __P((int (*get)(dev_t),
				    void (*poll)(dev_t, int),
				    void (*bell)(dev_t, u_int, u_int, u_int)));
void	wsdisplay_unset_cons_kbd __P((void));

/*
 * Calls to the keyboard interface from the glue code.
 */
struct wsmux_softc;
struct device *wskbd_set_console_display
		__P((struct device *, struct wsmux_softc *));
int wskbd_pickfree __P((void));


text:
#ifndef BOOST_GEOMETRY_PROJECTIONS_PUTP5_HPP
#define BOOST_GEOMETRY_PROJECTIONS_PUTP5_HPP

// Boost.Geometry - extensions-gis-projections (based on PROJ4)
// This file is automatically generated. DO NOT EDIT.

// Copyright Barend Gehrels (1995-2009), Geodan Holding B.V. Amsterdam, the Netherlands.
// Copyright Bruno Lalande (2008-2009)
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// This file is converted from PROJ4, http://trac.osgeo.org/proj
// PROJ4 is originally written by Gerald Evenden (then of the USGS)
// PROJ4 is maintained by Frank Warmerdam
// PROJ4 is converted to Boost.Geometry by Barend Gehrels (Geodan, Amsterdam)

// Original copyright notice:

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#include <boost/concept_check.hpp>
#include <boost/math/special_functions/hypot.hpp>

#include <boost/geometry/extensions/gis/projections/impl/base_static.hpp>
#include <boost/geometry/extensions/gis/projections/impl/base_dynamic.hpp>
#include <boost/geometry/extensions/gis/projections/impl/projects.hpp>
#include <boost/geometry/extensions/gis/projections/impl/factory_entry.hpp>

namespace boost { namespace geometry { namespace projection
{
    #ifndef DOXYGEN_NO_DETAIL
    namespace detail { namespace putp5{
            static const double C = 1.01346;
            static const double D = 1.2158542;

            struct par_putp5
            {
                double    A, B;
            };

            // template class, using CRTP to implement forward/inverse
            template <typename Geographic, typename Cartesian, typename Parameters>
            struct base_putp5_spheroid : public base_t_fi<base_putp5_spheroid<Geographic, Cartesian, Parameters>,
                     Geographic, Cartesian, Parameters>
            {

                 typedef double geographic_type;
                 typedef double cartesian_type;

                par_putp5 m_proj_parm;

                inline base_putp5_spheroid(const Parameters& par)
                    : base_t_fi<base_putp5_spheroid<Geographic, Cartesian, Parameters>,
                     Geographic, Cartesian, Parameters>(*this, par) {}

                inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const
                {
                    xy_x = C * lp_lon * (this->m_proj_parm.A - this->m_proj_parm.B * sqrt(1. + D * lp_lat * lp_lat));
                    xy_y = C * lp_lat;
                }

                inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const
                {
                    lp_lat = xy_y / C;
                    lp_lon = xy_x / (C * (this->m_proj_parm.A - this->m_proj_parm.B * sqrt(1. + D * lp_lat * lp_lat)));
                }
            };

            template <typename Parameters>
            void setup(Parameters& par, par_putp5& proj_parm)
            {
                boost::ignore_unused_variable_warning(par);
                boost::ignore_unused_variable_warning(proj_parm);
                par.es = 0.;
                // par.inv = s_inverse;
                // par.fwd = s_forward;
            }

            // Putnins P5
            template <typename Parameters>
            void setup_putp5(Parameters& par, par_putp5& proj_parm)
            {
                proj_parm.A = 2.;
                proj_parm.B = 1.;
                setup(par, proj_parm);
            }

            // Putnins P5'
            template <typename Parameters>
            void setup_putp5p(Parameters& par, par_putp5& proj_parm)
            {
                proj_parm.A = 1.5;
                proj_parm.B = 0.5;
                setup(par, proj_parm);
            }

        }} // namespace detail::putp5
    #endif // doxygen

    /*!
        \brief Putnins P5 projection
        \ingroup projections
        \tparam Geographic latlong point type
        \tparam Cartesian xy point type
        \tparam Parameters parameter type
        \par Projection characteristics
         - Pseudocylindrical
         - Spheroid
        \par Example
        \image html ex_putp5.gif
    */
    template <typename Geographic, typename Cartesian, typename Parameters = parameters>
    struct putp5_spheroid : public detail::putp5::base_putp5_spheroid<Geographic, Cartesian, Parameters>
    {
        inline putp5_spheroid(const Parameters& par) : detail::putp5::base_putp5_spheroid<Geographic, Cartesian, Parameters>(par)
        {
            detail::putp5::setup_putp5(this->m_par, this->m_proj_parm);
        }
    };

    /*!
        \brief Putnins P5' projection
        \ingroup projections
        \tparam Geographic latlong point type
        \tparam Cartesian xy point type
        \tparam Parameters parameter type
        \par Projection characteristics
         - Pseudocylindrical
         - Spheroid
        \par Example
        \image html ex_putp5p.gif
    */
    template <typename Geographic, typename Cartesian, typename Parameters = parameters>
    struct putp5p_spheroid : public detail::putp5::base_putp5_spheroid<Geographic, Cartesian, Parameters>
    {
        inline putp5p_spheroid(const Parameters& par) : detail::putp5::base_putp5_spheroid<Geographic, Cartesian, Parameters>(par)
        {
            detail::putp5::setup_putp5p(this->m_par, this->m_proj_parm);
        }
    };

    #ifndef DOXYGEN_NO_DETAIL
    namespace detail
    {

        // Factory entry(s)
        template <typename Geographic, typename Cartesian, typename Parameters>
        class putp5_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>
        {
            public :
                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const
                {
                    return new base_v_fi<putp5_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);
                }
        };

        template <typename Geographic, typename Cartesian, typename Parameters>
        class putp5p_entry : public detail::factory_entry<Geographic, Cartesian, Parameters>
        {
            public :
                virtual projection<Geographic, Cartesian>* create_new(const Parameters& par) const
                {
                    return new base_v_fi<putp5p_spheroid<Geographic, Cartesian, Parameters>, Geographic, Cartesian, Parameters>(par);
                }
        };

        template <typename Geographic, typename Cartesian, typename Parameters>
        inline void putp5_init(detail::base_factory<Geographic, Cartesian, Parameters>& factory)
        {
            factory.add_to_factory("putp5", new putp5_entry<Geographic, Cartesian, Parameters>);
            factory.add_to_factory("putp5p", new putp5p_entry<Geographic, Cartesian, Parameters>);
        }

    } // namespace detail
    #endif // doxygen

}}} // namespace boost::geometry::projection

#endif // BOOST_GEOMETRY_PROJECTIONS_PUTP5_HPP


text:
[#]: collector: (lujun9972)
[#]: translator: ( )
[#]: reviewer: ( )
[#]: publisher: ( )
[#]: url: ( )
[#]: subject: (A few bytes here, a few there, pretty soon you're talking real memory)
[#]: via: (https://dave.cheney.net/2021/01/05/a-few-bytes-here-a-few-there-pretty-soon-youre-talking-real-memory)
[#]: author: (Dave Cheney https://dave.cheney.net/author/davecheney)

A few bytes here, a few there, pretty soon you're talking real memory
======

Today's post comes from a recent Go pop quiz. Consider this benchmark fragment.[1][1]

```
func BenchmarkSortStrings(b *testing.B) {
        s := []string{"heart", "lungs", "brain", "kidneys", "pancreas"}
        b.ReportAllocs()
        for i := 0; i < b.N; i++ {
                sort.Strings(s)
        }
}
```

A convenience wrapper around `sort.Sort(sort.StringSlice(s))`, `sort.Strings` sorts the input in place, so it isn't expected to allocate (or at least that's what 43% of the tweeps who responded thought). However it turns out that, at least in recent versions of Go, each iteration of the benchmark causes one heap allocation. Why does this happen?

Interfaces, as all Go programmers should know, are implemented as a [two word structure][2]. Each interface value contains a field which holds the type of the interface's contents, and a pointer to the interface's contents.[2][3]

In pseudo Go code, an interface might look something like this:

```
type interface struct {
        // the ordinal number for the type of the value
        // assigned to the interface
        type uintptr

        // (usually) a pointer to the value assigned to
        // the interface
        data uintptr
}
```

`interface.data` can hold one machine word–8 bytes in most cases–but a `[]string` is 24 bytes; one word for the pointer to the slice's underlying array; one word for the length; and one for the remaining capacity of the underlying array, so how does Go fit 24 bytes into 8? With the oldest trick in the book, indirection. `s`, a `[]string` is 24 bytes, but `*[]string`–a pointer to a slice of strings–is only 8.

### Escaping to the heap

To make the example a little more explicit, here's the benchmark rewritten without the `sort.Strings` helper function:

```
func BenchmarkSortStrings(b *testing.B) {
        s := []string{"heart", "lungs", "brain", "kidneys", "pancreas"}
        b.ReportAllocs()
        for i := 0; i < b.N; i++ {
                var ss sort.StringSlice = s
                var si sort.Interface = ss // allocation
                sort.Sort(si)
        }
}
```

To make the interface magic work, the compiler rewrites the assignment as `var si sort.Interface = &ss`–the _address_ of `ss` is assigned to the interface value.[3][4] We now have a situation where the interface value holds a pointer to `ss`, but where does it point? Where in memory does `ss` live?

It appears that `ss` is moved to the heap, causing the allocation that the benchmark reports.

```
Total:    296.01MB   296.01MB (flat, cum) 99.66%
    8            .          .           func BenchmarkSortStrings(b *testing.B) {
    9            .          .             s := []string{"heart", "lungs", "brain", "kidneys", "pancreas"}
   10            .          .             b.ReportAllocs()
   11            .          .             for i := 0; i < b.N; i++ {
   12            .          .                 var ss sort.StringSlice = s
   13     296.01MB   296.01MB                 var si sort.Interface = ss // allocation
   14            .          .                 sort.Sort(si)
   15            .          .             }
   16            .          .           }
```

The allocation occurs because the compiler currently cannot convince itself that `ss` outlives `si`. The general attitude amongst Go compiler hackers seems to be that [this could be improved][5], but that's a discussion for another time. As it stands, `ss` is allocated on the heap. Thus the question becomes, how many bytes are allocated per iteration? Why don't we ask the `testing` package.

```
% go test -bench=. sort_test.go
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-5650U CPU @ 2.20GHz
BenchmarkSortStrings-4          12591951                91.36 ns/op           24 B/op          1 allocs/op
PASS
ok      command-line-arguments  1.260s
```

Using Go 1.16beta1, on amd64, 24 bytes are allocated per operation.[4][6] However, the previous Go version, on the same platform, consumes 32 bytes per operation

```
% go1.15 test -bench=. sort_test.go
goos: darwin
goarch: amd64
BenchmarkSortStrings-4          11453016                96.4 ns/op            32 B/op          1 allocs/op
PASS
ok      command-line-arguments  1.225s
```

This brings us, circuitously, to the subject of this post, a nifty quality of life improvement coming in Go 1.16. But before I can talk about it, I need to discuss size classes.

### Size classes

To explain what a size class is, consider how a theoretical Go runtime could allocate 24 bytes on its heap. A simple way to do this would be keep track of all the memory allocated so far using a pointer to the last allocated byte on the heap. To allocate 24 bytes, the heap pointer is incremented by 24, and the previous value returned to the caller. As long as the code that asked for 24 bytes never writes beyond that mark this mechanism has no overhead. Sadly, in real life, memory allocators don't just allocate memory, sometimes they have to free it.

Eventually the Go runtime will have to free those 24 bytes, but from the runtime's point of view, the only thing it knows is the starting address it gave to the caller. It does not know how many bytes after that address were allocated. To permit deallocation, our hypothetical Go runtime allocator would have to record, for each allocation on the heap, its length. Where are the allocation for those lengths allocated? On the heap of course.

In our scenario, when the runtime wants to allocate memory, it could request a little more than it was asked for and use it to store the amount requested. For our slice example, when we asked for 24 bytes, we'd actually consume 24 bytes plus some overhead to store the number 24. How large is this overhead? It turns out the minimum amount that is practical is one word.[5][7]

To record a 24 byte allocation the overhead would 8 bytes. 25% is not great, but not terrible, and as the size of the allocation goes up, the overhead would become insignificant. However, what would happen if we wanted to store just one `byte` on the heap? The overhead would be eight times the amount of data we asked for! Is there are more efficient way to allocate small amounts on the heap?

Rather than storing the length alongside each allocation, what if all the thing of the same size were stored together? If all the 24 byte things are stored together, then the runtime would automatically know how large they are. All the runtime needs is a single bit to indicate if a 24 byte area is in use or not. In Go these areas are known as size classes, because all the things of the same size are stored together (think school class–all the students are the same grade–not a C++ class). When the runtime needs to allocate a small amount, it does so using the smallest size class that can accomodate the allocation.

### Unlimited size classes for all

Now we know how size classes work, the obvious question is, where are they stored? Not surprisingly, the memory for a size class comes from the heap. To minimise overhead, the runtime allocates a larger amount from the heap (usually a multiple of the system page size) then dedicates that space for allocations of a single size. But, there's a problem.

The pattern of allocating a large area to store things of the same size works well[6][8] if there's a fixed, preferably small, number of allocation sizes, but in a general purpose language programs can ask the runtime for an allocation of any size.[7][9]

For example, imagine asking the runtime for 9 bytes. 9 bytes is an uncommon size, so it's likely that a new size class for things of size 9 would be required. As 9 byte things are uncommon, it's likely the remainder of the allocation, 4kb or more, would be wasted. Because of this the set of possible size classes is fixed. If a size class of the exact amount is not available, the allocation is rounded up to the next size class. In our example 9 bytes might be allocated in the 12 byte size class. The overhead of 3 unused bytes is better than an entire size class allocation which goes mostly unused.

### All together now

This is the final piece of the puzzle. Go 1.15 did not have a 24 byte size class, so the heap allocation of `ss` was allocated in the 32 byte size class. Thanks to the work of Martin Möhrmann Go 1.16 has a 24 byte size class, which is a perfect fit for slice values assigned to interfaces.

  1. This is not the correct way to benchmark a sort function because after the first iteration, the input is sorted. But I digress.[][10]
  2. The accuracy of this statement depends on the version of Go in use. For example, Go 1.15 added the ability to [store some integers directly in the interface value,][11] saving the allocation and indirection. However, for the majority of values, if it wasn't a pointer type already, its address is taken and stored in the interface value.[][12]
  3. The compiler keeps track of this sleight of hand in the interface value's type field so it remembers that the type assigned to `si` is `sort.StringSlice`, not `*sort.StringSlice`.[][13]
  4. On 32 bit platforms this number is halved, [but we never look back][14].[][15]
  5. If you were prepared to limit allocations to 4G, or maybe 64kb, you could use a smaller amount of memory to store the size of the allocation, but this would mean the first word of the allocation is not naturally aligned so in practice the savings of using less than a word to store the length header are undermined by padding.[][16]
  6. Storing things of the same size together is also an effective strategy to combat fragmentation.[][17]
  7. This isn't a far fetched scenario, strings come in all shapes and sizes and generating a string of a size not previously seen before can be as simple as appending a space.[][18]

#### Related posts:

  1. [I'm talking about Go at DevFest Siberia 2017][19]
  2. [If aligned memory writes are atomic, why do we need the sync/atomic package?][20]
  3. [A real serial console for your Raspberry Pi][21]
  4. [Why is a Goroutine's stack infinite ?][22]

--------------------------------------------------------------------------------

via: https://dave.cheney.net/2021/01/05/a-few-bytes-here-a-few-there-pretty-soon-youre-talking-real-memory

作者:[Dave Cheney][a]
选题:[lujun9972][b]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]: https://dave.cheney.net/author/davecheney
[b]: https://github.com/lujun9972
[1]: tmp.AZQSXjFgPm#easy-footnote-bottom-1-4231 (This is not the correct way to benchmark a sort function because after the first iteration, the input is sorted. But I digress.)
[2]: https://research.swtch.com/interfaces
[3]: tmp.AZQSXjFgPm#easy-footnote-bottom-2-4231 (The accuracy of this statement depends on the version of Go in use. For example, Go 1.15 added the ability to store some integers directly in the interface value, saving the allocation and indirection. However, for the majority of values, if it wasn't a pointer type already, its address is taken and stored in the interface value.)
[4]: tmp.AZQSXjFgPm#easy-footnote-bottom-3-4231 (The compiler keeps track of this sleight of hand in the interface value's type field so it remembers that the type assigned to si is sort.StringSlice, not *sort.StringSlice.)
[5]: https://github.com/golang/go/issues/23676
[6]: tmp.AZQSXjFgPm#easy-footnote-bottom-4-4231 (On 32 bit platforms this number is halved, but we never look back.)
[7]: tmp.AZQSXjFgPm#easy-footnote-bottom-5-4231 (If you were prepared to limit allocations to 4G, or maybe 64kb, you could use a smaller amount of memory to store the size of the allocation, but this would mean the first word of the allocation is not naturally aligned so in practice the savings of using less than a word to store the length header are undermined by padding.)
[8]: tmp.AZQSXjFgPm#easy-footnote-bottom-6-4231 (Storing things of the same size together is also an effective strategy to combat fragmentation.)
[9]: tmp.AZQSXjFgPm#easy-footnote-bottom-7-4231 (This isn't a far fetched scenario, strings come in all shapes and sizes and generating a string of a size not previously seen before can be as simple as appending a space.)
[10]: tmp.AZQSXjFgPm#easy-footnote-1-4231
[11]: https://golang.org/doc/go1.15#runtime
[12]: tmp.AZQSXjFgPm#easy-footnote-2-4231
[13]: tmp.AZQSXjFgPm#easy-footnote-3-4231
[14]: https://www.tallengestore.com/products/i-never-look-back-darling-it-distracts-from-the-now-edna-mode-inspirational-quote-tallenge-motivational-poster-collection-large-art-prints
[15]: tmp.AZQSXjFgPm#easy-footnote-4-4231
[16]: tmp.AZQSXjFgPm#easy-footnote-5-4231
[17]: tmp.AZQSXjFgPm#easy-footnote-6-4231
[18]: tmp.AZQSXjFgPm#easy-footnote-7-4231
[19]: https://dave.cheney.net/2017/08/23/im-talking-about-go-at-devfest-siberia-2017 (I'm talking about Go at DevFest Siberia 2017)
[20]: https://dave.cheney.net/2018/01/06/if-aligned-memory-writes-are-atomic-why-do-we-need-the-sync-atomic-package (If aligned memory writes are atomic, why do we need the sync/atomic package?)
[21]: https://dave.cheney.net/2014/01/05/a-real-serial-console-for-your-raspberry-pi (A real serial console for your Raspberry Pi)
[22]: https://dave.cheney.net/2013/06/02/why-is-a-goroutines-stack-infinite (Why is a Goroutine's stack infinite ?)


text:
Ce repo GitHub contient la **compétition pratique** de génie informatique des [Jeux de Génie 2015](http://jeuxdegenie.qc.ca/).
Les instructions en **français** se trouvent ci-dessus, ou au bout du lien suivant:

#### [Examen français (README-FR.md)](https://github.com/ebelair/jdg15-info/blob/master/README-FR.md)

# Engineering Games 2015 - Computer Eng.
This GitHub repository contains the **practical competition** in Computer Engineering of the [Engineering Games 2015](http://jeuxdegenie.qc.ca/).
The instructions in **English** can be found above, or using the following link:

#### [English Exam (README-EN.md)](https://github.com/ebelair/jdg15-info/blob/master/README-EN.md)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="weather_type_null">'Tidak ada data'</string>
    <string name="weather_type_0">Cerah</string>
    <string name="weather_type_1">Berawan</string>
    <string name="weather_type_2">Berkabut</string>
    <string name="weather_type_3">Berkabut</string>
    <string name="weather_type_4">Hujan badai parah</string>
    <string name="weather_type_5">Hujan badai</string>
    <string name="weather_type_6">Hujan sangat deras</string>
    <string name="weather_type_7">Badai petir</string>
    <string name="weather_type_8">Hujan lebat</string>
    <string name="weather_type_9">Hujan deras</string>
    <string name="weather_type_10">Hujan</string>
    <string name="weather_type_11">Gerimis</string>
    <string name="weather_type_12">Hujan es salju</string>
    <string name="weather_type_13">Badai salju</string>
    <string name="weather_type_14">Gerimis salju</string>
    <string name="weather_type_15">Hujan salju deras</string>
    <string name="weather_type_16">Hujan salju</string>
    <string name="weather_type_17">Hujan salju ringan</string>
    <string name="weather_type_18">Badai pasir kuat</string>
    <string name="weather_type_19">Badai pasir</string>
    <string name="weather_type_20">Badai pasir ringan</string>
    <string name="weather_type_21">Badai pasir</string>
    <string name="weather_type_22">Hujan es</string>
    <string name="weather_type_23">Berdebu</string>
    <string name="weather_type_24">Kabut</string>
</resources>


text:
require 'spec_helper'

describe ApplicationHelper do
  let :period do
    Period.new(2012, 2)
  end

  it 'should return period_url' do
    expect(period_url(period)).to eq '/moviments?year=2012&month=02'
  end

  context 'tags link' do
    let :tags do
      [
        double('Tag#1', :name => 'tag1'),
        double('Tag#2', :name => 'tag2')
      ]
    end

    it 'should return tags with link' do
      expect(tags_with_link(tags)).to eq "tag1 e tag2"
    end
  end

  context 'currency' do
    it 'greater than zero' do
      expect(currency(10)).to eq "R$ 10,00"
    end

    it 'less than zero' do
      expect(currency(-10)).to eq "-R$ 10,00"
    end
  end
end


text:
<?php

namespace Molajo\Query\Factory;

use Exception;
use CommonApi\Exception\RuntimeException;
use CommonApi\Query\ModelInterface;
use CommonApi\Query\QueryInterface;
use CommonApi\Resource\FactoryInterface;

/**
 * Controller Factory
 *
 * @package    Molajo
 * @copyright  2014-2015 Amy Stephen. All rights reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @since      1.0.0
 */
class ControllerFactory implements FactoryInterface
{
    /**
     * Query Instance
     *
     * @var    object  CommonApi\Query\QueryInterface
     * @since  1.0
     */
    protected $query = null;

    /**
     * Model Instance
     *
     * @var    object  CommonApi\Query\ModelInterface
     * @since  1.0
     */
    protected $model;

    /**
     * Model Registry
     *
     * @var    array
     * @since  1.0
     */
    protected $model_registry = null;

    /**
     * Runtime Data
     *
     * @var    object
     * @since  1.0
     */
    protected $runtime_data = null;

    /**
     * Schedule Event - anonymous function to FrontController schedule_event method
     *
     * @var    callable
     * @since  1.0
     */
    protected $schedule_event;

    /**
     * Get Cache - anonymous function to FrontController getCache method
     *
     * @var    callable
     * @since  1.0
     */
    protected $get_cache_callback;

    /**
     * Set Cache - anonymous function to FrontController setCache method
     *
     * @var    callable
     * @since  1.0
     */
    protected $set_cache_callback;

    /**
     * Function to Delete Cache, either by key or all
     *
     * @var    callable
     * @since  1.0
     */
    protected $delete_cache_callback;

    /**
     * SQL
     *
     * @var    string
     * @since  1.0
     */
    protected $sql;

    /**
     * Crud Type
     *
     * @var    string
     * @since  1.0
     */
    public $crud_type = null;

    /**
     * Constructor
     *
     * @param  QueryInterface $query
     * @param  ModelInterface $model
     * @param  array          $model_registry
     * @param  object         $runtime_data
     * @param  callback       $schedule_event
     * @param  callback       $get_cache_callback
     * @param  callback       $set_cache_callback
     * @param  callable       $delete_cache_callback
     * @param  string         $sql
     * @param  string         $crud_type
     *
     * @since  1.0
     */
    public function __construct(
        QueryInterface $query,
        ModelInterface $model,
        $model_registry,
        $runtime_data,
        $schedule_event = null,
        $get_cache_callback = null,
        $set_cache_callback = null,
        $delete_cache_callback = null,
        $sql = '',
        $crud_type = 'read'
    ) {
        $this->query                 = $query;
        $this->model                 = $model;
        $this->model_registry        = $model_registry;
        $this->runtime_data          = $runtime_data;
        $this->schedule_event        = $schedule_event;
        $this->get_cache_callback    = $get_cache_callback;
        $this->set_cache_callback    = $set_cache_callback;
        $this->delete_cache_callback = $delete_cache_callback;
        $this->sql                   = $sql;
        $this->crud_type             = $crud_type;
    }

    /**
     * Instantiate Class, load the Model Registry and SQL
     *
     * @return  object
     * @since   1.0.0
     * @throws  \CommonApi\Exception\RuntimeException
     */
    public function instantiateClass()
    {
        $class = 'Molajo\\Controller\\' . ucfirst(strtolower($this->crud_type));

        try {
            $instance = new $class (
                $this->model,
                $this->runtime_data,
                $this->query,
                $this->schedule_event,
                $this->get_cache_callback,
                $this->set_cache_callback,
                $this->delete_cache_callback
            );
        } catch (Exception $e) {
            throw new RuntimeException(
                'Molajo\\Query\\Factory\\ControllerFactory::instantiateClass Failed Instantiating: '
                . $class
                . ' '
                . $e->getMessage()
            );
        }

        $instance->clearQuery();

        $instance->setModelRegistry(null, $this->model_registry);

        if ($this->crud_type === 'Create') {
            $this->crud_type = 'insert';
        } elseif ($this->crud_type === 'Createfrom') {
            $this->crud_type = 'insertfrom';
        } else {
            $this->crud_type = strtolower($this->crud_type);
        }

        $instance->setType($this->crud_type);

        if (trim($this->sql) === '') {
        } else {
            $instance->set('sql', $this->sql);
        }

        return $instance;
    }
}


text:
"use strict";

var HttpStatus = require('http-status');
var User = require('../models/user');

/**
 * Create a user
 * @param req
 * @param res
 */
exports.create = function (req, res) {
    res.problem(HttpStatus.METHOD_NOT_ALLOWED,
        "You're not allowed to create users on this system",
        "Users are created via 3rd party (Facebook) authentication");
};

/**
 * Gets a list of all users
 *
 * @errors (500) Unexpected problem
 *
 * @param req An express request object
 * @param res An express res object, expected to contain res.problem middleware
 * @return {problem|null|object}
 */
exports.list = function (req, res) {
    User.publicList(req.query.skip, req.query.take, function (err, results) {
        if (err) {
            return res.problem(HttpStatus.INTERNAL_SERVER_ERROR,
                "Unexpected problem",
                "Could not list users due to internal error");
        }

        if (results === null) {
            return res.json(HttpStatus.NO_CONTENT);
        } else {
            return res.json(HttpStatus.OK, results);
        }
    });
};

/**
 * Gets a user by ID
 *
 * @param req An express request object
 * @param res An express response object
 */
exports.getById = function (req, res) {
    // Example mongodb id: 52aff48d78b818c844000001
    User.getById(req.params.mid, function (err, results) {
        res.json(HttpStatus.OK, results);
    });
};

/**
 * Updates a user (either new or existing)
 *
 * @param req An express request object
 * @param res An express response object
 */
exports.update = function (req, res) {
    var upd = req.body;
    User.fb(req.user.facebookId, function (err, user) {
        if (err || user === null) {
            return res.problem(
                HttpStatus.BAD_REQUEST,
                "Could not save user information",
                "There was an error processing the request to save your information"
            );
        }

        // only new users can change their usernames
        if (!user.registrationDone) {
            // must start with a letter and be between 5 and 16 alphanumeric characters
            if (/^[a-zA-Z]{1}[a-zA-Z0-9_]{4,15}$/.test(upd.username) === false) {
                return res.problem(
                    HttpStatus.BAD_REQUEST,
                    "Invalid Username",
                    "User names must be 5-16 characters"
                );
            }

            user.username = upd.username;
        }

        user.registrationDone = true;
        user.firstName = upd.firstName || user.firstName;
        user.lastName = upd.lastName || user.lastName;
        user.email = upd.email || user.email;
        user.state = User.States.ONLINE;
        user.avatar = upd.avatar;

        user.save(function (err, user /*, numAffected */) {
            res.json(HttpStatus.OK, user);
        });
    });
};

/**
 * Deletes the account of the current user
 *
 * @param req An express request object
 * @param res An express response object
 */
exports.delete = function (req, res) {
    User.fb(req.user.facebookId, function (err, user) {
        if (err || user === null) {
            return res.problem(
                HttpStatus.BAD_REQUEST,
                "Could not delete user",
                "There was an error processing the request to save your information"
            );
        }

        return user.remove(function (err, result) {
            res.json(HttpStatus.OK, result);
        });
    });
};

/**
 * Gets messages for the logged in user
 *
 * @param req An express request object
 * @param res An express response object
 */
exports.getMessages = function (req, res) {
    User.getMessages(req.params.mid, function (err, doc) {
        if (err || doc === null || doc.messages === null) {
            return res.problem(
                HttpStatus.NO_CONTENT
            );
        }

        return res.json(HttpStatus.OK, doc);
    });
};

/**
 * Gets the list of cohorts for a user, given the user's id.
 *
 * @param req
 * @param res
 */
exports.getCohortsById = function (req, res) {
    User.getCohortsById(req.params.mid, function (err, results) {
        if (err) {
            return res.problem(HttpStatus.INTERNAL_SERVER_ERROR,
                "Unexpected problem",
                "Could not retrieve cohorts due to internal error");
        }

        if (results === null || results.length === 0) {
            return res.json(HttpStatus.NO_CONTENT);
        } else {
            return res.json(HttpStatus.OK, results);
        }
    });
};

/**
 * Add a single cohort to a user object.
 *
 * @param req
 * @param res
 */
exports.addCohortForUser = function (req, res) {
    User.addCohort(req.params.mid, req.params.id, function (err, results) {
        if (err) {
            return res.problem(HttpStatus.INTERNAL_SERVER_ERROR,
                "Unexpected problem",
                "Could not save cohort due to internal error");
        }

        if (results === null || results.length === 0) {
            return res.json(HttpStatus.NO_CONTENT);
        } else {
            return res.json(HttpStatus.OK, results);
        }
    });
};

/**
 * Remove a single cohort from a user object.
 *
 * @param req
 * @param res
 */
exports.removeCohortFromUser = function (req, res) {
    User.removeCohort(req.params.mid, req.params.id, function (err, results) {
        if (err) {
            return res.problem(HttpStatus.INTERNAL_SERVER_ERROR,
                "Unexpected problem",
                "Could not remove cohort due to internal error");
        }

        if (results === null || results.length === 0) {
            return res.json(HttpStatus.NO_CONTENT);
        } else {
            return res.json(HttpStatus.OK, results);
        }
    });
};


text:
import loaderFactory from './src/loader';

export const loader = loaderFactory(
  typeof fetch !== 'undefined' && fetch, // use built-in fetch API
  null // no file system access
);

export {
  default as read
} from './src/read';

export {
  inferType,
  inferTypes,
  typeParsers
} from './src/type';

export {
  format,
  formats,
  responseType
} from './src/formats/index';


text:
<?php
/* @var $this PostPassageController */
/* @var $model PostPassage */

$this->breadcrumbs=array(
	'Post Passages'=>array('index'),
	'Manage',
);

$this->menu=array(
	array('label'=>'List PostPassage', 'url'=>array('index')),
	array('label'=>'Create PostPassage', 'url'=>array('create')),
);

Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
	$('.search-form').toggle();
	return false;
});
$('.search-form form').submit(function(){
	$('#post-passage-grid').yiiGridView('update', {
		data: $(this).serialize()
	});
	return false;
});
");
?>

Manage Post Passages

You may optionally enter a comparison operator (<, <=, >, >=, <>
or =) at the beginning of each of your search values to specify how the comparison should be done.

<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>

<?php $this->renderPartial('_search',array(
	'model'=>$model,
)); ?>

<?php $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'post-passage-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
	'columns'=>array(
		'posten_passage_ID',
		'post_ID',
		'event_ID',
		'day_ID',
		'group_ID',
		/*
		'gepasseerd',
		'binnenkomst',
		'vertrek',
		'score',
		'create_time',
		'create_user_ID',
		'update_time',
		'update_user_ID',
		*/
		array(
			'class'=>'CButtonColumn',
		),
	),
)); ?>


text:
namespace OnTheRoad.Mvp.Models
{
    public class TripModel
    {
        public byte[] ImageContent { get; set; }
    }
}


text:
package main

import (
	"fmt"
	"math/rand"
	"runtime"

	"github.com/containernetworking/plugins/pkg/ns"
	"github.com/coreos/go-iptables/iptables"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

const TABLE = "filter" // We'll monkey around here

// TODO: run these tests in a new namespace
var _ = Describe("chain tests", func() {
	var testChain chain
	var ipt *iptables.IPTables
	var cleanup func()

	BeforeEach(func() {

		// Save a reference to the original namespace,
		// Add a new NS
		currNs, err := ns.GetCurrentNS()
		Expect(err).NotTo(HaveOccurred())

		testNs, err := ns.NewNS()
		Expect(err).NotTo(HaveOccurred())

		tlChainName := fmt.Sprintf("cni-test-%d", rand.Intn(10000000))
		chainName := fmt.Sprintf("cni-test-%d", rand.Intn(10000000))

		testChain = chain{
			table:       TABLE,
			name:        chainName,
			entryRule:   []string{"-d", "203.0.113.1"},
			entryChains: []string{tlChainName},
		}

		ipt, err = iptables.NewWithProtocol(iptables.ProtocolIPv4)
		Expect(err).NotTo(HaveOccurred())

		runtime.LockOSThread()
		err = testNs.Set()
		Expect(err).NotTo(HaveOccurred())

		err = ipt.ClearChain(TABLE, tlChainName) // This will create the chain
		if err != nil {
			currNs.Set()
			Expect(err).NotTo(HaveOccurred())
		}

		cleanup = func() {
			if ipt == nil {
				return
			}
			ipt.ClearChain(TABLE, testChain.name)
			ipt.ClearChain(TABLE, tlChainName)
			ipt.DeleteChain(TABLE, testChain.name)
			ipt.DeleteChain(TABLE, tlChainName)
			currNs.Set()
		}

	})

	It("creates and destroys a chain", func() {
		defer cleanup()

		tlChainName := testChain.entryChains[0]

		// add an extra rule to the test chain to make sure it's not touched
		err := ipt.Append(TABLE, tlChainName, "-m", "comment", "--comment",
			"canary value", "-j", "ACCEPT")
		Expect(err).NotTo(HaveOccurred())

		// Create the chain
		chainRules := [][]string{
			{"-m", "comment", "--comment", "test 1", "-j", "RETURN"},
			{"-m", "comment", "--comment", "test 2", "-j", "RETURN"},
		}
		err = testChain.setup(ipt, chainRules)
		Expect(err).NotTo(HaveOccurred())

		// Verify the chain exists
		ok := false
		chains, err := ipt.ListChains(TABLE)
		Expect(err).NotTo(HaveOccurred())
		for _, chain := range chains {
			if chain == testChain.name {
				ok = true
				break
			}
		}
		if !ok {
			Fail("Could not find created chain")
		}

		// Check that the entry rule was created
		haveRules, err := ipt.List(TABLE, tlChainName)
		Expect(err).NotTo(HaveOccurred())
		Expect(haveRules).To(Equal([]string{
			"-N " + tlChainName,
			"-A " + tlChainName + " -d 203.0.113.1/32 -j " + testChain.name,
			"-A " + tlChainName + ` -m comment --comment "canary value" -j ACCEPT`,
		}))

		// Check that the chain and rule was created
		haveRules, err = ipt.List(TABLE, testChain.name)
		Expect(err).NotTo(HaveOccurred())
		Expect(haveRules).To(Equal([]string{
			"-N " + testChain.name,
			"-A " + testChain.name + ` -m comment --comment "test 1" -j RETURN`,
			"-A " + testChain.name + ` -m comment --comment "test 2" -j RETURN`,
		}))

		err = testChain.teardown(ipt)
		Expect(err).NotTo(HaveOccurred())

		tlRules, err := ipt.List(TABLE, tlChainName)
		Expect(err).NotTo(HaveOccurred())
		Expect(tlRules).To(Equal([]string{
			"-N " + tlChainName,
			"-A " + tlChainName + ` -m comment --comment "canary value" -j ACCEPT`,
		}))

		chains, err = ipt.ListChains(TABLE)
		Expect(err).NotTo(HaveOccurred())
		for _, chain := range chains {
			if chain == testChain.name {
				Fail("chain was not deleted")
			}
		}
	})

	It("creates chains idempotently", func() {
		defer cleanup()

		// Create the chain
		chainRules := [][]string{
			{"-m", "comment", "--comment", "test", "-j", "RETURN"},
		}
		err := testChain.setup(ipt, chainRules)
		Expect(err).NotTo(HaveOccurred())

		// Create it again!
		err = testChain.setup(ipt, chainRules)
		Expect(err).NotTo(HaveOccurred())

		// Make sure there are only two rules
		// (the first rule is an -N because go-iptables
		rules, err := ipt.List(TABLE, testChain.name)
		Expect(err).NotTo(HaveOccurred())

		Expect(len(rules)).To(Equal(2))

	})

	It("deletes chains idempotently", func() {
		defer cleanup()

		// Create the chain
		chainRules := [][]string{
			{"-m", "comment", "--comment", "test", "-j", "RETURN"},
		}
		err := testChain.setup(ipt, chainRules)
		Expect(err).NotTo(HaveOccurred())

		err = testChain.teardown(ipt)
		Expect(err).NotTo(HaveOccurred())

		chains, err := ipt.ListChains(TABLE)
		for _, chain := range chains {
			if chain == testChain.name {
				Fail("Chain was not deleted")
			}
		}

		err = testChain.teardown(ipt)
		Expect(err).NotTo(HaveOccurred())
		chains, err = ipt.ListChains(TABLE)
		for _, chain := range chains {
			if chain == testChain.name {
				Fail("Chain was not deleted")
			}
		}
	})
})


text:
package br.com.dlbca.hibernate.memcached.generator.exception;

/**
 * Exception for invalid machine time.
 *
 * @author bruno
 *
 */
@SuppressWarnings("serial")
public class MachineTimeException extends RuntimeException {

	public MachineTimeException(String message){
		super(message);
	}

}


text:
title: It's Been a While...
layout: article
image:
    teaser: beenawhile.jpeg
categories: [musings]
---

This will be a short one, just to try and get myself in the habit again...

So, I didn't do a great job of keeping up with this.  Like, at all.  I'm hoping to start it up again.  Mostly as a way to keep myself "honest" with my learning of Machine Learning, and devops on the server side.  I bought a neat .dev domain, and will be getting a DO droplet, and working through the configuration of all of that.

Oh, and on Machine Learning. I went to IO19, and it seems to be the hot thing.  I don't want to end up like the Dodo Bird, and so, I will be learning machine learning.....or trying to atleast.  It's a little daunting; but I mean, everything is when you first start it.


text:
//
//  GON_NSString+Base64.h
//
//  Created by Nicolas Goutaland on 04/04/15.
//  Copyright 2015 Nicolas Goutaland. All rights reserved.
//

@interface NSString(Base64)
/* Return data from string, assuming that's a base 64 encoded one */
- (NSData *)dataFromBase64String;
@end