text:
using Dangl.WebDocumentation.Dtos;
using Dangl.WebDocumentation.Models;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;

namespace Dangl.WebDocumentation.Services
{
    public class ProjectFilesService : IProjectFilesService
    {
        private readonly ApplicationDbContext _context;
        private readonly AspNetCore.FileHandling.IFileManager _fileManager;
        private static readonly FileExtensionContentTypeProvider _fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider();
        private readonly IProjectUploadNotificationsService _projectUploadNotificationsService;
        private readonly IProjectVersionAssetFilesService _projectVersionAssetFilesService;

        public ProjectFilesService(ApplicationDbContext context,
            Dangl.AspNetCore.FileHandling.IFileManager fileManager,
            IProjectVersionAssetFilesService projectVersionAssetFilesService,
            IProjectUploadNotificationsService projectUploadNotificationsService)
        {
            _context = context;
            _fileManager = fileManager;
            _projectUploadNotificationsService = projectUploadNotificationsService;
            _projectVersionAssetFilesService = projectVersionAssetFilesService;
        }

        public Task<string> GetEntryFilePathForProject(string projectName)
        {
            var entryPath = _context.DocumentationProjects
                .Where(p => p.Name == projectName)
                .Select(p => p.PathToIndex)
                .FirstAsync();
            return entryPath;
        }

        public async Task<ProjectFileDto> GetFileForProject(string projectName, string version, string filePath)
        {
            var projectId = await _context.DocumentationProjects
                .Where(p => p.Name == projectName)
                .Select(p => new { p.Id })
                .FirstOrDefaultAsync();
            if (projectId == null)
            {
                return null;
            }
            var versionPackageId = await _context.DocumentationProjectVersions
                .Where(v => v.ProjectName == projectName && v.Version == version)
                .Select(v => new { v.FileId })
                .FirstOrDefaultAsync();
            if (versionPackageId == null)
            {
                return null;
            }
            var archivePath = GetPackagePath(projectId.Id, versionPackageId.FileId);
            var fileResult = await GetFileFromZipArchive(archivePath, filePath);
            return fileResult;
        }

        private async Task<ProjectFileDto> GetFileFromZipArchive(string archivePath, string filePath)
        {
            var mimeType = GetMimeTypeForFilePath(filePath);
            var memoryStream = new MemoryStream();
            var repoResult = await _fileManager.GetFileAsync(AppConstants.PROJECTS_CONTAINER, archivePath);
            if (!repoResult.IsSuccess)
            {
                return null;
            }
            using (var fileStream = repoResult.Value)
            {
                using (var zipArchive = new ZipArchive(fileStream))
                {
                    var fileEntry = zipArchive.Entries.FirstOrDefault(e => e.FullName.Replace('/', '\\') == filePath.Replace('/', '\\'));
                    if (fileEntry == null)
                    {
                        return null;
                    }
                    var zipEntryStream = fileEntry.Open();
                    await zipEntryStream.CopyToAsync(memoryStream);
                }
            }
            memoryStream.Position = 0;
            return new ProjectFileDto
            {
                MimeType = mimeType,
                FileStream = memoryStream
            };
        }

        private string GetMimeTypeForFilePath(string filePath)
        {
            var extension = Path.GetExtension(filePath);
            if (_fileExtensionContentTypeProvider.Mappings.ContainsKey(extension))
            {
                return _fileExtensionContentTypeProvider.Mappings[extension];
            }
            return "application/octet-stream";
        }

        public Task<bool> PackageAlreadyExistsAsync(string projectName, string version)
        {
            return _context.DocumentationProjectVersions.AnyAsync(p => p.ProjectName == projectName && p.Version == version);
        }

        public async Task<bool> UploadProjectPackageAsync(string projectName, string version, string markdownChangelog, Stream zipArchiveStream)
        {
            var projectId = await _context.DocumentationProjects
                .Where(p => p.Name == projectName)
                .Select(p => p.Id)
                .FirstAsync();
            // Try to read as zip file
            try
            {
                var transactionResult = false;
                var executionStrategy = _context.Database.CreateExecutionStrategy();
                await executionStrategy.ExecuteAsync(async () =>
                {
                    using (var transaction = await _context.Database.BeginTransactionAsync())
                    {
                        var newVersion = new DocumentationProjectVersion
                        {
                            ProjectName = projectName,
                            Version = version,
                            MarkdownChangelog = markdownChangelog
                        };
                        _context.DocumentationProjectVersions.Add(newVersion);
                        await _context.SaveChangesAsync();
                        var packagePath = GetPackagePath(projectId, newVersion.FileId);

                        var repoResult = await _fileManager.SaveFileAsync(AppConstants.PROJECTS_CONTAINER, packagePath, zipArchiveStream);
                        if (repoResult.IsSuccess)
                        {
                            transaction.Commit();
                            await _projectUploadNotificationsService.ScheduleProjectUploadNotifications(projectName, version);
                            transactionResult = true;
                        }
                    }
                });

                return transactionResult;
            }
            catch (InvalidDataException)
            {
                // Could not read the file as zip
                return false;
            }
            catch
            {
                return false;
            }
        }

        public async Task<bool> DeleteProjectVersionPackageAsync(Guid projectId, string version)
        {
            var projectVersion = await _context.DocumentationProjectVersions
                .FirstOrDefaultAsync(v => v.Version == version && v.Project.Id == projectId);
            if (projectVersion == null)
            {
                return false;
            }
            var packagePath = GetPackagePath(projectId, projectVersion.FileId);
            try
            {
                await _fileManager.DeleteFileAsync(AppConstants.PROJECTS_CONTAINER, packagePath);
            }
            catch
            {
                return false;
            }

            var assetFiles = await _context.ProjectVersionAssetFiles
                .Where(a => a.ProjectVersion.Version == projectVersion.Version
                        && a.ProjectVersion.Project.Id == projectId)
                .ToListAsync();

            foreach (var assetFile in assetFiles)
            {
                await _fileManager.DeleteFileAsync(assetFile.FileId, AppConstants.PROJECT_ASSETS_CONTAINER, assetFile.FileName);
                _context.ProjectVersionAssetFiles.Remove(assetFile);
            }

            _context.DocumentationProjectVersions.Remove(projectVersion);
            await _context.SaveChangesAsync();
            return true;
        }

        private string GetPackagePath(Guid projectId, Guid versionFileId)
        {
            var packagePath = Path.Combine(projectId.ToString(), versionFileId + ".zip");
            return packagePath;
        }
    }
}


text:
from __future__ import absolute_import
from webassets.filter import Filter

__all__ = ('Jinja2',)

class Jinja2(Filter):
    """Process a file through the Jinja2 templating engine.

    Requires the ``jinja2`` package (https://github.com/mitsuhiko/jinja2).
    """

    name = 'jinja2'
    options = {
        'context': 'JINJA2_CONTEXT',
    }

    def setup(self):
        try:
            import jinja2
        except ImportError:
            raise EnvironmentError('The "jinja2" package is not installed.')
        else:
            self.jinja2 = jinja2
        super(Jinja2, self).setup()

    def output(self, _in, out, **kw):
        out.write(self.jinja2.Template(_in.read()).render(self.context or {}))

redpajama_set_name: RedPajamaGithub


text:
Personal Blog for David Gilhooley
==========

This blog's theme is from Travelogue.
Travelogue is a minimal, single-column [Jekyll](http://jekyllrb.com/) theme that provides an immersive read experience for your readers.


text:
require "spec_helper"

app_require "commands/stories/mark_feed_as_read"

describe MarkFeedAsRead do
  describe "#mark_feed_as_read" do
    let(:stories) { double }
    let(:repo) { double(fetch_unread_for_feed_by_timestamp: stories) }

    it "marks feed 1 as read" do
      command = MarkFeedAsRead.new(1, Time.now.to_i, repo)
      stories.should_receive(:update_all).with(is_read: true)
      command.mark_feed_as_read
    end
  end
end


text:
package org.antlr.intellij.plugin.preview;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileChooser.FileChooserFactory;
import com.intellij.openapi.fileChooser.FileSaverDescriptor;
import com.intellij.openapi.fileChooser.FileSaverDialog;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFileWrapper;
import com.intellij.ui.JBColor;
import com.intellij.util.ui.UIUtil;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.apache.commons.lang.StringUtils;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Shows a contextual menu when the user right-clicks on the parse tree preview. The menu contains options
 * to export the parse tree to several image formats.
 */
class ParseTreeContextualMenu {

    static void showPopupMenu(UberTreeViewer parseTreeViewer, MouseEvent event) {
        JPopupMenu menu = new JPopupMenu();

        menu.add(createExportMenuItem(parseTreeViewer, "Export to image (white background)", false));
        menu.add(createExportMenuItem(parseTreeViewer, "Export to image (transparent background)", true));

        menu.show(parseTreeViewer, event.getX(), event.getY());
    }

    private static JMenuItem createExportMenuItem(UberTreeViewer parseTreeViewer, String label, boolean useTransparentBackground) {
        JMenuItem item = new JMenuItem(label);
        boolean isMacNativSaveDialog = SystemInfo.isMac && Registry.is("ide.mac.native.save.dialog");

        item.addActionListener(event -> {
            String[] extensions = useTransparentBackground ? new String[]{"png", "svg"} : new String[]{"png", "jpg", "svg"};
            FileSaverDescriptor descriptor = new FileSaverDescriptor("Export Image to", "Choose the destination file", extensions);
            FileSaverDialog dialog = FileChooserFactory.getInstance().createSaveFileDialog(descriptor, (Project) null);

            String fileName = "parseTree" + (isMacNativSaveDialog ? ".png" : "");
            VirtualFileWrapper vf = dialog.save(null, fileName);

            if (vf == null) {
                return;
            }

            File file = vf.getFile();
            String imageFormat = FileUtilRt.getExtension(file.getName());
            if (StringUtils.isBlank(imageFormat)) {
                imageFormat = "png";
            }

            if ("svg".equals(imageFormat)) {
                exportToSvg(parseTreeViewer, file, useTransparentBackground);
            } else {
                exportToImage(parseTreeViewer, file, useTransparentBackground, imageFormat);
            }
        });

        return item;
    }

    private static void exportToImage(UberTreeViewer parseTreeViewer, File file, boolean useTransparentBackground, String imageFormat) {
        int imageType = useTransparentBackground ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
        BufferedImage bi = UIUtil.createImage(parseTreeViewer.getWidth(), parseTreeViewer.getHeight(), imageType);
        Graphics graphics = bi.getGraphics();

        if (!useTransparentBackground) {
            graphics.setColor(JBColor.WHITE);
            graphics.fillRect(0, 0, parseTreeViewer.getWidth(), parseTreeViewer.getHeight());
        }

        parseTreeViewer.paint(graphics);

        try {
            if (!ImageIO.write(bi, imageFormat, file)) {
                Notification notification = new Notification(
                        "ANTLR 4 export",
                        "Error while exporting parse tree to file " + file.getAbsolutePath(),
                        "unknown format '" + imageFormat + "'?",
                        NotificationType.WARNING
                );
                Notifications.Bus.notify(notification);
            }
        } catch (IOException e) {
            Logger.getInstance(ParseTreeContextualMenu.class)
                    .error("Error while exporting parse tree to file " + file.getAbsolutePath(), e);
        }
    }

    private static void exportToSvg(UberTreeViewer parseTreeViewer, File file, boolean useTransparentBackground) {
        DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
        Document document = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

        if (!useTransparentBackground) {
            svgGenerator.setColor(JBColor.WHITE);
            svgGenerator.fillRect(0, 0, parseTreeViewer.getWidth(), parseTreeViewer.getHeight());
        }
        parseTreeViewer.paint(svgGenerator);

        try {
            svgGenerator.stream(file.getAbsolutePath(), true);
        } catch (SVGGraphics2DIOException e) {
            Logger.getInstance(ParseTreeContextualMenu.class)
                    .error("Error while exporting parse tree to SVG file " + file.getAbsolutePath(), e);
        }
    }
}


text:
package files

import (
	"archive/zip"
	"compress/gzip"
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

// check if error, then stop
func checkError(err error) {
	if err != nil {
		panic(err)
	}
}

// Just create an empty file
func CreateEmptly(fileName string) {

	newFile, err := os.Create(fileName)
	checkError(err)
	defer newFile.Close()

	log.Println(newFile)
}

// Truncate a file by given size
func Truncate(fileName string, size int64) {

	err := os.Truncate(fileName, size)
	checkError(err)
}

// Display file information
func GetInfo(fileName string) {

	fileInfo, err := os.Stat(fileName)
	checkError(err)

	fmt.Println("File name:", fileInfo.Name())
	fmt.Println("Size in bytes:", fileInfo.Size())
	fmt.Println("Permissions:", fileInfo.Mode())
	fmt.Println("Last modified:", fileInfo.ModTime())
	fmt.Println("Is Directory: ", fileInfo.IsDir())
	fmt.Printf("System interface type: %T\n", fileInfo.Sys())
	fmt.Printf("System info: %+v\n\n", fileInfo.Sys())

}

// Move file to new location
func Move(oldLoc string, newLoc string) {

	err := os.Rename(oldLoc, newLoc)
	checkError(err)
}

// Delete a file
func Delete(fileName string) {

	err := os.Remove(fileName)
	checkError(err)

}

// Example of how to open a file.
func Open(fileName string) {

	file, err := os.Open(fileName)
	if err != nil {
		log.Fatal(os.IsNotExist(err))
	}
	file.Close()

	file, err = os.OpenFile(fileName, os.O_APPEND, 0666)
	checkError(err)
	file.Close()
}

// Check write permission
func CheckPermission(fileName string) {

	file, err := os.OpenFile(fileName, os.O_WRONLY, 0666)
	if err != nil {
		log.Fatal(os.IsPermission(err))
	}
	file.Close()
}

// Change file permission
func ChangePermission(fileName string, mode int) {

	err := os.Chmod(fileName, os.FileMode(mode))
	checkError(err)
}

// Change a file ownership
func ChangeOwnership(fileName string, uid, gid int) {

	if uid == 0 {
		uid = os.Getuid()
	}
	if gid == 0 {
		gid = os.Getgid()
	}

	err := os.Chown(fileName, uid, gid)
	checkError(err)
}

// Change file timestamps
func ChangeTime(fileName string, atime, mtime time.Time) {
	if err := os.Chtimes(fileName, atime, mtime); err != nil {
		log.Fatal(err)
	}
}

// Create a hard link
func HardLink(oldname, newname string) {
	if oldname == "" || newname == "" {
		return
	}

	if err := os.Link(oldname, newname); err != nil {
		log.Fatal(err)
	}
}

// Create symbolic link
func SymLink(oldname, newname string) {
	if err := os.Symlink(oldname, newname); err != nil {
		log.Fatal(err)
	}
}

// Copy file (hard link)
func Copy(oldname, newname string) (err error) {

	oldfile, err := os.Stat(oldname)
	checkError(err)
	if !oldfile.Mode().IsRegular() {
		return fmt.Errorf("Copy: non-regular old file %s (%q)", oldfile.Name(), oldfile.Mode().String())
	}

	newfile, err := os.Stat(newname)
	if err != nil {
		if !os.IsNotExist(err) {
			return
		}
	} else {
		if !(newfile.Mode().IsRegular()) {
			return fmt.Errorf("Copy: non-regular new file %s (%q)", oldfile.Name(), oldfile.Mode().String())
		}
		if os.SameFile(oldfile, newfile) {
			return
		}
	}

	if err = os.Link(oldname, newname); err != nil {
		return
	}

	err = copyFileContents(oldname, newname)

	return
}

// Copy content to new file
func copyFileContents(oldname, newname string) (err error) {

	oldfile, err := os.Open(oldname)
	if err != nil {
		return
	}
	defer oldfile.Close()

	newfile, err := os.Create(newname)
	if err != nil {
		return
	}
	defer func() {
		nerr := newfile.Close()
		if err == nil {
			err = nerr
		}
	}()

	if _, err = io.Copy(newfile, oldfile); err != nil {
		return
	}
	err = newfile.Sync()

	return
}

// seek file
func Seek(fileName string, offset int64, whence int) int64 {

	file, err := os.Open(fileName)
	checkError(err)
	defer file.Close()

	newPos, err := file.Seek(offset, whence)
	checkError(err)

	return newPos
}

// Write content to a file
func Write(fileName string, content []byte) {

	file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
	checkError(err)
	defer file.Close()

	_, err = file.Write(content)
	checkError(err)
}

// Read file by given length
func Read(fileName string, len int) {

	file, err := os.Open(fileName)
	checkError(err)
	defer file.Close()

	byteSlice := make([]byte, len)
	bytesRead, err := file.Read(byteSlice)
	checkError(err)

	log.Println(byteSlice[:len])
	log.Println(bytesRead)
}

// Archive given files
func CreateArchiveFile(zipName string, fileNames []string) {

	file, err := os.OpenFile(zipName, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
	checkError(err)
	defer file.Close()

	zipWriter := zip.NewWriter(file)

	for _, fileName := range fileNames {

		infile, err := os.Open(fileName)

		data, err := ioutil.ReadAll(infile)
		checkError(err)

		fileWrite, err := zipWriter.Create(fileName)
		checkError(err)

		_, err = fileWrite.Write(data)
		checkError(err)
	}

	err = zipWriter.Close()
	checkError(err)

}

// Extract a zip archive file
func ExtractArchiveFile(zipName string, targetDirectory string) {

	zipReader, err := zip.OpenReader(zipName)
	checkError(err)
	defer zipReader.Close()

	for _, file := range zipReader.Reader.File {

		zippedfile, err := file.Open()
		checkError(err)
		defer zippedfile.Close()

		if targetDirectory == "" {
			targetDirectory = "./"
		}
		extractedFilePath := filepath.Join(targetDirectory, file.Name)

		if file.FileInfo().IsDir() {
			os.MkdirAll(extractedFilePath, file.Mode())
		} else {
			outputFile, err := os.OpenFile(extractedFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
			checkError(err)
			defer outputFile.Close()

			_, err = io.Copy(outputFile, zippedfile)
			checkError(err)
		}

	}
}

// Compress "fileName" to zip "gzFileName"
func CompressFile(gzFileName string, fileName string) {

	outfile, err := os.Create(gzFileName)
	checkError(err)

	gzipWriter := gzip.NewWriter(outfile)
	defer gzipWriter.Close()

	inFile, err := os.Open(fileName)
	checkError(err)

	data, err := ioutil.ReadAll(inFile)
	checkError(err)

	_, err = gzipWriter.Write(data)
	checkError(err)
}

// Uncompress file "gzFileName" to "newFileName"
func UncompressFile(gzFileName string, newFileName string) {

	gzipFile, err := os.Open(gzFileName)
	checkError(err)
	defer gzipFile.Close()

	gzipReader, err := gzip.NewReader(gzipFile)
	checkError(err)
	defer gzipReader.Close()

	outFileWriter, err := os.Create(newFileName)
	checkError(err)
	defer outFileWriter.Close()

	_, err = io.Copy(outFileWriter, gzipReader)
	checkError(err)

}

// Create a temporary file which will remove at file end
func CerateTempFile(fileName string) {

	tempFile, err := ioutil.TempFile("", fileName)
	checkError(err)
	defer func() {
		tempFile.Close()
		removeTempFile(tempFile.Name())
	}()

}

// remove a afile
func removeTempFile(fileName string) {
	err := os.Remove(fileName)
	checkError(err)
}

// Read file from HTTP and write content to a file.
func FileFromHTTP(fileName, url string) {

	newFile, err := os.Create(fileName)
	checkError(err)
	defer newFile.Close()

	res, err := http.Get(url)
	checkError(err)
	defer res.Body.Close()

	_, err = io.Copy(newFile, res.Body)
	checkError(err)
}

// Create checksum from a file content
func ChecksumFileContent(fileName string) {

	data, err := ioutil.ReadFile(fileName)
	checkError(err)

	fmt.Printf("Md5: %x\n\n", md5.Sum(data))
	fmt.Printf("Sha1: %x\n\n", sha1.Sum(data))
	fmt.Printf("Sha256: %x\n\n", sha256.Sum256(data))
	fmt.Printf("Sha512: %x\n\n", sha512.Sum512(data))
}

// Create checksum by file handler
func ChecksumFile(fileName string) {
	file, err := os.Open(fileName)
	checkError(err)
	defer file.Close()

	hasher := md5.New()
	_, err = io.Copy(hasher, file)
	checkError(err)

	sum := hasher.Sum(nil)
	fmt.Printf("Md5 checksum: %x\n", sum)
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="me.eddiep.android.monopolytracker.MainActivity">
    <item
        android:id="@+id/menu_save"
        android:orderInCategory="100"
        android:title="Done"
        android:icon="@drawable/ic_action_action_get_app"
        app:showAsAction="always" />
</menu>


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright (C) 2013 The Android Open Source Project

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_play"
          android:icon="@drawable/selector_play"
          android:title="Play"
          android:showAsAction="ifRoom|withText" />
</menu>


text:
package org.fax4j.spi.windows;

import org.fax4j.FaxException;
import org.fax4j.common.FaxActionType;
import org.fax4j.spi.FaxClientSpi;
import org.fax4j.test.TestUtil;
import org.fax4j.test.TestUtil.EmptyFaxClientSpi;
import org.fax4j.util.ProcessExecutorHelper.ProcessOutput;
import org.junit.Before;
import org.junit.Test;

/**
 * Test Class
 *
 * @author Sagie Gur-Ari
 */
public class WindowsProcessOutputValidatorTest {
    /** The validator to test */
    private WindowsProcessOutputValidator validator;
    /** Empty fax client SPI */
    private FaxClientSpi faxClientSpi;

    /**
     * Sets up the test objects.
     *
     * @throws Exception
     *             Any exception
     */
    @Before
    public void setUp() throws Exception {
        this.validator = new WindowsProcessOutputValidator();
        this.faxClientSpi = TestUtil.createFaxClientSpi(EmptyFaxClientSpi.class.getName(), null);
    }

    /**
     * Test
     *
     * @throws Exception
     *             Any exception
     */
    @Test
    public void validateProcessOutputValidTest() throws Exception {
        ProcessOutput processOutput = new ProcessOutput("fax.operation.done=true", "err", 0);
        this.validator.validateProcessOutput(this.faxClientSpi, processOutput, FaxActionType.SUBMIT_FAX_JOB);
    }

    /**
     * Test
     *
     * @throws Exception
     *             Any exception
     */
    @Test(expected = FaxException.class)
    public void validateProcessOutputNoFaxOutputTest() throws Exception {
        ProcessOutput processOutput = new ProcessOutput("abc", "err", 0);
        this.validator.validateProcessOutput(this.faxClientSpi, processOutput, FaxActionType.SUBMIT_FAX_JOB);
    }

    /**
     * Test
     *
     * @throws Exception
     *             Any exception
     */
    @Test(expected = FaxException.class)
    public void validateProcessOutputErrorOutputNullMessageTest() throws Exception {
        ProcessOutput processOutput = new ProcessOutput("fax.operation.done=false\nfax.error=", "err", 0);
        this.validator.validateProcessOutput(this.faxClientSpi, processOutput, FaxActionType.SUBMIT_FAX_JOB);
    }

    /**
     * Test
     *
     * @throws Exception
     *             Any exception
     */
    @Test(expected = FaxException.class)
    public void validateProcessOutputErrorOutputEmptyMessageTest() throws Exception {
        ProcessOutput processOutput = new ProcessOutput("fax.operation.done=false\nfax.error=\n", "err", 0);
        this.validator.validateProcessOutput(this.faxClientSpi, processOutput, FaxActionType.SUBMIT_FAX_JOB);
    }

    /**
     * Test
     *
     * @throws Exception
     *             Any exception
     */
    @Test(expected = FaxException.class)
    public void validateProcessOutputErrorOutputWithMessageTest() throws Exception {
        ProcessOutput processOutput = new ProcessOutput("fax.operation.done=false\nfax.error=MY ERROR\nSOME MESSAGE\n",
                "err", 0);
        this.validator.validateProcessOutput(this.faxClientSpi, processOutput, FaxActionType.SUBMIT_FAX_JOB);
    }

    /**
     * Test
     *
     * @throws Exception
     *             Any exception
     */
    @Test(expected = FaxException.class)
    public void validateProcessOutputNullOutputTest() throws Exception {
        ProcessOutput processOutput = new ProcessOutput(null, "err", 0);
        this.validator.validateProcessOutput(this.faxClientSpi, processOutput, FaxActionType.SUBMIT_FAX_JOB);
    }

    /**
     * Test
     *
     * @throws Exception
     *             Any exception
     */
    @Test(expected = FaxException.class)
    public void validateProcessOutputEmptyOutputTest() throws Exception {
        ProcessOutput processOutput = new ProcessOutput("", "err", 0);
        this.validator.validateProcessOutput(this.faxClientSpi, processOutput, FaxActionType.SUBMIT_FAX_JOB);
    }

    /**
     * Test
     *
     * @throws Exception
     *             Any exception
     */
    @Test(expected = FaxException.class)
    public void validateProcessOutputInvalidExitCodeTest() throws Exception {
        ProcessOutput processOutput = new ProcessOutput("fax.operation.done=true", "err", 1);
        this.validator.validateProcessOutput(this.faxClientSpi, processOutput, FaxActionType.SUBMIT_FAX_JOB);
    }

    /**
     * Test
     *
     * @throws Exception
     *             Any exception
     */
    @Test(expected = FaxException.class)
    public void validateProcessOutputInvalidNullOutputTest() throws Exception {
        ProcessOutput processOutput = new ProcessOutput(null, "err", 1);
        this.validator.validateProcessOutput(this.faxClientSpi, processOutput, FaxActionType.SUBMIT_FAX_JOB);
    }

    /**
     * Test
     *
     * @throws Exception
     *             Any exception
     */
    @Test(expected = FaxException.class)
    public void validateProcessOutputInvalidEmptyOutputTest() throws Exception {
        ProcessOutput processOutput = new ProcessOutput(null, "err", 1);
        this.validator.validateProcessOutput(this.faxClientSpi, processOutput, FaxActionType.SUBMIT_FAX_JOB);
    }
}


text:
package cc.protea.spreedly;

import android.util.Base64;

public class DefaultBase64Converter implements Base64Converter {

    @Override
    public String encode(String input) {
        return Base64.encodeToString(input.getBytes(), Base64.DEFAULT);
    }
}


text:
package edu.harvard.we99.services.storage.entities;

import edu.harvard.we99.domain.Coordinate;

import javax.persistence.Entity;

/**
 * @author mford
 */
@Entity
public class WellMapEntity extends AbstractWellEntity<WellMapEntity> {
    @SuppressWarnings("unused")
    public WellMapEntity() {}

    public WellMapEntity(Coordinate coord) {
        super(coord);
    }

    public WellMapEntity(int row, int col) {
        super(row, col);
    }

}


text:
package org.jetbrains.plugins.scala
package codeInspection.collections

import org.jetbrains.plugins.scala.codeInspection.InspectionBundle
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScExpression

/**
 * Nikolay.Tropin
 * 2014-05-05
 */
class MapGetOrElseFalseInspection extends OperationOnCollectionInspection {
  override def possibleSimplificationTypes: Array[SimplificationType] =
    Array(MapGetOrElseFalse)
}

object MapGetOrElseFalse extends SimplificationType() {
  def hint = InspectionBundle.message("map.getOrElse.false.hint")

  override def getSimplification(expr: ScExpression): Option[Simplification] = {
    expr match {
      case qual`.map`(f @ returnsBoolean())`.getOrElse`(literal("false")) =>
        Some(replace(expr).withText(invocationText(qual, "exists", f)).highlightFrom(qual))
      case _ => None
    }
  }
}


text:
/**
 * SessionFactory Class
 * Author: Patricio Ferreira
 *
 * Description: Polymorphic Factory Class.
 */

 var Backbone = require('backbone'),
    _ = require('underscore');

var SessionFactory = Backbone.Base.extend({

    initialize: function() { throw new Error('SessionFactory cannot be instanciated'); }

}, {

    NAME: 'SessionFactory',

    factories: new Backbone.Collection([]),

    addFactory: function(Factory) {
        var f = SessionFactory.factories.findWhere({ type: Factory.NAME });
        if(!f) SessionFactory.factories.add({ type: Factory.NAME, class: Factory });
    },

    createSession: function(type, config) {
        var Factory = SessionFactory.factories.findWhere({ type: type });
        if(!Factory) throw new Error('Unsupported SessionType. Session Factory not found for the SessionType');
        return Factory.get('class').create(_.extend({}, config));
    }

});

module.exports = SessionFactory;


text:
#include "platform.h"
#include "hex_strings.h"

#include "lib.h"

// these must be kept in sync with errors.h

char *TspErrorCodesArray[] = {
  "NO_ERROR",
  "NO_ERROR_SHOW_HELP",
  "TSP_ERROR",
  "SOCKET_ERROR",
  "INTERFACE_SETUP_FAILED",
  "KEEPALIVE_TIMEOUT",
  "KEEPALIVE_ERROR",
  "TUNNEL_ERROR",
  "TSP_VERSION_ERROR",
  "AUTHENTICATION_ERROR",
  "LEASE_EXPIRED",
  "SERVER_SIDE_ERROR",
  "INVALID_ARGUMENTS",
  "MEMORY_ERROR",
  "INVALID_SERVER",
  "INVALID_CONFIG_FILE",
  "INVALID_CLIENT_IPV4",
  "INVALID_CLIENT_IPV6",
  "LOGGING_CONFIGURATION_ERROR",
  "BROKER_REDIRECTION",
  "BROKER_REDIRECTION_ERROR",
  "SOCKET_ERROR_CANT_CONNECT",
  "INITIALIZATION_ERROR",
#ifdef HACCESS
  "HACCESS_INITIALIZATION_ERROR",
  "HACCESS_SETUP_ERROR",
  "HACCESS_EXPOSE_DEVICES_ERROR",
#endif
  NULL
};

// Prototype.
sint32_t GetSizeOfNullTerminatedArray( char ** );

/*
   Check if all characters in Value are within AllowedChars list.
*/
sint32_t IsAll( char *AllowedChars, char *Value )
{
  if( Value )
  {
    for(;*Value; Value++)
    {
      if(strchr(AllowedChars, *Value) == NULL)
        return 0;
    }
  }
  else
  {
    return 0;
  }

  return 1;
}

/*
   Check to see if there is a value in the char *
   If not, then the value was not supplied.
*/
sint32_t IsPresent( char *Value )
{
  if( Value && pal_strlen(Value) )
    return 1;
  return 0;
}

/* This next function is very dangerous.
   If you can call be certain the array
   finished by NULL or it will do bad things.
*/
sint32_t GetSizeOfNullTerminatedArray(char **a)
{
  sint32_t i;
  for (i = 0;;i++)
  {
    if (a[i] == NULL)
      return i;
  }
  // unreachable code.
}

char *tspGetErrorByCode(sint32_t code)
{
  static char buf[1024];
  sint32_t i;

  i = GetSizeOfNullTerminatedArray(TspErrorCodesArray);
  if (code < i && code > -1)
    return TspErrorCodesArray[code];
  else
    pal_snprintf(buf, sizeof(buf), GOGO_STR_NOT_DEF_AS_CLIENT_ERROR, code);
  return buf;
}

/* Function: IsAddressInPrefix

  Verifies if a given IPv6 address is part of the given IPv6 prefix.

  Returns 0 if address is part of prefix.
  Returns 1 if address is NOT part of prefix.
  Returns -1 if either address or prefix is an invalid IPv6 address.

*/
sint32_t IsAddressInPrefix( const char* address, const char* prefix, const sint16_t prefix_len )
{
  short compare_bytes=0;
  short compare_bits =0;
  sint32_t ret_code=1;
  struct addrinfo hints, *res_address=NULL, *res_prefix=NULL;
  struct in6_addr *in6_address, *in6_prefix;

  memset( &hints, 0x00, sizeof(struct addrinfo) );
  hints.ai_family = AF_INET6;

  while( 1 )
  {
    if( (prefix_len > 0   &&  prefix_len <= 128) &&
        (address != NULL  &&  prefix != NULL   ) &&
        (getaddrinfo( address, NULL, &hints, &res_address ) != 0  ||  getaddrinfo( prefix, NULL, &hints, &res_prefix )   != 0) )
    {
      ret_code = -1;
      break;
    }

    if( res_address == NULL  ||  res_prefix == NULL )
    {
      ret_code = -1;
      break;
    }
    in6_address   = &((struct sockaddr_in6*)(res_address->ai_addr))->sin6_addr;
    in6_prefix    = &((struct sockaddr_in6*)(res_prefix->ai_addr))->sin6_addr;

    /* Compute how many bytes and bits to compare */
    compare_bytes = prefix_len / 8;
    compare_bits  = prefix_len % 8;

    /* Compare the bytes of address and prefix */
    if( memcmp( in6_address, in6_prefix, compare_bytes ) != 0 )
      break;

    /* Compare the bits */
    if( compare_bits > 0 )
      if( (in6_address->s6_addr[compare_bytes] >> compare_bits) != (in6_prefix->s6_addr[compare_bytes] >> compare_bits) )
        break;

    /* address is part of prefix */
    ret_code = 0;
    break;
  }

  /* Free memory used. */
  if( res_address ) freeaddrinfo( res_address );
  if( res_prefix  ) freeaddrinfo( res_prefix );

  return ret_code;
}


text:
<?php
	// Use $_SESSION variables
	session_start();
	// Include settings file
	include 'bin/settings.php';
	if ($_GET['token'] != $_SESSION['oc_token']) {
		// This page can only be addressed with the right token
		include('bin/404.php');
		die();
	}
	// Get file information from the URL
	$savePath = $_GET['savePath'];

if(!$savePath){
	// File does not exist
    die('file not found');
} else {
	if (strpos($savePath, $_SESSION['oc_uploadDirLinux']) === false) {
		// Access denied due to path
		//include('bin/404.php');
		die('wrong savePath '.$_SESSION['oc_uploadDirLinux'].' '.$savePath);
	}
	if (!file_exists($savePath)) {
		die('wrong request');
	}
	$fileSplit = explode("/", $savePath);

	// Depends on savePath and has to be adapted
	$file = $fileSplit[7];
	// Prepare download
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");

	// Currently set to image/png to support download of image data as prepared in the sample eCRF. PLEASE ADAPT!
    header("Content-Type: image/png");

    // read the file from disk
    readfile($savePath);
}
?>


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="shortcut icon" href="../img/favicon.ico">

        <title>Contributing - Displore documentation</title>

        <link href="../css/bootstrap-custom.min.css" rel="stylesheet">
        <link href="../css/font-awesome-4.0.3.css" rel="stylesheet">
        <link href="../css/prettify-1.0.css" rel="stylesheet">
        <link href="../css/base.css" rel="stylesheet">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                Toggle navigation

            </button>

            Displore documentation

                    Changelog

                    Contributing

                    Roadmap

                         Previous

                        Next

Contributing

Ways to contribute

Submitting issues

Suggesting features

Pull Requests

Coding style

Building the docs

Contributing

An interesting read is Contributing to a Github Project and Github's guide.

Ways to contribute

Submitting issues

Suggesting features

Pull Requests

Which branch?

Commit messages

Coding style

Building the docs

Submitting issues

If you run into problems, do not hesitate to file an issue (check the existing issues first). Please be as descriptive and clear as possible. Describe for example what you did, what the results where and what you expected. Also include information on the versions you are using of Laravel, Displore, etc. and if possible code/demos are helpful too.

Suggesting features

If you want to suggest a new feature, you can file an issue and include the [Proposal] or [Idea] tag in the title. Try to elaborate your suggestion as much as possible.
Features should only be proposed in the Displore/core repository if they apply the general mechanics of both the Displore and Journal package.

Pull Requests

This workflow is inspired by Github Flow

Which branch?

The master branch always contains the latest stable release.

Bug fixes should be sent to the master branch.

Minor features that are fully backwards compatible with the latest release may be sent to the master branch as well.

Incompatible features or bug fixes should be sent to the develop branch or relevant feature- branch.

Commit messages

Consider starting the commit message with an applicable prefix:

Fixed: when fixing a bug, an issue could be referenced.

Updated: when changing or improving code which did not necessarily cause bugs.

New: when introducing a new file, function or cool feature.

Deleted: when removing code or files.

Dev: when committing experimental code, please describe in the extended description what it is and why it is experimental.

Coding style

In general, follow Laravel's style.

Building the docs

The docs, hosted in their own repository, are pulled in the Github Pages repository to be hosted online. The docs are build with the MkDocs static site generator. Have a look at the site if you want to know how to generate a nice static docs site yourself. The required mkdocs.yml file is located in the root of the Github Pages repository.


text:
var assert = require('assert')
  ,	config = require('../../config')
  , models = require('../../models')
  , fixtures = require('../fixtures')
  , request = require('request');

describe('agents endpoint', function() {

    it('index should be not be accessible anonymously', function(done) {
        request(config.agents_endpoint, function(err, resp, body) {
            assert.equal(resp.statusCode, 401);
            done();
        });
    });

    it('index should return all agents', function(done) {
        request({ url: config.agents_endpoint,
                  headers: { Authorization: fixtures.models.accessTokens.system.toAuthHeader() },
                             json: true }, function(err,resp,body) {
            assert.ifError(err);
            assert.equal(resp.statusCode, 200);

            assert.notEqual(body.agents, undefined);
            assert.equal(body.agents.length > 0, true);
            assert.notEqual(body.agents[0].execute_as, undefined);
            done();
        });
    });

    it('should allow creating an agent by a user', function(done) {

        var agent = models.Agent({
            execute_as: fixtures.models.principals.device.id,
            action: ";",
            enabled: true
        });

        request.post(config.agents_endpoint,
            { headers: { Authorization: fixtures.models.accessTokens.user.toAuthHeader() },
                json: agent }, function(err, resp, body) {
                assert.ifError(err);
                assert.equal(resp.statusCode, 200);

                // should normalize agent execution to user
                assert.equal(body.agent.execute_as, fixtures.models.principals.user.id);

                done();
            }
        );
    });

    it('should allow updates to an agent by execute_as user', function(done) {
        fixtures.models.agents.nop.enabled = false;

        request.put(config.agents_endpoint + "/" + fixtures.models.agents.nop.id,
            { headers: { Authorization: fixtures.models.accessTokens.user.toAuthHeader() },
                json: fixtures.models.agents.nop }, function(err, resp, body) {
                assert.ifError(err);
                assert.equal(resp.statusCode, 200);

                assert.equal(body.agent.enabled, false);

                done();
            }
        );
    });

    it('should not allow updates to an agent by a non system principals that isnt execute_as', function(done) {
        request.put(config.agents_endpoint + "/" + fixtures.models.agents.nop.id,
            { headers: { Authorization: fixtures.models.accessTokens.device.toAuthHeader() },
                json: fixtures.models.agents.nop }, function(err, resp, body) {
                assert.ifError(err);
                assert.equal(resp.statusCode, 404);

                done();
            }
        );
    });
});


text:
import { ActionType, ContextModule, OwnerType, TappedRequestPriceEstimate } from "@artsy/cohesion"
import { RequestForPriceEstimateBanner_artwork$key } from "__generated__/RequestForPriceEstimateBanner_artwork.graphql"
import { RequestForPriceEstimateBanner_marketPriceInsights$key } from "__generated__/RequestForPriceEstimateBanner_marketPriceInsights.graphql"
import { RequestForPriceEstimateBanner_me$key } from "__generated__/RequestForPriceEstimateBanner_me.graphql"
import { Toast } from "app/Components/Toast/Toast"
import { navigate } from "app/navigation/navigate"
import { GlobalStore, useFeatureFlag } from "app/store/GlobalStore"
import { Box, Button, Flex, Separator, Text, WinningBidIcon } from "palette"
import { graphql, useFragment } from "react-relay"
import { useTracking } from "react-tracking"
interface RequestForPriceEstimateProps {
  artwork: RequestForPriceEstimateBanner_artwork$key
  marketPriceInsights: RequestForPriceEstimateBanner_marketPriceInsights$key | null
  me: RequestForPriceEstimateBanner_me$key | null
}
export const RequestForPriceEstimateBanner: React.FC<RequestForPriceEstimateProps> = ({
  ...otherProps
}) => {
  const { trackEvent } = useTracking()

  const artwork = useFragment(artworkFragment, otherProps.artwork)
  const marketPriceInsights = useFragment(
    marketPriceInsightsFragment,
    otherProps.marketPriceInsights
  )

  const me = useFragment(meFragment, otherProps.me)

  const enableRemotePriceEstimateRequestedLogic = useFeatureFlag(
    "AREnableNewRequestPriceEstimateLogic"
  )

  const localRequestedPriceEstimates = GlobalStore.useAppState(
    (state) => state.requestedPriceEstimates.requestedPriceEstimates
  )

  const priceEstimateRequested =
    (enableRemotePriceEstimateRequestedLogic && artwork.hasPriceEstimateRequest) ||
    !!localRequestedPriceEstimates[artwork.internalID]

  const isP1Artist = artwork.artist?.targetSupply?.isP1
  const isAlreadySubmitted = artwork.submissionId

  if (priceEstimateRequested) {
    return (
      <Box>
        <Flex alignItems="center" flexDirection="row">
          <WinningBidIcon />
          <Text variant="sm" ml={0.5} textAlign="center">
            Price Estimate Request Sent
          </Text>
        </Flex>

        <Separator mt={2} mb={3} borderColor="black10" />
      </Box>
    )
  }

  if (!isP1Artist || isAlreadySubmitted) {
    return null
  }

  return (
    <Box>
      <Text variant="sm" testID="request-price-estimate-banner-title">
        Get a Free Price Estimate
      </Text>
      <Text color="black60" mb={2} variant="xs" testID="request-price-estimate-banner-description">
        This artwork is eligible for a free evaluation from an Artsy specialist.
      </Text>
      <Button
        testID="request-price-estimate-button"
        onPress={() => {
          trackEvent(
            tracks.trackTappedRequestPriceEstimate(
              artwork.internalID,
              artwork.slug,
              marketPriceInsights?.demandRank ?? undefined
            )
          )
          if (!me) {
            Toast.show(
              "Error: Unable to retrieve your basic info. Please try again later.",
              "top",
              {
                backgroundColor: "red100",
              }
            )
            return
          }
          navigate(`/my-collection/artwork/${artwork.internalID}/price-estimate`, {
            passProps: {
              name: me.name,
              email: me.email,
              phone: me.phone,
              demandRank: marketPriceInsights?.demandRank ?? undefined,
              artworkSlug: artwork.slug,
            },
          })
        }}
        block
        variant="fillDark"
      >
        Request a Price Estimate
      </Button>

      <Separator mt={2} mb={3} borderColor="black10" />
    </Box>
  )
}

const artworkFragment = graphql`
  fragment RequestForPriceEstimateBanner_artwork on Artwork {
    artist {
      targetSupply {
        isP1
      }
    }
    internalID
    slug
    submissionId
    hasPriceEstimateRequest
  }
`

const marketPriceInsightsFragment = graphql`
  fragment RequestForPriceEstimateBanner_marketPriceInsights on MarketPriceInsights {
    demandRank
  }
`

const meFragment = graphql`
  fragment RequestForPriceEstimateBanner_me on Me {
    name
    email
    phone
  }
`

const tracks = {
  trackTappedRequestPriceEstimate: (
    artworkId: string,
    artworkSlug?: string,
    demandRank?: number
  ): TappedRequestPriceEstimate => ({
    action: ActionType.tappedRequestPriceEstimate,
    context_module: ContextModule.myCollectionArtworkInsights,
    context_screen: OwnerType.myCollectionArtworkInsights,
    context_screen_owner_type: OwnerType.myCollectionArtwork,
    context_screen_owner_id: artworkId,
    context_screen_owner_slug: artworkSlug,
    demand_index: demandRank,
  }),
}


text:
package com.yogee.zhebuy.modules.ebuy.service;

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

import com.yogee.zhebuy.common.persistence.Page;
import com.yogee.zhebuy.common.service.EbuyService;
import com.yogee.zhebuy.common.utils.StringUtils;
import com.yogee.zhebuy.modules.ebuy.entity.EbuyProtocol;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yogee.zhebuy.modules.ebuy.dao.EbuyProtocolDao;

/**
 * 审核消息Service
 * @author jackqth
 * @version 2017-06-02
 */
@Service
@Transactional(readOnly = true)
public class EbuyProtocolService extends EbuyService<EbuyProtocolDao, EbuyProtocol> {

	public EbuyProtocol get(String id) {
		return super.get(id);
	}

	public List<EbuyProtocol> findList(EbuyProtocol ebuyProtocol) {
		return super.findList(ebuyProtocol);
	}

	public Page<EbuyProtocol> findPage(Page<EbuyProtocol> page, EbuyProtocol ebuyProtocol) {
		return super.findPage(page, ebuyProtocol);
	}

	@Transactional(readOnly = false)
	public int save(EbuyProtocol ebuyProtocol) {

		if(StringUtils.isEmpty(ebuyProtocol.getId())){
			ebuyProtocol.setgmtCreate(new Date());
		}else{
			ebuyProtocol.setGmtModified(new Date());
		}
		return super.save(ebuyProtocol);
	}

	@Transactional(readOnly = false)
	public void delete(EbuyProtocol ebuyProtocol) {
		super.delete(ebuyProtocol);
	}

}


text:
/**
 *
 */
package cn.telling.common.action;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * @Title: DictionaryType.java
 * @Package com.Common.action
 * @Description: TODO(描述该文件做什么)
 * @author 冯俊杰
 * @date 2013-4-10 下午3:53:55
 * @version V1.0
 */
@Controller("Dictionary")
public class DictionaryType {

	@RequestMapping(value = "/list}", method = { RequestMethod.GET,RequestMethod.POST })
	public List<Map<String,String>> GetDictionaryList(String dicType)
	{
//		List<Map<String,String>> mapList=null;
		return null;
	}
}


text:
Jekyll theme for ryanaghdam.com.

## Installation

Add this line to your Jekyll site's Gemfile:

```ruby
gem "ryanaghdam-jekyll-theme"
```

And add this line to your Jekyll site's `_config.yml`:

```yaml
theme: ryanaghdam-jekyll-theme
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install ryanaghdam-jekyll-theme

## Development

To set up your environment to develop this theme, run `bundle install`.

Your theme is setup just like a normal Jekyll site! To test your theme, run `bundle exec jekyll serve` and open your browser at `http://localhost:4000`. This starts a Jekyll server using your theme. Add pages, documents, data, etc. like normal to test your theme's contents. As you make modifications to your theme and to your content, your site will regenerate and you should see the changes in the browser after a refresh, just like normal.

When your theme is released, only the files in `_layouts`, `_includes`, and `_sass` tracked with Git will be released.

## License

The theme is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
package vt

import (
	"encoding/json"
	"fmt"
	"net/url"
	"strings"
)

const (
	version = "0.3"
)

const (
	// Maximum size of payloads posted to VirusTotal's API endpoints.
	maxPayloadSize = 30 * 1024 * 1024 // 30 MB
	// Maximum file size that can scanned by VirusTotal.
	maxFileSize = 650 * 1024 * 1024 // 650 MB
)

var baseURL = url.URL{
	Scheme: "https",
	Host:   "www.virustotal.com",
	Path:   "api/v3/"}

// Request is the top level structure of an API request.
type Request struct {
	Data interface{} `json:"data"`
}

// Response is the top level structure of an API response.
type Response struct {
	Data  json.RawMessage        `json:"data"`
	Meta  map[string]interface{} `json:"meta"`
	Links Links                  `json:"links"`
	Error Error                  `json:"error"`
}

// Error contains information about an API error.
type Error struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

// Error implements the error interface.
func (e Error) Error() string {
	return e.Message
}

// URL returns a full VirusTotal API URL from a relative path (i.e: a path
// without the domain name and the "/api/v3/" prefix). The path can contain
// format 'verbs' as defined in the "fmt". This function is useful for creating
// URLs to be passed to any function expecting a *url.URL in this library.
func URL(pathFmt string, a ...interface{}) *url.URL {
	path := fmt.Sprintf(pathFmt, a...)
	url, err := url.Parse(path)
	if err != nil {
		msg := fmt.Sprintf(
			"error formatting URL \"%s\": %s",
			pathFmt, err)
		panic(msg)
	}
	return baseURL.ResolveReference(url)
}

// SetHost allows to change the host used while sending requests to the
// VirusTotal API. The default host is "www.virustotal.com" you rarely need to
// change it.
func SetHost(host string) {
	if strings.HasPrefix(host, "https://") {
		baseURL.Scheme = "https"
		baseURL.Host = strings.TrimPrefix(host, "https://")
	} else if strings.HasPrefix(host, "http://") {
		baseURL.Scheme = "http"
		baseURL.Host = strings.TrimPrefix(host, "http://")
	} else {
		baseURL.Host = host
	}
}


text:
package org.omnifaces.jaspictest.ejb;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;

/**
 * This is a "public" EJB in the sense that all its methods should be  accessible and there is no declarative role
 * checking prior to accessing a method.
 *
 */
@Stateless
public class PublicEJB {

	@Resource
	private EJBContext ejbContext;

	public String getUserName() {
		try {
			return ejbContext.getCallerPrincipal() != null? ejbContext.getCallerPrincipal().getName() : null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}


text:
Contributing to Ruby on Rails
=============================

This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails.

After reading this guide, you will know:

* How to use GitHub to report issues.
* How to clone master and run the test suite.
* How to help resolve existing issues.
* How to contribute to the Ruby on Rails documentation.
* How to contribute to the Ruby on Rails code.

Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation — all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.

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

Reporting an Issue
------------------

Ruby on Rails uses [GitHub Issue Tracking](https://github.com/rails/rails/issues) to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) GitHub account in order to submit an issue, to comment on them or to create pull requests.

NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing.

### Creating a Bug Report

If you've found a problem in Ruby on Rails which is not a security risk, do a search in GitHub under [Issues](https://github.com/rails/rails/issues) in case it was already reported. If you find no issue addressing it you can [add a new one](https://github.com/rails/rails/issues/new). (See the next section for reporting security issues.)

At the minimum, your issue report needs a title and descriptive text. But that's only a minimum. You should include as much relevant information as possible. You need at least to post the code sample that has the issue. Even better is to include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself — and others — to replicate the bug and figure out a fix.

Then, don't get your hopes up! Unless you have a "Code Red, Mission Critical, the World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating an issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with an "I'm having this problem too" comment.

### Create a Self-Contained gist for Active Record and Action Controller Issues

If you are filing a bug report, please use
[Active Record template for gems](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_gem.rb) or
[Action Controller template for gems](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_gem.rb)
if the bug is found in a published gem, and
[Active Record template for master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_master.rb) or
[Action Controller template for master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_master.rb)
if the bug happens in the master branch.

### Special Treatment for Security Issues

WARNING: Please do not report security vulnerabilities with public GitHub issue reports. The [Rails security policy page](http://rubyonrails.org/security) details the procedure to follow for security issues.

### What about Feature Requests?

Please don't put "feature request" items into GitHub Issues. If there's a new
feature that you want to see added to Ruby on Rails, you'll need to write the
code yourself - or convince someone else to partner with you to write the code.
Later in this guide you'll find detailed instructions for proposing a patch to
Ruby on Rails. If you enter a wishlist item in GitHub Issues with no code, you
can expect it to be marked "invalid" as soon as it's reviewed.

Sometimes, the line between 'bug' and 'feature' is a hard one to draw.
Generally, a feature is anything that adds new behavior, while a bug is
anything that fixes already existing behavior that is mis-behaving. Sometimes,
the core team will have to make a judgement call. That said, the distinction
generally just affects which release your patch will get in to; we love feature
submissions! They just won't get backported to maintenance branches.

If you'd like feedback on an idea for a feature before doing the work for make
a patch, please send an email to the [rails-core mailing
list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core). You
might get no response, which means that everyone is indifferent. You might find
someone who's also interested in building that feature. You might get a "This
won't be accepted." But it's the proper place to discuss new ideas. GitHub
Issues are not a particularly good venue for the sometimes long and involved
discussions new features require.

Setting Up a Development Environment
------------------------------------

To move on from submitting bugs to helping resolve existing issues or contributing your own code to Ruby on Rails, you _must_ be able to run its test suite. In this section of the guide you'll learn how to set up the tests on your own computer.

### The Easy Way

The easiest and recommended way to get a development environment ready to hack is to use the [Rails development box](https://github.com/rails/rails-dev-box).

### The Hard Way

In case you can't use the Rails development box, see section above, check [this other guide](development_dependencies_install.html).

Running an Application Against Your Local Branch
------------------------------------------------

The `--dev` flag of `rails new` generates an application that uses your local
branch:

```bash
$ cd rails
$ bundle exec rails new ~/my-test-app --dev
```

The application generated in `~/my-test-app` runs against your local branch
and in particular sees any modifications upon server reboot.

Testing Active Record
---------------------

This is how you run the Active Record test suite only for SQLite3:

```bash
$ cd activerecord
$ bundle exec rake test_sqlite3
```

You can now run the tests as you did for `sqlite3`. The tasks are respectively

```bash
test_mysql
test_mysql2
test_postgresql
```

Finally,

```bash
$ bundle exec rake test
```

will now run the four of them in turn.

You can also run any single test separately:

```bash
$ ARCONN=sqlite3 ruby -Itest test/cases/associations/has_many_associations_test.rb
```

You can invoke `test_jdbcmysql`, `test_jdbcsqlite3` or `test_jdbcpostgresql` also. See the file `activerecord/RUNNING_UNIT_TESTS.rdoc` for information on running more targeted database tests, or the file `ci/travis.rb` for the test suite run by the continuous integration server.

### Warnings

The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings.

As of this writing (December, 2010) they are especially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:

```bash
$ RUBYOPT=-W0 bundle exec rake test
```

### Older Versions of Ruby on Rails

If you want to add a fix to older versions of Ruby on Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 3-0-stable branch:

```bash
$ git branch --track 3-0-stable origin/3-0-stable
$ git checkout 3-0-stable
```

TIP: You may want to [put your Git branch name in your shell prompt](http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/) to make it easier to remember which version of the code you're working with.

Helping to Resolve Existing Issues
----------------------------------

As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the [Everyone's Issues](https://github.com/rails/rails/issues) list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:

### Verifying Bug Reports

For starters, it helps just to verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the issue saying that you're seeing the same thing.

If something is very vague, can you help squash it down into something specific? Maybe you can provide additional information to help reproduce a bug, or help by eliminating needless steps that aren't required to demonstrate the problem.

If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.

Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.

### Testing Patches

You can also help out by examining pull requests that have been submitted to Ruby on Rails via GitHub. To apply someone's changes you need first to create a dedicated branch:

```bash
$ git checkout -b testing_branch
```

Then you can use their remote branch to update your codebase. For example, let's say the GitHub user JohnSmith has forked and pushed to a topic branch "orange" located at https://github.com/JohnSmith/rails.

```bash
$ git remote add JohnSmith git://github.com/JohnSmith/rails.git
$ git pull JohnSmith orange
```

After applying their branch, test it out! Here are some things to think about:

* Does the change actually work?
* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
* Does it have the proper documentation coverage? Should documentation elsewhere be updated?
* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?

Once you're happy that the pull request contains a good change, comment on the GitHub issue indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:

<blockquote>
I like the way you've restructured that code in generate_finder_sql — much nicer. The tests look good too.
</blockquote>

If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the pull request.

Contributing to the Rails Documentation
---------------------------------------

Ruby on Rails has two main sets of documentation: the guides help you in learning about Ruby on Rails, and the API is a reference.

You can help improve the Rails guides by making them more coherent, consistent or readable, adding missing information, correcting factual errors, fixing typos, or bringing it up to date with the latest edge Rails. To get involved in the translation of Rails guides, please see [Translating Rails Guides](https://wiki.github.com/rails/docrails/translating-rails-guides).

You can either open a pull request to [Rails](http://github.com/rails/rails) or
ask the [Rails core team](http://rubyonrails.org/core) for commit access on
[docrails](http://github.com/rails/docrails) if you contribute regularly.
Please do not open pull requests in docrails, if you'd like to get feedback on your
change, ask for it in [Rails](http://github.com/rails/rails) instead.

Docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation.

If you are unsure of the documentation changes, you can create an issue in the [Rails](https://github.com/rails/rails/issues) issues tracker on GitHub.

When working with documentation, please take into account the [API Documentation Guidelines](api_documentation_guidelines.html) and the [Ruby on Rails Guides Guidelines](ruby_on_rails_guides_guidelines.html).

NOTE: As explained earlier, ordinary code patches should have proper documentation coverage. Docrails is only used for isolated documentation improvements.

NOTE: To help our CI servers you can add [ci skip] to your documentation commit message to skip build on that commit. Please remember to use it for commits containing only documentation changes.

WARNING: Docrails has a very strict policy: no code can be touched whatsoever, no matter how trivial or small the change. Only RDoc and guides can be edited via docrails. Also, CHANGELOGs should never be edited in docrails.

Contributing to the Rails Code
------------------------------

### Clone the Rails Repository

The first thing you need to do to be able to contribute code is to clone the repository:

```bash
$ git clone git://github.com/rails/rails.git
```

and create a dedicated branch:

```bash
$ cd rails
$ git checkout -b my_new_branch
```

It doesn't matter much what name you use, because this branch will only exist on your local computer and your personal repository on GitHub. It won't be part of the Rails Git repository.

### Write Your Code

Now get busy and add or edit code. You're on your branch now, so you can write whatever you want (you can check to make sure you're on the right branch with `git branch -a`). But if you're planning to submit your change back for inclusion in Rails, keep a few things in mind:

* Get the code right.
* Use Rails idioms and helpers.
* Include tests that fail without your code, and pass with it.
* Update the (surrounding) documentation, examples elsewhere, and the guides: whatever is affected by your contribution.

It is not customary in Rails to run the full test suite before pushing
changes. The railties test suite in particular takes a long time, and even
more if the source code is mounted in `/vagrant` as happens in the recommended
workflow with the [rails-dev-box](https://github.com/rails/rails-dev-box).

As a compromise, test what your code obviously affects, and if the change is
not in railties run the whole test suite of the affected component. If all is
green that's enough to propose your contribution. We have [Travis CI](https://travis-ci.org/rails/rails)
as a safety net for catching unexpected breakages
elsewhere.

TIP: Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of Rails will generally not be accepted.

### Follow the Coding Conventions

Rails follows a simple set of coding style conventions:

* Two spaces, no tabs (for indentation).
* No trailing whitespace. Blank lines should not have any spaces.
* Indent after private/protected.
* Use Ruby >= 1.9 syntax for hashes. Prefer `{ a: :b }` over `{ :a => :b }`.
* Prefer `&&`/`||` over `and`/`or`.
* Prefer class << self over self.method for class methods.
* Use `MyClass.my_method(my_arg)` not `my_method( my_arg )` or `my_method my_arg`.
* Use `a = b` and not `a=b`.
* Use assert_not methods instead of refute.
* Prefer `method { do_stuff }` instead of `method{do_stuff}` for single-line blocks.
* Follow the conventions in the source you see used already.

The above are guidelines — please use your best judgment in using them.

### Updating the CHANGELOG

The CHANGELOG is an important part of every release. It keeps the list of changes for every Rails version.

You should add an entry to the CHANGELOG of the framework that you modified if you're adding or removing a feature, committing a bug fix or adding deprecation notices. Refactorings and documentation changes generally should not go to the CHANGELOG.

A CHANGELOG entry should summarize what was changed and should end with author's name. You can use multiple lines if you need more space and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach issue's number. Here is an example CHANGELOG entry:

```
*   Summary of a change that briefly describes what was changed. You can use multiple
    lines and wrap them at around 80 characters. Code examples are ok, too, if needed:

        class Foo
          def bar
            puts 'baz'
          end
        end

    You can continue after the code example and you can attach issue number. GH#1234

    *Your Name*
```

Your name can be added directly after the last word if you don't provide any code examples or don't need multiple paragraphs. Otherwise, it's best to make as a new paragraph.

### Sanity Check

You should not be the only person who looks at the code before you submit it.
If you know someone else who uses Rails, try asking them if they'll check out
your work. If you don't know anyone else using Rails, try hopping into the IRC
room or posting about your idea to the rails-core mailing list.  Doing this in
private before you push a patch out publicly is the "smoke test" for a patch:
if you can't convince one other developer of the beauty of your code, you're
unlikely to convince the core team either.

### Commit Your Changes

When you're happy with the code on your computer, you need to commit the changes to Git:

```bash
$ git commit -a
```

At this point, your editor should be fired up and you can write a message for this commit. Well formatted and descriptive commit messages are extremely helpful for the others, especially when figuring out why given change was made, so please take the time to write it.

Good commit message should be formatted according to the following example:

```
Short summary (ideally 50 characters or less)

More detailed description, if necessary. It should be wrapped to 72
characters. Try to be as descriptive as you can, even if you think that
the commit content is obvious, it may not be obvious to others. You
should add such description also if it's already present in bug tracker,
it should not be necessary to visit a webpage to check the history.

Description can have multiple paragraphs and you can use code examples
inside, just indent it with 4 spaces:

    class PostsController
      def index
        respond_with Post.limit(10)
      end
    end

You can also add bullet points:

- you can use dashes or asterisks

- also, try to indent next line of a point for readability, if it's too
  long to fit in 72 characters
```

TIP. Please squash your commits into a single commit when appropriate. This simplifies future cherry picks, and also keeps the git log clean.

### Update Your Branch

It's pretty likely that other changes to master have happened while you were working. Go get them:

```bash
$ git checkout master
$ git pull --rebase
```

Now reapply your patch on top of the latest changes:

```bash
$ git checkout my_new_branch
$ git rebase master
```

No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.

### Fork

Navigate to the Rails [GitHub repository](https://github.com/rails/rails) and press "Fork" in the upper right hand corner.

Add the new remote to your local repository on your local machine:

```bash
$ git remote add mine git@github.com:<your user name>/rails.git
```

Push to your remote:

```bash
$ git push mine my_new_branch
```

You might have cloned your forked repository into your machine and might want to add the original Rails repository as a remote instead, if that's the case here's what you have to do.

In the directory you cloned your fork:

```bash
$ git remote add rails git://github.com/rails/rails.git
```

Download new commits and branches from the official repository:

```bash
$ git fetch rails
```

Merge the new content:

```bash
$ git checkout master
$ git rebase rails/master
```

Update your fork:

```bash
$ git push origin master
```

If you want to update another branch:

```bash
$ git checkout branch_name
$ git rebase rails/branch_name
$ git push origin branch_name
```

### Issue a Pull Request

Navigate to the Rails repository you just pushed to (e.g.
https://github.com/your-user-name/rails) and click on "Pull Requests" seen in
the right panel. On the next page, press "New pull request" in the upper right
hand corner.

Click on "Edit", if you need to change the branches being compared (it compares
"master" by default) and press "Click to create a pull request for this
comparison".

Ensure the changesets you introduced are included. Fill in some details about
your potential patch including a meaningful title. When finished, press "Send
pull request". The Rails core team will be notified about your submission.

### Get some Feedback

Most pull requests will go through a few iterations before they get merged.
Different contributors will sometimes have different opinions, and often
patches will need revised before they can get merged.

Some contributors to Rails have email notifications from GitHub turned on, but
others do not. Furthermore, (almost) everyone who works on Rails is a
volunteer, and so it may take a few days for you to get your first feedback on
a pull request. Don't despair! Sometimes it's quick, sometimes it's slow. Such
is the open source life.

If it's been over a week, and you haven't heard anything, you might want to try
and nudge things along. You can use the [rubyonrails-core mailing
list](http://groups.google.com/group/rubyonrails-core/) for this. You can also
leave another comment on the pull request.

While you're waiting for feedback on your pull request, open up a few other
pull requests and give someone else some! I'm sure they'll appreciate it in
the same way that you appreciate feedback on your patches.

### Iterate as Necessary

It's entirely possible that the feedback you get will suggest changes. Don't get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it's worth making the tweaks and resubmitting. If the feedback is that your code doesn't belong in the core, you might still think about releasing it as a gem.

#### Squashing commits

One of the things that we may ask you to do is "squash your commits," which
will combine all of your commits into a single commit. We prefer pull requests
that are a single commit. This makes it easier to backport changes to stable
branches, squashing makes it easier to revert bad commits, and the git history
can be a bit easier to follow. Rails is a large project, and a bunch of
extraneous commits can add a lot of noise.

In order to do this, you'll need to have a git remote that points at the main
Rails repository. This is useful anyway, but just in case you don't have it set
up, make sure that you do this first:

```bash
$ git remote add upstream https://github.com/rails/rails.git
```

You can call this remote whatever you'd like, but if you don't use `upstream`,
then change the name to your own in the instructions below.

Given that your remote branch is called `my_pull_request`, then you can do the
following:

```bash
$ git fetch upstream
$ git checkout my_pull_request
$ git rebase upstream/master
$ git rebase -i

< Choose 'squash' for all of your commits except the first one. >
< Edit the commit message to make sense, and describe all your changes. >

$ git push origin my_pull_request -f
```

You should be able to refresh the pull request on GitHub and see that it has
been updated.

### Backporting

Changes that are merged into master are intended for the next major release of Rails. Sometimes, it might be beneficial for your changes to propagate back to the maintenance releases for older stable branches. Generally, security fixes and bug fixes are good candidates for a backport, while new features and patches that introduce a change in behavior will not be accepted. When in doubt, it is best to consult a Rails team member before backporting your changes to avoid wasted effort.

For simple fixes, the easiest way to backport your changes is to [extract a diff from your changes in master and apply them to the target branch](http://ariejan.net/2009/10/26/how-to-create-and-apply-a-patch-with-git).

First make sure your changes are the only difference between your current branch and master:

```bash
$ git log master..HEAD
```

Then extract the diff:

```bash
$ git format-patch master --stdout > ~/my_changes.patch
```

Switch over to the target branch and apply your changes:

```bash
$ git checkout -b my_backport_branch 3-2-stable
$ git apply ~/my_changes.patch
```

This works well for simple changes. However, if your changes are complicated or if the code in master has deviated significantly from your target branch, it might require more work on your part. The difficulty of a backport varies greatly from case to case, and sometimes it is simply not worth the effort.

Once you have resolved all conflicts and made sure all the tests are passing, push your changes and open a separate pull request for your backport. It is also worth noting that older branches might have a different set of build targets than master. When possible, it is best to first test your backport locally against the Ruby versions listed in `.travis.yml` before submitting your pull request.

And then... think about your next contribution!

Rails Contributors
------------------

All contributions, either via master or docrails, get credit in [Rails Contributors](http://contributors.rubyonrails.org).


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('utama', '0003_peralatan_kondisi_alat'),
    ]

    operations = [
        migrations.AlterField(
            model_name='peralatan',
            name='kondisi_alat',
            field=models.BooleanField(verbose_name='Kondisi Peralatan', default=True),
        ),
    ]


text:
<?php

namespace Mtt\BlogBundle\Entity;

use DateTime;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Table(name="tracking")
 * @ORM\Entity(repositoryClass="Mtt\BlogBundle\Entity\Repository\TrackingRepository")
 */
class Tracking
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var \Mtt\BlogBundle\Entity\Post
     *
     * @ORM\ManyToOne(targetEntity="Post")
     * @ORM\JoinColumn(onDelete="CASCADE")
     */
    protected $post;

    /**
     * @var \Mtt\BlogBundle\Entity\TrackingAgent
     *
     * @ORM\ManyToOne(targetEntity="TrackingAgent", inversedBy="trackings")
     * @ORM\JoinColumn(name="user_agent_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $trackingAgent;

    /**
     * @var string
     *
     * @ORM\Column(name="ip_addr", type="string", length=15, nullable=true)
     */
    protected $ipAddress;

    /**
     * @var DateTime
     *
     * @ORM\Column(type="milliseconds_dt")
     */
    protected $timeCreated;

    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     */
    protected $timestampCreated;

    public function __construct()
    {
        $this->setTimeCreated(new DateTime());
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set ipAddress
     *
     * @param string $ipAddress
     *
     * @return Tracking
     */
    public function setIpAddress($ipAddress)
    {
        $this->ipAddress = $ipAddress;

        return $this;
    }

    /**
     * Get ipAddress
     *
     * @return string
     */
    public function getIpAddress()
    {
        return $this->ipAddress;
    }

    /**
     * Set timeCreated
     *
     * @param DateTime $timeCreated
     *
     * @return Tracking
     */
    public function setTimeCreated(DateTime $timeCreated)
    {
        $this->timeCreated = $timeCreated;
        $this->timestampCreated = (int)$timeCreated->format('U');

        return $this;
    }

    /**
     * Get timeCreated
     *
     * @return DateTime
     */
    public function getTimeCreated()
    {
        return $this->timeCreated;
    }

    /**
     * Set trackingAgent
     *
     * @param TrackingAgent $trackingAgent
     *
     * @return Tracking
     */
    public function setTrackingAgent(TrackingAgent $trackingAgent = null)
    {
        $this->trackingAgent = $trackingAgent;

        return $this;
    }

    /**
     * Get trackingAgent
     *
     * @return TrackingAgent
     */
    public function getTrackingAgent()
    {
        return $this->trackingAgent;
    }

    /**
     * Set post
     *
     * @param Post $post
     *
     * @return Tracking
     */
    public function setPost(Post $post = null)
    {
        $this->post = $post;

        return $this;
    }

    /**
     * Get post
     *
     * @return Post
     */
    public function getPost()
    {
        return $this->post;
    }

    /**
     * Set timestampCreated
     *
     * @param string $timestampCreated
     *
     * @return Tracking
     */
    public function setTimestampCreated($timestampCreated)
    {
        $this->timestampCreated = $timestampCreated;

        return $this;
    }

    /**
     * Get timestampCreated
     *
     * @return string
     */
    public function getTimestampCreated()
    {
        return $this->timestampCreated;
    }
}


text:
<?php

// This file was auto-generated from sdk-root/src/data/application-autoscaling/2016-02-06/smoke.json
return ['version' => 1, 'defaultRegion' => 'us-west-2', 'testCases' => [['operationName' => 'DescribeScalableTargets', 'input' => ['ServiceNamespace' => 'ec2'], 'errorExpectedFromService' => \false]]];


text:
#ifndef __CCSPRITE3D_H__
#define __CCSPRITE3D_H__

#include <vector>

#include "base/CCVector.h"
#include "base/ccTypes.h"
#include "base/CCProtocols.h"
#include "2d/CCNode.h"
#include "renderer/CCMeshCommand.h"

NS_CC_BEGIN

class GLProgramState;
class Mesh;
class Texture2D;

/** Sprite3D: TODO add description */
class Sprite3D : public Node, public BlendProtocol
{
public:
    /// creates a Sprite3D
    static Sprite3D* create(const std::string &modelPath);

    // creates a Sprite3D. It only supports one texture, and overrides the internal texture with 'texturePath'
    static Sprite3D* create(const std::string &modelPath, const std::string &texturePath);

    //set texture
    void setTexture(const std::string& texFile);
    void setTexture(Texture2D* texture);

    Mesh* getMesh() const { return _mesh; }

    // overrides
    virtual void setBlendFunc(const BlendFunc &blendFunc) override;
    virtual const BlendFunc &getBlendFunc() const override;

protected:
    Sprite3D();
    virtual ~Sprite3D();
    bool initWithFile(const std::string &path);

    //.mtl file should at the same directory with the same name if exist
    bool loadFromObj(const std::string& path);

    virtual void draw(Renderer *renderer, const Mat4 &transform, bool transformUpdated) override;

    virtual GLProgram* getDefaultGLProgram(bool textured = true);

    void genGLProgramState();

    Mesh              *_mesh;
    MeshCommand        _meshCommand;
    Texture2D*        _texture;
    BlendFunc _blend;
};

extern std::string s_attributeNames[];

NS_CC_END
#endif // __SPRITE3D_H_


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

using System;
using System.Reflection;
using OpenQA.Selenium.Remote;

namespace OpenQA.Selenium.Support.Extensions
{
    /// <summary>
    /// Provides extension methods for convenience in using WebDriver.
    /// </summary>
    public static class WebDriverExtensions
    {
        /// <summary>
        /// Gets a <see cref="Screenshot"/> object representing the image of the page on the screen.
        /// </summary>
        /// <param name="driver">The driver instance to extend.</param>
        /// <returns>A <see cref="Screenshot"/> object containing the image.</returns>
        /// <exception cref="WebDriverException">Thrown if this <see cref="IWebDriver"/> instance
        /// does not implement <see cref="ITakesScreenshot"/>, or the capabilities of the driver
        /// indicate that it cannot take screenshots.</exception>
        public static Screenshot TakeScreenshot(this IWebDriver driver)
        {
            ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
            if (screenshotDriver == null)
            {
                IHasCapabilities capabilitiesDriver = driver as IHasCapabilities;
                if (capabilitiesDriver == null)
                {
                    throw new WebDriverException("Driver does not implement ITakesScreenshot or IHasCapabilities");
                }

                if (!capabilitiesDriver.Capabilities.HasCapability(CapabilityType.TakesScreenshot) || !(bool)capabilitiesDriver.Capabilities.GetCapability(CapabilityType.TakesScreenshot))
                {
                    throw new WebDriverException("Driver capabilities do not support taking screenshots");
                }

                MethodInfo executeMethod = driver.GetType().GetMethod("Execute", BindingFlags.Instance | BindingFlags.NonPublic);
                Response screenshotResponse = executeMethod.Invoke(driver, new object[] { DriverCommand.Screenshot, null }) as Response;
                if (screenshotResponse == null)
                {
                    throw new WebDriverException("Unexpected failure getting screenshot; response was not in the proper format.");
                }

                string screenshotResult = screenshotResponse.Value.ToString();
                return new Screenshot(screenshotResult);
            }

            return screenshotDriver.GetScreenshot();
        }

        /// <summary>
        /// Executes JavaScript in the context of the currently selected frame or window
        /// </summary>
        /// <typeparam name="T">Expected return type of the JavaScript execution.</typeparam>
        /// <param name="driver">The driver instance to extend.</param>
        /// <param name="script">The JavaScript code to execute.</param>
        /// <param name="args">The arguments to the script.</param>
        /// <returns>The value returned by the script.</returns>
        /// <exception cref="WebDriverException">Thrown if this <see cref="IWebDriver"/> instance
        /// does not implement <see cref="IJavaScriptExecutor"/>, or if the actual return type
        /// of the JavaScript execution does not match the expected type.</exception>
        public static T ExecuteJavaScript<T>(this IWebDriver driver, string script, params object[] args)
        {
            IJavaScriptExecutor executor = driver as IJavaScriptExecutor;
            if (executor == null)
            {
                throw new WebDriverException("Driver does not implement IJavaScriptExecutor");
            }

            Type type = typeof(T);

            var result = default(T);

            object value = executor.ExecuteScript(script, args);
            if (value == null)
            {
                if (type.IsValueType && (Nullable.GetUnderlyingType(type) == null))
                {
                    throw new WebDriverException("Script returned null, but desired type is a value type");
                }
            }
            else if (!type.IsInstanceOfType(value))
            {
                throw new WebDriverException("Script returned a value, but the result could not be cast to the desired type");
            }
            else
            {
                result = (T)value;
            }

            return result;
        }
    }
}


text:
#ifndef TENSORFLOW_STREAM_EXECUTOR_SCRATCH_ALLOCATOR_H_
#define TENSORFLOW_STREAM_EXECUTOR_SCRATCH_ALLOCATOR_H_

#include "tensorflow/compiler/xla/stream_executor/scratch_allocator.h"

#endif  // TENSORFLOW_STREAM_EXECUTOR_SCRATCH_ALLOCATOR_H_


text:
package org.sacredscripture.platform.bible.service;

import org.sacredscripture.platform.bible.Bible;

import org.sacredscripturefoundation.commons.ServiceRequestMessage;

import java.util.Locale;

import javax.validation.constraints.NotNull;

/**
 * This class is the request to create or update a {@link Bible} entity.
 *
 * @author Paul Benedict
 * @see BibleMaintenanceService#save(SaveBibleRequest)
 * @since Sacred Scripture Platform 1.0
 */
public class SaveBibleRequest extends ServiceRequestMessage {

    private String id;
    private String code;
    private Locale locale;
    private boolean rightToLeftReading;
    private String abbreviation;
    private String name;
    private String copyrightNotice;
    private String license;
    private String title;

    @NotNull
    public final String getAbbreviation() {
        return abbreviation;
    }

    @NotNull
    public final String getCode() {
        return code;
    }

    @NotNull
    public final String getCopyrightNotice() {
        return copyrightNotice;
    }

    @NotNull
    public final String getId() {
        return id;
    }

    @NotNull
    public final String getLicense() {
        return license;
    }

    @NotNull
    public final Locale getLocale() {
        return locale;
    }

    @NotNull
    public final String getName() {
        return name;
    }

    @NotNull
    public final String getTitle() {
        return title;
    }

    public final boolean isRightToLeftReading() {
        return rightToLeftReading;
    }

    public final void setAbbreviation(String abbreviation) {
        this.abbreviation = abbreviation;
    }

    public final void setCode(String code) {
        this.code = code;
    }

    public final void setCopyrightNotice(String copyrightNotice) {
        this.copyrightNotice = copyrightNotice;
    }

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

    public final void setLicense(String license) {
        this.license = license;
    }

    public final void setLocale(Locale locale) {
        this.locale = locale;
    }

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

    public final void setRightToLeftReading(boolean rightToLeftReading) {
        this.rightToLeftReading = rightToLeftReading;
    }

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

}