text:
package org.olat.lms.security.authentication.ldap;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.naming.directory.Attributes;

import org.apache.log4j.Logger;
import org.olat.data.basesecurity.BaseSecurity;
import org.olat.data.basesecurity.SecurityGroup;
import org.olat.lms.user.UserService;
import org.olat.lms.user.propertyhandler.UserPropertyHandler;
import org.olat.system.commons.StringHelper;
import org.olat.system.commons.configuration.Initializable;
import org.olat.system.exception.StartupException;
import org.olat.system.logging.log4j.LoggerHelper;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

/**
 * Description: This Module loads all needed configuration for the LDAP Login. All configuration is done in the spring olatextconfig.xml file.
 *

 * LDAPLoginModule
 *

 *
 * @author maurus.rohrer@gmail.com
 */
public class LDAPLoginModule implements Initializable {
    // Connection configuration
    private static String ldapUrl;
    private static boolean ldapEnabled;
    private static boolean activeDirectory;
    private static String ldapDateFormat;
    // SSL configuration
    private static boolean sslEnabled;
    private static String trustStoreLoc;
    private static String trustStorePass;
    private static String trustStoreTyp;
    // System user: used for getting all users and connection testing
    private static String systemDN;
    private static String systemPW;
    // List of bases where to find users
    private static List<String> ldapBases;
    // Use a valid ldap password and save it as olat password to reduce dependency
    // to LDAP server availability and allow WeDAV access
    private static boolean cacheLDAPPwdAsOLATPwdOnLogin;
    // When the system detects an LDAP user that does already exist in OLAT but is not marked
    // as LDAP user, the OLAT user can be converted to an LDAP managed user.
    // When enabling this feature you should make sure that you don't have a user 'administrator'
    // in your ldapBases (not a problem but not recommended)
    private static boolean convertExistingLocalUsersToLDAPUsers;
    // Users that have been created vial LDAP sync but now can't be found on the LDAP anymore
    // can be deleted automatically. If unsure, set to false and delete those users manually
    // in the user management.
    private static boolean deleteRemovedLDAPUsersOnSync;
    // LDAP sync will not delete users if more than deleteRemovedLDAPUserPercentage are found to be deleted.
    private static int deleteRemovedLDAPUsersPercentage;
    // Propagate the password changes onto the LDAP server
    private static boolean propagatePasswordChangedOnLdapServer;
    // Configuration for syncing user attributes
    private static String ldapUserObjectClass;
    private static String ldapUserCreatedTimestampAttribute;
    private static String ldapUserLastModifiedTimestampAttribute;
    private static String ldapUserPasswordAttribute;
    // Should users be created and synchronized automatically? If you set this
    // configuration to false, the users will be generated on-the-fly when they
    // log in
    private static boolean ldapSyncOnStartup;
    private static boolean ldapSyncCronSync;
    private static String ldapSyncCronSyncExpression;
    // User LDAP attributes to be synced and a map with the mandatory attributes
    private static Map<String, String> userAttrMap;
    private static Map<String, String> reqAttr;
    private static Set<String> syncOnlyOnCreateProperties;
    private static String[] userAttr;
    // Static user properties that should be added to user when syncing
    private static Map<String, String> staticUserProperties;
    private static final Logger log = LoggerHelper.getLogger();

    private final Scheduler scheduler;
    private final BaseSecurity securityManager;
    private final LDAPLoginManager ldapManager;
    private final UserService userService;

    /**
     * [used by spring]
     */
    private LDAPLoginModule(final LDAPLoginManager ldapManager, final BaseSecurity securityManager, final UserService userManager, final Scheduler scheduler) {
        this.ldapManager = ldapManager;
        this.securityManager = securityManager;
        this.userService = userManager;
        this.scheduler = scheduler;
    }

    /**
	 */
    @Override
    public void init() {
        // Check if LDAP is enabled
        if (!isLDAPEnabled()) {
            log.info("LDAP login is disabled");
            return;
        }
        // Create LDAP Security Group if not existing. Used to identify users that
        // have to be synced with LDAP
        SecurityGroup ldapGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
        if (ldapGroup == null) {
            ldapGroup = securityManager.createAndPersistNamedSecurityGroup(LDAPConstants.SECURITY_GROUP_LDAP);
        }
        // check for valid configuration
        if (!checkConfigParameterIsNotEmpty(ldapUrl)) {
            return;
        }
        if (!checkConfigParameterIsNotEmpty(systemDN)) {
            return;
        }
        if (!checkConfigParameterIsNotEmpty(systemPW)) {
            return;
        }
        if (ldapBases == null || ldapBases.size() == 0) {
            log.error("Missing configuration 'ldapBases'. Add at least one LDAP Base to the this configuration in olatextconfig.xml first. Disabling LDAP");
            setEnableLDAPLogins(false);
            return;
        }
        if (!checkConfigParameterIsNotEmpty(ldapUserObjectClass)) {
            return;
        }
        if (!checkConfigParameterIsNotEmpty(ldapUserCreatedTimestampAttribute)) {
            return;
        }
        if (!checkConfigParameterIsNotEmpty(ldapUserLastModifiedTimestampAttribute)) {
            return;
        }
        if (userAttrMap == null || userAttrMap.size() == 0) {
            log.error("Missing configuration 'userAttrMap'. Add at least the email propery to the this configuration in olatextconfig.xml first. Disabling LDAP");
            setEnableLDAPLogins(false);
            return;
        }
        if (reqAttr == null || reqAttr.size() == 0) {
            log.error("Missing configuration 'reqAttr'. Add at least the email propery to the this configuration in olatextconfig.xml first. Disabling LDAP");
            setEnableLDAPLogins(false);
            return;
        }
        // check if OLAT user properties is defined in olat_userconfig.xml, if not disable the LDAP module
        if (!checkIfOlatPropertiesExists(userAttrMap)) {
            log.error("Invalid LDAP OLAT properties mapping configuration (userAttrMap). Disabling LDAP");
            setEnableLDAPLogins(false);
            return;
        }
        if (!checkIfOlatPropertiesExists(reqAttr)) {
            log.error("Invalid LDAP OLAT properties mapping configuration (reqAttr). Disabling LDAP");
            setEnableLDAPLogins(false);
            return;
        }
        if (syncOnlyOnCreateProperties != null && !checkIfStaticOlatPropertiesExists(syncOnlyOnCreateProperties)) {
            log.error("Invalid LDAP OLAT syncOnlyOnCreateProperties configuration. Disabling LDAP");
            setEnableLDAPLogins(false);
            return;
        }
        if (staticUserProperties != null && !checkIfStaticOlatPropertiesExists(staticUserProperties.keySet())) {
            log.error("Invalid static OLAT properties configuration (staticUserProperties). Disabling LDAP");
            setEnableLDAPLogins(false);
            return;
        }

        // check SSL certifications, throws Startup Exception if certificate is not found
        if (isSslEnabled()) {
            if (!checkServerCertValidity(0)) {
                throw new StartupException("LDAP enabled but no valid server certificate found. Please fix!");
            }
            if (!checkServerCertValidity(30)) {
                log.warn("Server Certificate will expire in less than 30 days.");
            }
        }

        // Check ldap connection
        if (ldapManager.bindSystem() == null) {
            // don't disable ldap, maybe just a temporary problem, but still report
            // problem in logfile
            log.warn("LDAP connection test failed during module initialization, edit config or contact network administrator");
        }
        // OK, everything finished checkes passed
        log.info("LDAP login is enabled");

        /*
		 *
		 */

        // Sync LDAP Users on Startup
        if (isLdapSyncOnStartup()) {
            initStartSyncJob();
        } else {
            log.info("LDAP start sync is disabled");
        }

        // Start LDAP cron sync job
        if (isLdapSyncCronSync()) {
            initCronSyncJob();
        } else {
            log.info("LDAP cron sync is disabled");
        }

        // OK, everything finished checkes passed
        log.info("LDAP login is enabled");
    }

    /**
     * Internal helper to sync users right away
     *
     * @param ldapManager
     */
    private void initStartSyncJob() {
        final LDAPError errors = new LDAPError();
        if (ldapManager.doBatchSync(errors)) {
            log.info("LDAP start sync: users synced");
        } else {
            log.warn("LDAP start sync error: " + errors.get());
        }
    }

    /**
     * Internal helper to initialize the cron syncer job
     */
    private void initCronSyncJob() {
        try {
            // Create job with cron trigger configuration
            final JobDetail jobDetail = new JobDetail("LDAP_Cron_Syncer_Job", Scheduler.DEFAULT_GROUP, LDAPUserSynchronizerJob.class);
            final CronTrigger trigger = new CronTrigger();
            trigger.setName("LDAP_Cron_Syncer_Trigger");
            trigger.setCronExpression(ldapSyncCronSyncExpression);
            // Schedule job now
            scheduler.scheduleJob(jobDetail, trigger);
            log.info("LDAP cron syncer is enabled with expression::" + ldapSyncCronSyncExpression);
        } catch (final ParseException e) {
            setLdapSyncCronSync(false);
            log.error("LDAP configuration in attribute 'ldapSyncCronSyncExpression' is not valid (" + ldapSyncCronSyncExpression
                    + "). See http://quartz.sourceforge.net/javadoc/org/quartz/CronTrigger.html to learn more about the cron syntax. Disabling LDAP cron syncing", e);
        } catch (final SchedulerException e) {
            log.error("Error while scheduling LDAP cron sync job. Disabling LDAP cron syncing", e);
        }
    }

    /**
     * Maps OLAT Property to the LDAP Attributes Configuration: LDAP Attributes Map = olatextconfig.xml (property=userAttrs)
     *
     * @param olatProperty
     *            OLAT PropertyattrID
     * @return LDAP Attribute
     */
    public static String mapOlatPropertyToLdapAttribute(final String olatProperty) {
        final Map<String, String> userAttrMapper = getReqAttrs();
        if (userAttrMapper.containsValue(olatProperty)) {
            final Iterator<String> itr = userAttrMapper.keySet().iterator();
            while (itr.hasNext()) {
                final String key = itr.next();
                if (userAttrMapper.get(key).compareTo(olatProperty) == 0) {
                    return key;
                }
            }
        }
        return null;
    }

    /**
     * Checks if Collection of naming Attributes contain defined required properties for OLAT * Configuration: LDAP Required Map = olatextconfig.xml (property=reqAttrs)
     *
     * @param attributes
     *            Collection of LDAP Naming Attribute
     * @return null If all required Attributes are found, otherwise String[] of missing Attributes
     */
    public static String[] checkReqAttr(final Attributes attrs) {
        final Map<String, String> reqAttrMap = getReqAttrs();
        final String[] missingAttr = new String[reqAttrMap.size()];
        int y = 0;
        for (String attKey : reqAttrMap.keySet()) {
            attKey = attKey.trim();
            if (attrs.get(attKey) == null) {
                missingAttr[y++] = attKey;
            }
        }
        if (y == 0) {
            return null;
        } else {
            return missingAttr;
        }
    }

    /**
     * Checks if defined OLAT Properties in olatextconfig.xml exist in OLAT. Configuration: LDAP Attributes Map = olatextconfig.xml (property=reqAttrs,
     * property=userAttributeMapper)
     *
     * @param attrs
     *            Map of OLAT Properties from of the LDAP configuration
     * @return true All exist OK, false Error
     */
    private boolean checkIfOlatPropertiesExists(final Map<String, String> attrs) {
        final List<UserPropertyHandler> upHandler = userService.getAllUserPropertyHandlers();
        for (final String ldapAttribute : attrs.keySet()) {
            boolean propertyExists = false;
            final String olatProperty = attrs.get(ldapAttribute);
            if (olatProperty.equals(LDAPConstants.LDAP_USER_IDENTIFYER)) {
                // LDAP user identifyer is not a user propery, it's the username
                continue;
            }
            for (final UserPropertyHandler userPropItr : upHandler) {
                if (olatProperty.equals(userPropItr.getName())) {
                    // ok, this property exist, continue with next one
                    propertyExists = true;
                    break;
                }
            }
            if (!propertyExists) {
                log.error("Error in checkIfOlatPropertiesExists(): configured LDAP attribute::" + ldapAttribute + " configured to map to OLAT user property::"
                        + olatProperty + " but no such user property configured in olat_userconfig.xml");
                return false;
            }
        }
        return true;
    }

    /**
     * Checks if defined Static OLAT Property in olatextconfig.xml exist in OLAT. Configuration: olatextconfig.xml (property=staticUserProperties)
     *
     * @param olatProperties
     *            Set of OLAT Properties from of the LDAP configuration
     * @return true All exist OK, false Error
     */
    private boolean checkIfStaticOlatPropertiesExists(final Set<String> olatProperties) {
        final List<UserPropertyHandler> upHandler = userService.getAllUserPropertyHandlers();
        for (final String olatProperty : olatProperties) {
            boolean propertyExists = false;
            for (final UserPropertyHandler userPropItr : upHandler) {
                if (olatProperty.equals(userPropItr.getName())) {
                    // ok, this property exist, continue with next one
                    propertyExists = true;
                    break;
                }
            }
            if (!propertyExists) {
                log.error("Error in checkIfStaticOlatPropertiesExists(): configured static OLAT user property::" + olatProperty
                        + " is not configured in olat_userconfig.xml");
                return false;
            }
        }
        return true;
    }

    /**
     * Checks if SSL certification is know and accepted by Java JRE.
     *
     * @param dayFromNow
     *            Checks expiration
     * @return true Certification accepted, false No valid certification
     * @throws Exception
     */
    private static boolean checkServerCertValidity(final int daysFromNow) {
        KeyStore keyStore;
        try {
            keyStore = KeyStore.getInstance(getTrustStoreType());
            keyStore.load(new FileInputStream(getTrustStoreLocation()), (getTrustStorePwd() != null) ? getTrustStorePwd().toCharArray() : null);
            final Enumeration<String> aliases = keyStore.aliases();
            while (aliases.hasMoreElements()) {
                final String alias = aliases.nextElement();
                final Certificate cert = keyStore.getCertificate(alias);
                if (cert instanceof X509Certificate) {
                    return isCertificateValid((X509Certificate) cert, daysFromNow);
                }
            }
        } catch (final Exception e) {
            return false;
        }
        return false;
    }

    private static boolean isCertificateValid(final X509Certificate x509Cert, final int daysFromNow) {
        try {
            x509Cert.checkValidity();
            if (daysFromNow > 0) {
                final Date nowPlusDays = new Date(System.currentTimeMillis() + (new Long(daysFromNow).longValue() * 24l * 60l * 60l * 1000l));
                x509Cert.checkValidity(nowPlusDays);
            }
        } catch (final Exception e) {
            return false;
        }
        return true;
    }

    /**
     * Internal helper to check for emtpy config variables
     *
     * @param param
     * @return true: not empty; false: empty or null
     */
    private boolean checkConfigParameterIsNotEmpty(final String param) {
        if (StringHelper.containsNonWhitespace(param)) {
            return true;
        } else {
            log.error("Missing configuration '" + param + "'. Add this configuration to olatextconfig.xml first. Disabling LDAP");
            setEnableLDAPLogins(false);
            return false;
        }
    }

    /*
     * Spring setter methods - don't use them to modify values at runtime!
     */
    public void setEnableLDAPLogins(final boolean enableLDAPLogins) {
        ldapEnabled = enableLDAPLogins;
    }

    public void setSslEnabled(final boolean sslEnabl) {
        sslEnabled = sslEnabl;
    }

    public void setActiveDirectory(final boolean aDirectory) {
        activeDirectory = aDirectory;
    }

    public void setLdapDateFormat(final String dateFormat) {
        ldapDateFormat = dateFormat;
    }

    public void setTrustStoreLocation(final String trustStoreLocation) {
        trustStoreLoc = trustStoreLocation.trim();
    }

    public void setTrustStorePwd(final String trustStorePwd) {
        trustStorePass = trustStorePwd.trim();
    }

    public void setTrustStoreType(final String trustStoreType) {
        trustStoreTyp = trustStoreType.trim();
    }

    public void setLdapSyncOnStartup(final boolean ldapStartSyncs) {
        ldapSyncOnStartup = ldapStartSyncs;
    }

    public void setLdapUserObjectClass(final String objectClass) {
        ldapUserObjectClass = objectClass.trim();
    }

    public void setLdapSystemDN(final String ldapSystemDN) {
        systemDN = ldapSystemDN.trim();
    }

    public void setLdapSystemPW(final String ldapSystemPW) {
        systemPW = ldapSystemPW.trim();
    }

    public void setLdapUrl(final String ldapUrlConfig) {
        ldapUrl = ldapUrlConfig.trim();
    }

    public void setLdapBases(final List<String> ldapBasesConfig) {
        ldapBases = ldapBasesConfig;
    }

    public void setUserAttributeMapper(final Map<String, String> userAttributeMapper) {
        // trim map
        userAttrMap = new HashMap<String, String>();
        for (final Entry<String, String> entry : userAttributeMapper.entrySet()) {
            userAttrMap.put(entry.getKey().trim(), entry.getValue().trim());
        }
        // optimizes for later usage
        userAttr = userAttrMap.keySet().toArray(new String[userAttrMap.size()]);
    }

    public void setReqAttrs(final Map<String, String> reqAttrs) {
        // trim map
        reqAttr = new HashMap<String, String>();
        for (final Entry<String, String> entry : reqAttrs.entrySet()) {
            reqAttr.put(entry.getKey().trim(), entry.getValue().trim());
        }
    }

    public void setSyncOnlyOnCreateProperties(final Set<String> syncOnlyOnCreatePropertiesConfig) {
        // trim map
        syncOnlyOnCreateProperties = new HashSet<String>();
        for (final String value : syncOnlyOnCreatePropertiesConfig) {
            syncOnlyOnCreateProperties.add(value.trim());
        }
    }

    public void setStaticUserProperties(final Map<String, String> staticUserPropertiesMap) {
        // trim map
        staticUserProperties = new HashMap<String, String>();
        for (final Entry<String, String> entry : staticUserPropertiesMap.entrySet()) {
            staticUserProperties.put(entry.getKey().trim(), entry.getValue().trim());
        }
    }

    public void setLdapUserLastModifiedTimestampAttribute(final String ldapUserLastModifiedTimestampAttribute) {
        LDAPLoginModule.ldapUserLastModifiedTimestampAttribute = ldapUserLastModifiedTimestampAttribute.trim();
    }

    public void setLdapUserCreatedTimestampAttribute(final String ldapUserCreatedTimestampAttribute) {
        LDAPLoginModule.ldapUserCreatedTimestampAttribute = ldapUserCreatedTimestampAttribute.trim();
    }

    public void setLdapUserPasswordAttribute(final String userPasswordAttribute) {
        LDAPLoginModule.ldapUserPasswordAttribute = userPasswordAttribute;
    }

    public void setLdapSyncCronSync(final boolean ldapSyncCronSync) {
        LDAPLoginModule.ldapSyncCronSync = ldapSyncCronSync;
    }

    public void setLdapSyncCronSyncExpression(final String ldapSyncCronSyncExpression) {
        LDAPLoginModule.ldapSyncCronSyncExpression = ldapSyncCronSyncExpression.trim();
    }

    public void setCacheLDAPPwdAsOLATPwdOnLogin(final boolean cacheLDAPPwdAsOLATPwdOnLogin) {
        LDAPLoginModule.cacheLDAPPwdAsOLATPwdOnLogin = cacheLDAPPwdAsOLATPwdOnLogin;
    }

    public void setConvertExistingLocalUsersToLDAPUsers(final boolean convertExistingLocalUsersToLDAPUsers) {
        LDAPLoginModule.convertExistingLocalUsersToLDAPUsers = convertExistingLocalUsersToLDAPUsers;
    }

    public void setDeleteRemovedLDAPUsersOnSync(final boolean deleteRemovedLDAPUsersOnSync) {
        LDAPLoginModule.deleteRemovedLDAPUsersOnSync = deleteRemovedLDAPUsersOnSync;
    }

    public void setDeleteRemovedLDAPUsersPercentage(final int deleteRemovedLDAPUsersPercentage) {
        LDAPLoginModule.deleteRemovedLDAPUsersPercentage = deleteRemovedLDAPUsersPercentage;
    }

    public void setPropagatePasswordChangedOnLdapServer(final boolean propagatePasswordChangedOnServer) {
        LDAPLoginModule.propagatePasswordChangedOnLdapServer = propagatePasswordChangedOnServer;
    }

    /*
     * Getters
     */
    public static String getLdapSystemDN() {
        return systemDN;
    }

    public static String getLdapSystemPW() {
        return systemPW;
    }

    public static String getLdapUrl() {
        return ldapUrl;
    }

    public static List<String> getLdapBases() {
        return ldapBases;
    }

    public static String getLdapUserObjectClass() {
        return ldapUserObjectClass;
    }

    public static String getLdapUserLastModifiedTimestampAttribute() {
        return ldapUserLastModifiedTimestampAttribute;
    }

    public static String getLdapUserCreatedTimestampAttribute() {
        return ldapUserCreatedTimestampAttribute;
    }

    public static String getLdapUserPasswordAttribute() {
        return ldapUserPasswordAttribute;
    }

    /**
     * @return a map of user properties to set for each LDAP user or NULL if no such properties have to be set
     */
    public static Map<String, String> getStaticUserProperties() {
        return staticUserProperties;
    }

    public static Map<String, String> getUserAttributeMapper() {
        return userAttrMap;
    }

    public static String[] getUserAttrs() {
        return userAttr;
    }

    public static Map<String, String> getReqAttrs() {
        return reqAttr;
    }

    public static Set<String> getSyncOnlyOnCreateProperties() {
        return syncOnlyOnCreateProperties;
    }

    public static boolean isLDAPEnabled() {
        return ldapEnabled;
    }

    public static boolean isSslEnabled() {
        return sslEnabled;
    }

    public static boolean isActiveDirectory() {
        return activeDirectory;
    }

    public static String getLdapDateFormat() {
        if (StringHelper.containsNonWhitespace(ldapDateFormat)) {
            return ldapDateFormat;
        }
        return "yyyyMMddHHmmss'Z'";// default
    }

    public static String getTrustStoreLocation() {
        return trustStoreLoc;
    }

    public static String getTrustStorePwd() {
        return trustStorePass;
    }

    public static String getTrustStoreType() {
        return trustStoreTyp;
    }

    public static boolean isLdapSyncOnStartup() {
        return ldapSyncOnStartup;
    }

    public static boolean isLdapSyncCronSync() {
        return ldapSyncCronSync;
    }

    public static String getLdapSyncCronSyncExpression() {
        return ldapSyncCronSyncExpression;
    }

    public static boolean isCacheLDAPPwdAsOLATPwdOnLogin() {
        return cacheLDAPPwdAsOLATPwdOnLogin;
    }

    public static boolean isConvertExistingLocalUsersToLDAPUsers() {
        return convertExistingLocalUsersToLDAPUsers;
    }

    public static boolean isDeleteRemovedLDAPUsersOnSync() {
        return deleteRemovedLDAPUsersOnSync;
    }

    public static int getDeleteRemovedLDAPUsersPercentage() {
        return deleteRemovedLDAPUsersPercentage;
    }

    public static boolean isPropagatePasswordChangedOnLdapServer() {
        return propagatePasswordChangedOnLdapServer;
    }
}


text:
'''
Created on 2013.09.07.
'''
import subprocess
import os
import re
import sys
import time, datetime

import RPi.GPIO as GPIO
import smbus
from libs.Adapy.Adafruit_I2C.Adafruit_I2C import Adafruit_I2C

from node.communication.log_message import LogMessage
from node.sensor.sensor_data import SensorData
from node.sensor.sensor_type import SensorType
from config.config import SensorConfig
from config.config import Config

class TempHumCollector(object):

    tempData = None
    humData = None

    def __init__(self):
	GPIO.setmode(GPIO.BCM)
        GPIO.setup(SensorConfig.GPIO_TEMP_HUM, GPIO.IN)
        #print("Temperature and humidity sensor data collector created.")
        self.tempData = SensorData(SensorType.TEMPERATURE, 4)
        self.humData = SensorData(SensorType.HUMIDITY, 4)

    def readTempHum(self):
        output = ""
        try:
            os.chdir('/home/pi/ahead/libs/Adapy/Adafruit_DHT_Driver')
            output = subprocess.check_output(["sudo", "./Adafruit_DHT", str(SensorConfig.SENSOR_MODEL_TEMP), str(SensorConfig.GPIO_TEMP_HUM)])
        except OSError:
            print("No such path.")
        except:
            print("Unknown error.")
        finally:
            if(output != ""):
                self.setTempData(output)
                self.setHumData(output)

    def setTempData(self, sensorOutput):
        matches = re.search("Temp =\s+([0-9.]+)", sensorOutput)
        if(matches):
            self.tempData = SensorData(SensorType.TEMPERATURE, float(matches.group(1)))
	    print "A jelenlegi homerseklet: " + str(float(matches.group(1))) + " C"

    def setHumData(self, sensorOutput):
        matches = re.search("Hum =\s+([0-9.]+)", sensorOutput)
        if(matches):
            self.humData = SensorData(SensorType.HUMIDITY, float(matches.group(1)))
	    print "A jelenlegi paratartalom: " + str(float(matches.group(1))) + " %"

class LuxCollector(object):
    # ## by huelke
    # ## http://www.adafruit.com/forums/viewtopic.php?f=8&t=34922&sid=dada906dd036fd7b07b6874748dae2d4&start=75

    i2c = None
    luxData = None

    def __init__(self, address=0x39, pause=0.8):
        self.i2c = Adafruit_I2C(address)
        self.address = address
        self.pause = pause
        self.gain = 0  # no gain preselected
        self.i2c.write8(0x80, 0x03)  # enable the device
        self.luxData = SensorData(SensorType.LUX, 0)

    def setGain(self, gain=1):
        """ Set the gain """
        if (gain != self.gain):
            if (gain == 1):
                self.i2c.write8(0x81, 0x02)  # set gain = 1X and timing = 402 mSec
                if(Config.DEVELOPER_MODE_ON):
                    print "Setting low gain"
            else:
                self.i2c.write8(0x81, 0x12)  # set gain = 16X and timing = 402 mSec
                if(Config.DEVELOPER_MODE_ON):
                    print "Setting high gain"
            self.gain = gain;  # safe gain for calculation
            time.sleep(self.pause)  # pause for integration (self.pause must be bigger than integration time)

    def readWord(self, reg):
        """Reads a word from the I2C device"""
        try:
            wordval = self.i2c.readU16(reg)
            newval = self.i2c.reverseByteOrder(wordval)
            #if(Config.DEVELOPER_MODE_ON):
                #print("I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, wordval & 0xFFFF, reg))
            return newval
        except IOError:
            print("Error accessing 0x%02X: Check your I2C address" % self.address)
            return -1

    def readFull(self, reg=0x8C):
        """Reads visible+IR diode from the I2C device"""
        return self.readWord(reg);

    def readIR(self, reg=0x8E):
        """Reads IR only diode from the I2C device"""
        return self.readWord(reg);

    def readLux(self, gain=1):
        """Grabs a lux reading either with autoranging (gain=0) or with a specified gain (1, 16)"""
        if (gain == 1 or gain == 16):
            self.setGain(gain)  # low/highGain
            ambient = self.readFull()
            IR = self.readIR()
        elif (gain == 0):  # auto gain
            self.setGain(16)  # first try highGain
            ambient = self.readFull()
            if (ambient < 65535):
                IR = self.readIR()
            if (ambient >= 65535 or IR >= 65535):  # value(s) exeed(s) datarange
                self.setGain(1)  # set lowGain
                ambient = self.readFull()
                IR = self.readIR()
        if (self.gain == 1):
            ambient *= 16  # scale 1x to 16x
            IR *= 16  # scale 1x to 16x
        ratio = (IR / float(ambient))  # changed to make it run under python 2
        #if(Config.DEVELOPER_MODE_ON):
            #print "IR Result", IR
            #print "Ambient Result", ambient
        if ((ratio >= 0) & (ratio <= 0.52)):
            lux = (0.0315 * ambient) - (0.0593 * ambient * (ratio ** 1.4))
        elif (ratio <= 0.65):
            lux = (0.0229 * ambient) - (0.0291 * IR)
        elif (ratio <= 0.80):
            lux = (0.0157 * ambient) - (0.018 * IR)
        elif (ratio <= 1.3):
            lux = (0.00338 * ambient) - (0.0026 * IR)
        elif (ratio > 1.3):
            lux = 0
        self.luxData = SensorData(SensorType.LUX, lux)
	print "A jelenlegi fenyerosseg: " +str(lux) + " Lux"

class DistanceCollector(object):

    distanceData = None
    arrgpio = None

    def __init__(self, decpulsetrigger=0.0001, inttimeout=2100):
        self.decpulsetrigger = decpulsetrigger  # Trigger duration
        self.inttimeout = inttimeout  # Number of loop iterations before timeout called
        # Which GPIO's are used [0]=BCM Port Number [1]=BCM Name [2]=Use [3]=Pin
        self.arrgpio = [(SensorConfig.GPIO_DISTANCE_ECHO, "GPIO0", "Echo", 11), (SensorConfig.GPIO_DISTANCE_TRIG, "GPIO7", "Trig", 7)]
        # Set GPIO Channels
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.arrgpio[0][0], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.arrgpio[1][0], GPIO.OUT)
        GPIO.output(self.arrgpio[1][0], False)
        if(Config.DEVELOPER_MODE_ON):
            GPIO.setwarnings(True)
            print("Distance sensor meter created")
        else:
            GPIO.setwarnings(False)

    def readDistance(self):
        # Trigger high for 0.0001s then low
        GPIO.output(self.arrgpio[1][0], True)
        time.sleep(self.decpulsetrigger)
        GPIO.output(self.arrgpio[1][0], False)
        # Wait for echo to go high (or timeout)
        intcountdown = self.inttimeout
        while (GPIO.input(self.arrgpio[0][0]) == 0 and intcountdown > 0):
            intcountdown = intcountdown - 1
        # If echo is high
        if intcountdown > 0:
            # Start timer and init timeout countdown
            echostart = time.time()
            intcountdown = self.inttimeout
            # Wait for echo to go low (or timeout)
            while (GPIO.input(self.arrgpio[0][0]) == 1 and intcountdown > 0):
                intcountdown = intcountdown - 1
            # Stop timer
            echoend = time.time()
            # Echo duration
            echoduration = echoend - echostart
        # Display distance
        if intcountdown > 0:
            intdistance = (echoduration * 1000000) / 58
            #if(Config.DEVELOPER_MODE_ON):
                #print "Distance = " + str(intdistance) + "cm"
            self.distanceData = SensorData(SensorType.DISTANCE, intdistance)
        else:
            self.distanceData = None
            if(Config.DEVELOPER_MODE_ON):
                print "Distance - timeout"

class MotionCollector(object):

    motionData = None

    def __init__(self):
        # Use BCM GPIO references, instead of physical pin numbers
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(SensorConfig.GPIO_MOTION, GPIO.IN)
        self.currentState = 0
        self.previousState = 0
        if Config.DEVELOPER_MODE_ON:
            print "Motion sensor meter created"

    def readMotion(self):
        self.currentState = GPIO.input(SensorConfig.GPIO_MOTION)
        if self.currentState == 1 and self.previousState == 0:
            if Config.DEVELOPER_MODE_ON:
                print "A mozgaserzekelo: mozgast eszlelt "
            self.motionData = SensorData(SensorType.MOTION, 1)
            self.previousState = 1
        elif self.currentState == 0 and self.previousState == 1:
            # PIR has returned to ready state
            if Config.DEVELOPER_MODE_ON:
                print "A mozgaserzekelo: nyugalmi allapot "
            self.motionData = SensorData(SensorType.MOTION, 0)
            self.previousState = 0
        else:
            self.motionData = None

class PowerCollector(object):

# ===========================================================================
# INA219 Class
# ===========================================================================

    i2c = None

# ===========================================================================
#   I2C ADDRESS/BITS
# ==========================================================================
    __INA219_ADDRESS = 0x40  # 1000000 (A0+A1=GND)
    __INA219_READ = 0x01
# ===========================================================================

# ===========================================================================
#    CONFIG REGISTER (R/W)
# ===========================================================================
    __INA219_REG_CONFIG = 0x00
# ===========================================================================
    __INA219_CONFIG_RESET = 0x8000  # Reset Bit
    __INA219_CONFIG_BVOLTAGERANGE_MASK = 0x2000  # Bus Voltage Range Mask
    __INA219_CONFIG_BVOLTAGERANGE_16V = 0x0000  # 0-16V Range
    __INA219_CONFIG_BVOLTAGERANGE_32V = 0x2000  # 0-32V Range

    __INA219_CONFIG_GAIN_MASK = 0x1800  # Gain Mask
    __INA219_CONFIG_GAIN_1_40MV = 0x0000  # Gain 1, 40mV Range
    __INA219_CONFIG_GAIN_2_80MV = 0x0800  # Gain 2, 80mV Range
    __INA219_CONFIG_GAIN_4_160MV = 0x1000  # Gain 4, 160mV Range
    __INA219_CONFIG_GAIN_8_320MV = 0x1800  # Gain 8, 320mV Range

    __INA219_CONFIG_BADCRES_MASK = 0x0780  # Bus ADC Resolution Mask
    __INA219_CONFIG_BADCRES_9BIT = 0x0080  # 9-bit bus res = 0..511
    __INA219_CONFIG_BADCRES_10BIT = 0x0100  # 10-bit bus res = 0..1023
    __INA219_CONFIG_BADCRES_11BIT = 0x0200  # 11-bit bus res = 0..2047
    __INA219_CONFIG_BADCRES_12BIT = 0x0400  # 12-bit bus res = 0..4097

    __INA219_CONFIG_SADCRES_MASK = 0x0078  # Shunt ADC Resolution and Averaging Mask
    __INA219_CONFIG_SADCRES_9BIT_1S_84US = 0x0000  # 1 x 9-bit shunt sample
    __INA219_CONFIG_SADCRES_10BIT_1S_148US = 0x0008  # 1 x 10-bit shunt sample
    __INA219_CONFIG_SADCRES_11BIT_1S_276US = 0x0010  # 1 x 11-bit shunt sample
    __INA219_CONFIG_SADCRES_12BIT_1S_532US = 0x0018  # 1 x 12-bit shunt sample
    __INA219_CONFIG_SADCRES_12BIT_2S_1060US = 0x0048  # 2 x 12-bit shunt samples averaged together
    __INA219_CONFIG_SADCRES_12BIT_4S_2130US = 0x0050  # 4 x 12-bit shunt samples averaged together
    __INA219_CONFIG_SADCRES_12BIT_8S_4260US = 0x0058  # 8 x 12-bit shunt samples averaged together
    __INA219_CONFIG_SADCRES_12BIT_16S_8510US = 0x0060  # 16 x 12-bit shunt samples averaged together
    __INA219_CONFIG_SADCRES_12BIT_32S_17MS = 0x0068  # 32 x 12-bit shunt samples averaged together
    __INA219_CONFIG_SADCRES_12BIT_64S_34MS = 0x0070  # 64 x 12-bit shunt samples averaged together
    __INA219_CONFIG_SADCRES_12BIT_128S_69MS = 0x0078  # 128 x 12-bit shunt samples averaged together

    __INA219_CONFIG_MODE_MASK = 0x0007  # Operating Mode Mask
    __INA219_CONFIG_MODE_POWERDOWN = 0x0000
    __INA219_CONFIG_MODE_SVOLT_TRIGGERED = 0x0001
    __INA219_CONFIG_MODE_BVOLT_TRIGGERED = 0x0002
    __INA219_CONFIG_MODE_SANDBVOLT_TRIGGERED = 0x0003
    __INA219_CONFIG_MODE_ADCOFF = 0x0004
    __INA219_CONFIG_MODE_SVOLT_CONTINUOUS = 0x0005
    __INA219_CONFIG_MODE_BVOLT_CONTINUOUS = 0x0006
    __INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS = 0x0007
# ===========================================================================

# ===========================================================================
#   SHUNT VOLTAGE REGISTER (R)
# ===========================================================================
    __INA219_REG_SHUNTVOLTAGE = 0x01
# ===========================================================================

# ===========================================================================
#   BUS VOLTAGE REGISTER (R)
# ===========================================================================
    __INA219_REG_BUSVOLTAGE = 0x02
# ===========================================================================

# ===========================================================================
#   POWER REGISTER (R)
# ===========================================================================
    __INA219_REG_POWER = 0x03
# ===========================================================================

# ==========================================================================
#    CURRENT REGISTER (R)
# ===========================================================================
    __INA219_REG_CURRENT = 0x04
# ===========================================================================

# ===========================================================================
#    CALIBRATION REGISTER (R/W)
# ===========================================================================
    __INA219_REG_CALIBRATION = 0x05
# ===========================================================================

    powerData = None
    currentData = None

    # Constructor
    def __init__(self, address=0x40, debug=False):
        self.i2c = Adafruit_I2C(address, debug=False)
        self.address = address
        self.ina219SetCalibration_32V_2A()
        if Config.DEVELOPER_MODE_ON:
            print("Power sensor meter created")

    def ina219SetCalibration_32V_2A(self):
        self.ina219_currentDivider_mA = 10  # Current LSB = 100uA per bit (1000/100 = 10)
        self.ina219_powerDivider_mW = 2  # Power LSB = 1mW per bit (2/1)

        # Set Calibration register to 'Cal' calculated above
        bytes = [(0x1000 >> 8) & 0xFF, 0x1000 & 0xFF]
        self.i2c.writeList(self.__INA219_REG_CALIBRATION, bytes)

        # Set Config register to take into account the settings above
        config = self.__INA219_CONFIG_BVOLTAGERANGE_32V | \
                 self.__INA219_CONFIG_GAIN_8_320MV | \
                 self.__INA219_CONFIG_BADCRES_12BIT | \
                 self.__INA219_CONFIG_SADCRES_12BIT_1S_532US | \
                 self.__INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS

        bytes = [(config >> 8) & 0xFF, config & 0xFF]
        self.i2c.writeList(self.__INA219_REG_CONFIG, bytes)

    def getBusVoltage_raw(self):
        result = self.i2c.readU16(self.__INA219_REG_BUSVOLTAGE)

        # Shift to the right 3 to drop CNVR and OVF and multiply by LSB
        return (result >> 3) * 4

    def getShuntVoltage_raw(self):
        result = self.i2c.readList(self.__INA219_REG_SHUNTVOLTAGE, 2)
        if (result[0] >> 7 == 1):
            value = ((result[0] & 0xF0) | (result[1])) - 1
            return ~value
        else:
            return (result[0] << 8) | (result[1])

    def getCurrent_raw(self):
        result = self.i2c.readList(self.__INA219_REG_CURRENT, 2)
        if (result[0] >> 7 == 1):
            value = ((result[0] & 0xF0) | (result[1])) - 1
            return ~value
        else:
            return (result[0] << 8) | (result[1])

    def getPower_raw(self):
        result = self.i2c.readList(self.__INA219_REG_POWER, 2)
        if (result[0] >> 7 == 1):
            value = ((result[0] & 0xF0) | (result[1])) - 1
            return ~value
        else:
            return (result[0] << 8) | (result[1])

    def getShuntVoltage_mV(self):
        value = self.getShuntVoltage_raw()
        return value * 0.01

    def getBusVoltage_V(self):
        value = self.getBusVoltage_raw()
        return value * 0.001

    def getCurrent_mA(self):
        valueDec = self.getCurrent_raw()
        valueDec /= self.ina219_currentDivider_mA
        return valueDec

    def getPower_mW(self):
        valueDec = self.getPower_raw()
        valueDec /= self.ina219_powerDivider_mW
        return valueDec

    def readPowerInWatt(self):
        watt = float(self.getPower_mW()) / 1000
        self.powerData = SensorData(SensorType.POWER, watt)
	print "A LED aramfogyasztasa: " + str(watt) + " Watt"

    def readCurrentInAmper(self):
        amper = float(self.getCurrent_mA()) / 1000
        self.currentData = SensorData(SensorType.CURRENT, amper)

redpajama_set_name: RedPajamaGithub


text:
/******************************************************************************
 Application management
*******************************************************************************/

'use strict';

var _ = require('underscore'),
    logger = require('../../../logger'),
    Models = require('../../../models');

module.exports = function(options, client, self) {
  // ------------------------------ LIST APPS ----------------------------------

  self.list_apps = function(callback) {
    var values = [];
    client.search({
      index: self.toMasterIndex(),
      type: self.toAppsIndex(),
      from: 0,
      size: options.elasticsearch.max_children,
      refresh: true,
    }, function(error, response) {
      if (!error && response && response.hits && response.hits.hits) {
        _.each(response.hits.hits, function(hit) {
          if (hit._source) values.push(new Models.Application(hit._source));
        });
      }
      callback(values);
    });
  };

  // -------------------------------- ADD APP ----------------------------------

  self.add_app = function(application, callback) {
    // update creation date
    var app_id = application.get('id');
    client.create({
      index: self.toMasterIndex(),
      type: self.toAppsIndex(),
      id: app_id,
      body: application.toJSON(),
    }, function(error, response) {
      if (error) {
        logger.error(app_id, 'add_app', error);
        callback();
      } else {
        // add mapping for users
        var mapping = {};
        mapping[self.toUserType(app_id)] = {
          _all: { enabled: false },
          properties: {
            id: { type: 'string', index: 'not_analyzed' },
            anonymous: { type: 'boolean' },
            admin: { type: 'boolean' },
            blocked: { type: 'boolean' },
            username: { type: 'string' },
            displayname: { type: 'string' },
            email: { type: 'string', index: 'not_analyzed' },
            avatar: { type: 'string', index: 'not_analyzed' },
            created: { type: 'long' },
            last_login: { type: 'long' },
            last_logout: { type: 'long' },
            onboard: { type: 'integer' },
            karma: { type: 'integer' },
            logout_karma: { type: 'integer' },
            meta: { type: 'object', enabled: false },
          },
        };
        client.indices.putMapping({
          index: self.toMasterIndex(),
          type: self.toUserType(app_id),
          body: mapping,
        }, function(error, response) {
          if (error) {
            logger.error(app_id, 'put_mapping', error);
          }
        });

        // add mapping for doc
        mapping = {};
        mapping[self.toDocType(app_id)] = {
          _all: { enabled: false },
          properties: {
            id: { type: 'string', index: 'not_analyzed' },
            parent: { type: 'string', index: 'not_analyzed' },
            parent_type: { type: 'string', index: 'not_analyzed' },
            type: { type: 'string', index: 'not_analyzed' },
            created: { type: 'long' },
            updated: { type: 'long' },
            initials: { type: 'string', index: 'not_analyzed' },
            header: { type: 'string' },
            body: { type: 'string' },
            thumbnail: { type: 'string', index: 'not_analyzed' },
            sticky: { type: 'boolean' },
            locked: { type: 'boolean' },
            visible: { type: 'boolean' },
            inappropriate: { type: 'boolean' },
            permission: { type: 'integer' },
            usage: { type: 'integer' },
            user_id: { type: 'string', index: 'not_analyzed' },
            user_username: { type: 'string' },
            user_displayname: { type: 'string' },
            user_avatar: { type: 'string', index: 'not_analyzed' },
            order: { type: 'integer' },
            children_count: { type: 'integer' },
            archived: { type: 'boolean' },
            archived_ts: { type: 'long' },
            meta: { type: 'object', enabled: false },
          },
        };
        client.indices.putMapping({
          index: self.toMasterIndex(),
          type: self.toDocType(app_id),
          body: mapping,
        }, function(error, response) {
          if (error) {
            logger.error(app_id, 'put_mapping', error);
            callback();
          } else {
            var home_document = (new Models.Document()).toHome();
            client.create({
              index: self.toMasterIndex(),
              type: self.toDocType(app_id),
              id: home_document.get('id'),
              body: home_document.toJSON(),
            }, function(error, response) {
              if (error) {
                logger.info(app_id, 'add_app', error);
              }
              callback(application);
            });
          }
        });
      }
    });
  };

  // ------------------------------- UPDATE APP --------------------------------

  self.update_app = function(application, attributes, callback) {
    var app_id = application.get('id');
    client.update({
      index: self.toMasterIndex(),
      type: self.toAppsIndex(),
      id: app_id,
      retryOnConflict: options.elasticsearch.retry_on_conflict,
      body: {
        doc: attributes || application.toJSON(),
      },
    }, function(error, response) {
      if (error) {
        logger.error(app_id, 'update_app', error);
        callback();
      } else {
        if (attributes) application.set(attributes);
        callback(application);
      }
    });
  };

  // ------------------------------- DELETE APP --------------------------------

  self.delete_app = function(application, callback) {
    var app_id = application.get('id');
    client.delete({
      index: self.toMasterIndex(),
      type: self.toAppsIndex(),
      id: app_id,
    }, function(error, response) {
      if (error) {
        logger.error(app_id, 'delete_app', error);
        callback();
      } else {
        // delete documents and users or index
        client.deleteByQuery({
          index: self.toMasterIndex(),
          type: self.toUserType(app_id),
        }, function(error, response) {
          if (error) {
            logger.error(app_id, 'delete_user_index', error);
            callback();
          } else {
            logger.info(app_id, 'delete_user_index', response.elements.length + ' users deleted');
            client.deleteByQuery({
              index: self.toMasterIndex(),
              type: self.toDocType(app_id),
            }, function(error, response) {
              if (error) {
                logger.error(app_id, 'delete_doc_index', error);
                callback();
              } else {
                logger.info(app_id, 'delete_doc_index', response.elements.length + ' docs deleted');
                callback(application);
              }
            });
          }
        });
      }
    });
  };

  // --------------------------------- GET APP ---------------------------------

  self.get_app = function(app_id, callback) {
    client.get({
      index: self.toMasterIndex(),
      type: self.toAppsIndex(),
      id: app_id,
    }, function(error, response) {
      if (error) {
        logger.error(app_id, 'get_app', error);
        callback();
      } else if (response._source) {
        callback(new Models.Application(response._source));
      }
    });
  };

  // -------------------------- GET APP FROM API_KEY ---------------------------

  self.get_api_key = function(api_key, callback) {
    client.search({
      index: self.toMasterIndex(),
      type: self.toAppsIndex(),
      refresh: true,
      body: {
        from: 0,
        size: options.elasticsearch.max_children,
        query: {
          multi_match: {
            query: api_key,
            fields: ['api_keys'],
          },
        },
      },
    }, function(error, response) {
      if (error) {
        logger.error(api_key, 'get_api_key', error);
      } else if (response.hits && response.hits.hits && response.hits.hits.length) {
        var application = null;
        _.each(response.hits.hits, function(hit) {
          if (hit._source.api_keys.indexOf(api_key) >= 0) {
            application = new Models.Application(hit._source);
          }
        });
        callback(application);
        return;
      }
      callback();
    });
  };

  // ------------------------------ RESET USERS --------------------------------

  self.reset_users = function(application, callback) {
    var app_id = application.get('id');
    client.deleteByQuery({
      index: self.toMasterIndex(),
      type: self.toUserType(app_id),
    }, function(error, response) {
      if (error) {
        logger.error(app_id, 'reset_users', error);
      } else {
        logger.info(app_id, 'reset_users', response);
      }
      callback();
    });
  };

  // ------------------------------- PROPERTIES --------------------------------

  self.set_app_property = function(app_id, property, value, callback) {
    var doc = {};
    doc[Models.PROPERTY_PREFIX + property] = value;
    client.update({
      index: self.toMasterIndex(),
      type: self.toAppsIndex(),
      id: app_id,
      retryOnConflict: options.elasticsearch.retry_on_conflict,
      body: {
        doc: doc,
      },
    }, function(error, response) {
      if (error) {
        logger.error(app_id, 'set_app_property', error);
        callback();
      } else {
        callback(property, value);
      }
    });
  };

  self.get_app_property = function(app_id, property, callback) {
    client.get({
      index: self.toMasterIndex(),
      type: self.toAppsIndex(),
      id: app_id,
    }, function(error, response) {
      if (error) {
        logger.error(app_id, 'get_app_property', error);
        callback();
      } else if (response._source && response._source[Models.PROPERTY_PREFIX + property] != undefined) {
        callback(property, response._source[Models.PROPERTY_PREFIX + property]);
      } else {
        callback();
      }
    });
  };
};


text:
namespace mash {
namespace wm {

// Lays out the shelf within shelf containers.
class ShelfLayoutManager : public LayoutManager {
 public:
  explicit ShelfLayoutManager(mus::Window* owner);
  ~ShelfLayoutManager() override;

  // Returns the shelf, which may be null.
  mus::Window* GetShelfWindow();

  void SetAlignment(shelf::mojom::Alignment alignment);
  void SetAutoHideBehavior(shelf::mojom::AutoHideBehavior auto_hide);

  shelf::mojom::Alignment alignment() const { return alignment_; }
  shelf::mojom::AutoHideBehavior auto_hide_behavior() const {
    return auto_hide_behavior_;
  }

 private:
  // Overridden from LayoutManager:
  void LayoutWindow(mus::Window* window) override;

  shelf::mojom::Alignment alignment_;
  shelf::mojom::AutoHideBehavior auto_hide_behavior_;

  DISALLOW_COPY_AND_ASSIGN(ShelfLayoutManager);
};

}  // namespace wm
}  // namespace mash

#endif  // MASH_WM_SHELF_LAYOUT_MANAGER_H_


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using BenchmarkDotNet.Extensions;
using BenchmarkDotNet.Loggers;
using BenchmarkDotNet.Reports;

namespace BenchmarkDotNet.Exporters
{
    public class CompositeExporter : IExporter
    {
        private readonly ImmutableArray<IExporter> exporters;

        public CompositeExporter(ImmutableArray<IExporter> exporters) => this.exporters = exporters;

        public string Name => nameof(CompositeExporter);

        public void ExportToLog(Summary summary, ILogger logger)
        {
            if (summary.GetColumns().IsNullOrEmpty())
                logger.WriteLineHint("You haven't configured any columns, your results will be empty");

            foreach (var exporter in exporters)
            {
                try
                {
                    exporter.ExportToLog(summary, logger);
                }
                catch (Exception e)
                {
                    logger.WriteLineError(e.ToString());
                }
            }
        }

        public IEnumerable<string> ExportToFiles(Summary summary, ILogger consoleLogger)
            => exporters.SelectMany(exporter =>
            {
                var files = new List<string>();
                try
                {
                    files.AddRange(exporter.ExportToFiles(summary, consoleLogger));
                }
                catch (Exception e)
                {
                    consoleLogger.WriteLineError(e.ToString());
                }
                return files;
            });
    }
}


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

    <string name="app_name">MyTools</string>

    <!-- GuideActivity -->
    <string name="selSocket">Socket请求</string>
    <string name="selHttp">Http连接</string>
    <!-- GuideActivity -->

    <!-- tips -->
    <string name="empty">您输入的信息不全</string>
    <string name="notNumber">您输入的不是数字</string>
    <string name="positive">您需要输入的是正数</string>
    <string name="url_error">输入有误</string>
    <string name="bigNumber">线程数太大,请不要超过</string>
    <!-- tips -->

    <string name="label_thread_num">线程数</string>
    <string name="label_url">地址</string>

    <!-- TCP UDP -->

    <string name="ip">IP:</string>
    <string name="udp">UDP</string>
    <string name="tcp">TCP</string>
    <string name="packSize">数据包大小</string>
    <string name="bt_start">开始测试</string>
    <string name="label_TcpThreadNum">TCP线程数</string>
    <string name="label_UdpThreadNum">UDP线程数</string>

    <!-- TCP UDP -->

    <!-- AppSearchActivity -->
    <string name="list_app_name">应用程序名称</string>
    <string name="list_package_id">应用包名</string>
    <string name="list_image">程序图标</string>
    <string name="noApp">没有该应用</string>
    <string name="inputApp">请输入应用名称</string>
    <string name="search_app">查找应用Package ID</string>
    <string name="bt_search">搜索</string>
    <string name="label_appName">软件名称</string>
    <!-- AppSearchActivity -->

    <!-- RSA -->
    <string name="bt_encrypt">加密</string>
    <string name="bt_decrypt">解密</string>
    <string name="rsaTitle">RSA加密与解密</string>
    <string name="rsaDescription">加密内容显示在界面,并存储到文件中</string>
    <string name="lable_rsa">加密的内容</string>
    <string name="rsa_encrypt_tip">没有给mContent赋值,请在程序中进行赋值后再使用加密方法</string>
    <string name="rsa_decrypt_tip">没有给mContent赋值,请在程序中进行赋值后再使用解密方法</string>
    <!-- RSA -->

    <!-- uid -->
    <string name="uid_search">Uid检查</string>
    <string name="uid_searchSame">同Uid检查</string>
    <string name="uid_list">Uid遍历</string>
    <string name="uid">uid</string>
    <string name="appName">appName</string>
    <string name="pid">pid</string>
    <string name="explain_sameUid">说明:列表显示的是相同UID的应用的列表</string>
    <string name="explain_allUid">说明:列表显示的是所有UID的应用的列表</string>
    <!-- uid -->

    <!-- media -->
    <string name="media">多媒体播放</string>

    <!-- camera -->
    <string name="camera">Camera Intent</string>

    <!-- custom_loading -->
    <string name="custom_loading">custom_loading</string>

    <!-- camera-->
    <string name="camera_new">camera</string>

    <string name="seek_bar">seek_bar</string>

    <!-- DatePicker-->
    <string name="sans_serif" translatable="false">sans-serif</string>
    <string name="action_settings">Settings</string>

</resources>


text:
package org.twak.streetview;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

public class Utils {

	public static void main (String[] args) throws Throwable { // dumps downloaded panoramas as lat/long for qgis

//		joinPanoramas();
//		fileNamesToCSV();
	}

	private static void fileNamesToCSV() throws IOException {
		BufferedWriter out = new BufferedWriter( new FileWriter( new File("/home/twak/Desktop/tmp.csv") ) );

		for (File f : new File ("/home/twak/Downloads").listFiles()) {

			try {
			String[] vals = f.getName().split( "_" );

			out.write( vals[0] +","+vals[1]+"," + f.getName() +"\n");
			}
			catch (Throwable th ) {
				System.err.println(f);
				th.printStackTrace();
			}
		}

		out.close();
	}
}


text:
module Less2Sass
  module Less
    module Tree
      # Represents the value of any Less AST node.
      #
      # It has no individual representation in Sass,
      # so it returns its value node's Sass representation,
      # when {#to_sass} gets called.
      #
      # Sass equivalents:
      #   - {::Sass::Script::Tree::Literal} if part of property declaration
      #   - {::Sass::Script::Tree::ListLiteral} if part of variable definition
      #
      # @see Node
      class ValueNode < Node
        # @todo update Sass and check out a lately commit regarding the deprecated SassScript usage in CSS rules
        # @see https://github.com/sass/sass/commit/b671122234d2d4df088a6c6d4c54b64d6997d255

        # The ValueNode is not the final value of a variable
        # or a property.
        #
        # @return [Node, Array<Node>]
        attr_accessor :value

        # This node's value is either a single expression,
        # or an array of those. The array needs to be further
        # processed.
        #
        # @return [::Sass::Script::Tree::Literal, ::Sass::Script::Tree::ListLiteral]
        # @see Node#to_sass
        def to_sass
          if @value.is_a?(Array)
            # TODO: don't forget about interpolation. What if one of the expressions is a variable?
            if @parent.variable_definition? || contains_variables?
              elements = @value.inject([]) { |elements, elem| elements << elem.to_sass }
              node(::Sass::Script::Tree::ListLiteral.new(elements, :comma), line)
            else
              value = @value.inject([]) do |value, elem|
                substring = elem.to_sass
                # TODO: describe solution for '"Source Code Pro", Monaco, monospace'
                substring = substring.value.value if substring.is_a?(::Sass::Script::Tree::Literal)
                value << substring
              end.join(', ')
              node(::Sass::Script::Tree::Literal.new(::Sass::Script::Value::String.new(value)), line)
            end
          else
            @value.to_sass
          end
        end

        # @see RuleNode#eval
        def eval
          @value.eval
        end
      end
    end
  end
end


text:
#ifndef D_TestTestingFixture_H
#define D_TestTestingFixture_H

class TestTestingFixture
{
public:

	TestTestingFixture()
	{
		output_ = new StringBufferTestOutput();
		result_ = new TestResult(*output_);
		genTest_ = new ExecFunctionTestShell();
		registry_ = new TestRegistry();

		registry_->setCurrentRegistry(registry_);
		registry_->addTest(genTest_);
	}
	;

	virtual ~TestTestingFixture()
	{
		registry_->setCurrentRegistry(0);
		delete registry_;
		delete result_;
		delete output_;
		delete genTest_;
	}

	void setTestFunction(void(*testFunction)())
	{
		genTest_->testFunction_ = testFunction;
	}

	void setSetup(void(*setupFunction)())
	{
		genTest_->setup_ = setupFunction;
	}

	void setTeardown(void(*teardownFunction)())
	{
		genTest_->teardown_ = teardownFunction;
	}

	void runAllTests()
	{
		registry_->runAllTests(*result_);
	}

	int getFailureCount()
	{
		return result_->getFailureCount();
	}

	void assertPrintContains(const SimpleString& contains)
	{
		assertPrintContains(output_, contains);
	}

	static void assertPrintContains(StringBufferTestOutput* output,
			const SimpleString& contains)
	{
		if (output->getOutput().contains(contains)) return;
		SimpleString message("\tActual <");
		message += output->getOutput().asCharString();
		message += ">\n";
		message += "\tdid not contain <";
		message += contains.asCharString();
		message += ">\n";
		FAIL(message.asCharString());

	}

	TestRegistry* registry_;
	ExecFunctionTestShell* genTest_;
	StringBufferTestOutput* output_;
	TestResult * result_;
};

#endif


text:
package de.thaso.swa.db.common.base;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * EntityBaseTest
 *
 * @author thaler
 * @since 13.09.16
 */
public class EntityBaseTest {

    private static final String SOME_VALUE = "some value";
    private static final String OTHER_VALUE = "some other value";

    private TestEntity firstEntity;
    private TestEntity secondEntity;
    private OtherEntity otherEntity;

    @Test
    public void equals_whenBothIdAreIdentical() {
        // given
        firstEntity = new TestEntity(1L, SOME_VALUE);
        secondEntity = new TestEntity(1L, OTHER_VALUE);
        // then
        assertThat(firstEntity.equals(secondEntity), is(true));
    }

    @Test
    public void equals_whenBothIdNotSet() {
        // given
        firstEntity = new TestEntity(null, SOME_VALUE);
        secondEntity = new TestEntity(null, SOME_VALUE);
        // then
        assertThat(firstEntity.equals(secondEntity), is(false));
    }

    @Test
    public void equals_whenOnlyFirstIdIsSet() {
        // given
        firstEntity = new TestEntity(1L, SOME_VALUE);
        secondEntity = new TestEntity(null, SOME_VALUE);
        // then
        assertThat(firstEntity.equals(secondEntity), is(false));
    }

    @Test
    public void equals_whenOnlySecondIdIsSet() {
        // given
        firstEntity = new TestEntity(null, SOME_VALUE);
        secondEntity = new TestEntity(1L, SOME_VALUE);
        // then
        assertThat(firstEntity.equals(secondEntity), is(false));
    }

    @Test
    public void equals_whenSecondEntityIsNull() {
        // given
        firstEntity = new TestEntity(1L, SOME_VALUE);
        // then
        assertThat(firstEntity.equals(null), is(false));
    }

    @Test
    public void equals_whenSecondEntityIsOtherEntity() {
        // given
        firstEntity = new TestEntity(1L, SOME_VALUE);
        otherEntity = new OtherEntity(1L, SOME_VALUE);
        // then
        assertThat(firstEntity.equals(otherEntity), is(false));
    }

    private class TestEntity extends EntityBase {
        private Long id;
        private String name;

        public TestEntity(final Long id, final String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public Long getId() {
            return id;
        }

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

        public String getName() {
            return name;
        }

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

    private class OtherEntity extends EntityBase {
        private Long id;
        private String name;

        public OtherEntity(final Long id, final String name) {
            this.id = id;
            this.name = name;
        }

        @Override
        public Long getId() {
            return id;
        }

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

        public String getName() {
            return name;
        }

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


text:
package org.craftedsw.tripservicekata.trip;

public class Trip {

}


text:
require 'json'

class PingResult
  ATTRIBUTES = [:avg, :dst_ip, :loss_percentage, :max, :min, :received, :stddev, :transmitted]
  attr_reader *ATTRIBUTES

  def to_json
    result_data = {}
    ATTRIBUTES.each do |attribute|
      result_data[attribute] = send(attribute)
    end
    result_data.to_json
  end
end


text:
static NSString * const RCIOFileManagerSharedExamplesName = @"RCIOFileManagerSharedExamplesName";
static NSString * const RCIOFileManagerSharedExamplesCreateBlock = @"RCIOFileManagerSharedExamplesCreateBlock";

static NSString * const RCIOFileManagerSharedReactionExamples = @"RCIOFileManagerSharedReactionExamples";
static NSString * const RCIOFileManagerSharedReactionExamplesTestRootDirectoryURL = @"RCIOFileManagerSharedReactionExamplesTestRootDirectoryURL";
static NSString * const RCIOFileManagerSharedReactionExamplesCreateBlock = @"RCIOFileManagerSharedReactionExamplesCreateBlock";
static NSString * const RCIOFileManagerSharedReactionExamplesMoveBlock = @"RCIOFileManagerSharedReactionExamplesMoveBlock";
static NSString * const RCIOFileManagerSharedReactionExamplesCopyBlock = @"RCIOFileManagerSharedReactionExamplesCopyBlock";
static NSString * const RCIOFileManagerSharedReactionExamplesRemoveBlock = @"RCIOFileManagerSharedReactionExamplesRemoveBlock";

SharedExampleGroupsBegin(RCIOFileManager)

sharedExamplesFor(RCIOFileManagerSharedReactionExamples, ^(NSDictionary *data) {
	__block NSURL *testRootDirectoryURL;
	__block void(^createFilesystemItem)(NSURL *);
	__block void(^moveFilesystemItem)(NSURL *, NSURL *);
	__block void(^copyFilesystemItem)(NSURL *, NSURL *);
	__block void(^removeFilesystemItem)(NSURL *);

	__block void(^subscribeToContentsOfDirectoryAtURL)(NSURL *);
	__block RACDisposable *subscriptionDisposable;

	__block NSSet *result;
	__block NSError *outerError;
	__block BOOL outerErrored;
	__block BOOL outerCompleted;
	__block BOOL innerSuccess;
	__block NSError *innerError;

	before(^{
		testRootDirectoryURL = data[RCIOFileManagerSharedReactionExamplesTestRootDirectoryURL];
		createFilesystemItem = data[RCIOFileManagerSharedReactionExamplesCreateBlock];
		moveFilesystemItem = data[RCIOFileManagerSharedReactionExamplesMoveBlock];
		copyFilesystemItem = data[RCIOFileManagerSharedReactionExamplesCopyBlock];
		removeFilesystemItem = data[RCIOFileManagerSharedReactionExamplesRemoveBlock];

		subscribeToContentsOfDirectoryAtURL = ^(NSURL *url) {
			subscriptionDisposable = [[[RCIOFileManager contentsOfDirectoryAtURL:url options:0] skip:1] subscribeNext:^(RACSignal *signal) {
				result = pathSetFromURLArray([[signal collect] firstOrDefault:nil success:&innerSuccess error:&innerError]);
			} error:^(NSError *error) {
				outerError = error;
				outerErrored = YES;
			} completed:^{
				outerCompleted = YES;
			}];
		};

		result = nil;
		outerError = nil;
		outerErrored = NO;
		outerCompleted = NO;
		innerSuccess = NO;
		innerError = nil;
	});

	after(^{
		expect(outerError).to.beNil();
		expect(outerErrored).to.beFalsy();
		expect(outerCompleted).to.beFalsy();
		[subscriptionDisposable dispose];
	});

	describe(@"should react to", ^{
		__block NSURL *directoryURL;

		before(^{
			directoryURL = [testRootDirectoryURL URLByAppendingPathComponent:@"directory"];
			[[[NSFileManager alloc] init] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:nil error:NULL];
		});

		describe(@"the directory being changed", ^{
			__block NSURL *newDirectoryURL;

			before(^{
				newDirectoryURL = [testRootDirectoryURL URLByAppendingPathComponent:@"newDirectory"];
			});

			it(@"by moving from the url", ^{
				subscribeToContentsOfDirectoryAtURL(directoryURL);

				moveFilesystemItem(directoryURL, newDirectoryURL);

				expect(innerError).willNot.beNil();
				expect(innerSuccess).to.beFalsy();
			});

			it(@"by moving to the url", ^{
				NSString *itemName = @"item";
				NSURL *itemURL = [directoryURL URLByAppendingPathComponent:itemName];
				NSURL *newItemURL = [newDirectoryURL URLByAppendingPathComponent:itemName];
				createFilesystemItem(itemURL);

				subscribeToContentsOfDirectoryAtURL(newDirectoryURL);

				moveFilesystemItem(directoryURL, newDirectoryURL);

				expect(result).will.equal(pathSetFromURLArray(@[ newItemURL ]));
				expect(innerError).to.beNil();
				expect(innerSuccess).to.beTruthy();
			});

			it(@"by copying to the url", ^{
				NSString *itemName = @"item";
				NSURL *itemURL = [directoryURL URLByAppendingPathComponent:itemName];
				NSURL *newItemURL = [newDirectoryURL URLByAppendingPathComponent:itemName];
				createFilesystemItem(itemURL);

				subscribeToContentsOfDirectoryAtURL(newDirectoryURL);

				copyFilesystemItem(directoryURL, newDirectoryURL);

				expect(result).will.equal(pathSetFromURLArray(@[ newItemURL ]));
				expect(innerError).to.beNil();
				expect(innerSuccess).to.beTruthy();
			});

			it(@"by removing from the url", ^{
				subscribeToContentsOfDirectoryAtURL(directoryURL);

				removeFilesystemItem(directoryURL);

				expect(innerError).willNot.beNil();
				expect(innerSuccess).to.beFalsy();
			});
		});

		describe(@"the contents of", ^{
			__block NSURL *itemURLOutsideDirectory;

			before(^{
				itemURLOutsideDirectory = [testRootDirectoryURL URLByAppendingPathComponent:@"item"];
			});

			describe(@"the directory being changed", ^{
				__block NSURL *itemURLInsideDirectory;
				__block NSURL *anotherItemURLInsideDirectory;

				before(^{
					itemURLInsideDirectory = [directoryURL URLByAppendingPathComponent:@"item"];
					anotherItemURLInsideDirectory = [directoryURL URLByAppendingPathComponent:@"another item"];
				});

				it(@"by creating an item in it", ^{
					subscribeToContentsOfDirectoryAtURL(directoryURL);

					createFilesystemItem(itemURLInsideDirectory);

					expect(result).will.equal(pathSetFromURLArray(@[ itemURLInsideDirectory ]));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by moving an item into it", ^{
					createFilesystemItem(itemURLOutsideDirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					moveFilesystemItem(itemURLOutsideDirectory, itemURLInsideDirectory);

					expect(result).will.equal(pathSetFromURLArray(@[ itemURLInsideDirectory ]));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by moving an item out of it", ^{
					createFilesystemItem(itemURLInsideDirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					moveFilesystemItem(itemURLInsideDirectory, itemURLOutsideDirectory);

					expect(result).will.equal(pathSetFromURLArray(@[]));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by moving an item around in it", ^{
					createFilesystemItem(itemURLInsideDirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					moveFilesystemItem(itemURLInsideDirectory, anotherItemURLInsideDirectory);

					expect(result).will.equal(pathSetFromURLArray(@[ anotherItemURLInsideDirectory ]));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by copying an item into it", ^{
					createFilesystemItem(itemURLOutsideDirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					copyFilesystemItem(itemURLOutsideDirectory, itemURLInsideDirectory);

					expect(result).will.equal(pathSetFromURLArray(@[ itemURLInsideDirectory ]));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by copying an item around in it", ^{
					createFilesystemItem(itemURLInsideDirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					copyFilesystemItem(itemURLInsideDirectory, anotherItemURLInsideDirectory);

					expect(result).will.equal((pathSetFromURLArray(@[ itemURLInsideDirectory, anotherItemURLInsideDirectory ])));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by removing an item in it", ^{
					createFilesystemItem(itemURLInsideDirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					removeFilesystemItem(itemURLInsideDirectory);

					expect(result).will.equal(pathSetFromURLArray(@[]));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});
			});

			describe(@"a subdirectory being changed", ^{
				__block NSURL *subdirectoryURL;
				__block NSURL *itemURLInsideSubdirectory;
				__block NSURL *anotherItemURLInsideSubdirectory;

				before(^{
					subdirectoryURL = [directoryURL URLByAppendingPathComponent:@"subdirectory"];
					[[[NSFileManager alloc] init] createDirectoryAtURL:subdirectoryURL withIntermediateDirectories:YES attributes:nil error:NULL];
					itemURLInsideSubdirectory = [subdirectoryURL URLByAppendingPathComponent:@"item"];
					anotherItemURLInsideSubdirectory = [subdirectoryURL URLByAppendingPathComponent:@"another item"];
				});

				it(@"by creating an item in it", ^{
					subscribeToContentsOfDirectoryAtURL(directoryURL);

					createFilesystemItem(itemURLInsideSubdirectory);

					expect(result).will.equal((pathSetFromURLArray(@[ subdirectoryURL, itemURLInsideSubdirectory ])));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by moving an item into it", ^{
					createFilesystemItem(itemURLOutsideDirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					moveFilesystemItem(itemURLOutsideDirectory, itemURLInsideSubdirectory);

					expect(result).will.equal((pathSetFromURLArray(@[ subdirectoryURL, itemURLInsideSubdirectory ])));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by moving an item out of it", ^{
					createFilesystemItem(itemURLInsideSubdirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					moveFilesystemItem(itemURLInsideSubdirectory, itemURLOutsideDirectory);

					expect(result).will.equal(pathSetFromURLArray(@[ subdirectoryURL ]));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by moving an item around in it", ^{
					createFilesystemItem(itemURLInsideSubdirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					moveFilesystemItem(itemURLInsideSubdirectory, anotherItemURLInsideSubdirectory);

					expect(result).will.equal((pathSetFromURLArray(@[ subdirectoryURL, anotherItemURLInsideSubdirectory ])));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by copying an item into it", ^{
					createFilesystemItem(itemURLOutsideDirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					copyFilesystemItem(itemURLOutsideDirectory, itemURLInsideSubdirectory);

					expect(result).will.equal((pathSetFromURLArray(@[ subdirectoryURL, itemURLInsideSubdirectory ])));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by copying an item around in it", ^{
					createFilesystemItem(itemURLInsideSubdirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					copyFilesystemItem(itemURLInsideSubdirectory, anotherItemURLInsideSubdirectory);

					expect(result).will.equal((pathSetFromURLArray(@[ subdirectoryURL, itemURLInsideSubdirectory, anotherItemURLInsideSubdirectory ])));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});

				it(@"by removing an item in it", ^{
					createFilesystemItem(itemURLInsideSubdirectory);

					subscribeToContentsOfDirectoryAtURL(directoryURL);

					removeFilesystemItem(itemURLInsideSubdirectory);

					expect(result).will.equal(pathSetFromURLArray(@[ subdirectoryURL ]));
					expect(innerError).to.beNil();
					expect(innerSuccess).to.beTruthy();
				});
			});
		});
	});
});

sharedExamplesFor(RCIOFileManagerSharedExamplesName, ^(NSDictionary *data) {
	__block NSURL *testRootDirectoryURL;
	__block void(^createFilesystemItem)(NSURL *);
	__block BOOL success;
	__block NSError *error;

	before(^{
		testRootDirectoryURL = [[NSURL fileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:randomString()];
		[[[NSFileManager alloc] init] createDirectoryAtURL:testRootDirectoryURL withIntermediateDirectories:YES attributes:nil error:NULL];

		createFilesystemItem = data[RCIOFileManagerSharedExamplesCreateBlock];
		success = NO;
		error = nil;
	});

	after(^{
		[[[NSFileManager alloc] init] removeItemAtURL:testRootDirectoryURL error:NULL];
	});

	describe(@"file management", ^{
		__block NSURL *directoryURL;
		__block NSURL *itemURL;
		__block NSURL *newRootItemURL;
		__block NSURL *newItemURL;

		before(^{
			directoryURL = [testRootDirectoryURL URLByAppendingPathComponent:@"directory"];
			itemURL = [testRootDirectoryURL URLByAppendingPathComponent:@"item"];
			newRootItemURL = [testRootDirectoryURL URLByAppendingPathComponent:@"newItem"];
			newItemURL = [directoryURL URLByAppendingPathComponent:@"newItem"];

			[[[NSFileManager alloc] init] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:nil error:NULL];
			createFilesystemItem(itemURL);
		});

		describe(@"moving", ^{
			it(@"should not move an item if the signal is not subscribed to", ^{
				[RCIOFileManager moveItemAtURL:itemURL toURL:newItemURL];

				expect(itemExistsAtURL(itemURL)).to.beTruthy();
				expect(itemExistsAtURL(newItemURL)).to.beFalsy();
			});

			it(@"should move an item twice if the signal is subscribed to twice", ^{
				RACSignal *signal = [RCIOFileManager moveItemAtURL:itemURL toURL:newItemURL];

				[signal asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).to.beNil();
				expect(success).to.beTruthy();
				expect(itemExistsAtURL(itemURL)).to.beFalsy();
				expect(itemExistsAtURL(newItemURL)).to.beTruthy();

				[[[NSFileManager alloc] init] removeItemAtURL:newItemURL error:NULL];
				createFilesystemItem(itemURL);
				expect(itemExistsAtURL(itemURL)).to.beTruthy();
				expect(itemExistsAtURL(newItemURL)).to.beFalsy();

				[signal asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).to.beNil();
				expect(success).to.beTruthy();
				expect(itemExistsAtURL(itemURL)).to.beFalsy();
				expect(itemExistsAtURL(newItemURL)).to.beTruthy();
			});

			it(@"should not move an item if one exists at the destination", ^{
				createFilesystemItem(newItemURL);

				[[RCIOFileManager moveItemAtURL:itemURL toURL:newItemURL] asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).notTo.beNil();
				expect(success).to.beFalsy();
				expect(itemExistsAtURL(itemURL)).to.beTruthy();
				expect(itemExistsAtURL(newItemURL)).to.beTruthy();
			});

			it(@"should move an item to a different directory", ^{
				[[RCIOFileManager moveItemAtURL:itemURL toURL:newItemURL] asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).to.beNil();
				expect(success).to.beTruthy();
				expect(itemExistsAtURL(itemURL)).to.beFalsy();
				expect(itemExistsAtURL(newItemURL)).to.beTruthy();
			});

			it(@"should rename an item", ^{
				[[RCIOFileManager moveItemAtURL:itemURL toURL:newRootItemURL] asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).to.beNil();
				expect(success).to.beTruthy();
				expect(itemExistsAtURL(itemURL)).to.beFalsy();
				expect(itemExistsAtURL(newRootItemURL)).to.beTruthy();
			});
		});

		describe(@"copying", ^{
			it(@"should not copy an item if the signal is not subscribed to", ^{
				[RCIOFileManager copyItemAtURL:itemURL toURL:newItemURL];

				expect(itemExistsAtURL(itemURL)).to.beTruthy();
				expect(itemExistsAtURL(newItemURL)).to.beFalsy();
			});

			it(@"should copy an item twice if the signal is subscribed to twice", ^{
				RACSignal *signal = [RCIOFileManager copyItemAtURL:itemURL toURL:newItemURL];

				[signal asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).to.beNil();
				expect(success).to.beTruthy();
				expect(itemExistsAtURL(itemURL)).to.beTruthy();
				expect(itemExistsAtURL(newItemURL)).to.beTruthy();

				[[[NSFileManager alloc] init] removeItemAtURL:newItemURL error:NULL];
				expect(itemExistsAtURL(itemURL)).to.beTruthy();
				expect(itemExistsAtURL(newItemURL)).to.beFalsy();

				[signal asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).to.beNil();
				expect(success).to.beTruthy();
				expect(itemExistsAtURL(itemURL)).to.beTruthy();
				expect(itemExistsAtURL(newItemURL)).to.beTruthy();
			});

			it(@"should not copy an item if one exists at the destination", ^{
				createFilesystemItem(newItemURL);

				[[RCIOFileManager copyItemAtURL:itemURL toURL:newItemURL] asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).notTo.beNil();
				expect(success).to.beFalsy();
				expect(itemExistsAtURL(itemURL)).to.beTruthy();
				expect(itemExistsAtURL(newItemURL)).to.beTruthy();
			});

			it(@"should copy an item to a different directory", ^{
				[[RCIOFileManager copyItemAtURL:itemURL toURL:newItemURL] asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).to.beNil();
				expect(success).to.beTruthy();
				expect(itemExistsAtURL(itemURL)).to.beTruthy();
				expect(itemExistsAtURL(newItemURL)).to.beTruthy();
			});

			it(@"should copy an item in the same directory", ^{
				[[RCIOFileManager copyItemAtURL:itemURL toURL:newRootItemURL] asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).to.beNil();
				expect(success).to.beTruthy();
				expect(itemExistsAtURL(itemURL)).to.beTruthy();
				expect(itemExistsAtURL(newRootItemURL)).to.beTruthy();
			});
		});

		describe(@"removing", ^{
			it(@"should not remove an item if the signal is not subscribed to", ^{
				[RCIOFileManager removeItemAtURL:itemURL];

				expect(itemExistsAtURL(itemURL)).to.beTruthy();
			});

			it(@"should remove an item twice if the signal is subscribed to twice", ^{
				RACSignal *signal = [RCIOFileManager removeItemAtURL:itemURL];

				[signal asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).to.beNil();
				expect(success).to.beTruthy();
				expect(itemExistsAtURL(itemURL)).to.beFalsy();

				createFilesystemItem(itemURL);
				expect(itemExistsAtURL(itemURL)).to.beTruthy();

				[signal asynchronousFirstOrDefault:nil success:&success error:&error];

				expect(error).to.beNil();
				expect(success).to.beTruthy();
				expect(itemExistsAtURL(itemURL)).to.beFalsy();
			});
		});
	});

	describe(@"directory listings", ^{
		it(@"should list items", ^{
			NSURL *directoryURL = [testRootDirectoryURL URLByAppendingPathComponent:@"directory"];
			NSURL *itemURL = [directoryURL URLByAppendingPathComponent:@"item"];
			[[[NSFileManager alloc] init] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:nil error:NULL];
			createFilesystemItem(itemURL);

			RACSignal *signal = [[RCIOFileManager contentsOfDirectoryAtURL:testRootDirectoryURL options:0] firstOrDefault:nil success:&success error:&error];

			expect(error).to.beNil();
			expect(success).to.beTruthy();
			expect(signal).notTo.beNil();

			NSSet *result = pathSetFromURLArray([[signal collect] firstOrDefault:nil success:&success error:&error]);

			expect(error).to.beNil();
			expect(success).to.beTruthy();
			expect(result).to.equal((pathSetFromURLArray(@[ directoryURL, itemURL ])));
		});

		it(@"should skip resource forks", ^{
			NSURL *resourceForkURL = [testRootDirectoryURL URLByAppendingPathComponent:@"._resourceFork"];
			createFilesystemItem(resourceForkURL);

			RACSignal *signal = [[RCIOFileManager contentsOfDirectoryAtURL:testRootDirectoryURL options:0] firstOrDefault:nil success:&success error:&error];

			expect(error).to.beNil();
			expect(success).to.beTruthy();
			expect(signal).notTo.beNil();

			NSSet *result = pathSetFromURLArray([[signal collect] firstOrDefault:nil success:&success error:&error]);

			expect(error).to.beNil();
			expect(success).to.beTruthy();
			expect(result).to.equal((pathSetFromURLArray(@[])));
		});

		it(@"should skip subdirectory descendants", ^{
			NSURL *directoryURL = [testRootDirectoryURL URLByAppendingPathComponent:@"directory"];
			NSURL *itemURL = [directoryURL URLByAppendingPathComponent:@"item"];
			[[[NSFileManager alloc] init] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:nil error:NULL];
			createFilesystemItem(itemURL);

			RACSignal *signal = [[RCIOFileManager contentsOfDirectoryAtURL:testRootDirectoryURL options:NSDirectoryEnumerationSkipsSubdirectoryDescendants] firstOrDefault:nil success:&success error:&error];

			expect(error).to.beNil();
			expect(success).to.beTruthy();
			expect(signal).notTo.beNil();

			NSSet *result = pathSetFromURLArray([[signal collect] firstOrDefault:nil success:&success error:&error]);

			expect(error).to.beNil();
			expect(success).to.beTruthy();
			expect(result).to.equal((pathSetFromURLArray(@[ directoryURL ])));
		});

		it(@"should skip hidden items", ^{
			NSURL *hiddenItemURL = [testRootDirectoryURL URLByAppendingPathComponent:@".hiddenItem"];
			createFilesystemItem(hiddenItemURL);

			RACSignal *signal = [[RCIOFileManager contentsOfDirectoryAtURL:testRootDirectoryURL options:NSDirectoryEnumerationSkipsHiddenFiles] firstOrDefault:nil success:&success error:&error];

			expect(error).to.beNil();
			expect(success).to.beTruthy();
			expect(signal).notTo.beNil();

			NSSet *result = pathSetFromURLArray([[signal collect] firstOrDefault:nil success:&success error:&error]);

			expect(error).to.beNil();
			expect(success).to.beTruthy();
			expect(result).to.equal((pathSetFromURLArray(@[])));
		});

		it(@"should error on the inner signal if a directory doesn't exist", ^{
			NSURL *nonExistingDirectoryURL = [testRootDirectoryURL URLByAppendingPathComponent:@"does not exist"];

			RACSignal *signal = [[RCIOFileManager contentsOfDirectoryAtURL:nonExistingDirectoryURL options:0] firstOrDefault:nil success:&success error:&error];

			expect(error).to.beNil();
			expect(success).to.beTruthy();
			expect(signal).notTo.beNil();

			[[signal collect] firstOrDefault:nil success:&success error:&error];

			expect(error).toNot.beNil();
			expect(success).toNot.beTruthy();
		});

		itShouldBehaveLike(RCIOFileManagerSharedReactionExamples, ^{
			return @{
				RCIOFileManagerSharedReactionExamplesTestRootDirectoryURL: testRootDirectoryURL,
				RCIOFileManagerSharedReactionExamplesCreateBlock: createFilesystemItem,
				RCIOFileManagerSharedReactionExamplesMoveBlock: [^(NSURL *source, NSURL *destination) {
					[[[RCIOFileManager moveItemAtURL:source toURL:destination] ignoreValues] first];
				} copy],
				RCIOFileManagerSharedReactionExamplesCopyBlock: [^(NSURL *source, NSURL *destination) {
					[[[RCIOFileManager copyItemAtURL:source toURL:destination] ignoreValues] first];
				} copy],
				RCIOFileManagerSharedReactionExamplesRemoveBlock: [^(NSURL *url) {
					[[[RCIOFileManager removeItemAtURL:url] ignoreValues] first];
				} copy]
			};
		});

#if !TARGET_OS_IPHONE
		// If we're on OS X this should work even without using RCIOFileManager.
		itShouldBehaveLike(RCIOFileManagerSharedReactionExamples, ^{
			return @{
				RCIOFileManagerSharedReactionExamplesTestRootDirectoryURL: testRootDirectoryURL,
				RCIOFileManagerSharedReactionExamplesCreateBlock: createFilesystemItem,
				RCIOFileManagerSharedReactionExamplesMoveBlock: [^(NSURL *source, NSURL *destination) {
					[[[NSFileManager alloc] init] moveItemAtURL:source toURL:destination error:NULL];
				} copy],
				RCIOFileManagerSharedReactionExamplesCopyBlock: [^(NSURL *source, NSURL *destination) {
					[[[NSFileManager alloc] init] copyItemAtURL:source toURL:destination error:NULL];
				} copy],
				RCIOFileManagerSharedReactionExamplesRemoveBlock: [^(NSURL *url) {
					[[[NSFileManager alloc] init] removeItemAtURL:url error:NULL];
				} copy]
			};
		});
#endif

	});
});

SharedExampleGroupsEnd

SpecBegin(RCIOFileManager)

itShouldBehaveLike(RCIOFileManagerSharedExamplesName, @{ RCIOFileManagerSharedExamplesCreateBlock: [^(NSURL *url) {
	touch(url);
} copy] });

itShouldBehaveLike(RCIOFileManagerSharedExamplesName, @{ RCIOFileManagerSharedExamplesCreateBlock: [^(NSURL *url) {
	[[[NSFileManager alloc] init] createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:NULL];
} copy] });

SpecEnd


text:
extern crate metl;

use metl::extras::window::{Event, WindowBuilder, View, ViewDelegate};
use metl::{ClearColor, PixelFormat};

fn main() {
    struct MyViewDelegate;
    impl ViewDelegate for MyViewDelegate {
        fn draw_into_view(&self, view: &mut View) {
            view.draw();
        }
        fn on_resize(&self, _view: &mut View, new_size: (f64, f64)) {
            println!("Resized to {:?}", new_size);
        }
    }

    let device = metl::Device::system_default_device().unwrap();
    let mut window = WindowBuilder::new(device)
                     .with_dimensions(800, 600)
                     .with_title("Metal Window".into())
                     .build()
                     .unwrap();

    window.view.set_depth_stencil_pixel_format(PixelFormat::Rgba8Unorm);
    window.view.set_clear_color(ClearColor::new(1.0, 0.0, 0.0, 1.0));
    window.view.set_delegate(MyViewDelegate);

    'mainloop: loop {
        for event in window.poll_events() {
            match event {
                Event::Closed => {
                    break 'mainloop
                }
                _ => {}
            }
        }

    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" /><link rel="canonical" href="http://mongoc.org/libbson/current/bson_mem_restore_vtable.html"/>
    <title>bson_mem_restore_vtable() — libbson 1.21.2</title>
    <link rel="stylesheet" href="_static/readable.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="_static/readable.css" type="text/css" />

    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="bson_mem_set_vtable()" href="bson_mem_set_vtable.html" />
    <link rel="prev" title="bson_malloc0()" href="bson_malloc0.html" />

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9">

Navigation

          next

          previous |

libbson 1.21.2 »

API Reference »

Memory Management »

bson_mem_restore_vtable()¶

Synopsis¶

void
bson_mem_restore_vtable (void);

Description¶

This function shall restore the default memory allocator to be used by Libbson.

Warning

This function MUST be called at the end of the process. Failure to do so will result in memory being freed by the wrong allocator.

Table Of Contents

Tutorial

Guides

Cross Platform Notes

API Reference

bson_t

bson_context_t

bson_decimal128_t

bson_error_t

bson_iter_t

bson_json_reader_t

bson_md5_t

bson_oid_t

bson_reader_t

Character and String Routines

bson_string_t

bson_subtype_t

bson_type_t

bson_unichar_t

bson_value_t

bson_visitor_t

bson_writer_t

System Clock

Memory Management

Libbson Versioning

Index

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    © Copyright 2017-present, MongoDB, Inc.
    Created using Sphinx 4.1.2.


text:
const q = 'hello';

let amqp = require('amqplib');

async function run() {
  console.log(' [*] Waiting for messages in %s. To exit press CTRL+C', q);
  let conn = await amqp.connect('amqp://192.168.99.100');
  let ch = await conn.createChannel();
  ch.assertQueue(q, { durable: false });
  ch.consume(q, (msg) => {
    console.log(' [x] Received %s', msg.content.toString());
  }, {noAck: true});
};

run().catch(console.log);


text:
$( window ).load(function() {

	var input = document.getElementById('originalImage');
	input.addEventListener('change', handleFiles);

	function handleFiles(e) {
	    var ctx = document.getElementById('canvas').getContext('2d');
	    var img = new Image;
	    img.src = URL.createObjectURL(e.target.files[0]);
	    img.onload = function() {
	        ctx.drawImage(img, 20,20);
	    }
	}

});


text:
"""Helpers for reading the Google Cloud SDK's configuration."""

import json
import os
import subprocess

import six

from google.auth import environment_vars
from google.auth import exceptions

# The ~/.config subdirectory containing gcloud credentials.
_CONFIG_DIRECTORY = "gcloud"
# Windows systems store config at %APPDATA%\gcloud
_WINDOWS_CONFIG_ROOT_ENV_VAR = "APPDATA"
# The name of the file in the Cloud SDK config that contains default
# credentials.
_CREDENTIALS_FILENAME = "application_default_credentials.json"
# The name of the Cloud SDK shell script
_CLOUD_SDK_POSIX_COMMAND = "gcloud"
_CLOUD_SDK_WINDOWS_COMMAND = "gcloud.cmd"
# The command to get the Cloud SDK configuration
_CLOUD_SDK_CONFIG_COMMAND = ("config", "config-helper", "--format", "json")
# The command to get google user access token
_CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND = ("auth", "print-access-token")
# Cloud SDK's application-default client ID
CLOUD_SDK_CLIENT_ID = (
    "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com"
)

def get_config_path():
    """Returns the absolute path the the Cloud SDK's configuration directory.

    Returns:
        str: The Cloud SDK config path.
    """
    # If the path is explicitly set, return that.
    try:
        return os.environ[environment_vars.CLOUD_SDK_CONFIG_DIR]
    except KeyError:
        pass

    # Non-windows systems store this at ~/.config/gcloud
    if os.name != "nt":
        return os.path.join(os.path.expanduser("~"), ".config", _CONFIG_DIRECTORY)
    # Windows systems store config at %APPDATA%\gcloud
    else:
        try:
            return os.path.join(
                os.environ[_WINDOWS_CONFIG_ROOT_ENV_VAR], _CONFIG_DIRECTORY
            )
        except KeyError:
            # This should never happen unless someone is really
            # messing with things, but we'll cover the case anyway.
            drive = os.environ.get("SystemDrive", "C:")
            return os.path.join(drive, "\\", _CONFIG_DIRECTORY)

def get_application_default_credentials_path():
    """Gets the path to the application default credentials file.

    The path may or may not exist.

    Returns:
        str: The full path to application default credentials.
    """
    config_path = get_config_path()
    return os.path.join(config_path, _CREDENTIALS_FILENAME)

def get_project_id():
    """Gets the project ID from the Cloud SDK.

    Returns:
        Optional[str]: The project ID.
    """
    if os.name == "nt":
        command = _CLOUD_SDK_WINDOWS_COMMAND
    else:
        command = _CLOUD_SDK_POSIX_COMMAND

    try:
        output = subprocess.check_output(
            (command,) + _CLOUD_SDK_CONFIG_COMMAND, stderr=subprocess.STDOUT
        )
    except (subprocess.CalledProcessError, OSError, IOError):
        return None

    try:
        configuration = json.loads(output.decode("utf-8"))
    except ValueError:
        return None

    try:
        return configuration["configuration"]["properties"]["core"]["project"]
    except KeyError:
        return None

def get_auth_access_token(account=None):
    """Load user access token with the ``gcloud auth print-access-token`` command.

    Args:
        account (Optional[str]): Account to get the access token for. If not
            specified, the current active account will be used.

    Returns:
        str: The user access token.

    Raises:
        google.auth.exceptions.UserAccessTokenError: if failed to get access
            token from gcloud.
    """
    if os.name == "nt":
        command = _CLOUD_SDK_WINDOWS_COMMAND
    else:
        command = _CLOUD_SDK_POSIX_COMMAND

    try:
        if account:
            command = (
                (command,)
                + _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND
                + ("--account=" + account,)
            )
        else:
            command = (command,) + _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND

        access_token = subprocess.check_output(command, stderr=subprocess.STDOUT)
        # remove the trailing "\n"
        return access_token.decode("utf-8").strip()
    except (subprocess.CalledProcessError, OSError, IOError) as caught_exc:
        new_exc = exceptions.UserAccessTokenError(
            "Failed to obtain access token", caught_exc
        )
        six.raise_from(new_exc, caught_exc)


text:
*Work in progress*

# SimplerSettings

[![Build status](https://ci.appveyor.com/api/projects/status/c0r2yisa2ri8l3rg?svg=true)](https://ci.appveyor.com/project/Parkanizer/simplersettings)

Simple library for reading app.config/web.config appSettings section.

## Why not just use ConfigurationManager?

1. Diagnostics: `"Foo setting is not set."` exception message instead of getting `null`.
1. Some basic parsing out of the box. Also with diagnostics: `"Foo setting should be valid boolean, but was 'not-bool'."`.

## OK, how do I use it?

Install it:

``` PowerShell
Install-Package SimplerSettings
```

Import it:

``` C#
using SimplerSettings;
```

Get some settings:

``` C#
// get your setting

AppSetting setting = AppSettings.Get("SomeSetting");

// check if you found anything

var isSettingSet = setting.IsSet;

// convert it

var stringValue = setting.Value;
var intValue = setting.AsInt();
var boolValue = setting.AsBool();

// or just implicitly cast it

string someString = setting;
int someInt = setting;
bool someBool = setting;
```


text:
ALTER TABLE `players`
ADD COLUMN `banking_pin`  int(4) NOT NULL AFTER `last_seen`;