text:
'use strict';

const globalVariables = require('../../lib/utils/global-variables.js');
const express = require('express');
const consts = require('../../lib/consts/consts.js');
const _ = require('lodash');
const config = require('config');
const validator = require('validator');
const async = require('async');
const util = require('util');
const router = express.Router();

// Get all action type
router.get('/action-type/:appid', validate, getConverter, function(req, res, next){
    let appid = req.params.appid;
    let collection = config.mongod.prefix + 'app' + appid;
    let fieldMapped = req.meotrics_converters._typeid;

    globalVariables
        .get('db')
        .collection(collection)
        .distinct(fieldMapped, (err, result) => {
            if(err) {
                return res.json({
                    ec: consts.CODE.ERROR,
                    error: util.inspect(err)
                });
            }

            res.json({
                ec: consts.CODE.SUCCESS,
                data: result
            });
        });
});

// Middleware for checking data
function validate(req, res, next) {
    return next();
}

function getConverter(req, res, next) {
    globalVariables.get('converter').toIDs(['_typeid'], ids => {
        req.meotrics_converters = ids;
        return next();
    });
}

module.exports = function (app) {
    app.use('/', router);
};

redpajama_set_name: RedPajamaGithub


text:
class AddCountryColumnToSubscriptionReportForProjectOwners < ActiveRecord::Migration
  def up
    execute <<-SQL
      CREATE OR REPLACE VIEW public.subscription_report_for_project_owners AS
      SELECT
        s.project_id,
        u.name,
        u.public_name,
        u.email,
        (((s.checkout_data ->> 'amount'::text))::numeric / (100)::numeric) AS amount,
        r.title,
        r.description,
        (sum(((p.data ->> 'amount'::text))::numeric) FILTER (WHERE (p.status = 'paid'::payment_service.payment_status)) / (100)::numeric) AS total_backed,
        s.status,
        (s.checkout_data ->> 'payment_method'::text) AS payment_method,
        to_char(last_paid_payment.created_at, 'DD/MM/YYYY'::text) AS last_paid_at,
        to_char(s.created_at, 'DD/MM/YYYY'::text) AS started_at,
        count(p.*) FILTER (WHERE (p.status = 'paid'::payment_service.payment_status)) AS payments_count,
        u.id AS user_id,
        CASE
          WHEN (((s.checkout_data ->> 'anonymous'::text))::boolean = true) THEN 'sim'::text
          ELSE 'não'::text
        END AS anonymous,
        user_address.street::text,
        user_address.complement::text,
        user_address.number::text,
        user_address.neighborhood::text,
        user_address.city::text,
        user_address.state::text,
        user_address.zipcode::text,
        u.cpf,
        user_address.country::text
      FROM
        common_schema.subscriptions s
      JOIN
        users u ON u.common_id = s.user_id
      LEFT JOIN
        common_schema.catalog_payments p ON p.subscription_id = s.id
      LEFT JOIN
        rewards r ON r.common_id = s.reward_id
      LEFT JOIN LATERAL (
        SELECT
          cp.id,
          cp.data,
          cp.created_at
        FROM
          common_schema.catalog_payments cp
        WHERE
          cp.subscription_id = s.id
          AND cp.status = 'paid'::payment_service.payment_status
        ORDER BY
          cp.created_at DESC
        LIMIT 1) last_paid_payment ON TRUE
      LEFT JOIN LATERAL (
        SELECT
          a.id,
          a.address_street AS street,
          a.address_complement AS complement,
          a.address_number AS number,
          a.address_neighbourhood AS neighborhood,
          a.address_city AS city,
          s.acronym AS state,
          a.address_zip_code AS zipcode,
          country."name" AS country
        FROM
          addresses AS a
        LEFT JOIN
          states AS s ON a.state_id = s.id
        LEFT JOIN
          countries AS country ON country.id = a.country_id
        WHERE
          u.address_id = a.id) user_address ON true
      WHERE
        s.status <> 'deleted'::payment_service.subscription_status
      GROUP BY
        user_address.street,
        user_address.complement,
        user_address.number,
        user_address.neighborhood,
        user_address.city,
        user_address.state,
        user_address.zipcode,
        user_address.country,
        s.project_id,
        u.name,
        u.public_name,
        u.email,
        s.checkout_data,
        r.title,
        r.description,
        s.status,
        last_paid_payment.created_at,
        s.created_at,
        u.id,
        last_paid_payment.data
    SQL
  end

  def down
    execute <<-SQL
      CREATE OR REPLACE VIEW public.subscription_report_for_project_owners AS
      SELECT s.project_id,
          u.name,
          u.public_name,
          u.email,
          (((s.checkout_data ->> 'amount'::text))::numeric / (100)::numeric) AS amount,
          r.title,
          r.description,
          (sum(((p.data ->> 'amount'::text))::numeric) FILTER (WHERE (p.status = 'paid'::payment_service.payment_status)) / (100)::numeric) AS total_backed,
          s.status,
          (s.checkout_data ->> 'payment_method'::text) AS payment_method,
          to_char(last_paid_payment.created_at, 'DD/MM/YYYY'::text) AS last_paid_at,
          to_char(s.created_at, 'DD/MM/YYYY'::text) AS started_at,
          count(p.*) FILTER (WHERE (p.status = 'paid'::payment_service.payment_status)) AS payments_count,
          u.id AS user_id,
              CASE
                  WHEN (((s.checkout_data ->> 'anonymous'::text))::boolean = true) THEN 'sim'::text
                  ELSE 'não'::text
              END AS anonymous,
          user_address.street,
          user_address.complement,
          user_address.number,
          user_address.neighborhood,
          user_address.city,
          (user_address.state)::text AS state,
          user_address.zipcode,
          u.cpf
        FROM (((((common_schema.subscriptions s
          JOIN public.users u ON ((u.common_id = s.user_id)))
          LEFT JOIN common_schema.catalog_payments p ON ((p.subscription_id = s.id)))
          LEFT JOIN public.rewards r ON ((r.common_id = s.reward_id)))
          LEFT JOIN LATERAL ( SELECT cp.id,
                  cp.data,
                  cp.created_at
                FROM common_schema.catalog_payments cp
                WHERE ((cp.subscription_id = s.id) AND (cp.status = 'paid'::payment_service.payment_status))
                ORDER BY cp.created_at DESC
              LIMIT 1) last_paid_payment ON (true))
          LEFT JOIN LATERAL ( SELECT a.id,
                  a.address_street AS street,
                  a.address_complement AS complement,
                  a.address_number AS number,
                  a.address_neighbourhood AS neighborhood,
                  a.address_city AS city,
                  s_1.acronym AS state,
                  a.address_zip_code AS zipcode
                FROM (public.addresses a
                  LEFT JOIN public.states s_1 ON ((a.state_id = s_1.id)))
                WHERE (u.address_id = a.id)) user_address ON (true))
        WHERE (s.status <> 'deleted'::payment_service.subscription_status)
        GROUP BY user_address.street, user_address.complement, user_address.number, user_address.neighborhood, user_address.city, user_address.state, user_address.zipcode, s.project_id, u.name, u.public_name, u.email, s.checkout_data, r.title, r.description, s.status, last_paid_payment.created_at, s.created_at, u.id, last_paid_payment.data;

    SQL
  end
end


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Rectangle Overlay</title>

Drag the markers to move the rectangle.


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=struct.ObjectMetadata.html">

Redirecting to struct.ObjectMetadata.html...


text:
#include <pdal/pdal_test_main.hpp>

#include <pdal/PipelineManager.hpp>

#include "Support.hpp"

TEST(MergeTest, test1)
{
    using namespace pdal;

    PipelineManager mgr;
    mgr.readPipeline(Support::configuredpath("filters/merge.xml"));
    mgr.execute();

    PointViewSet viewSet = mgr.views();

    EXPECT_EQ(1u, viewSet.size());
    PointViewPtr view = *viewSet.begin();
    EXPECT_EQ(2130u, view->size());
}

TEST(MergeTest, test2)
{
    using namespace pdal;

    PipelineManager mgr;
    mgr.readPipeline(Support::configuredpath("filters/merge2.xml"));
    mgr.execute();

    PointViewSet viewSet = mgr.views();

    EXPECT_EQ(1u, viewSet.size());
    PointViewPtr view = *viewSet.begin();
    EXPECT_EQ(2130u, view->size());
}

TEST(MergeTest, test3)
{
    using namespace pdal;

    PipelineManager mgr;
    mgr.readPipeline(Support::configuredpath("filters/merge3.xml"));

    std::ostringstream oss;
    std::ostream& o = std::clog;
    auto ctx = Utils::redirect(o, oss);

    mgr.execute();
    std::string s = oss.str();
    EXPECT_TRUE(s.find("inconsistent spatial references") != s.npos);
    Utils::restore(o, ctx);

    PointViewSet viewSet = mgr.views();

    EXPECT_EQ(1u, viewSet.size());
    PointViewPtr view = *viewSet.begin();
    EXPECT_EQ(2130u, view->size());
}

TEST(MergeTest, test4)
{
    using namespace pdal;

    PipelineManager mgr;
    mgr.readPipeline(Support::configuredpath("filters/merge.json"));
    mgr.execute();

    PointViewSet viewSet = mgr.views();

    EXPECT_EQ(1u, viewSet.size());
    PointViewPtr view = *viewSet.begin();
    EXPECT_EQ(2130u, view->size());
}

TEST(MergeTest, test5)
{
    using namespace pdal;

    PipelineManager mgr;
    mgr.readPipeline(Support::configuredpath("filters/merge2.json"));
    mgr.execute();

    PointViewSet viewSet = mgr.views();

    EXPECT_EQ(1u, viewSet.size());
    PointViewPtr view = *viewSet.begin();
    EXPECT_EQ(2130u, view->size());
}

TEST(MergeTest, test6)
{
    using namespace pdal;

    PipelineManager mgr;
    mgr.readPipeline(Support::configuredpath("filters/merge3.json"));

    std::ostringstream oss;
    std::ostream& o = std::clog;
    auto ctx = Utils::redirect(o, oss);

    mgr.execute();
    std::string s = oss.str();
    EXPECT_TRUE(s.find("inconsistent spatial references") != s.npos);
    Utils::restore(o, ctx);

    PointViewSet viewSet = mgr.views();

    EXPECT_EQ(1u, viewSet.size());
    PointViewPtr view = *viewSet.begin();
    EXPECT_EQ(2130u, view->size());
}


text:
package io.quarkus.devtools.project.compress;

import static io.quarkus.devtools.project.compress.QuarkusProjectCompress.DIR_UNIX_MODE;
import static io.quarkus.devtools.project.compress.QuarkusProjectCompress.zip;
import static org.apache.commons.io.FileUtils.contentEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.junit.jupiter.api.Test;

import io.quarkus.devtools.commands.CreateProject;
import io.quarkus.devtools.commands.data.QuarkusCommandException;
import io.quarkus.devtools.commands.data.QuarkusCommandOutcome;
import io.quarkus.devtools.project.BuildTool;
import io.quarkus.devtools.project.QuarkusProject;
import io.quarkus.devtools.project.QuarkusProjectHelper;
import io.quarkus.devtools.testing.PlatformAwareTestBase;
import io.quarkus.devtools.testing.SnapshotTesting;

class QuarkusProjectCompressTest extends PlatformAwareTestBase {

    @Test
    public void createZip() throws Exception {
        // Given a Quarkus project
        final Path testDir = Paths.get("target/zip");
        SnapshotTesting.deleteTestDirectory(testDir.toFile());
        testDir.toFile().mkdirs();
        Path zip = testDir.resolve("project.zip");

        final Path projectPath = createProject(testDir);

        // When zipping without including the project directory
        zip(projectPath, zip, false);
        assertTrue(zip.toFile().exists());

        // Then the zip content is valid
        final Path unzipProject = testDir.resolve("unzipProject");
        unzip(zip, unzipProject);

        checkUnzipped(projectPath, unzipProject);
    }

    @Test
    public void createZipWithParentFolder() throws Exception {
        // Given a Quarkus project
        final Path testDir = Paths.get("target/zip");
        SnapshotTesting.deleteTestDirectory(testDir.toFile());
        testDir.toFile().mkdirs();
        Path zip = testDir.resolve("project.zip");

        final Path projectPath = createProject(testDir);

        // When zipping without including the project directory
        zip(projectPath, zip, true);
        assertTrue(zip.toFile().exists());

        // Then the zip content is valid and included in a parent directory
        final Path unzipProject = testDir.resolve("unzipProject");
        unzip(zip, unzipProject);

        checkUnzipped(projectPath, unzipProject.resolve(projectPath.getFileName()));
    }

    @Test
    void checkUnixMode() {
        assertEquals(DIR_UNIX_MODE, 040755);
        assertEquals(QuarkusProjectCompress.getFileUnixMode(true), 0100755);
        assertEquals(QuarkusProjectCompress.getFileUnixMode(false), 0100644);
    }

    private void checkUnzipped(Path projectPath, Path unzipProject) throws IOException {
        assertTrue(contentEquals(unzipProject.resolve(".gitignore").toFile(), projectPath.resolve(".gitignore").toFile()));
        assertTrue(contentEquals(unzipProject.resolve("pom.xml").toFile(), projectPath.resolve("pom.xml").toFile()));
    }

    private Path createProject(Path testDir) throws QuarkusCommandException, IOException {
        final Path projectPath = testDir.resolve("project");
        final QuarkusProject project = QuarkusProjectHelper.getProject(projectPath, BuildTool.MAVEN);
        final QuarkusCommandOutcome result = new CreateProject(project)
                .groupId("org.acme")
                .artifactId("basic-rest")
                .version("1.0.0-SNAPSHOT")
                .execute();
        // Create a fake wrapper
        Files.write(projectPath.resolve("mvnw"), "testmvnw".getBytes());
        projectPath.resolve("mvnw").toFile().setExecutable(true);
        Files.write(projectPath.resolve("mvnw.bat"), "testmvnw".getBytes());
        projectPath.resolve("mvnw.bat").toFile().setExecutable(true);
        assertTrue(result.isSuccess());

        return projectPath;
    }

    private static void unzip(final Path zipPath, final Path outputDir) throws IOException {
        try (FileInputStream fis = new FileInputStream(zipPath.toFile()); ZipInputStream zis = new ZipInputStream(fis)) {
            ZipEntry zipEntry = zis.getNextEntry();
            byte[] buffer = new byte[1024];
            while (zipEntry != null) {
                File newFile = createEntryFile(outputDir.toFile(), zipEntry);
                if (zipEntry.isDirectory()) {
                    newFile.mkdirs();
                } else {
                    new File(newFile.getParent()).mkdirs();
                    FileOutputStream fos = new FileOutputStream(newFile);
                    int len;
                    while ((len = zis.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                }
                zipEntry = zis.getNextEntry();
            }
            zis.closeEntry();
        }
    }

    private static File createEntryFile(File destinationDir, ZipEntry zipEntry) throws IOException {
        File destFile = new File(destinationDir, zipEntry.getName());

        String destDirPath = destinationDir.getCanonicalPath();
        String destFilePath = destFile.getCanonicalPath();

        if (!destFilePath.startsWith(destDirPath + File.separator)) {
            throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
        }

        return destFile;
    }

}


text:
layout: post
title: Why Not Callbacks
tags: ruby rails
---

## The Problem

You often want something to happen at a stage in an ActiveRecord object's
standard workflow - most often this is "After I save I want to do X."

For Example:

```ruby
class File < ActiveRecord::Base
  validates :file_path, :presence => true
end

File.save # => Persist, if successful,
# create a thumbnail version for the web.
```

## Why Callbacks

An often recommended way to deal with this is as an after_save callback.

```ruby
class File < ActiveRecord::Base
  validates :file_path, :presence => true
  after_save :create_thumbnail

  private

  def create_thumbnail
    ThumbnailCreator.call(file_path)
  end
end
```

**PROs**:
- Simple, concise, all the logic is in one place you can look at.
- You can never accidentally save a file without it creating a thumbnail.

Before I get to the CONs, let's look at some assumptions made:

**Assumptions**:
- We're okay opening up the file class whenever we want to change when and how
  we create a thumbnail.
- We ALWAYS want to create a thumbnail.
- If we save a file, we're okay with whatever overhead exists to create that
  thumbnail.
- We're okay with not injecting dependencies (ThumbnailCreator), and thus when
  that changes we're happy to change it in File.

**CONs**:
- State is mixed up with business logic. Suddenly my "File" is not just
  "attributes with persistence", and is now "attributes with persistence
  and side effects too"
- NOT creating a thumbnail is hard. How do I avoid callbacks? Only this SPECIFIC
  callback?
- Doing something like pushing that thumbnail creation to the background is
  complicated logic that will sit in the model.
- ThumbnailCreator is hard-wired, its responsibility is inflexible.

## Why Not Callbacks

It turns out the assumption that `we ALWAYS want to create a thumbnail` is a big
one. It's rare that you ALWAYS want something to happen, and building in that
assumption is the beginning to expensive backtracking or hacks later.

The big point is this: `business logic changes at a different rate than object
representation`. Tying the logic of when and how to create a thumbnail to the
representation of how a File is stored means coupling changes in the File to
changes in how a thumbnail is created, unnecessarily.

## Alternatives

### Service Objects

We can encapsulate what to do when an object is saved by putting all of it in
one object.

```ruby
class FileSaver
  attr_reader :file, :thumbnail_creator
  def initialize(file, thumbnail_creator)
    @file = file
    @thumbnail_creator = thumbnail_creator
  end

  def run
    if file.save
      thumbnail_creator.call(file.file_path)
    end
  end
end
```

This works - you can inject ThumbnailCreator, you only use the FileSaver when
you want, and you will never accidentally create a thumbnail.

However, what tends to happen is that ALL behavior gets stored here and the
problem of "how do I ignore just ONE callback action" remains.

### Decoration of Functionality

We can decorate JUST this functionality onto the object.

```ruby
class CreatesThumbnails < SimpleDelegator
  attr_reader :thumbnail_creator

  def initialize(file, thumbnail_creator)
    @thumbnail_creator = thumbnail_creator
    super(file)
  end

  def save
    if __getobj__.save
      thumbnail_creator.call(file_path)
    end
  end
end

CreatesThumbnails.new(File.new(:file_path => "/file"), ThumbnailCreator).save
```

Now when you want to create a thumbnail on save you can decorate the object with
this, call save, and you're good. If when or how to run the thumbnail creator
changes, you can inject a new thumbnail creator or change just the
CreatesThumbnails object. Business logic is now separated from state.

Decorating all the necessary actions and dependencies for a transaction can get
complicated, at which point the Factory Pattern can help. I may do a post on
this at a later date.


text:
package org.apache.clerezza.utils;

import org.apache.clerezza.Graph;
import org.apache.clerezza.IRI;
import org.apache.clerezza.Literal;
import org.apache.clerezza.Triple;
import org.apache.clerezza.implementation.TripleImpl;
import org.apache.clerezza.implementation.in_memory.SimpleGraph;
import org.apache.clerezza.implementation.literal.PlainLiteralImpl;
import org.apache.clerezza.ontologies.FOAF;
import org.apache.clerezza.ontologies.OWL;
import org.apache.clerezza.ontologies.RDFS;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

import java.util.Iterator;

/**
 * @author reto
 */
@RunWith(JUnitPlatform.class)
public class SameAsSmushTest {

    private final IRI uriA = new IRI("http://example.org/A");
    private final IRI uriB = new IRI("http://example.org/B");
    private final Literal lit = new PlainLiteralImpl("That's me (and you)");

    private Graph sameAsStatements = new SimpleGraph();

    {
        sameAsStatements.add(new TripleImpl(uriA, OWL.sameAs, uriB));
    }

    private Graph dataGraph = new SimpleGraph();

    {
        dataGraph.add(new TripleImpl(uriA, FOAF.knows, uriB));
        dataGraph.add(new TripleImpl(uriB, RDFS.label, lit));
        dataGraph.add(new TripleImpl(uriA, RDFS.label, lit));
    }

    @Test
    public void simple() {
        Assertions.assertEquals(3, dataGraph.size());
        Smusher.sameAsSmush(dataGraph, sameAsStatements);
        Assertions.assertEquals(3, dataGraph.size());
        Assertions.assertTrue(dataGraph.filter(null, OWL.sameAs, null).hasNext());
        //exactly one statement with literal
        Iterator<Triple> litStmts = dataGraph.filter(null, null, lit);
        Assertions.assertTrue(litStmts.hasNext());
        Triple litStmt = litStmts.next();
        Assertions.assertFalse(litStmts.hasNext());
        Iterator<Triple> knowsStmts = dataGraph.filter(null, FOAF.knows, null);
        Assertions.assertTrue(knowsStmts.hasNext());
        Triple knowStmt = knowsStmts.next();
        Assertions.assertEquals(knowStmt.getSubject(), knowStmt.getObject());
        Assertions.assertEquals(litStmt.getSubject(), knowStmt.getObject());
        Assertions.assertEquals(litStmt.getSubject(), dataGraph.filter(null, OWL.sameAs, null).next().getObject());
    }
}


text:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
import datetime
from django.utils.encoding import python_2_unicode_compatible
import uuid
from django.db import models
from django.conf import settings

def chop_microseconds(delta):
    return delta - datetime.timedelta(microseconds=delta.microseconds)
# Create your models here.
class Project(models.Model):
    title = models.CharField(max_length = 200)

    def __unicode__(self):
        return self.title

class Punch(models.Model):
    user     = models.ForeignKey(settings.AUTH_USER_MODEL)
    project  = models.ForeignKey(Project)
    time_in  = models.DateTimeField(auto_now_add = True)
    time_out = models.DateTimeField(blank=True, null=True)
    note     = models.CharField(max_length = 200, blank=True, null=True)

    def is_clocked_in(self):
        if self.time_out == None:
            return True
        return False

    def duration(self):
        if self.time_out and self.time_in:
            return chop_microseconds(self.time_out - self.time_in)
        else:
            return chop_microseconds(datetime.timedelta())

    def __unicode__(self):
        return "%s (in: %s, out: %s, dur: %s)" % (self.user, str(self.time_in), str(self.time_out), str(self.duration()))
        return "%s (%s)" % (self.user, str(self.duration()))

    class Meta:
        verbose_name_plural = "punches"


text:
exports.config = {
  // See http://brunch.io/#documentation for docs.
  files: {
    javascripts: {
      joinTo: "js/app.js"

      // To use a separate vendor.js bundle, specify two files path
      // http://brunch.io/docs/config#-files-
      // joinTo: {
      //   "js/app.js": /^js/,
      //   "js/vendor.js": /^(?!js)/
      // }
      //
      // To change the order of concatenation of files, explicitly mention here
      // order: {
      //   before: [
      //     "vendor/js/jquery-2.1.1.js",
      //     "vendor/js/bootstrap.min.js"
      //   ]
      // }
    },
    stylesheets: {
      joinTo: "css/app.css"
    },
    templates: {
      joinTo: "js/app.js"
    }
  },

  conventions: {
    // This option sets where we should place non-css and non-js assets in.
    // By default, we set this to "/assets/static". Files in this directory
    // will be copied to `paths.public`, which is "priv/static" by default.
    assets: /^(static)/
  },

  // Phoenix paths configuration
  paths: {
    // Dependencies and current project directories to watch
    watched: ["static", "css", "js", "vendor"],
    // Where to compile files to
    public: "../priv/static"
  },

  // Configure your plugins
  plugins: {
    babel: {
      // Do not use ES6 compiler in vendor code
      ignore: [/vendor/]
    },
    sass: {
      mode: "native"
    }
  },

  modules: {
    autoRequire: {
      "js/app.js": ["js/app"]
    }
  },

  npm: {
    enabled: true
  }
};


text:
require 'rails_helper'

describe 'Sessions API', type: :request do
  describe 'POST /api/schedules/:schedule_id/sessions' do
    context 'response for valid session' do
      before :each do
        schedule = FactoryGirl.create :schedule
        session_attributes = FactoryGirl.attributes_for :session
        post "/api/schedules/#{schedule.id}/sessions", session_attributes
      end

      it 'has 200 status code' do
        expect(response).to be_success
      end

      it 'contains the session id' do
        expect(response_json['id']).to_not be_nil
      end
    end
  end
end


text:
package com.sola.v2ex_android.ui.base.application;

import android.app.Application;
import android.content.Context;

import com.sola.v2ex_android.model.V2exUser;
import com.sola.v2ex_android.util.SharedPreferencesUtils;
import com.sola.v2ex_android.util.ToastUtil;

public class MyApplication extends Application {

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        //获取Context
        context = getApplicationContext();
        ToastUtil.init(this);
        SharedPreferencesUtils.init(this);
        V2exUser.init();
    }

    //返回
    public static Context getContextObject() {
        return context;
    }

}


text:
<?php
/**
 * CodeByJoe Ltd :: http://www.codebyjoe.com
 *
 * @category CodeByJoe
 * @package CodeByJoe_Toolbox
 * @author Joseph McDermott <code@josephmcdermott.co.uk>
 * @license http://choosealicense.com/licenses/mit/ MIT License
 */
class CodeByJoe_Toolbox_Helper_Config extends Mage_Core_Helper_Abstract
{
    const SCOPE_DEFAULT = 'default';
    const SCOPE_WEBSITE = 'websites';
    const SCOPE_STORE   = 'stores';

    const DEFAULT_SCOPE_ID = 0;

    /**
     * @param string $path
     * @param string $value
     * @param string $scope
     * @param int $scopeId
     * @return $this
     * @author Joseph McDermott <code@josephmcdermott.co.uk>
     */
    public function save($path, $value, $scope = self::SCOPE_DEFAULT, $scopeId = self::DEFAULT_SCOPE_ID)
    {
        $config = $this->_getCoreConfig();
        $config->saveConfig($path, $value, $scope, $scopeId);

        return $this;
    }

    /**
     * @param string $path
     * @param string $scope
     * @param int $scopeId
     * @return $this
     * @author Joseph McDermott <code@josephmcdermott.co.uk>
     */
    public function delete($path, $scope = self::SCOPE_DEFAULT, $scopeId = self::DEFAULT_SCOPE_ID)
    {
        $config = $this->_getCoreConfig();
        $config->deleteConfig($path, $scope, $scopeId);

        return $this;
    }

    /**
     * @return Mage_Core_Model_Config
     * @author Joseph McDermott <code@josephmcdermott.co.uk>
     */
    protected function _getCoreConfig()
    {
        $config = Mage::getModel('core/config');

        return $config;
    }
}


text:
package libvirt

/*
#cgo LDFLAGS: -lvirt -ldl
#include <libvirt/libvirt.h>
#include <libvirt/virterror.h>
#include <stdlib.h>
*/
import "C"

import (
	"unsafe"
)

type VirNWFilter struct {
	ptr C.virNWFilterPtr
}

func (f *VirNWFilter) Free() error {
	if result := C.virNWFilterFree(f.ptr); result != 0 {
		return GetLastError()
	}
	return nil
}

func (f *VirNWFilter) GetName() (string, error) {
	name := C.virNWFilterGetName(f.ptr)
	if name == nil {
		return "", GetLastError()
	}
	return C.GoString(name), nil
}

func (f *VirNWFilter) Undefine() error {
	result := C.virNWFilterUndefine(f.ptr)
	if result == -1 {
		return GetLastError()
	}
	return nil
}

func (f *VirNWFilter) GetUUID() ([]byte, error) {
	var cUuid [C.VIR_UUID_BUFLEN](byte)
	cuidPtr := unsafe.Pointer(&cUuid)
	result := C.virNWFilterGetUUID(f.ptr, (*C.uchar)(cuidPtr))
	if result != 0 {
		return []byte{}, GetLastError()
	}
	return C.GoBytes(cuidPtr, C.VIR_UUID_BUFLEN), nil
}

func (f *VirNWFilter) GetUUIDString() (string, error) {
	var cUuid [C.VIR_UUID_STRING_BUFLEN](C.char)
	cuidPtr := unsafe.Pointer(&cUuid)
	result := C.virNWFilterGetUUIDString(f.ptr, (*C.char)(cuidPtr))
	if result != 0 {
		return "", GetLastError()
	}
	return C.GoString((*C.char)(cuidPtr)), nil
}

func (f *VirNWFilter) GetXMLDesc(flags uint32) (string, error) {
	result := C.virNWFilterGetXMLDesc(f.ptr, C.uint(flags))
	if result == nil {
		return "", GetLastError()
	}
	xml := C.GoString(result)
	C.free(unsafe.Pointer(result))
	return xml, nil
}


text:
import { VFC } from 'react';
import { useLocationSettings } from 'hooks/useLocationSettings';
import { formatDateYMD } from 'utils/formatDate';
import { parseISO } from 'date-fns';
import { TextCell } from 'component/common/Table/cells/TextCell/TextCell';

interface IDateCellProps {
    value?: Date | string | null;
}

export const DateCell: VFC<IDateCellProps> = ({ value }) => {
    const { locationSettings } = useLocationSettings();

    const date = value
        ? value instanceof Date
            ? formatDateYMD(value, locationSettings.locale)
            : formatDateYMD(parseISO(value), locationSettings.locale)
        : undefined;

    return <TextCell lineClamp={1}>{date}</TextCell>;
};


text:
package serial

import (
	"errors"
	"reflect"

	"github.com/golang/protobuf/proto"
)

// ToTypedMessage converts a proto Message into TypedMessage.
func ToTypedMessage(message proto.Message) *TypedMessage {
	if message == nil {
		return nil
	}
	settings, _ := proto.Marshal(message)
	return &TypedMessage{
		Type:  GetMessageType(message),
		Value: settings,
	}
}

// GetMessageType returns the name of this proto Message.
func GetMessageType(message proto.Message) string {
	return proto.MessageName(message)
}

// GetInstance creates a new instance of the message with messageType.
func GetInstance(messageType string) (interface{}, error) {
	mType := proto.MessageType(messageType)
	if mType == nil || mType.Elem() == nil {
		return nil, errors.New("Serial: Unknown type: " + messageType)
	}
	return reflect.New(mType.Elem()).Interface(), nil
}

// GetInstance converts current TypedMessage into a proto Message.
func (v *TypedMessage) GetInstance() (proto.Message, error) {
	instance, err := GetInstance(v.Type)
	if err != nil {
		return nil, err
	}
	protoMessage := instance.(proto.Message)
	if err := proto.Unmarshal(v.Value, protoMessage); err != nil {
		return nil, err
	}
	return protoMessage, nil
}