text:
package com.persinity.haka.example.impl;

import static com.persinity.common.StringUtils.format;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

import com.persinity.common.logging.Log4jLogger;
import com.persinity.haka.JobIdentity;
import com.persinity.haka.JobProducer;

/**
 * Processes {@link FileReaderJob} into {@link LineCounterJob}.
 * <p/>
 * When a {@link LineCounterJob} is processed the impl accumulates
 * words count in the parent {@link FileReaderJob}.
 *
 * @author Ivo Yanakiev
 */
public class FileReaderJobProducer implements JobProducer<FileReaderJob, LineCounterJob> {

    @Override
    public Set<LineCounterJob> process(FileReaderJob job) {

        if (job.isProcessed()) {
            log.debug("Skipping file: {} ,it is already processed.", job.getFile());
            return Collections.emptySet();
        }

        File file = job.getFile();
        String absPath = file.getAbsolutePath();

        log.debug("Processing file: {} in {}", absPath, job.getId().toShortString());

        Set<LineCounterJob> result = new HashSet<>();
        int lineNumber = 0;

        try (BufferedReader br = new BufferedReader(new FileReader(file))) {

            for (String line; (line = br.readLine()) != null; ) {

                lineNumber++;
                JobIdentity childId = new JobIdentity(job.getId());
                result.add(new LineCounterJob(childId, line));
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(format("Unable to find file: {}", absPath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        job.setProcessed(true);
        log.debug("Processed file: {}, lines: {}", absPath, lineNumber);
        return result;
    }

    @Override
    public void processed(FileReaderJob parentJob, LineCounterJob childJob) {

        parentJob.aggregate(childJob.getResult());
        log.debug("Aggregated: {} to: {}", childJob.getId().toShortString(), parentJob.getId().toShortString());
    }

    private static final Log4jLogger log = new Log4jLogger(Logger.getLogger(FileReaderJobProducer.class));
}


text:
namespace SnagitJiraOutputAccessory.Commands
{
    using Atlassian.Jira;
    using SnagitJiraOutputAccessory.Models;
    using SnagitJiraOutputAccessory.ViewModels;
    using SnagitJiraOutputAccessory.Views;
    using SNAGITLib;

    public class AttachToNewIssueCommand : ICommand
    {
        private readonly ISnagIt _snagit;
        private OutputPreferencesRepository _outputPreferencesRepo;

        public AttachToNewIssueCommand(ISnagIt snagit, OutputPreferencesRepository outputPreferencesRepo)
        {
            _snagit = snagit;
            _outputPreferencesRepo = outputPreferencesRepo;
        }

        public void Execute()
        {
            var prefs = _outputPreferencesRepo.Read();
            Jira jira = new Jira(prefs.JiraRootUrl, prefs.Username, prefs.Password);

            AttachToNewIssueView view = new AttachToNewIssueView();
            var windowHelper = new System.Windows.Interop.WindowInteropHelper(view);
            windowHelper.Owner = (System.IntPtr)(_snagit.TopLevelHWnd);
            view.DataContext = new AttachToNewIssueViewModel(_snagit, jira, _outputPreferencesRepo);
            view.ShowDialog();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ignite.internal.processors.hadoop.taskexecutor;

/**
* State of the task.
*/
public enum HadoopTaskState {
    /** Running task. */
    RUNNING,

    /** Completed task. */
    COMPLETED,

    /** Failed task. */
    FAILED,

    /** Canceled task. */
    CANCELED,

    /** Process crashed. */
    CRASHED
}


text:
package org.apache.airavata.registry.core.experiment.catalog.model;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Collection;

@Entity
@Table(name = "EXPERIMENT")
public class Experiment {
    private final static Logger logger = LoggerFactory.getLogger(Experiment.class);
    private String experimentId;
    private String projectId;
    private String gatewayId;
    private String experimentType;
    private String userName;
    private String experimentName;
    private Timestamp creationTime;
    private String description;
    private String executionId;
    private String gatewayExecutionId;
    private Boolean enableEmailNotification;
    private String emailAddresses;
    private Users user;
    private Project project;
    private Collection<ExperimentError> experimentErrors;
    private Collection<ExperimentInput> experimentInputs;
    private Collection<ExperimentOutput> experimentOutputs;
    private Collection<ExperimentStatus> experimentStatuses;
    private Collection<Process> processes;
    private UserConfigurationData userConfigurationData;

    @Id
    @Column(name = "EXPERIMENT_ID")
    public String getExperimentId() {
        return experimentId;
    }

    public void setExperimentId(String experimentId) {
        this.experimentId = experimentId;
    }

    @Basic
    @Column(name = "GATEWAY_ID")
    public String getGatewayId() {
        return gatewayId;
    }

    public void setGatewayId(String gatewayId) {
        this.gatewayId = gatewayId;
    }

    @Basic
    @Column(name = "PROJECT_ID")
    public String getProjectId() {
        return projectId;
    }

    public void setProjectId(String projectId) {
        this.projectId = projectId;
    }

    @Basic
    @Column(name = "EXPERIMENT_TYPE")
    public String getExperimentType() {
        return experimentType;
    }

    public void setExperimentType(String experimentType) {
        this.experimentType = experimentType;
    }

    @Basic
    @Column(name = "USER_NAME")
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Basic
    @Column(name = "EXPERIMENT_NAME")
    public String getExperimentName() {
        return experimentName;
    }

    public void setExperimentName(String experimentName) {
        this.experimentName = experimentName;
    }

    @Basic
    @Column(name = "CREATION_TIME")
    public Timestamp getCreationTime() {
        return creationTime;
    }

    public void setCreationTime(Timestamp creationTime) {
        this.creationTime = creationTime;
    }

    @Basic
    @Column(name = "DESCRIPTION")
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Basic
    @Column(name = "EXECUTION_ID")
    public String getExecutionId() {
        return executionId;
    }

    public void setExecutionId(String executionId) {
        this.executionId = executionId;
    }

    @Basic
    @Column(name = "GATEWAY_EXECUTION_ID")
    public String getGatewayExecutionId() {
        return gatewayExecutionId;
    }

    public void setGatewayExecutionId(String gatewayExecutionId) {
        this.gatewayExecutionId = gatewayExecutionId;
    }

    @Basic
    @Column(name = "ENABLE_EMAIL_NOTIFICATION")
    public Boolean getEnableEmailNotification() {
        return enableEmailNotification;
    }

    public void setEnableEmailNotification(Boolean enableEmailNotification) {
        this.enableEmailNotification = enableEmailNotification;
    }

    @Basic
    @Lob
    @Column(name = "EMAIL_ADDRESSES")
    public String getEmailAddresses() {
        return emailAddresses;
    }

    public void setEmailAddresses(String emailAddresses) {
        this.emailAddresses = emailAddresses;
    }

//    @Override
//    public boolean equals(Object o) {
//        if (this == o) return true;
//        if (o == null || getClass() != o.getClass()) return false;
//
//        Experiment that = (Experiment) o;
//
//        if (creationTime != null ? !creationTime.equals(that.creationTime) : that.creationTime != null) return false;
//        if (description != null ? !description.equals(that.description) : that.description != null) return false;
//        if (emailAddresses != null ? !emailAddresses.equals(that.emailAddresses) : that.emailAddresses != null)
//            return false;
//        if (enableEmailNotification != null ? !enableEmailNotification.equals(that.enableEmailNotification) : that.enableEmailNotification != null)
//            return false;
//        if (executionId != null ? !executionId.equals(that.executionId) : that.executionId != null) return false;
//        if (experimentId != null ? !experimentId.equals(that.experimentId) : that.experimentId != null) return false;
//        if (experimentName != null ? !experimentName.equals(that.experimentName) : that.experimentName != null)
//            return false;
//        if (experimentType != null ? !experimentType.equals(that.experimentType) : that.experimentType != null)
//            return false;
//        if (gatewayExecutionId != null ? !gatewayExecutionId.equals(that.gatewayExecutionId) : that.gatewayExecutionId != null)
//            return false;
//        if (projectId != null ? !projectId.equals(that.projectId) : that.projectId != null) return false;
//        if (gatewayId != null ? !gatewayId.equals(that.gatewayId) : that.gatewayId != null) return false;
//        if (userName != null ? !userName.equals(that.userName) : that.userName != null) return false;
//
//        return true;
//    }
//
//    @Override
//    public int hashCode() {
//        int result = experimentId != null ? experimentId.hashCode() : 0;
//        result = 31 * result + (projectId != null ? projectId.hashCode() : 0);
//        result = 31 * result + (gatewayId != null ? gatewayId.hashCode() : 0);
//        result = 31 * result + (experimentType != null ? experimentType.hashCode() : 0);
//        result = 31 * result + (userName != null ? userName.hashCode() : 0);
//        result = 31 * result + (experimentName != null ? experimentName.hashCode() : 0);
//        result = 31 * result + (creationTime != null ? creationTime.hashCode() : 0);
//        result = 31 * result + (description != null ? description.hashCode() : 0);
//        result = 31 * result + (executionId != null ? executionId.hashCode() : 0);
//        result = 31 * result + (gatewayExecutionId != null ? gatewayExecutionId.hashCode() : 0);
//        result = 31 * result + (enableEmailNotification != null ? enableEmailNotification.hashCode() : 0);
//        result = 31 * result + (emailAddresses != null ? emailAddresses.hashCode() : 0);
//        return result;
//    }

    @ManyToOne
    @JoinColumn(name = "USER_NAME", referencedColumnName = "USER_NAME", nullable = false)
    public Users getUser() {
        return user;
    }

    public void setUser(Users userByUserName) {
        this.user = userByUserName;
    }

    @ManyToOne
    @JoinColumn(name = "PROJECT_ID", referencedColumnName = "PROJECT_ID", nullable = false)
    public Project getProject() {
        return project;
    }

    public void setProject(Project projectByProjectId) {
        this.project = projectByProjectId;
    }

    @OneToMany(mappedBy = "experiment")
    public Collection<ExperimentError> getExperimentErrors() {
        return experimentErrors;
    }

    public void setExperimentErrors(Collection<ExperimentError> experimentErrorsByExperimentId) {
        this.experimentErrors = experimentErrorsByExperimentId;
    }

    @OneToMany(mappedBy = "experiment")
    public Collection<ExperimentInput> getExperimentInputs() {
        return experimentInputs;
    }

    public void setExperimentInputs(Collection<ExperimentInput> experimentInputsByExperimentId) {
        this.experimentInputs = experimentInputsByExperimentId;
    }

    @OneToMany(mappedBy = "experiment")
    public Collection<ExperimentOutput> getExperimentOutputs() {
        return experimentOutputs;
    }

    public void setExperimentOutputs(Collection<ExperimentOutput> experimentOutputsByExperimentId) {
        this.experimentOutputs = experimentOutputsByExperimentId;
    }

    @OneToMany(mappedBy = "experiment")
    public Collection<ExperimentStatus> getExperimentStatuses() {
        return experimentStatuses;
    }

    public void setExperimentStatuses(Collection<ExperimentStatus> experimentStatusesByExperimentId) {
        this.experimentStatuses = experimentStatusesByExperimentId;
    }

    @OneToMany(mappedBy = "experiment")
    public Collection<Process> getProcesses() {
        return processes;
    }

    public void setProcesses(Collection<Process> processesesByExperimentId) {
        this.processes = processesesByExperimentId;
    }

    @OneToOne(mappedBy = "experiment")
    public UserConfigurationData getUserConfigurationData() {
        return userConfigurationData;
    }

    public void setUserConfigurationData(UserConfigurationData userConfigurationDataByExperimentId) {
        this.userConfigurationData = userConfigurationDataByExperimentId;
    }
}


text:
package com.pedromassango.programmers.server;

import android.content.Context;
import android.support.annotation.NonNull;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;
import com.pedromassango.programmers.extras.Util;
import com.pedromassango.programmers.interfaces.Callbacks;
import com.pedromassango.programmers.interfaces.IPresenceLIstener;
import com.pedromassango.programmers.models.Post;

import static com.pedromassango.programmers.extras.Util.showLog;

/**
 * Created by Pedro Massango on 06/06/2017 at 02:19.
 */

/**
 * This class is responsable to do Any operation in server
 * that will be called more than one.
 */
public class Worker {
    public static void handleUserPresence(String userId, final IPresenceLIstener presenceLIstener) {

        final DatabaseReference userChatRef = Library.getAllUsersChatsRef().child(userId);
        final DatabaseReference onlineRef = userChatRef.child("online");
        final DatabaseReference lastOnlineRef = userChatRef.child("lastOnline");

        lastOnlineRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                long timestamp;
                String lastOnline;

                if (dataSnapshot == null) {
                    timestamp = System.currentTimeMillis();
                    lastOnline = Util.getTimeAgo(timestamp);
                    presenceLIstener.onFriendOffline(lastOnline);
                    return;
                }

                timestamp = dataSnapshot.getValue(Long.class);
                lastOnline = Util.getTimeAgo(timestamp);
                presenceLIstener.onFriendOffline(lastOnline);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        onlineRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot == null) {
                    presenceLIstener.onFriendOnline(false);
                    return;
                }

                presenceLIstener.onFriendOnline(dataSnapshot.getValue(Boolean.class));
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

                showLog("FRIEND Presence Listener was disconnected");
            }
        });
    }

    public static void sendCurrentUserFCMToken(final Context context) {

//        // Current user id
//        String userId = PrefsUtil.getId(context);
//
//        // Getting FcmToken from PrefsUtil
//        final FcmToken fcmToken = PrefsUtil.getFCMToken(context);
//        String token = FirebaseInstanceId.getInstance().getToken();
//
//        if (fcmToken.getToken() == null || fcmToken.getToken().isEmpty()) {
//            showLog("FCM TOKEN: getting token manualy");
//
//            fcmToken.setToken(token);
//        }
//
//        // If NULL, we are not connected
//        // So we do not need to continue
//        if (userId == null || userId.isEmpty()) {
//            showLog("FCM TOKEN no user found");
//            return;
//        }
//
//        if (!fcmToken.isSaved()) {
//            showLog("FCM TOKEN have not seved");
//            return;
//        }
//
//        if (fcmToken.isSent()) {
//            showLog("FCM TOKEN arleady sent");
//            return;
//        }
//
//        // Sending the current token on server
//        Library.getCurrentUserRef()
//                .child("fcmToken")
//                .setValue(fcmToken.getToken())
//                .addOnFailureListener(new OnFailureListener() {
//                    @Override
//                    public void onFailure(@NonNull Exception e) {
//
//                        fcmToken.setSent(false);
//                        PrefsUtil.saveFCMToken(context, fcmToken);
//                        showLog("ERROR IN UPDATE TOKEN ON SERVER");
//
//                    }
//                })
//                .addOnSuccessListener(new OnSuccessListener<Void>() {
//                    @Override
//                    public void onSuccess(Void aVoid) {
//
//                        fcmToken.setSent(true);
//                        PrefsUtil.saveFCMToken(context, fcmToken);
//                        showLog("TOKEN UPDATED ON SERVER");
//                    }
//                });
    }

    public static void sendEmailVerification(final Callbacks.IRequestCallback callback, final String email) {

        FirebaseAuth auth = Library.getFirebaseAuth();

        auth.sendPasswordResetEmail(email)
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        callback.onError();
                    }
                })
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {

                        callback.onSuccess();
                    }
                });
    }

    public static void runPostViewsCountTransition(DatabaseReference postRef) {
        postRef.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
                Post post = mutableData.getValue(Post.class);
                if (post == null) {
                    return Transaction.success(mutableData);
                }

                int viewsCount = post.getViews() + 1;

                post.setViews(viewsCount);
                mutableData.setValue(post);
                return Transaction.success(mutableData);
            }

            @Override
            public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
                showLog("runCommentsCountTransition " + (databaseError != null));

                        /* if (databaseError == null) {
                            errorListener.onError();
                        }*/
            }
        });
    }
}


text:
import os
import sys
import unittest
from nose.plugins.isolate import IsolationPlugin
from nose.plugins import PluginTester

support = os.path.join(os.path.dirname(__file__), 'support')

class TestDiscovery(PluginTester, unittest.TestCase):
    activate = '--with-isolation'
    args = ['-v']
    plugins = [IsolationPlugin()]
    suitepath = os.path.join(support, 'ipt')

    def runTest(self):
        print str(self.output)

        for line in self.output:
            if not line.strip():
                continue
            if line.startswith('-'):
                break
            assert line.strip().endswith('ok'), \
                   "Failed test: %s" % line.strip()

class TestLoadFromNames(PluginTester, unittest.TestCase):
    activate = '--with-isolation'
    args = ['-v', 'test1/tests.py', 'test2/tests.py']
    plugins = [IsolationPlugin()]
    suitepath = None

    def setUp(self):
        self._dir = os.getcwd()
        os.chdir(os.path.join(support, 'ipt'))
        super(TestLoadFromNames, self).setUp()

    def tearDown(self):
        os.chdir(self._dir)
        super(TestLoadFromNames, self).tearDown()

    def makeSuite(self):
        return None

    def runTest(self):
        print str(self.output)

        for line in self.output:
            if not line.strip():
                continue
            if line.startswith('-'):
                break
            assert line.strip().endswith('ok'), \
                   "Failed test: %s" % line.strip()

if __name__ == '__main__':
    unittest.main()


text:
module Spree
  module Core
    module UserBanners
      def self.included(base)
        base.preference :dismissed_banners, :string, :default => ''
      end

      def dismissed_banner_ids
        dismissed = self.preferred_dismissed_banners
        dismissed.split(',').map(&:to_sym)
      end

      def dismiss_banner(banner_id)
        self.preferred_dismissed_banners = dismissed_banner_ids.push(banner_id.to_sym).uniq.join(',')
      end

      def dismissed_banner?(banner_id)
        dismissed_banner_ids.include? banner_id.to_sym
      end
    end
  end
end


text:
package org.wso2.identity.integration.test.utils;

/**
 * OAuth2 constant
 */
public final class OAuth2Constant {

    public static final String OAUTH2_GRANT_TYPE_IMPLICIT = "token";
    public static final String OAUTH2_GRANT_TYPE_CODE = "code";
    public static final String OAUTH2_GRANT_TYPE_CLIENT_CREDENTIALS = "client_credentials";
    public static final String OAUTH2_GRANT_TYPE_RESOURCE_OWNER = "password";

    public static final String OAUTH2_GRANT_TYPE_AUTHORIZATION_CODE = "authorization_code";
    public static final String AUTHORIZATION_HEADER = "Authorization";

    public final static String ACCESS_TOKEN = "access_token";
    public final static String ACCESS_TOKEN_TYPE = "bearer";
    public final static String OAUTH_VERSION_2 = "OAuth-2.0";
    public final static String REDIRECT_LOCATIONS = "http.protocol.redirect-locations";
    public final static String ACCESS_TOKEN_ENDPOINT = "https://localhost:9853/oauth2/token";
    public final static String USER_INFO_ENDPOINT = "https://localhost:9853/oauth2/userinfo?schema=openid";
    public final static String AUTHTOKEN_VALIDATE_SERVICE = CommonConstants.DEFAULT_SERVICE_URL + "OAuth2TokenValidationService";
    public final static String COMMON_AUTH_URL = "https://localhost:9853/commonauth";
    public final static String USER_AGENT = "Apache-HttpClient/4.2.5 (java 1.6)";
    public final static String APPROVAL_URL = "https://localhost:9853/oauth2/authorize";
    public final static String AUTHORIZE_PARAM = "Authorize";
    public final static String TOKEN_VALIDATION_SERVICE_URL = CommonConstants.DEFAULT_SERVICE_URL + "OAuth2TokenValidationService";
    public final static String HTTP_RESPONSE_HEADER_LOCATION = "location";
    public final static String OAUTH2_SCOPE_OPENID = "openid";
    public final static String OAUTH2_SCOPE_DEFAULT = "";
    public final static String OAUTH_APPLICATION_NAME = "oauthTestApplication";
    public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type";

    public final static String CALLBACK_URL = "http://localhost:8490/playground2/oauth2client";
    public final static String AUTHORIZED_USER_URL = "http://localhost:8490/playground2/oauth2-authorize-user.jsp";
    public final static String AUTHORIZED_URL = "http://localhost:8490/playground2/oauth2.jsp";
    public final static String GET_ACCESS_TOKEN_URL = "http://localhost:8490/playground2/oauth2-get-access-token.jsp";
    public final static String ACCESS_RESOURCES_URL = "http://localhost:8490/playground2/oauth2-access-resource.jsp";
    public final static String PLAYGROUND_APP_CONTEXT_ROOT = "/playground2";
    public static final String GRANT_TYPE_PLAYGROUND_NAME = "grantType";
    public static final String CONSUMER_KEY_PLAYGROUND_NAME = "consumerKey";
    public static final String CALLBACKURL_PLAYGROUND_NAME = "callbackurl";
    public static final String AUTHORIZE_ENDPOINT_PLAYGROUND_NAME = "authorizeEndpoint";
    public static final String AUTHORIZE_PLAYGROUND_NAME = "authorize";
    public static final String SCOPE_PLAYGROUND_NAME = "scope";

    public final static String WSO2_CLAIM_DIALECT_ROLE="http://wso2.org/claims/role";
    public static final String GRANT_TYPE_NAME = "grant_type";
    public static final String AUTHORIZATION_CODE_NAME = "code";
    public static final String REDIRECT_URI_NAME = "redirect_uri";
    public static final String BASIC_HEADER = "Basic";
    public static final String INVALID_GRANT_ERROR = "invalid_grant";
    public static final String SESSION_DATA_KEY_CONSENT = "sessionDataKeyConsent";

    private OAuth2Constant() {
	}
}


text:
package la.alsocan.jsonshapeshifter.transformations;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Iterator;
import la.alsocan.jsonshapeshifter.DataSet;
import la.alsocan.jsonshapeshifter.Transformation;
import la.alsocan.jsonshapeshifter.bindings.ArrayConstantBinding;
import la.alsocan.jsonshapeshifter.schemas.Schema;
import la.alsocan.jsonshapeshifter.schemas.SchemaNode;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import org.junit.Test;

/**
 * @author Florian Poulin - https://github.com/fpoulin
 */
public class TypesTransformationsTest {

	public static final Boolean DEFAULT_BOOLEAN = false;
	public static final Integer DEFAULT_INTEGER = 0;
	public static final Number DEFAULT_NUMBER = 0.0;
	public static final String DEFAULT_STRING = "?";

	@Test
	public void transformationShouldProduceDefaultsForAllTypes() throws IOException {

		Schema source = Schema.buildSchema(new ObjectMapper().readTree(DataSet.ALL_TYPES_SCHEMA));
		Schema target = Schema.buildSchema(new ObjectMapper().readTree(DataSet.ALL_TYPES_SCHEMA));
		Transformation t = new Transformation(source, target);

		Iterator<SchemaNode> it = t.toBind();
		t.bind(it.next(), new ArrayConstantBinding(1));

		JsonNode result = t.apply(null);

		JsonNode node = result.at("/someArray/0/someBoolean");
		assertThat(node, is(not(nullValue())));
		assertThat(node.asBoolean(), is(equalTo(DEFAULT_BOOLEAN)));

		node = result.at("/someArray/0/someInteger");
		assertThat(node, is(not(nullValue())));
		assertThat(node.asInt(), is(equalTo(DEFAULT_INTEGER)));

		node = result.at("/someArray/0/someNumber");
		assertThat(node, is(not(nullValue())));
		assertThat(node.numberValue(), is(equalTo(DEFAULT_NUMBER)));

		node = result.at("/someArray/0/someNull");
		assertThat(node, is(not(nullValue())));
		assertThat(node.isNull(), is(equalTo(true)));

		node = result.at("/someArray/0/someString");
		assertThat(node, is(not(nullValue())));
		assertThat(node.asText(), is(equalTo(DEFAULT_STRING)));
	}
}


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
namespace ITCC.Geocoding.Yandex
{
    public struct GeoBound
    {
        public GeoPoint LowerCorner;
        public GeoPoint UpperCorner;
        public GeoBound(GeoPoint lowerCorner, GeoPoint upperCorner)
        {
            LowerCorner = lowerCorner;
            UpperCorner = upperCorner;
        }

        public override string ToString() => $"[{LowerCorner}] [{UpperCorner}]";
    }
}


text:
module Norm
  module SQL
    class Insert < Statement

      def initialize(*args)
        @withs     = WithClause.new
        @insert    = InsertClause.new
        @values    = ValuesClause.new
        @returning = ReturningClause.new
        insert!(*args) unless args.empty?
      end

      def initialize_copy(orig)
        @withs     = @withs.dup
        @insert    = @insert.dup
        @values    = @values.dup
        @returning = @returning.dup
        @sql       = nil
        @params    = nil
      end

      def sql
        return @sql if @sql
        compile!
        @sql
      end

      def params
        return @params if @params
        compile!
        @params
      end

      def with(*args, **opts)
        dup.with!(*args, **opts)
      end

      def with!(*args, recursive: false, **opts)
        @withs << CTE.new(*args, **opts)
        @withs.recursive! if recursive
        self
      end

      def insert(*args)
        dup.insert!(*args)
      end

      def insert!(table_name, column_names = [])
        column_names = Array(column_names)
        if column_names.empty?
          @insert.value = Fragment.new(Attribute::Identifier(table_name))
        else
          table, *cols = [table_name, *column_names].map { |name|
            Attribute::Identifier(name)
          }
          @insert.value = Fragment.new("#{table} (#{cols.join(', ')})")
        end
        self
      end

      def insert_sql(*args)
        dup.insert_sql!(*args)
      end

      def insert_sql!(*args)
        @insert.value = Fragment.new(*args)
        self
      end

      def values(*args)
        dup.values!(*args)
      end

      def values!(*args)
        @values << Fragment.new((['$?'] * args.size).join(', '), *args)
        self
      end

      def values_sql(*args)
        dup.values_sql!(*args)
      end

      def values_sql!(*args)
        @values << Fragment.new(*args)
        self
      end

      def returning(*args)
        dup.returning!(*args)
      end

      def returning!(*args)
        @returning.value = Fragment.new(*args)
        self
      end

      private

      def clauses
        [@withs, @insert, @values, @returning]
      end

    end
  end
end


text:
package com.example.calculator;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for multiply complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="multiply">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="arg0" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="arg1" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "multiply", propOrder = {
    "arg0",
    "arg1"
})
public class Multiply {

    protected int arg0;
    protected int arg1;

    /**
     * Gets the value of the arg0 property.
     *
     */
    public int getArg0() {
        return arg0;
    }

    /**
     * Sets the value of the arg0 property.
     *
     */
    public void setArg0(int value) {
        this.arg0 = value;
    }

    /**
     * Gets the value of the arg1 property.
     *
     */
    public int getArg1() {
        return arg1;
    }

    /**
     * Sets the value of the arg1 property.
     *
     */
    public void setArg1(int value) {
        this.arg1 = value;
    }

}


text:
desc 'dogestry' do
  latest = github('dogestry', 'dogestry').first
  version = latest.tag_name.gsub(/^v/, '')
  latest.assets.select! { |e| e.name.match(/darwin/) }
  url = latest.assets.first.browser_download_url
  Latest.new version: version, url: url
end


text:
package org.hibernate.validator.test.internal.engine.groups.defaultgroupsequenceprovider;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.GroupDefinitionException;
import javax.validation.Validator;
import javax.validation.constraints.NotNull;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.group.GroupSequenceProvider;
import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider;

import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertCorrectConstraintViolationMessages;
import static org.hibernate.validator.testutil.ConstraintViolationAssert.assertNumberOfViolations;
import static org.hibernate.validator.testutil.ValidatorUtil.getValidator;

/**
 * @author Kevin Pollet <kevin.pollet@serli.com> (C) 2011 SERLI
 */
public class DefaultGroupSequenceProviderTest {

	private static Validator validator;

	@BeforeClass
	public static void init() {
		validator = getValidator();
	}

	@Test(
			expectedExceptions = GroupDefinitionException.class,
			expectedExceptionsMessageRegExp = ".* must be part of the redefined default group sequence."
	)
	public void testNullProviderDefaultGroupSequence() {
		validator.validate( new A() );
	}

	@Test(
			expectedExceptions = GroupDefinitionException.class,
			expectedExceptionsMessageRegExp = ".* must be part of the redefined default group sequence."
	)
	public void testNotValidProviderDefaultGroupSequenceDefinition() {
		validator.validate( new B() );
	}

	@Test(
			expectedExceptions = GroupDefinitionException.class,
			expectedExceptionsMessageRegExp = "HV[0-9]*: The default group sequence provider defined for .* has the wrong type"
	)
	public void testDefinitionOfDefaultGroupSequenceProviderWithWrongType() {
		validator.validate( new D() );
	}

	@Test
	public void testValidateUserProviderDefaultGroupSequence() {
		User user = new User( "$password" );
		Set<ConstraintViolation<User>> violations = validator.validate( user );

		assertNumberOfViolations( violations, 1 );
		assertCorrectConstraintViolationMessages( violations, "must match \"\\w+\"" );

		User admin = new User( "short", true );
		violations = validator.validate( admin );

		assertNumberOfViolations( violations, 1 );
		assertCorrectConstraintViolationMessages( violations, "length must be between 10 and 20" );
	}

	@Test
	public void testValidatePropertyUserProviderDefaultGroupSequence() {
		User user = new User( "$password" );
		Set<ConstraintViolation<User>> violations = validator.validateProperty( user, "password" );

		assertNumberOfViolations( violations, 1 );
		assertCorrectConstraintViolationMessages( violations, "must match \"\\w+\"" );

		User admin = new User( "short", true );
		violations = validator.validateProperty( admin, "password" );

		assertNumberOfViolations( violations, 1 );
		assertCorrectConstraintViolationMessages( violations, "length must be between 10 and 20" );
	}

	@Test
	public void testValidateValueUserProviderDefaultGroupSequence() {
		Set<ConstraintViolation<User>> violations = validator.validateValue(
				User.class, "password", "$password"
		);

		assertNumberOfViolations( violations, 1 );
		assertCorrectConstraintViolationMessages( violations, "must match \"\\w+\"" );
	}

	@Test
	public void testValidateReturnValueProviderDefaultGroupSequence() throws NoSuchMethodException {
		C c = new CImpl();
		Method fooMethod = C.class.getDeclaredMethod( "foo", String.class );

		Set<ConstraintViolation<C>> violations = validator.forExecutables().validateReturnValue(
				c, fooMethod, c.foo( null )
		);
		assertNumberOfViolations( violations, 1 );
		assertCorrectConstraintViolationMessages( violations, "may not be null" );

		violations = validator.forExecutables().validateReturnValue( c, fooMethod, c.foo( "foo" ) );
		assertNumberOfViolations( violations, 1 );
		assertCorrectConstraintViolationMessages( violations, "length must be between 10 and 20" );
	}

	@GroupSequenceProvider(NullGroupSequenceProvider.class)
	private static class A {
		@NotNull
		String c;

		@NotNull(groups = TestGroup.class)
		String d;
	}

	@GroupSequenceProvider(InvalidGroupSequenceProvider.class)
	private static class B {
	}

	private interface C {

		@NotNull(message = "may not be null")
		@Length(min = 10, max = 20, groups = TestGroup.class, message = "length must be between {min} and {max}")
		String foo(String param);
	}

	@GroupSequenceProvider(MethodGroupSequenceProvider.class)
	private static class CImpl implements C {

		@Override
		public String foo(String param) {
			return param;
		}
	}

	@GroupSequenceProvider(NullGroupSequenceProvider.class)
	private static class D {
	}

	private interface TestGroup {
	}

	public static class MethodGroupSequenceProvider implements DefaultGroupSequenceProvider<CImpl> {

		@Override
		public List<Class<?>> getValidationGroups(CImpl object) {
			return Arrays.<Class<?>>asList( TestGroup.class, CImpl.class );
		}
	}

	public static class NullGroupSequenceProvider implements DefaultGroupSequenceProvider<A> {

		@Override
		public List<Class<?>> getValidationGroups(A object) {
			return null;
		}
	}

	public static class InvalidGroupSequenceProvider implements DefaultGroupSequenceProvider<B> {

		@Override
		public List<Class<?>> getValidationGroups(B object) {
			List<Class<?>> defaultGroupSequence = new ArrayList<Class<?>>();
			defaultGroupSequence.add( TestGroup.class );

			return defaultGroupSequence;
		}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Magazine Template</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />

< Magazine />

REPORTING & ESSAYS

ARTS & CULTURE

HUMOR

FICTION & POETRY

THE TALK OF THE TOWN

ONLINE ONLY

SUBSCRIBE

ABOUT US

ARCHIVE

VIEDO

       What is Lorem Ipsum?
       September 1, 2009 | (0) Comments

What We Speak.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

There are many variations of passages of Lorem Ipsum available:

If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet.

It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable.

What is Lorem Ipsum?

Why Do We Use It?

Where Does It Come From?

Where Can I Get Some?

There are many variations of passages of Lorem Ipsum available

Alteration In Some Form

If you are going to use a passage

You Need To Be Sure There

The generated Lorem Ipsum is

Blogroll

Category One

There are many

Lorem Ipsum available

If you are going

All the Lorem Ipsum

200 Latin words

It uses a dictionary

Lorem ipsum dolor

Latin professor at

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
 dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
 proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Neque porro quisquam?

Lorem Ipsum is simply dummy text of the printing

It is a long established fact that a reader

There are many variations of passages of Lorem Ipsum

Contrary to popular belief, Lorem Ipsum is not simply random text

Where Does It Come From?

Contrary to popular belief, Lorem Ipsum is not
 simply random text.

It is a long established fact that a reader will be distracted by the
readable content of a page when looking at its layout.

Lorem Ipsum passages

more recently with desktop publishing

Name*:<input name="Name" type="text" class="footerInputArea" />

Email*:<input name="Email" type="text" class="footerInputArea" />

Phone Number:<input name="Number" type="text" class="footerInputArea" />

Message: <textarea name="" class="footertextarea" rows="2" cols="3"></textarea>

        <input name="" type="button" class="footerSubmit" />

All the Lorem Ipsum generators on the
 Internet tend to repeat predefined chunks as
 necessary, making this the first true generator
 on the Internet. It uses a dictionary of over
 200 Latin words, combined with a handful of
 model sentence structures, to generate Lorem
 Ipsum which looks reasonable. The generated
 Lorem Ipsum is therefore always free from
 repetition, injected humour, or
 non-characteristic words etc.

	 Designed by VectorArt
	 Copyright 2009 Lorem Ipsum. All Rights Reserved


text:
set -eux

SCRIPT_DIR="$(cd "$(dirname -- "${BASH_SOURCE[0]}")" >/dev/null && pwd)"
source "$SCRIPT_DIR/commands.sh"

echo "Installing version: $NODE_VERSION -- arch: $NODE_ARCH";

nvm_load
nvm install $NODE_VERSION $NODE_ARCH


text:
package com.google.cloud.tools.eclipse.appengine.deploy.ui;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class Messages {
  private static final String BUNDLE_NAME =
      "com.google.cloud.tools.eclipse.appengine.deploy.ui.messages"; //$NON-NLS-1$

  private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);

  private Messages() {
  }

  public static String getString(String key, Object... params) {
    try {
      return MessageFormat.format(RESOURCE_BUNDLE.getString(key), params);
    } catch (MissingResourceException ex) {
      return '!' + key + '!';
    }
  }
}


text:
<?php

require('soap_config.php');

$client = new SoapClient(null, array('location' => $soap_location,
                                     'uri'      => $soap_uri,
									 'trace' => 1,
									 'exceptions' => 1));

try {
	if($session_id = $client->login($username,$password)) {
		echo 'Logged successfull. Session ID:'.$session_id.'
';
	}

	//* Parameters
	$filter_id = 1;
	$client_id = 1;

	//* Get the email filter record
	$mail_filter_record = $client->mail_filter_get($session_id, $filter_id);

	//* Change the status to inactive
	$mail_filter_record['active'] = 'n';

	$affected_rows = $client->mail_filter_update($session_id, $client_id, $filter_id, $mail_filter_record);

	echo "Number of records that have been changed in the database: ".$affected_rows."
";

	if($client->logout($session_id)) {
		echo 'Logged out.
';
	}

} catch (SoapFault $e) {
	echo $client->__getLastResponse();
	die('SOAP Error: '.$e->getMessage());
}

?>


text:
require 'spec_helper'

describe Withdrawal do
  subject { build(:withdrawal) }

  it { is_expected.to be_valid }
  it { is_expected.to validate_presence_of(:plan_id) }
  it { is_expected.to validate_presence_of(:user_id) }
  it { is_expected.to validate_presence_of(:amount) }
end

describe Withdrawal, 'prolongation' do
  it { is_expected.to have_many :withdrawal_prolongations }

  describe '#prolongation_days' do
    subject { create(:withdrawal) }

    context 'prolongated' do
      before { create_list(:withdrawal_prolongation, 2, days_number: 1, withdrawal: subject) }

      it 'returns sum of prolongation days' do
        expect(subject.prolongation_days).to eq 2
      end
    end

    context 'no prolongation' do
      it 'returns zero' do
        expect(subject.prolongation_days).to eq 0
      end
    end
  end
end

describe Withdrawal, 'user balance decreases' do
  let(:user) { create(:user_with_balance) }
  let(:plan) { create(:plan) }
  let(:amount) { 1 }

  it 'decreases users balance on create' do
    balance_before = user.balance
    create(:withdrawal, user: user, plan: plan, amount: 1)
    expect(user.reload.balance).to eq(balance_before - amount)
  end

  context 'user has not enough funds' do
    let(:user) { create(:user) }

    it 'does not decrease balance' do
      expect { create(:withdrawal, user: user, plan: plan) }.to raise_error ActiveRecord::RecordInvalid
    end
  end
end

# == Schema Information
#
# Table name: withdrawals
#
#  id         :integer          not null, primary key
#  amount     :decimal(, )
#  user_id    :integer
#  plan_id    :integer
#  created_at :datetime
#  updated_at :datetime
#


text:
layout: page
title: Notes
permalink: /notes.html
---

A collection of useful notes on development environment configurations and other findings.

* [Ubuntu Desktop Setup Tips](#ubuntu-desktop-setup-tips)
* [Gradle Plugins](#gradle-plugins)
* [SBT Plugins](#sbt-plugins)

---

### Ubuntu Desktop Setup Tips

The following is a collection of resources (e.g. packages, PPAs, themes) I'm using in my Ubuntu desktop:

#### General

* [Apple Keyboard Fn switch](https://superuser.com/a/223471) - Switch `Fn` key function in Ubuntu for use with Mac keyboards (`echo 2 | sudo tee /sys/module/hid_apple/parameters/fnmode`).
* [emoji-keyboard](https://github.com/OzymandiasTheGreat/emoji-keyboard) - Emoji support via virtual keyboard.
* [rtl8192cu-fixes](https://github.com/pvaret/rtl8192cu-fixes) - Repackaged Realtek 8192CU USB WiFi driver.

#### Developer Tools

* [asdf](https://github.com/asdf-vm/asdf) - Extendable version control manager for Erlang, Elixir, Elm, etc.
* [bat](https://github.com/sharkdp/bat) - Better `cat`.
* [docker](https://docs.docker.com/) - Container (virtualization) engine.
  * Install instructions: <https://linuxconfig.org/how-to-install-docker-on-ubuntu-20-04-lts-focal-fossa>
* [docker-compose](https://docs.docker.com/compose/) - Single-machine container orchestration.
  * Install instructions: <https://linuxconfig.org/how-to-install-docker-compose-on-ubuntu-20-04-focal-fossa-linux>
* [fd](https://github.com/sharkdp/fd) - Better `find`.
* [Fira Code](https://github.com/tonsky/FiraCode) - Monospaced font for coding with ligature support.
* [nvm](https://github.com/nvm-sh/nvm) - Install and manage multiple versions of Nodejs.
* [Ruby package](https://www.brightbox.com/docs/ruby/ubuntu/) - Use 3rd party Ruby repository to get the latest version, including dev packages and version switch utility.
* [SDKMAN](https://sdkman.io/) - Install and manage multiple versions of Java SDKs and build tools.

#### Productivity Tools

* [Joplin](https://joplinapp.org/) - Note-taking tool with sync capabilities.
* [Remmina](https://remmina.org/) - RDP client for Linux.

#### OS Tools

* [cpufreq](https://extensions.gnome.org/extension/1082/cpufreq/) - CPU monitor and power management tool.
  * Remove `irqbalance` if required: `sudo apt-get remove irqbalance`
* [f.lux](https://justgetflux.com/) - Adapt computer monitor glow by time of day.
* [psensor](http://wpitchoune.net/psensor/) - Show system temperature in toolbar.
* [Stacer](https://github.com/oguzhaninan/Stacer) - Linux system optimiser and monitoring.
* [system-monitor](https://extensions.gnome.org/extension/120/system-monitor/) - Show system resource usages (e.g. CPU, memory, network) in toolbar.
  * `Clutter` install command if required: `apt install gir1.2-clutter-1.0`
* [tilix](https://gnunn1.github.io/tilix-web/) - Tiling terminal emulator.

#### Shell Customisation

* [Bashstrap](https://github.com/barryclark/bashstrap) - Theme and aliases for OSX bash.
* [Oh My Zsh](https://ohmyz.sh/) - Zsh terminal customisations.
* [Powerline for Agnoster](https://blog.zhaytam.com/2019/04/19/powerline-and-zshs-agnoster-theme-in-vs-code/) - Fix Powerline fonts for ZSH Agnoster theme.
* [Starship.rs](https://starship.rs/) - Cross-shell shell customisations.

#### Theming (20.04)

* [Gnome Shell Extension](http://ubuntuhandbook.org/index.php/2017/05/enable-shell-theme-in-gnome-tweak-tool-in-ubuntu/) - Enable Gnome user-shell extension for Gnome Tweak tool.
* [Sushi](https://github.com/GNOME/sushi) - Smart file previews.
* [Yaru Dark VLC](https://gitlab.com/NovaQC/vlc-yaru-dark/) - Ubuntu's Yaru Dark VLC theme.
* Change dock 'on click' behaviour:
  * View options: `gsettings range org.gnome.shell.extensions.dash-to-dock click-action`
  * Set value (e.g. preview): `gsettings set org.gnome.shell.extensions.dash-to-dock click-action 'previews'`
* Remove mounted drives on dock `gsettings set org.gnome.shell.extensions.dash-to-dock show-mounts false`

#### Theming (18.04)

* [Adapta](https://github.com/adapta-project/adapta-gtk-theme) - Google Material design theme.
* [Flatpak](https://flatpak.org/setup/Ubuntu/) - Cross-distro Linux application distribution platform.
* [Gnome Shell Extension](http://ubuntuhandbook.org/index.php/2017/05/enable-shell-theme-in-gnome-tweak-tool-in-ubuntu/) - Enable Gnome user-shell extension for Gnome Tweak tool.
* [Papirus - Icons](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) - Flat icons with Adapta theme.
* Change dock 'on click' behaviour:
  * View options: `gsettings range org.gnome.shell.extensions.dash-to-dock click-action`
  * Set value (e.g. preview): `gsettings set org.gnome.shell.extensions.dash-to-dock click-action 'previews'`

#### Theming (16.04)

* [Arc Theme - Firefox](https://github.com/horst3180/arc-firefox-theme) - Arc theme extension for Firefox.
* [Arc Theme - GTK](https://github.com/horst3180/arc-theme) - Flat theme with transparent element for GTK (incl. Unity).
* [Arc Theme - Thunderbird](https://github.com/JD342/arc-thunderbird-integration) - Arc theme extension for Thunderbird.
* [Flatabulous - Icons](https://github.com/anmoljagetia/Flatabulous#flat-icons) - Flat icons collection.
* [Unity Dash Icon update](http://askubuntu.com/a/654404) - Update Unity dash with a custom icon.
* [Unity Tweak](https://apps.ubuntu.com/cat/applications/unity-tweak-tool/) - Easily change themes and fonts in Unity.

#### Other

* Erlang `asdf` installation:
  * Install `libwxgtk3.0-gtk3-dev` and `libwxgtk-webview3.0-gtk3-dev` to fix missing wxWidgets developer packages.
* Fix screen tearing:
  * [Firefox](https://askubuntu.com/a/1181037) - Force hardware acceleration (`about:config` and then set `layers.acceleration.force-enabled` to `true`).
  * [System-wide](https://askubuntu.com/a/1119262) - Add xorg device configuration.
* [Random string generation](https://unix.stackexchange.com/a/230676) - Generate random string in bash (`</dev/urandom tr -dc 'A-Za-z0-9!"#$%&'\''()*+,-./:;<=>?@[\]^_{|}~' | head -c 64; echo`)
* [Restore grub](https://itsfoss.com/no-grub-windows-linux/) - Restore grub after Windows 10 update (`bcdedit /set {bootmgr} path \EFI\ubuntu\grubx64.efi` in command shell).

---

### Gradle Plugins

The following is a list of useful Gradle plugins I'm using in my Java / Kotlin / Scala projects:

* [gradle-test-logger](https://github.com/radarsh/gradle-test-logger-plugin) - Test output formatting with themes and parallel execution support.
* [gradle-scoverage](https://github.com/scoverage/gradle-scoverage) - Enable Scoverage in Scala project
* [gradle-stats](https://github.com/aalmiray/stats-gradle-plugin) - Provides source code statistics in individual or aggregate project.
* [spotless](https://github.com/diffplug/spotless) - Source code formatter support; supports Java, Scala, Kotlin, SQL, etc.

---

### SBT Plugins

The following is a list of useful global SBT plugins I'm using in my Scala / SBT projects:

* [sbt-coursier](https://github.com/coursier/coursier) - An improved Scala artifact fetcher, with parallel downloads and better offline mode.
* [sbt-dependency-graph](https://github.com/jrudolph/sbt-dependency-graph) - Add support to visualize dependency graph within SBT (supports both ASCII and HTML output).
* [sbt-dependency-updates](https://github.com/rtimush/sbt-updates) - Add support to fetch and display available dependency updates in current project.
* [sbt-ensime](http://ensime.org/build_tools/sbt/) - Adds an SBT command to generates `.ensime` file in SBT projects for use by [ENSIME](http://ensime.org/) (e.g. in Atom, emacs, or VS Code).
* [sbt-stats](https://github.com/orrsella/sbt-stats) - Provides source code statistics in individual or aggregate project.
* [scala-clippy](https://github.com/softwaremill/scala-clippy) - Improved compiler error messages and syntax colorizer.


text:
namespace aura {
class Window;
}

namespace views {
namespace corewm {

namespace test {
class TooltipControllerTestHelper;
}  // namespace test

// TooltipStateManager separates the state handling from the events handling of
// the TooltipController. It is in charge of updating the tooltip state and
// keeping track of it.
class VIEWS_EXPORT TooltipStateManager {
 public:
  explicit TooltipStateManager(std::unique_ptr<Tooltip> tooltip);
  TooltipStateManager(const TooltipStateManager&) = delete;
  TooltipStateManager& operator=(const TooltipStateManager&) = delete;
  ~TooltipStateManager();

  int GetMaxWidth(const gfx::Point& location) const;

  // Hide the tooltip, clear timers, and reset controller states.
  void HideAndReset();

  // Returns true if there's a timer that'll show the tooltip running.
  bool IsWillShowTooltipTimerRunning() const {
    return will_show_tooltip_timer_.IsRunning();
  }

  bool IsVisible() const { return tooltip_->IsVisible(); }

  // Update the tooltip state attributes and start timer to show the tooltip. If
  // |hide_timeout| is greater than 0, set a timer to hide it after a specific
  // delay. Otherwise, show indefinitely.
  void Show(aura::Window* window,
            const std::u16string& tooltip_text,
            const gfx::Point& position,
            TooltipTrigger trigger,
            const base::TimeDelta hide_delay);

  void StopWillHideTooltipTimer();
  void StopWillShowTooltipTimer();

  // Returns the |tooltip_id_|, which corresponds to the pointer of the view on
  // which the tooltip was last added.
  const void* tooltip_id() const { return tooltip_id_; }

  // Returns the |tooltip_text_|, which corresponds to the last value the
  // tooltip got updated to.
  const std::u16string& tooltip_text() const { return tooltip_text_; }

  const aura::Window* tooltip_parent_window() const {
    return tooltip_parent_window_;
  }

  TooltipTrigger tooltip_trigger() const { return tooltip_trigger_; }

  // Update the |position_| if we're about to show the tooltip. This is to
  // ensure that the tooltip's position is aligned with either the latest cursor
  // location for a cursor triggered tooltip or the most recent position
  // received for a keyboard triggered tooltip.
  void UpdatePositionIfNeeded(const gfx::Point& position,
                              TooltipTrigger trigger);

 private:
  friend class test::TooltipControllerTestHelper;

  // For tests only.
  bool IsWillHideTooltipTimerRunningForTesting() const {
    return will_hide_tooltip_timer_.IsRunning();
  }

  // Calling this will enable/disable the delay that prevents the tooltip from
  // being displayed right away.
  void SetTooltipShowDelayedForTesting(bool is_delayed);

  // Called once the |will_show_timer_| fires to show the tooltip.
  void ShowNow(const std::u16string& trimmed_text,
               const base::TimeDelta hide_delay);

  // Start the show timer to show the tooltip.
  void StartWillShowTooltipTimer(const std::u16string& trimmed_text,
                                 const base::TimeDelta hide_delay);

  // The current position of the tooltip. This position is relative to the
  // |tooltip_window_| and in that window's coordinate space.
  gfx::Point position_;

  std::unique_ptr<Tooltip> tooltip_;

  // The pointer to the view for which the tooltip is set.
  raw_ptr<const void> tooltip_id_ = nullptr;

  // The text value used at the last tooltip update.
  std::u16string tooltip_text_;

  // The window on which the tooltip is added.
  raw_ptr<aura::Window> tooltip_parent_window_ = nullptr;

  TooltipTrigger tooltip_trigger_ = TooltipTrigger::kCursor;

  // Two timers for the tooltip: one to hide an on-screen tooltip after a delay,
  // and one to display the tooltip when the timer fires.
  base::OneShotTimer will_hide_tooltip_timer_;
  base::OneShotTimer will_show_tooltip_timer_;

  // The delay after which the tooltip shows up. It is only modified in the unit
  // tests.
  base::TimeDelta tooltip_show_delay_;

  // WeakPtrFactory to use for callbacks.
  base::WeakPtrFactory<TooltipStateManager> weak_factory_{this};
};

}  // namespace corewm
}  // namespace views

#endif  // UI_VIEWS_COREWM_TOOLTIP_STATE_MANAGER_H_


text:
#include "NFSceneView.h"
#include "NFUIModule.h"

NFSceneView::NFSceneView(NFIPluginManager* p, NFViewType vt) : NFIView(p, vt, GET_CLASS_NAME(NFSceneView))
{

}

bool NFSceneView::Execute()
{
    /*
    // My Game has a different viewport than the editor's one:
    const int W = 1080 / 2;
    const int H = 1920 / 2;
    // We set the same viewport size (plus margin) to the next window (if first use)
    ImGui::SetNextWindowSize(ImVec2(W + 10, H + 10),
        ImGuiSetCond_FirstUseEver);
    ImGui::Begin("Game rendering");
    {
        // Get the current cursor position (where your window is)
        ImVec2 pos = ImGui::GetCursorScreenPos();

        // A boolean to allow me to stop the game rendering
        if (runApp) {
            glViewport(0, 0, W, H);
            // Render the scene into an FBO
            game->render(time);
            // Restore previous viewport
            glViewport(0, 0, w, h);
        }
        // Get the texture associated to the FBO
        auto tex = game->getRendered();

        // Ask ImGui to draw it as an image:
        // Under OpenGL the ImGUI image type is GLuint
        // So make sure to use "(void *)tex" but not "&tex"
        ImGui::GetWindowDrawList()->AddImage((void*)tex, ImVec2(ImGui::GetItemRectMin().x + pos.x, ImGui::GetItemRectMin().y + pos.y), ImVec2(pos.x + h / 2, pos.y + w / 2), ImVec2(0, 1), ImVec2(1, 0));
    }
    ImGui::End();
    */
	//1. get all scene from static config data
	//2. let the user choose one scene
	//3. get all objects of this level
	//4. draw object by imgui
	//5. show the props and records if the user picked an object
	//6. use can modify the value of props to trigger the saving job

   if (ImGui::IsWindowFocused())
   {
      NF_SHARE_PTR<NFIView> pView = m_pUIModule->GetView(NFViewType::HierachyView);
      if (pView)
      {
         pView->OccupySubRender(this);
      }
   }

	return false;
}

void NFSceneView::SubRender()
{
   ImGui::Text(this->name.c_str());
}


text:
package io.paradoxical.cassieq.commands;

import io.dropwizard.cli.Command;
import io.dropwizard.setup.Bootstrap;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;

import java.io.File;

public class DebugCommand extends Command {
    public DebugCommand() {
        super("debug", "Runs bash so that you can explore the container");
    }

    @Override
    public void configure(final Subparser subparser) {
    }

    @Override
    public void run(final Bootstrap<?> bootstrap, final Namespace namespace) throws Exception {
        new ProcessBuilder("/bin/bash")
                .directory(new File("/data"))
                .inheritIO()
                .start()
                .waitFor();
    }
}


text:
const fs = require('fs')
const path = require('path')
const PolyK = require('.')

const directories = {
  in: path.join(__dirname, 'test', 'in') + path.sep,
  out: path.join(__dirname, 'test', 'out') + path.sep
}
const polygon = require(directories.in + 'polygon.json')

test('Slice', () => {
  const start = [134.208984375, -4.390228926463384]
  const end = [129.0234375, -43.51668853502907]
  const sliced = PolyK.Slice(polygon, start[0], start[1], end[0], end[1])
  if (process.env.REGEN) { fs.writeFileSync(directories.out + 'sliced.json', JSON.stringify(sliced, null, 2)) }
  expect(sliced).toEqual(require(directories.out + 'sliced.json'))
})

test('Raycast', () => {
  const polygon = require(directories.in + 'polygon.json')
  const start = [135, -25]
  const direction = [110, -10]
  const raycast = PolyK.Raycast(polygon, start[0], start[1], direction[0], direction[1])
  if (process.env.REGEN) { fs.writeFileSync(directories.out + 'raycast.json', JSON.stringify(raycast, null, 2)) }
  expect(raycast).toEqual(require(directories.out + 'raycast.json'))
})

test('Triangulate', () => {
  const triangulate = PolyK.Triangulate(polygon)
  if (process.env.REGEN) { fs.writeFileSync(directories.out + 'triangulate.json', JSON.stringify(triangulate, null, 2)) }
  expect(triangulate).toEqual(require(directories.out + 'triangulate.json'))
})

test('ContainsPoint', () => {
  const polygon = require(directories.in + 'polygon.json')
  const inside = [135, -25]
  const outside = [102, -16]
  expect(PolyK.ContainsPoint(polygon, inside[0], inside[1])).toBe(true)
  expect(PolyK.ContainsPoint(polygon, outside[0], outside[1])).toBe(false)
})


text:
import React from 'react'
import { Grid, Segment, Header, Icon } from 'stardust'

const PageNotFound = () => (
  <Grid padded textAlign='center' stretched>
    <Grid.Row columns='equal'>
      <Grid.Column>
        <Header as='h1' icon textAlign='center'>
          <Icon name='game' />
          404
          <Header.Subheader>
            How about some good old Atari?
          </Header.Subheader>
        </Header>
      </Grid.Column>
    </Grid.Row>
    <Grid.Row columns='equal'>
      <Grid.Column>
        <Segment basic>
          <embed
            src='http://www.pizn.com/swf/classic-asteroids.swf'
            width='425'
            height='318'
            align='center'
            quality='high'
            pluginspage='http://www.macromedia.com/go/getflashplayer'
            type='application/x-shockwave-flash'
            style={{ zoom: '1.13' }}
          />
        </Segment>
      </Grid.Column>
      <Grid.Column>
        <Segment basic>
          <embed
            src='http://www.pizn.com/swf/1-space-invaders.swf'
            width='425'
            height='359'
            align='center'
            quality='high'
            pluginspage='http://www.macromedia.com/go/getflashplayer'
            type='application/x-shockwave-flash'
          />
        </Segment>
      </Grid.Column>
    </Grid.Row>
  </Grid>
)

export default PageNotFound


text:
require 'rails_helper'

RSpec.describe Question, :type => :model do

  let(:quiz) { FactoryGirl.create :quiz_with_questions_and_answers }
  let(:ordered_questions) {quiz.questions.rank(:row_order)}

  describe "#row_order_index" do
  	it 'should be in the right row_order_index' do
  		expect(quiz.questions.count).to eq(4)

  		expect(ordered_questions[0].row_order_index).to eq(0)
  		expect(ordered_questions[1].row_order_index).to eq(1)
  		expect(ordered_questions[2].row_order_index).to eq(2)
  		expect(ordered_questions[3].row_order_index).to eq(3)
  	end
  end

  describe "#format" do

    let(:question) { FactoryGirl.create :question_with_answers }

    context 'format=:title_with_answers' do

      it 'display with proper format' do
        expect(question.answers.count).to eq(4)
        expected_hash = {
                            :title=>"Which color is the sky ?",
                            :answers=>[
                                        {:id=>question.answers[0].id, :title=>"blue"},
                                        {:id=>question.answers[1].id, :title=>"red"},
                                        {:id=>question.answers[2].id, :title=>"white"},
                                        {:id=>question.answers[3].id, :title=>"green"}
                                      ]
                        }

        expect(question.format(:title_with_answers)).to eq(expected_hash)
      end

    end
    context 'unknown format' do

    end
  end

end


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
        android:src="@drawable/ic_audio_ring_notif_vibrate_am"
        android:autoMirrored="true">
</bitmap>


text:
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <sound/core.h>
#include <sound/compress_params.h>
#include <sound/compress_driver.h>
#include <sound/soc.h>
#include <sound/initval.h>
#include <sound/soc-dpcm.h>

static int soc_compr_open(struct snd_compr_stream *cstream)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	int ret = 0;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	if (platform->driver->compr_ops && platform->driver->compr_ops->open) {
		ret = platform->driver->compr_ops->open(cstream);
		if (ret < 0) {
			pr_err("compress asoc: can't open platform %s\n",
				platform->component.name);
			goto out;
		}
	}

	if (rtd->dai_link->compr_ops && rtd->dai_link->compr_ops->startup) {
		ret = rtd->dai_link->compr_ops->startup(cstream);
		if (ret < 0) {
			pr_err("compress asoc: %s startup failed\n", rtd->dai_link->name);
			goto machine_err;
		}
	}

	snd_soc_runtime_activate(rtd, cstream->direction);

	mutex_unlock(&rtd->pcm_mutex);

	return 0;

machine_err:
	if (platform->driver->compr_ops && platform->driver->compr_ops->free)
		platform->driver->compr_ops->free(cstream);
out:
	mutex_unlock(&rtd->pcm_mutex);
	return ret;
}

static int soc_compr_open_fe(struct snd_compr_stream *cstream)
{
	struct snd_soc_pcm_runtime *fe = cstream->private_data;
	struct snd_pcm_substream *fe_substream = fe->pcm->streams[0].substream;
	struct snd_soc_platform *platform = fe->platform;
	struct snd_soc_dpcm *dpcm;
	struct snd_soc_dapm_widget_list *list;
	int stream;
	int ret = 0;

	if (cstream->direction == SND_COMPRESS_PLAYBACK)
		stream = SNDRV_PCM_STREAM_PLAYBACK;
	else
		stream = SNDRV_PCM_STREAM_CAPTURE;

	mutex_lock_nested(&fe->card->mutex, SND_SOC_CARD_CLASS_RUNTIME);

	if (platform->driver->compr_ops && platform->driver->compr_ops->open) {
		ret = platform->driver->compr_ops->open(cstream);
		if (ret < 0) {
			pr_err("compress asoc: can't open platform %s\n",
				platform->component.name);
			goto out;
		}
	}

	if (fe->dai_link->compr_ops && fe->dai_link->compr_ops->startup) {
		ret = fe->dai_link->compr_ops->startup(cstream);
		if (ret < 0) {
			pr_err("compress asoc: %s startup failed\n", fe->dai_link->name);
			goto machine_err;
		}
	}

	fe->dpcm[stream].runtime = fe_substream->runtime;

	ret = dpcm_path_get(fe, stream, &list);
	if (ret < 0)
		goto fe_err;
	else if (ret == 0)
		dev_dbg(fe->dev, "ASoC: %s no valid %s route\n",
			fe->dai_link->name, stream ? "capture" : "playback");

	/* calculate valid and active FE <-> BE dpcms */
	dpcm_process_paths(fe, stream, &list, 1);

	fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_FE;

	ret = dpcm_be_dai_startup(fe, stream);
	if (ret < 0) {
		/* clean up all links */
		list_for_each_entry(dpcm, &fe->dpcm[stream].be_clients, list_be)
			dpcm->state = SND_SOC_DPCM_LINK_STATE_FREE;

		dpcm_be_disconnect(fe, stream);
		fe->dpcm[stream].runtime = NULL;
		goto fe_err;
	}

	dpcm_clear_pending_state(fe, stream);
	dpcm_path_put(&list);

	fe->dpcm[stream].state = SND_SOC_DPCM_STATE_OPEN;
	fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO;

	snd_soc_runtime_activate(fe, stream);

	mutex_unlock(&fe->card->mutex);

	return 0;

fe_err:
	if (fe->dai_link->compr_ops && fe->dai_link->compr_ops->shutdown)
		fe->dai_link->compr_ops->shutdown(cstream);
machine_err:
	if (platform->driver->compr_ops && platform->driver->compr_ops->free)
		platform->driver->compr_ops->free(cstream);
out:
	fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO;
	mutex_unlock(&fe->card->mutex);
	return ret;
}

/*
 * Power down the audio subsystem pmdown_time msecs after close is called.
 * This is to ensure there are no pops or clicks in between any music tracks
 * due to DAPM power cycling.
 */
static void close_delayed_work(struct work_struct *work)
{
	struct snd_soc_pcm_runtime *rtd =
			container_of(work, struct snd_soc_pcm_runtime, delayed_work.work);
	struct snd_soc_dai *codec_dai = rtd->codec_dai;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	dev_dbg(rtd->dev, "ASoC: pop wq checking: %s status: %s waiting: %s\n",
		 codec_dai->driver->playback.stream_name,
		 codec_dai->playback_active ? "active" : "inactive",
		 rtd->pop_wait ? "yes" : "no");

	/* are we waiting on this codec DAI stream */
	if (rtd->pop_wait == 1) {
		rtd->pop_wait = 0;
		snd_soc_dapm_stream_event(rtd, SNDRV_PCM_STREAM_PLAYBACK,
					  SND_SOC_DAPM_STREAM_STOP);
	}

	mutex_unlock(&rtd->pcm_mutex);
}

static int soc_compr_free(struct snd_compr_stream *cstream)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
	struct snd_soc_dai *codec_dai = rtd->codec_dai;
	int stream;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	if (cstream->direction == SND_COMPRESS_PLAYBACK)
		stream = SNDRV_PCM_STREAM_PLAYBACK;
	else
		stream = SNDRV_PCM_STREAM_CAPTURE;

	snd_soc_runtime_deactivate(rtd, stream);

	snd_soc_dai_digital_mute(codec_dai, 1, cstream->direction);

	if (!cpu_dai->active)
		cpu_dai->rate = 0;

	if (!codec_dai->active)
		codec_dai->rate = 0;

	if (rtd->dai_link->compr_ops && rtd->dai_link->compr_ops->shutdown)
		rtd->dai_link->compr_ops->shutdown(cstream);

	if (platform->driver->compr_ops && platform->driver->compr_ops->free)
		platform->driver->compr_ops->free(cstream);

	if (cstream->direction == SND_COMPRESS_PLAYBACK) {
		if (snd_soc_runtime_ignore_pmdown_time(rtd)) {
			snd_soc_dapm_stream_event(rtd,
					SNDRV_PCM_STREAM_PLAYBACK,
					SND_SOC_DAPM_STREAM_STOP);
		} else {
			rtd->pop_wait = 1;
			queue_delayed_work(system_power_efficient_wq,
					   &rtd->delayed_work,
					   msecs_to_jiffies(rtd->pmdown_time));
		}
	} else {
		/* capture streams can be powered down now */
		snd_soc_dapm_stream_event(rtd,
			SNDRV_PCM_STREAM_CAPTURE,
			SND_SOC_DAPM_STREAM_STOP);
	}

	mutex_unlock(&rtd->pcm_mutex);
	return 0;
}

static int soc_compr_free_fe(struct snd_compr_stream *cstream)
{
	struct snd_soc_pcm_runtime *fe = cstream->private_data;
	struct snd_soc_platform *platform = fe->platform;
	struct snd_soc_dpcm *dpcm;
	int stream, ret;

	mutex_lock_nested(&fe->card->mutex, SND_SOC_CARD_CLASS_RUNTIME);

	if (cstream->direction == SND_COMPRESS_PLAYBACK)
		stream = SNDRV_PCM_STREAM_PLAYBACK;
	else
		stream = SNDRV_PCM_STREAM_CAPTURE;

	snd_soc_runtime_deactivate(fe, stream);

	fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_FE;

	ret = dpcm_be_dai_hw_free(fe, stream);
	if (ret < 0)
		dev_err(fe->dev, "compressed hw_free failed %d\n", ret);

	ret = dpcm_be_dai_shutdown(fe, stream);

	/* mark FE's links ready to prune */
	list_for_each_entry(dpcm, &fe->dpcm[stream].be_clients, list_be)
		dpcm->state = SND_SOC_DPCM_LINK_STATE_FREE;

	dpcm_dapm_stream_event(fe, stream, SND_SOC_DAPM_STREAM_STOP);

	fe->dpcm[stream].state = SND_SOC_DPCM_STATE_CLOSE;
	fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO;

	dpcm_be_disconnect(fe, stream);

	fe->dpcm[stream].runtime = NULL;

	if (fe->dai_link->compr_ops && fe->dai_link->compr_ops->shutdown)
		fe->dai_link->compr_ops->shutdown(cstream);

	if (platform->driver->compr_ops && platform->driver->compr_ops->free)
		platform->driver->compr_ops->free(cstream);

	mutex_unlock(&fe->card->mutex);
	return 0;
}

static int soc_compr_trigger(struct snd_compr_stream *cstream, int cmd)
{

	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	struct snd_soc_dai *codec_dai = rtd->codec_dai;
	int ret = 0;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	if (platform->driver->compr_ops && platform->driver->compr_ops->trigger) {
		ret = platform->driver->compr_ops->trigger(cstream, cmd);
		if (ret < 0)
			goto out;
	}

	switch (cmd) {
	case SNDRV_PCM_TRIGGER_START:
		snd_soc_dai_digital_mute(codec_dai, 0, cstream->direction);
		break;
	case SNDRV_PCM_TRIGGER_STOP:
		snd_soc_dai_digital_mute(codec_dai, 1, cstream->direction);
		break;
	}

out:
	mutex_unlock(&rtd->pcm_mutex);
	return ret;
}

static int soc_compr_trigger_fe(struct snd_compr_stream *cstream, int cmd)
{
	struct snd_soc_pcm_runtime *fe = cstream->private_data;
	struct snd_soc_platform *platform = fe->platform;
	int ret = 0, stream;

	if (cmd == SND_COMPR_TRIGGER_PARTIAL_DRAIN ||
		cmd == SND_COMPR_TRIGGER_DRAIN) {

		if (platform->driver->compr_ops &&
		    platform->driver->compr_ops->trigger)
			return platform->driver->compr_ops->trigger(cstream,
								    cmd);
	}

	if (cstream->direction == SND_COMPRESS_PLAYBACK)
		stream = SNDRV_PCM_STREAM_PLAYBACK;
	else
		stream = SNDRV_PCM_STREAM_CAPTURE;

	mutex_lock_nested(&fe->card->mutex, SND_SOC_CARD_CLASS_RUNTIME);

	if (platform->driver->compr_ops && platform->driver->compr_ops->trigger) {
		ret = platform->driver->compr_ops->trigger(cstream, cmd);
		if (ret < 0)
			goto out;
	}

	fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_FE;

	ret = dpcm_be_dai_trigger(fe, stream, cmd);

	switch (cmd) {
	case SNDRV_PCM_TRIGGER_START:
	case SNDRV_PCM_TRIGGER_RESUME:
	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
		fe->dpcm[stream].state = SND_SOC_DPCM_STATE_START;
		break;
	case SNDRV_PCM_TRIGGER_STOP:
	case SNDRV_PCM_TRIGGER_SUSPEND:
		fe->dpcm[stream].state = SND_SOC_DPCM_STATE_STOP;
		break;
	case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
		fe->dpcm[stream].state = SND_SOC_DPCM_STATE_PAUSED;
		break;
	}

out:
	fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO;
	mutex_unlock(&fe->card->mutex);
	return ret;
}

static int soc_compr_set_params(struct snd_compr_stream *cstream,
					struct snd_compr_params *params)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	int ret = 0;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	/* first we call set_params for the platform driver
	 * this should configure the soc side
	 * if the machine has compressed ops then we call that as well
	 * expectation is that platform and machine will configure everything
	 * for this compress path, like configuring pcm port for codec
	 */
	if (platform->driver->compr_ops && platform->driver->compr_ops->set_params) {
		ret = platform->driver->compr_ops->set_params(cstream, params);
		if (ret < 0)
			goto err;
	}

	if (rtd->dai_link->compr_ops && rtd->dai_link->compr_ops->set_params) {
		ret = rtd->dai_link->compr_ops->set_params(cstream);
		if (ret < 0)
			goto err;
	}

	if (cstream->direction == SND_COMPRESS_PLAYBACK)
		snd_soc_dapm_stream_event(rtd, SNDRV_PCM_STREAM_PLAYBACK,
					SND_SOC_DAPM_STREAM_START);
	else
		snd_soc_dapm_stream_event(rtd, SNDRV_PCM_STREAM_CAPTURE,
					SND_SOC_DAPM_STREAM_START);

	/* cancel any delayed stream shutdown that is pending */
	rtd->pop_wait = 0;
	mutex_unlock(&rtd->pcm_mutex);

	cancel_delayed_work_sync(&rtd->delayed_work);

	return ret;

err:
	mutex_unlock(&rtd->pcm_mutex);
	return ret;
}

static int soc_compr_set_params_fe(struct snd_compr_stream *cstream,
					struct snd_compr_params *params)
{
	struct snd_soc_pcm_runtime *fe = cstream->private_data;
	struct snd_pcm_substream *fe_substream = fe->pcm->streams[0].substream;
	struct snd_soc_platform *platform = fe->platform;
	int ret = 0, stream;

	if (cstream->direction == SND_COMPRESS_PLAYBACK)
		stream = SNDRV_PCM_STREAM_PLAYBACK;
	else
		stream = SNDRV_PCM_STREAM_CAPTURE;

	mutex_lock_nested(&fe->card->mutex, SND_SOC_CARD_CLASS_RUNTIME);

	if (platform->driver->compr_ops && platform->driver->compr_ops->set_params) {
		ret = platform->driver->compr_ops->set_params(cstream, params);
		if (ret < 0)
			goto out;
	}

	if (fe->dai_link->compr_ops && fe->dai_link->compr_ops->set_params) {
		ret = fe->dai_link->compr_ops->set_params(cstream);
		if (ret < 0)
			goto out;
	}

	/*
	 * Create an empty hw_params for the BE as the machine driver must
	 * fix this up to match DSP decoder and ASRC configuration.
	 * I.e. machine driver fixup for compressed BE is mandatory.
	 */
	memset(&fe->dpcm[fe_substream->stream].hw_params, 0,
		sizeof(struct snd_pcm_hw_params));

	fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_FE;

	ret = dpcm_be_dai_hw_params(fe, stream);
	if (ret < 0)
		goto out;

	ret = dpcm_be_dai_prepare(fe, stream);
	if (ret < 0)
		goto out;

	dpcm_dapm_stream_event(fe, stream, SND_SOC_DAPM_STREAM_START);
	fe->dpcm[stream].state = SND_SOC_DPCM_STATE_PREPARE;

out:
	fe->dpcm[stream].runtime_update = SND_SOC_DPCM_UPDATE_NO;
	mutex_unlock(&fe->card->mutex);
	return ret;
}

static int soc_compr_get_params(struct snd_compr_stream *cstream,
					struct snd_codec *params)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	int ret = 0;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	if (platform->driver->compr_ops && platform->driver->compr_ops->get_params)
		ret = platform->driver->compr_ops->get_params(cstream, params);

	mutex_unlock(&rtd->pcm_mutex);
	return ret;
}

static int soc_compr_get_caps(struct snd_compr_stream *cstream,
				struct snd_compr_caps *caps)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	int ret = 0;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	if (platform->driver->compr_ops && platform->driver->compr_ops->get_caps)
		ret = platform->driver->compr_ops->get_caps(cstream, caps);

	mutex_unlock(&rtd->pcm_mutex);
	return ret;
}

static int soc_compr_get_codec_caps(struct snd_compr_stream *cstream,
				struct snd_compr_codec_caps *codec)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	int ret = 0;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	if (platform->driver->compr_ops && platform->driver->compr_ops->get_codec_caps)
		ret = platform->driver->compr_ops->get_codec_caps(cstream, codec);

	mutex_unlock(&rtd->pcm_mutex);
	return ret;
}

static int soc_compr_ack(struct snd_compr_stream *cstream, size_t bytes)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	int ret = 0;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	if (platform->driver->compr_ops && platform->driver->compr_ops->ack)
		ret = platform->driver->compr_ops->ack(cstream, bytes);

	mutex_unlock(&rtd->pcm_mutex);
	return ret;
}

static int soc_compr_pointer(struct snd_compr_stream *cstream,
			struct snd_compr_tstamp *tstamp)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	if (platform->driver->compr_ops && platform->driver->compr_ops->pointer)
		 platform->driver->compr_ops->pointer(cstream, tstamp);

	mutex_unlock(&rtd->pcm_mutex);
	return 0;
}

static int soc_compr_copy(struct snd_compr_stream *cstream,
			  char __user *buf, size_t count)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	int ret = 0;

	mutex_lock_nested(&rtd->pcm_mutex, rtd->pcm_subclass);

	if (platform->driver->compr_ops && platform->driver->compr_ops->copy)
		ret = platform->driver->compr_ops->copy(cstream, buf, count);

	mutex_unlock(&rtd->pcm_mutex);
	return ret;
}

static int soc_compr_set_metadata(struct snd_compr_stream *cstream,
				struct snd_compr_metadata *metadata)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	int ret = 0;

	if (platform->driver->compr_ops && platform->driver->compr_ops->set_metadata)
		ret = platform->driver->compr_ops->set_metadata(cstream, metadata);

	return ret;
}

static int soc_compr_get_metadata(struct snd_compr_stream *cstream,
				struct snd_compr_metadata *metadata)
{
	struct snd_soc_pcm_runtime *rtd = cstream->private_data;
	struct snd_soc_platform *platform = rtd->platform;
	int ret = 0;

	if (platform->driver->compr_ops && platform->driver->compr_ops->get_metadata)
		ret = platform->driver->compr_ops->get_metadata(cstream, metadata);

	return ret;
}

/* ASoC Compress operations */
static struct snd_compr_ops soc_compr_ops = {
	.open		= soc_compr_open,
	.free		= soc_compr_free,
	.set_params	= soc_compr_set_params,
	.set_metadata   = soc_compr_set_metadata,
	.get_metadata	= soc_compr_get_metadata,
	.get_params	= soc_compr_get_params,
	.trigger	= soc_compr_trigger,
	.pointer	= soc_compr_pointer,
	.ack		= soc_compr_ack,
	.get_caps	= soc_compr_get_caps,
	.get_codec_caps = soc_compr_get_codec_caps
};

/* ASoC Dynamic Compress operations */
static struct snd_compr_ops soc_compr_dyn_ops = {
	.open		= soc_compr_open_fe,
	.free		= soc_compr_free_fe,
	.set_params	= soc_compr_set_params_fe,
	.get_params	= soc_compr_get_params,
	.set_metadata   = soc_compr_set_metadata,
	.get_metadata	= soc_compr_get_metadata,
	.trigger	= soc_compr_trigger_fe,
	.pointer	= soc_compr_pointer,
	.ack		= soc_compr_ack,
	.get_caps	= soc_compr_get_caps,
	.get_codec_caps = soc_compr_get_codec_caps
};

/**
 * snd_soc_new_compress - create a new compress.
 *
 * @rtd: The runtime for which we will create compress
 * @num: the device index number (zero based - shared with normal PCMs)
 *
 * Return: 0 for success, else error.
 */
int snd_soc_new_compress(struct snd_soc_pcm_runtime *rtd, int num)
{
	struct snd_soc_codec *codec = rtd->codec;
	struct snd_soc_platform *platform = rtd->platform;
	struct snd_soc_dai *codec_dai = rtd->codec_dai;
	struct snd_soc_dai *cpu_dai = rtd->cpu_dai;
	struct snd_compr *compr;
	struct snd_pcm *be_pcm;
	char new_name[64];
	int ret = 0, direction = 0;
	int playback = 0, capture = 0;

	if (rtd->num_codecs > 1) {
		dev_err(rtd->card->dev, "Multicodec not supported for compressed stream\n");
		return -EINVAL;
	}

	/* check client and interface hw capabilities */
	snprintf(new_name, sizeof(new_name), "%s %s-%d",
			rtd->dai_link->stream_name, codec_dai->name, num);

	if (codec_dai->driver->playback.channels_min)
		playback = 1;
	if (codec_dai->driver->capture.channels_min)
		capture = 1;

	capture = capture && cpu_dai->driver->capture.channels_min;
	playback = playback && cpu_dai->driver->playback.channels_min;

	/*
	 * Compress devices are unidirectional so only one of the directions
	 * should be set, check for that (xor)
	 */
	if (playback + capture != 1) {
		dev_err(rtd->card->dev, "Invalid direction for compress P %d, C %d\n",
				playback, capture);
		return -EINVAL;
	}

	if(playback)
		direction = SND_COMPRESS_PLAYBACK;
	else
		direction = SND_COMPRESS_CAPTURE;

	compr = kzalloc(sizeof(*compr), GFP_KERNEL);
	if (compr == NULL) {
		snd_printk(KERN_ERR "Cannot allocate compr\n");
		return -ENOMEM;
	}

	compr->ops = devm_kzalloc(rtd->card->dev, sizeof(soc_compr_ops),
				  GFP_KERNEL);
	if (compr->ops == NULL) {
		dev_err(rtd->card->dev, "Cannot allocate compressed ops\n");
		ret = -ENOMEM;
		goto compr_err;
	}

	if (rtd->dai_link->dynamic) {
		snprintf(new_name, sizeof(new_name), "(%s)",
			rtd->dai_link->stream_name);

		ret = snd_pcm_new_internal(rtd->card->snd_card, new_name, num,
				rtd->dai_link->dpcm_playback,
				rtd->dai_link->dpcm_capture, &be_pcm);
		if (ret < 0) {
			dev_err(rtd->card->dev, "ASoC: can't create compressed for %s\n",
				rtd->dai_link->name);
			goto compr_err;
		}

		rtd->pcm = be_pcm;
		rtd->fe_compr = 1;
		if (rtd->dai_link->dpcm_playback)
			be_pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream->private_data = rtd;
		else if (rtd->dai_link->dpcm_capture)
			be_pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream->private_data = rtd;
		memcpy(compr->ops, &soc_compr_dyn_ops, sizeof(soc_compr_dyn_ops));
	} else
		memcpy(compr->ops, &soc_compr_ops, sizeof(soc_compr_ops));

	/* Add copy callback for not memory mapped DSPs */
	if (platform->driver->compr_ops && platform->driver->compr_ops->copy)
		compr->ops->copy = soc_compr_copy;

	mutex_init(&compr->lock);

	snprintf(new_name, sizeof(new_name), "%s %s-%d",
		 rtd->dai_link->stream_name,
		 rtd->codec_dai->name, num);

	ret = snd_compress_new(rtd->card->snd_card, num, direction,
				new_name, compr);
	if (ret < 0) {
		pr_err("compress asoc: can't create compress for codec %s\n",
			codec->component.name);
		goto compr_err;
	}

	/* DAPM dai link stream work */
	INIT_DELAYED_WORK(&rtd->delayed_work, close_delayed_work);

	rtd->compr = compr;
	compr->private_data = rtd;

	printk(KERN_INFO "compress asoc: %s <-> %s mapping ok\n", codec_dai->name,
		cpu_dai->name);
	return ret;

compr_err:
	kfree(compr);
	return ret;
}
EXPORT_SYMBOL_GPL(snd_soc_new_compress);


text:
#include <linux/module.h>
#include <linux/printk.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/sunxi-sid.h>

static ssize_t sys_info_show(struct class *class,
			     struct class_attribute *attr, char *buf)
{
	int i;
	int databuf[4] = {0};
	char tmpbuf[129] = {0};
	size_t size = 0;

	/* platform */
	sunxi_get_platform(tmpbuf, 129);
	size += sprintf(buf + size, "sunxi_platform    : %s\n", tmpbuf);

	/* secure */
	size += sprintf(buf + size, "sunxi_secure      : ");
	if (sunxi_soc_is_secure())
		size += sprintf(buf + size, "%s\n", "secure");
	else
		size += sprintf(buf + size, "%s\n", "normal");

	/* chipid */
	sunxi_get_serial((u8 *)databuf);
	for (i = 0; i < 4; i++)
		sprintf(tmpbuf + i*8, "%08x", databuf[i]);
	tmpbuf[128] = 0;
	size += sprintf(buf + size, "sunxi_chipid      : %s\n", tmpbuf);

	/* chiptype */
	sunxi_get_soc_chipid_str(tmpbuf);
	size += sprintf(buf + size, "sunxi_chiptype    : %s\n", tmpbuf);

	/* socbatch number */
	size += sprintf(buf + size, "sunxi_batchno     : %#x\n",
			sunxi_get_soc_ver()&0x0ffff);

	return size;
}

static struct class_attribute info_class_attrs[] = {
	__ATTR(sys_info, 0644, sys_info_show, NULL),
	__ATTR_NULL,
};

static struct class info_class = {
	.name           = "sunxi_info",
	.owner          = THIS_MODULE,
	.class_attrs    = info_class_attrs,
};

static int __init sunxi_sys_info_init(void)
{
	pr_debug("sunxi get sys info driver init\n");
	return class_register(&info_class);
}

static void __exit sunxi_sys_info_exit(void)
{
	pr_debug("sunxi get sys info driver exit\n");
	class_unregister(&info_class);
}

module_init(sunxi_sys_info_init);
module_exit(sunxi_sys_info_exit);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("xiafeng<xiafeng@allwinnertech.com>");
MODULE_DESCRIPTION("sunxi sys info.");


text:
package com.junichi11.netbeans.modules.template.settings.preferences;

import java.util.prefs.Preferences;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectUtils;

/**
 *
 * @author junichi11
 */
public final class TemplateSettingsPreferences {

    private static final String SETTINGS = "settings"; // NOI18N
    private static final String ENABLED = "enabled"; // NOI18N

    private static final String DEFAULT_SETTINGS
            = "# If you enable settings in this project, your settings will be used when you create a new template.\n" // NOI18N
            + "\n" // NOI18N
            + "# uncomment the next line and specify your user name to be used in new templates\n" // NOI18N
            + "#user=your user name\n"; // NOI18N

    private TemplateSettingsPreferences() {
    }

    public static boolean isEnabled(Project project) {
        return getPreferences(project, false).getBoolean(ENABLED, false);
    }

    public static void setEnabled(Project project, boolean isEnabled) {
        getPreferences(project, false).putBoolean(ENABLED, isEnabled);
    }

    public static String getSettings(Project project) {
        return getPreferences(project, false).get(SETTINGS, DEFAULT_SETTINGS); // NOI18N
    }

    public static void setSettings(Project project, String properties) {
        getPreferences(project, false).put(SETTINGS, properties);
    }

    private static Preferences getPreferences(Project project) {
        return getPreferences(project, true);
    }

    private static Preferences getPreferences(Project project, boolean isShared) {
        return ProjectUtils.getPreferences(project, TemplateSettingsPreferences.class, isShared);
    }
}