text:
layout: sidebar-right
title: BBC Springwatch
date: 2016-05-31 09:41:00+00:00
author: brandon-king
category: articles
excerpt: As BBC Springwatch returns to RSPB Minsmere, see our top books on all things wildlife.
breadcrumb: non-fiction
---
![BBC Springwatch British wildlife by Stephen Moss](/images/featured/featured-bbc-springwatch-british-wildlife.jpg)

Fingers in the sparkle jar: lessons in life and death by Chris Packham

In a rich, lyrical and emotionally exposing memoir, Springwatch presenter Chris brings to life his childhood in the 70s, from his bedroom bursting with fox skulls, birds' eggs and sweaty jam jars, to his feral adventures. But pervading his story is the search for freedom, meaning and acceptance in a world that didn't understand him.

Why do robins have red breasts?: all your wildlife questions answered by Joanna Stevens and Martin Hughes-Games

Which birds have the most air miles? Are adders born venomous? This book brings together all the most-asked questions from the surprise hit BBC TV programme of the same name. The heart of the book is what has become the star of the TV programme - the viewers' anecdotes and questions.

No way but gentlenesse: a memoir of how Kes, my kestrel, changed my life by Richard Hines

A breathtaking memoir of one remarkable boy's love for a culture lost to time, and his attempt to find salvation in the natural world.

A brush with nature: reflections on the natural world by Richard Mabey

Often described as Britain's foremost nature writer, Richard Mabey has revealed his passion for the natural world in elegantly written stories for 'BBC Wildlife Magazine' for the past 25 years. This collection brings together his favourite pieces and presents a fascinating and inspiring view of our natural landscape.

The running sky: a bird-watching life by Tim Dee

This title records a lifetime of looking at birds. It follows the birds' year from one summer to the next. Dee maps his own observations and encounters over four decades, tracking birds well-known and bizarre, flying free, in the nest, in his hand as he rings them, or dead and stuffed on his mantelpiece.

Landmarks by Robert MacFarlane

Words are grained into our landscapes, and landscapes are grained into our words. Landmarks is about the power of language to shape our sense of place. It is a field guide to the literature of nature, and a glossary containing thousands of remarkable words used in England, Scotland, Ireland and Wales to describe land, nature and weather.

Wild hares and hummingbirds: the natural history of an English village by Stephen Moss

This is a very personal celebration of why the natural world matters to all of us, wherever we live. The book is nature writing at its finest, expressed through the natural history of one very special place.

Claxton: field notes from a small planet by Mark Cocker

In a single twelve-month cycle of daily writings Mark Cocker explores his relationship to the East Anglian landscape, to nature and to all the living things around him. Cocker describes all the wildlife in the village - not just birds, but plants, trees, mammals, hoverflies, moths, butterflies, bush crickets, grasshoppers, ants and bumblebees. The book explores how these other species are as essential to our sense of genuine well-being and to our feelings of rootedness as any other kind of fellowship.

Coastlines: the story of our shore by Patrick Barkham and Emily Faccini

Told through a series of walks beside the sea, this is a story of the most beautiful 742 miles of coastline in England, Wales and Northern Ireland: their rocks, plants and animals, their views, walks and history, and the people who have made their lives within sight of the waves.

BBC Springwatch British wildlife by Stephen Moss

The Springwatch team guides you through Britain's rich and diverse natural heritage. You will be introduced to the birds, mammals and plants that inhabit our gardens, cities and countryside, with detailed descriptions allowing you to understand their appearance, behaviour and habitats.

Chris Packham's back garden nature reserve by Chris Packham

A practical guide to attracting wildlife to your own home. It allows any reader to transform their own garden into a valuable refuge for a greater range of species than before.


text:
<?php

namespace NerdsAndCompany\Schematic\Converters\Models;

use Craft;
use craft\base\Model;

class TagGroup extends Base
{
    /**
     * {@inheritdoc}
     */
    public function saveRecord(Model $record, array $definition): bool
    {
        return Craft::$app->tags->saveTagGroup($record);
    }

    /**
     * {@inheritdoc}
     */
    public function deleteRecord(Model $record): bool
    {
        return Craft::$app->tags->deleteTagGroupById($record->id);
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation, Inc. All rights reserved.
// Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.AspNet.Identity
{
    internal static class AsyncHelper
    {
        private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None,
            TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);

        public static TResult RunSync<TResult>(Func<Task<TResult>> func)
        {
            var cultureUi = CultureInfo.CurrentUICulture;
            var culture = CultureInfo.CurrentCulture;
            return _myTaskFactory.StartNew(() =>
            {
                Thread.CurrentThread.CurrentCulture = culture;
                Thread.CurrentThread.CurrentUICulture = cultureUi;
                return func();
            }).Unwrap().GetAwaiter().GetResult();
        }

        public static void RunSync(Func<Task> func)
        {
            var cultureUi = CultureInfo.CurrentUICulture;
            var culture = CultureInfo.CurrentCulture;
            _myTaskFactory.StartNew(() =>
            {
                Thread.CurrentThread.CurrentCulture = culture;
                Thread.CurrentThread.CurrentUICulture = cultureUi;
                return func();
            }).Unwrap().GetAwaiter().GetResult();
        }
    }
}


text:
package org.springframework.boot.logging.log4j2;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.filter.AbstractFilter;
import org.apache.logging.log4j.message.Message;

import org.springframework.boot.logging.LogFile;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggerConfiguration;
import org.springframework.boot.logging.LoggingInitializationContext;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.boot.logging.Slf4JLoggingSystem;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

/**
 * {@link LoggingSystem} for Log4j 2.
 *
 * @author Daniel Fullarton
 * @author Andy Wilkinson
 * @author Alexander Heusingfeld
 * @author Ben Hale
 * @since 1.2.0
 */
public class Log4J2LoggingSystem extends Slf4JLoggingSystem {

	private static final String FILE_PROTOCOL = "file";

	private static final LogLevels<Level> LEVELS = new LogLevels<>();

	static {
		LEVELS.map(LogLevel.TRACE, Level.TRACE);
		LEVELS.map(LogLevel.DEBUG, Level.DEBUG);
		LEVELS.map(LogLevel.INFO, Level.INFO);
		LEVELS.map(LogLevel.WARN, Level.WARN);
		LEVELS.map(LogLevel.ERROR, Level.ERROR);
		LEVELS.map(LogLevel.FATAL, Level.FATAL);
		LEVELS.map(LogLevel.OFF, Level.OFF);
	}

	private static final Filter FILTER = new AbstractFilter() {

		@Override
		public Result filter(LogEvent event) {
			return Result.DENY;
		}

		@Override
		public Result filter(Logger logger, Level level, Marker marker, Message msg,
				Throwable t) {
			return Result.DENY;
		}

		@Override
		public Result filter(Logger logger, Level level, Marker marker, Object msg,
				Throwable t) {
			return Result.DENY;
		}

		@Override
		public Result filter(Logger logger, Level level, Marker marker, String msg,
				Object... params) {
			return Result.DENY;
		}

	};

	public Log4J2LoggingSystem(ClassLoader classLoader) {
		super(classLoader);
	}

	@Override
	protected String[] getStandardConfigLocations() {
		return getCurrentlySupportedConfigLocations();
	}

	private String[] getCurrentlySupportedConfigLocations() {
		List<String> supportedConfigLocations = new ArrayList<>();
		if (isClassAvailable("com.fasterxml.jackson.dataformat.yaml.YAMLParser")) {
			Collections.addAll(supportedConfigLocations, "log4j2.yaml", "log4j2.yml");
		}
		if (isClassAvailable("com.fasterxml.jackson.databind.ObjectMapper")) {
			Collections.addAll(supportedConfigLocations, "log4j2.json", "log4j2.jsn");
		}
		supportedConfigLocations.add("log4j2.xml");
		return supportedConfigLocations
				.toArray(new String[supportedConfigLocations.size()]);
	}

	protected boolean isClassAvailable(String className) {
		return ClassUtils.isPresent(className, getClassLoader());
	}

	@Override
	public void beforeInitialize() {
		LoggerContext loggerContext = getLoggerContext();
		if (isAlreadyInitialized(loggerContext)) {
			return;
		}
		super.beforeInitialize();
		loggerContext.getConfiguration().addFilter(FILTER);
	}

	@Override
	public void initialize(LoggingInitializationContext initializationContext,
			String configLocation, LogFile logFile) {
		LoggerContext loggerContext = getLoggerContext();
		if (isAlreadyInitialized(loggerContext)) {
			return;
		}
		loggerContext.getConfiguration().removeFilter(FILTER);
		super.initialize(initializationContext, configLocation, logFile);
		markAsInitialized(loggerContext);
	}

	@Override
	protected void loadDefaults(LoggingInitializationContext initializationContext,
			LogFile logFile) {
		if (logFile != null) {
			loadConfiguration(getPackagedConfigFile("log4j2-file.xml"), logFile);
		}
		else {
			loadConfiguration(getPackagedConfigFile("log4j2.xml"), logFile);
		}
	}

	@Override
	protected void loadConfiguration(LoggingInitializationContext initializationContext,
			String location, LogFile logFile) {
		super.loadConfiguration(initializationContext, location, logFile);
		loadConfiguration(location, logFile);
	}

	protected void loadConfiguration(String location, LogFile logFile) {
		Assert.notNull(location, "Location must not be null");
		try {
			LoggerContext ctx = getLoggerContext();
			URL url = ResourceUtils.getURL(location);
			ConfigurationSource source = getConfigurationSource(url);
			ctx.start(ConfigurationFactory.getInstance().getConfiguration(ctx, source));
		}
		catch (Exception ex) {
			throw new IllegalStateException(
					"Could not initialize Log4J2 logging from " + location, ex);
		}
	}

	private ConfigurationSource getConfigurationSource(URL url) throws IOException {
		InputStream stream = url.openStream();
		if (FILE_PROTOCOL.equals(url.getProtocol())) {
			return new ConfigurationSource(stream, ResourceUtils.getFile(url));
		}
		return new ConfigurationSource(stream, url);
	}

	@Override
	protected void reinitialize(LoggingInitializationContext initializationContext) {
		getLoggerContext().reconfigure();
	}

	@Override
	public Set<LogLevel> getSupportedLogLevels() {
		return LEVELS.getSupported();
	}

	@Override
	public void setLogLevel(String loggerName, LogLevel logLevel) {
		Level level = LEVELS.convertSystemToNative(logLevel);
		LoggerConfig loggerConfig = getLoggerConfig(loggerName);
		if (loggerConfig == null) {
			loggerConfig = new LoggerConfig(loggerName, level, true);
			getLoggerContext().getConfiguration().addLogger(loggerName, loggerConfig);
		}
		else {
			loggerConfig.setLevel(level);
		}
		getLoggerContext().updateLoggers();
	}

	@Override
	public List<LoggerConfiguration> getLoggerConfigurations() {
		List<LoggerConfiguration> result = new ArrayList<>();
		Configuration configuration = getLoggerContext().getConfiguration();
		for (LoggerConfig loggerConfig : configuration.getLoggers().values()) {
			result.add(convertLoggerConfiguration(loggerConfig));
		}
		result.sort(CONFIGURATION_COMPARATOR);
		return result;
	}

	@Override
	public LoggerConfiguration getLoggerConfiguration(String loggerName) {
		return convertLoggerConfiguration(getLoggerConfig(loggerName));
	}

	private LoggerConfiguration convertLoggerConfiguration(LoggerConfig loggerConfig) {
		if (loggerConfig == null) {
			return null;
		}
		LogLevel level = LEVELS.convertNativeToSystem(loggerConfig.getLevel());
		String name = loggerConfig.getName();
		if (!StringUtils.hasLength(name) || LogManager.ROOT_LOGGER_NAME.equals(name)) {
			name = ROOT_LOGGER_NAME;
		}
		return new LoggerConfiguration(name, level, level);
	}

	@Override
	public Runnable getShutdownHandler() {
		return new ShutdownHandler();
	}

	@Override
	public void cleanUp() {
		super.cleanUp();
		LoggerContext loggerContext = getLoggerContext();
		markAsUninitialized(loggerContext);
		loggerContext.getConfiguration().removeFilter(FILTER);
	}

	private LoggerConfig getLoggerConfig(String name) {
		if (!StringUtils.hasLength(name) || ROOT_LOGGER_NAME.equals(name)) {
			name = LogManager.ROOT_LOGGER_NAME;
		}
		return getLoggerContext().getConfiguration().getLoggers().get(name);
	}

	private LoggerContext getLoggerContext() {
		return (LoggerContext) LogManager.getContext(false);
	}

	private boolean isAlreadyInitialized(LoggerContext loggerContext) {
		return LoggingSystem.class.getName().equals(loggerContext.getExternalContext());
	}

	private void markAsInitialized(LoggerContext loggerContext) {
		loggerContext.setExternalContext(LoggingSystem.class.getName());
	}

	private void markAsUninitialized(LoggerContext loggerContext) {
		loggerContext.setExternalContext(null);
	}

	private final class ShutdownHandler implements Runnable {

		@Override
		public void run() {
			getLoggerContext().stop();
		}

	}

}


text:
/* -*- mode:C; c-file-style: "bsd" -*- */
/*
 * Copyright (c) 2008-2014 Yubico AB
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef	__YKPERS_H_INCLUDED__
#define	__YKPERS_H_INCLUDED__

#include <stddef.h>
#include <stdbool.h>
#include <ykstatus.h>
#include <ykdef.h>

# ifdef __cplusplus
extern "C" {
# endif

typedef struct ykp_config_t YKP_CONFIG;

/* This only works with Yubikey 1 unless it's fed with a YK_STATUS using
   ykp_configure_for(). */
YKP_CONFIG *ykp_create_config(void);
int ykp_free_config(YKP_CONFIG *cfg);

/* allocate an empty YKP_CONFIG, use ykp_configure_version() to set
   version information. */
YKP_CONFIG *ykp_alloc(void);

/* Set the version information in st in cfg. */
void ykp_configure_version(YKP_CONFIG *cfg, YK_STATUS *st);

/* This is used to tell what YubiKey version we're working with and what
   command we want to send to it. If this isn't used YubiKey 1 only will
   be assumed. */
int ykp_configure_command(YKP_CONFIG *cfg, uint8_t command);
/* wrapper function for ykp_configure_command */
int ykp_configure_for(YKP_CONFIG *cfg, int confnum, YK_STATUS *st);

int ykp_AES_key_from_hex(YKP_CONFIG *cfg, const char *hexkey);
int ykp_AES_key_from_raw(YKP_CONFIG *cfg, const char *key);
int ykp_AES_key_from_passphrase(YKP_CONFIG *cfg, const char *passphrase,
				const char *salt);
int ykp_HMAC_key_from_hex(YKP_CONFIG *cfg, const char *hexkey);
int ykp_HMAC_key_from_raw(YKP_CONFIG *cfg, const char *key);

/* Functions for constructing the YK_NDEF struct before writing it to a neo */
YK_NDEF *ykp_alloc_ndef(void);
int ykp_free_ndef(YK_NDEF *ndef);
int ykp_construct_ndef_uri(YK_NDEF *ndef, const char *uri);
int ykp_construct_ndef_text(YK_NDEF *ndef, const char *text, const char *lang, bool isutf16);
int ykp_set_ndef_access_code(YK_NDEF *ndef, unsigned char *access_code);
int ykp_ndef_as_text(YK_NDEF *ndef, char *text, size_t len);

YK_DEVICE_CONFIG *ykp_alloc_device_config(void);
int ykp_free_device_config(YK_DEVICE_CONFIG *device_config);
int ykp_set_device_mode(YK_DEVICE_CONFIG *device_config, unsigned char mode);
int ykp_set_device_chalresp_timeout(YK_DEVICE_CONFIG *device_config, unsigned char timeout);
int ykp_set_device_autoeject_time(YK_DEVICE_CONFIG *device_config, unsigned short eject_time);

int ykp_set_access_code(YKP_CONFIG *cfg, unsigned char *access_code, size_t len);
int ykp_set_fixed(YKP_CONFIG *cfg, unsigned char *fixed, size_t len);
int ykp_set_uid(YKP_CONFIG *cfg, unsigned char *uid, size_t len);
int ykp_set_oath_imf(YKP_CONFIG *cfg, unsigned long imf);
unsigned long ykp_get_oath_imf(const YKP_CONFIG *cfg);

int ykp_set_tktflag_TAB_FIRST(YKP_CONFIG *cfg, bool state);
int ykp_set_tktflag_APPEND_TAB1(YKP_CONFIG *cfg, bool state);
int ykp_set_tktflag_APPEND_TAB2(YKP_CONFIG *cfg, bool state);
int ykp_set_tktflag_APPEND_DELAY1(YKP_CONFIG *cfg, bool state);
int ykp_set_tktflag_APPEND_DELAY2(YKP_CONFIG *cfg, bool state);
int ykp_set_tktflag_APPEND_CR(YKP_CONFIG *cfg, bool state);
int ykp_set_tktflag_PROTECT_CFG2(YKP_CONFIG *cfg, bool state);
int ykp_set_tktflag_OATH_HOTP(YKP_CONFIG *cfg, bool state);
int ykp_set_tktflag_CHAL_RESP(YKP_CONFIG *cfg, bool state);

int ykp_set_cfgflag_SEND_REF(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_TICKET_FIRST(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_PACING_10MS(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_PACING_20MS(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_ALLOW_HIDTRIG(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_STATIC_TICKET(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_SHORT_TICKET(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_STRONG_PW1(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_STRONG_PW2(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_MAN_UPDATE(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_OATH_HOTP8(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_OATH_FIXED_MODHEX1(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_OATH_FIXED_MODHEX2(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_OATH_FIXED_MODHEX(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_CHAL_YUBICO(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_CHAL_HMAC(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_HMAC_LT64(YKP_CONFIG *cfg, bool state);
int ykp_set_cfgflag_CHAL_BTN_TRIG(YKP_CONFIG *cfg, bool state);

int ykp_set_extflag_SERIAL_BTN_VISIBLE(YKP_CONFIG *cfg, bool state);
int ykp_set_extflag_SERIAL_USB_VISIBLE(YKP_CONFIG *cfg, bool state);
int ykp_set_extflag_SERIAL_API_VISIBLE (YKP_CONFIG *cfg, bool state);
int ykp_set_extflag_USE_NUMERIC_KEYPAD (YKP_CONFIG *cfg, bool state);
int ykp_set_extflag_FAST_TRIG (YKP_CONFIG *cfg, bool state);
int ykp_set_extflag_ALLOW_UPDATE (YKP_CONFIG *cfg, bool state);
int ykp_set_extflag_DORMANT (YKP_CONFIG *cfg, bool state);
int ykp_set_extflag_LED_INV (YKP_CONFIG *cfg, bool state);

bool ykp_get_tktflag_TAB_FIRST(const YKP_CONFIG *cfg);
bool ykp_get_tktflag_APPEND_TAB1(const YKP_CONFIG *cfg);
bool ykp_get_tktflag_APPEND_TAB2(const YKP_CONFIG *cfg);
bool ykp_get_tktflag_APPEND_DELAY1(const YKP_CONFIG *cfg);
bool ykp_get_tktflag_APPEND_DELAY2(const YKP_CONFIG *cfg);
bool ykp_get_tktflag_APPEND_CR(const YKP_CONFIG *cfg);
bool ykp_get_tktflag_PROTECT_CFG2(const YKP_CONFIG *cfg);
bool ykp_get_tktflag_OATH_HOTP(const YKP_CONFIG *cfg);
bool ykp_get_tktflag_CHAL_RESP(const YKP_CONFIG *cfg);

bool ykp_get_cfgflag_SEND_REF(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_TICKET_FIRST(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_PACING_10MS(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_PACING_20MS(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_ALLOW_HIDTRIG(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_STATIC_TICKET(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_SHORT_TICKET(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_STRONG_PW1(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_STRONG_PW2(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_MAN_UPDATE(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_OATH_HOTP8(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_OATH_FIXED_MODHEX1(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_OATH_FIXED_MODHEX2(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_OATH_FIXED_MODHEX(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_CHAL_YUBICO(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_CHAL_HMAC(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_HMAC_LT64(const YKP_CONFIG *cfg);
bool ykp_get_cfgflag_CHAL_BTN_TRIG(const YKP_CONFIG *cfg);

bool ykp_get_extflag_SERIAL_BTN_VISIBLE(const YKP_CONFIG *cfg);
bool ykp_get_extflag_SERIAL_USB_VISIBLE(const YKP_CONFIG *cfg);
bool ykp_get_extflag_SERIAL_API_VISIBLE (const YKP_CONFIG *cfg);
bool ykp_get_extflag_USE_NUMERIC_KEYPAD (const YKP_CONFIG *cfg);
bool ykp_get_extflag_FAST_TRIG (const YKP_CONFIG *cfg);
bool ykp_get_extflag_ALLOW_UPDATE (const YKP_CONFIG *cfg);
bool ykp_get_extflag_DORMANT (const YKP_CONFIG *cfg);
bool ykp_get_extflag_LED_INV (const YKP_CONFIG *cfg);

int ykp_clear_config(YKP_CONFIG *cfg);

int ykp_write_config(const YKP_CONFIG *cfg,
		     int (*writer)(const char *buf, size_t count,
				   void *userdata),
		     void *userdata);
int ykp_read_config(YKP_CONFIG *cfg,
		    int (*reader)(char *buf, size_t count,
				  void *userdata),
		    void *userdata);

YK_CONFIG *ykp_core_config(YKP_CONFIG *cfg);
int ykp_command(YKP_CONFIG *cfg);
int ykp_config_num(YKP_CONFIG *cfg);

int ykp_export_config(const YKP_CONFIG *cfg, char *buf, size_t len, int format);
int ykp_import_config(YKP_CONFIG *cfg, const char *buf, size_t len, int format);

#define YKP_FORMAT_LEGACY	0x01
#define YKP_FORMAT_YCFG		0x02

void ykp_set_acccode_type(YKP_CONFIG *cfg, unsigned int type);
unsigned int ykp_get_acccode_type(const YKP_CONFIG *cfg);

#define YKP_ACCCODE_NONE	0x01
#define YKP_ACCCODE_RANDOM	0x02
#define YKP_ACCCODE_SERIAL	0x03

int ykp_get_supported_key_length(const YKP_CONFIG *cfg);

extern int * _ykp_errno_location(void);
#define ykp_errno (*_ykp_errno_location())
const char *ykp_strerror(int errnum);

#define YKP_ENOTYETIMPL	0x01
#define YKP_ENOCFG	0x02
#define YKP_EYUBIKEYVER	0x03
#define YKP_EOLDYUBIKEY	0x04
#define YKP_EINVCONFNUM	0x05
#define YKP_EINVAL	0x06
#define YKP_ENORANDOM	0x07

# ifdef __cplusplus
}
# endif

#endif	/* __YKPERS_H_INCLUDED__ */


text:
<?php

namespace App\Http\Controllers;

use App\Diligencia;
use App\Status;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

class StatusesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * Get statuses percentages ( amount of calls of each status)
     *
     * @return mixed
     */
    public function getStatusesPercentages()
    {
        $statuses = Status::all();

        $diligencias = Diligencia::all();

        $total_diligencias = $diligencias->count();

        $calls_percentages = [];

        // Group calls based on status
        foreach($statuses as $status) {
            $filtered_calls_of_this_status = $diligencias->filter(function($item) use ($status) {
                return $item->status_id == $status->id;
            });

            // Count the calls of this status
            $calls_percentages[$status->slug] = $filtered_calls_of_this_status->count();

            if ($total_diligencias == 0)
                $calls_percentages[$status->slug] = 0;
            else
                // Percentage
                $calls_percentages[$status->slug] = $calls_percentages[$status->slug] * 100 / $total_diligencias;
        }

        return Response::json($calls_percentages);
    }
}


text:
"use strict";
var canSymbol = require("can-symbol");

module.exports = {
	metaSymbol: canSymbol.for("can.meta"),
	// not an actual symbol. This is so it can be enumerable
	// by default. We could create a KeyTree with a type where symbols are
	// enumerable.
	patchesSymbol: "can.patches",
	keysSymbol: "can.keys"
};


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Pyramid not just an achitecture wonder</title>

		<meta name="description" content="Presentation of the Pyramid framework">
		<meta name="author" content="Rach Belaid">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/lostproperty.css" id="theme">

		<link rel="stylesheet" href="lib/css/tomorrow.css">

		lostpropertyhq.com

Pyramid, not just a architecture Wonder

A sneak peak into great feature of the Pyramid web framework

						Created by Rach
								Belaid / @rachbelaid

Who I am.

Python charmer, Git Lover and a PostgreSQL
						Fan.

						I build web thing and love learning something new.

						work at  Lost property

						Notes..

History

						Notes..

Active project and well documented

						Notes..

Great values

					Simplicity, Minimalism, Documentation, Speed, Reliability

						Notes..

Learn from past mistake

					Learn from the others (Zope, Repose, Pylons, Django..)

						Notes..

Fast

						Notes..

Route + View lookup

						Notes..

Flexible configuration (class,method, function)

						Notes..

Builtin Events Pipeline

						Notes..

Tweakable without playing dirty

						Notes..

Extending with Directive

						Notes..

Powerful auth

				Strong ACL and  authentication or authorization policy

						Notes..

Traversal and Resource

						Notes..

Flexible and Agnostic

						Notes..

Renderer

						Notes..

Custom Predicates

						Notes..

More Important : The Coolest t-shirt

						Notes..

						Notes..

						Notes..

						Notes..

						Notes..

So why look somewhere else then?

To discover other solutions to common problems

You are a python developer and not a Django developer

It's fun and exicting

Due to frustrations

To extend your mind and toolbelt with new tools

To come back with a fresh eyes

						Notes..

Loads of frameworks out there!

Web2py

Flask

Pyramid

TurboGears

Grok

Zope

						Notes..

Why Pyramid?

						Never met a web2py developer ... seriously!

I was living a happy life

 and had my own swiss army knife as a toolkit

						Notes..

One day!

Somebody asked me to build this!

						Notes..

What I really needed!

was this!

						Notes..

Modular

Flexible

Agnostic, Not opiniated

Extensible

Fast

Full Control

For small and big webapps

						Notes..

And sometimes ...

...doing things is easier than undoing things

						Notes..

What's Pyramid?

						Never met a web2py developer ... seriously!

Simple example

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
    return Response('Hello world!')

if __name__ == '__main__':
    config = Configurator()
    config.add_route('home', '/')
    config.add_view(hello_world, route_name='home')
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

						micro frameworks example

Same example but another way

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from pyramid.view import view_config

@view_config(route_name='home')
def hello_world(request):
    return Response('Hello world!')

if __name__ == '__main__':
    config = Configurator()
    config.add_route('home', '/')
    config.scan()
    #run the app
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

						micro frameworks example

TIMTOWTDI. Blasphemy !!

with pyramid there is more than one way to do things!!!

I want my tools to bend to my needs and not me to them.

Battery not included.

Nor the shell, nor the wheels.

Time to go shopping and get the best out there!!

						Notes..

Pyramid has "extensible" applications, not pluggable applications

						Notes..

Routing

View != Route

Base on method, xhr, param, custom function(predicate)

						Notes..

Routing Example via Method

@view_config(route_name='test', request_method='GET')
def hello_world(request):
    return Response('Hello world!')

@view_config(route_name='test', request_method='POST')
def thanks_you(request):
    return Response('Thanks you')

if __name__ == '__main__':
   config = Configurator()
   config.add_route('test', '/test')
   config.scan()

						micro frameworks example

Routing Example with param

@view_config(route_name='action', match_param='action=hello')
def hello_view(request):
    return Response('Hello')

@view_config(route_name='action', match_param='action=bye')
def bye_view(request):
    return Response('Bye Bye')

@view_config(route_name='action', match_param='action')
def bye_view(request):
    return Response('Let's continue')

if __name__ == '__main__':
config = Configurator()
config.add_route('action', '/{action:\w+}') config.scan()

						micro frameworks example

Routing Example with predicate

def useless_predicate(info, request):
	from datetime import date
	today = date.today()
	return today.day == 29 && today.month == 2

@view_config(route_name='home', custom_predicate=useless_predicate)
def useless_view(request):
	return Response('Leap year')

if __name__ == '__main__':
    config = Configurator()
    config.add_route('home', '/')
    config.scan()

						micro frameworks example

Routing with class and method too

@view_config(route_name='test')
def test(request):
    return Response('ok')

class Test(object):
    def __init__(self, request):
        self.request = request

    @view_config(route_name='test')
    def test(self):
        return Response('ok')

@view_config(route_name='test')
class Test(object):
    def __init__(self, request):
        self.request = request

    def __call__(self):
        return Response('ok')

						micro frameworks example

ORM

You can choose but the choice is easy.

						If there is a piece of software which amazed me in my dev life.
						It's SQLAlchemy

SQLAlchemy, the only true ORM

Once you go SQLAlchemy, you never go back.

Finally an ORM that allows you to write better queries.

						If there is a piece of software which amazed me in my dev life.
						It's SQLAlchemy

Templating

Mako

Chameleon

Jinja2

 ... and they are fast.

						They all have their feature and advantages

Admin

Sorry, there is none ... but you may have a chance with FormAlchemy.

						Notes..

Hooks

Tweens, Event, Finished, Callbacks, Response Adapter ...

 to play ther role of middleware, context processor django

						Notes..

Tweens

A tween (a contraction of the word "between") is a bit of code that sits between the Pyramid router's main request handling function and the upstream WSGI

						Notes..

Response Adaptor

to control how Pyramid treats the view result

from pyramid.response import Response

def string_response_adapter(s):
    response = Response(s)
    return response

# config is an instance of pyramid.config.Configurator

config.add_response_adapter(string_response_adapter, str)

						Notes..

Events

loads of events : NewResponse, ApplicationCreated, ...

from pyramid.events import subscriber
from pyramid.events import BeforeRender

@subscriber(BeforeRender)
def add_global(event):
    event['mykey'] = 'foo'

						Notes..

Subscriber Predicates

to narrow the set of circumstances in which a subscriber to an event will be called

						Notes..

Finished Callback

Will be call no matter what happens!

import logging

log = logging.getLogger(__name__)

def log_callback(request):
    """Log information at the end of request"""
    log.debug('Request is finished.')
request.add_finished_callback(log_callback)

						Notes..

It's Alive! It's Alive!

						So much power

Validation

Colander, FormEncode

						Notes..

Form

WTForms, Deform with colander, WTForms-Alchemy , simple_form

						WTForms, Deform (with colander), WTForms-Alchemy , pyramid_simpleform (with Formencode)

Authentication & Authorization policy

Clear separation between Authorization and Authentication

Powerfull ACL

Resource Tree dependency

Or build your own

						Notes..

Config

 Imperative configuration or .ini file for non dev colleagues or even ZCML(XML)

 .ini file can support to serve multi wsgi app (paste legacy)

Python Package friendly

Application ready to package (egg, wheel, deb,..) or to distribute

Interrested in Pyramid?

 Have a chat.

Check the doc, tutorial.

Come to the Pyramid London Meetup.

A Final Word

 Frameworks are just tools. Use the ones which make you happy to code.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var get_status_timer;

$(document).ready(function(){
    setTimeout(function () {
        folder_reload();
    }, 100);

    $('#botton_tab').tabs({
        onSelect: function(title,index){
            switch (title) {
                case "Variables": {
                        get_variables_list()
                    }break;
                case "Stack":{
                        get_stack_list()
                    }break;
                case "Breakpoint":{
                        get_breakpoint_list()
                    }break;
            }
        }
    });

     $('#start_stop_debug').switchbutton({
        onChange: function(checked){
            if (checked) {
                start_debug();
            }
            else {
                stop_debug();
            }
        }
    });

    $("#botton_tab").tabs({
        onSelect:function(title,index) {
            update_cur_selected_tab_info();
        }
    });
});

var rigth_click_line_no = 0;
var rigth_click_file_path = "";

function modify_highlight(id) {
    var $numbering;

    //var ul_id = id + "_pre-numbering";
    $('#'+id).each(function(){
        var lines = $(this).text().split('\n').length;
        $numbering = $('
').addClass('pre-numbering');
        //$numbering.attr("id", ul_id);
        $(this).append($numbering);
        $('#' + id + " code").addClass('has-numbering')
        for(i=0;i<=lines;i++){
            $numbering.append($('
').text(i+1));
        }
    });

    $('#'+id).bind('contextmenu', function(e){
        $('#right_click_src_menu').menu('show', {
            left: e.pageX,
            top: e.pageY
        });
        return false;
    });

    $numbering.on('contextmenu', 'li', function(e){
        rigth_click_line_no = e.currentTarget.innerHTML;
        rigth_click_file_path = e.target.parentNode.parentNode.getAttribute("path");
        $('#right_click_line_menu').menu('show', {
            left: e.pageX,
            top: e.pageY
        });
        return false;
    });

    $numbering.on('click', 'li', function(e) {
        var $target = $(e.currentTarget),
            isactive = $target.hasClass('active'),
            isrun_active = $target.hasClass('run_active'),
            isrun = $target.hasClass('run'),
            lineno = $target.index() + 1;

        file_path = $(this).parents('pre')[0].attributes.path.value;
        if (isrun_active) {
            remove_line_breakpoint(file_path, lineno);
        }
        else if (isrun) {
            set_line_breakpoint(file_path, lineno)
        }
        else if(isactive) {
            remove_line_breakpoint(file_path, lineno);
        }
        else {
            set_line_breakpoint(file_path, lineno)
        }
        console.log(lineno);
    });
}

function update_files(id,path) {
    $.post("getfile", {"path":path},
        function(data){
            $("#" + id).empty();                                            // ɾ³ýÔÀ´´úÂë
            $("").appendTo($("#" + id));      // ÐÂÔö´úÂë¿é
            var context = base64_decode(data.data);

            $("#" + id + " ."+ data.type).html(highlight_code(data.type, context).value);     // ÉèÖôúÂë¿éÄÚÈÝ
            modify_highlight(id);
            update_file_breakpoint_line_display(id,path);
            update_cur_run_line_no();
        }, "json");
}

function openFiles(name,path,id){
    var exists = $("#files_tab").find('#' + id);
    if (exists.length> 0) {
        $("#files_tab pre").each(function(index){
             if ($(this).get(0).id == id) {
                var tab = $('#files_tab').tabs('getSelected');
                var sel_index = $('#files_tab').tabs('getTabIndex',tab);
                if (sel_index != index) {
                    $('#files_tab').tabs('select',index);
                }
                else {
                }
             }
        });
       return;
    }
    $('#files_tab').tabs('add',{
        title: name,
        content: '
'+ '
',
        closable: true
    });
    update_files(id,path);
}

function remove_run_line_no() {
    var pres = $("#files_tab pre");
    for(var i=0; i < pres.length; i++) {
        var file_id = pres[i].id;
        var sel_pre_query = "#" + file_id;
        var $before_target_run = $(sel_pre_query + " ul li.run:first");
        if (0 != $before_target_run.size()) {
            $before_target_run.removeClass("run");
        }

        var $before_target_run_active = $(sel_pre_query + " ul li.run_active:first");
        if (0 != $before_target_run_active.size()) {
            $before_target_run_active.removeClass("run_active").addClass('active');
        }
    }
}

function set_current_run_line_no(file_id, run_line) {
    var sel_pre_query = "#" + file_id;
    var $before_target_run = $(sel_pre_query + " ul li.run:first");
    if (0 != $before_target_run.size()) {
        $before_target_run.removeClass("run");
    }

    var $before_target_run_active = $(sel_pre_query + " ul li.run_active:first");
    if (0 != $before_target_run_active.size()) {
        $before_target_run_active.removeClass("run_active").addClass('active');
    }

    $(sel_pre_query).parent().scrollTop(run_line *14);

    var index = run_line - 1;
    var query_line = sel_pre_query + " ul li:eq(" + index + ")";
    var $target = $(query_line);
    if (0 == $target.size()) {
        return;
    }
    if ($target.hasClass("run_active")) {
        return;
    }
    else if ($target.hasClass("run")) {
        return;
    }
    else if ($target.hasClass("active")) {
        $target.removeClass("active").addClass("run_active");
    }
    else {
        $target.addClass("run");
    }
}

function update_cur_source_run_line_no() {
    $.post("do", {"action":"get_cur_stack_info", "param":""},
        function(data){
            if (data.ret == 1) {
                openFiles(data["data"]["filename_last"], data["data"]["filename"], data["data"]["file_id"]);
                update_file_breakpoint_line_display(data["data"]["file_id"], data["data"]["filename"])
                set_current_run_line_no(data["data"]["file_id"], data["data"]["lineno"]);
            }
            console.log(data);
        }, "json");
}

function update_cur_run_line_no() {
    $.post("do", {"action":"get_cur_stack_info", "param":""},
        function(data){
            if (data.ret == 1) {
                set_current_run_line_no(data["data"]["file_id"], data["data"]["lineno"]);
            }
            console.log(data);
        }, "json");
}

function update_cur_open_file_breakpoint_display() {
    var fileid = $('#files_tab').tabs('getSelected').find("pre").attr("id");
    var filename = $('#files_tab').tabs('getSelected').find("pre").attr("path");
    filename = base64_decode(filename);
    update_file_breakpoint_line_display(fileid,filename);
}

function update_file_breakpoint_line_display(fileid,filename) {
    var param = '{"filename":"' + filename + '"}';
    var param_en = base64_encode(param);
    $.post("do", {"action":"get_file_breakpoint_lineno", "param":param_en},
        function(data){
            if (data.ret == 1) {
                $('#'+fileid + " ul .active").removeClass("active");
                for (index = 0; index < data.breakpoint_list_lineno.length; index++) {
                    var lineno_index = data.breakpoint_list_lineno[index] - 1;
                    var $target = $('#'+fileid + " ul li:eq("+lineno_index+")"),
                        isactive = $target.hasClass('active'),
                        isrun_active = $target.hasClass('run_active'),
                        isrun = $target.hasClass('run');

                    if (isrun_active) {
                        $target.removeClass('run_active');
                        $target.addClass('run');
                    }
                    else if (isrun) {
                        $target.removeClass('run');
                        $target.addClass('run_active');
                    }
                    else if(isactive) {
                        $target.removeClass('active');
                    }
                    else {
                        $target.addClass('active');
                    }

                    $('#'+fileid + " ul li:eq("+lineno_index+")").addClass('active');
                }
            }
            console.log(data);
        }, "json");
}

function update_cur_selected_tab_info() {
    var tab = $('#botton_tab').tabs('getSelected');
    switch (tab.panel('options').title) {
        case "Variables": {
                get_variables_list();
            }break;
        case "Stack":{
                get_stack_list();
            }break;
        case "Breakpoint":{
                get_breakpoint_list();
            }break;
        case 'Files Watch':{
                get_files_watch();
            }break;
        case 'Variables Watch':{
                get_variables_watch();
            }break;
    }
}

function get_selected_text(){
    //ÊÊÓÃÓÚIE
    if (document.selection && document.selection.createRange){
        return document.selection.createRange().text;
        //ÊÊÓÃÓÚÆäËûä¯ÀÀÆ÷
    } else if (window.getSelection){
        return window.getSelection().toString();
    }
}

var selected_text = "";
function save_selected_text() {
    selected_text = get_selected_text();
}


text:
class Conversation < ApplicationRecord
  belongs_to :sender, polymorphic: true
  belongs_to :recipient, polymorphic: true
  has_many :messages, dependent: :destroy

  validates :sender, :recipient, presence: true

  scope :for, -> (user) do
    where(sender: user).or(where(recipient: user))
  end

  def self.between(sender, recipient_attrs)
    conditions1 = recipient_attrs.dup.merge(sender: sender)

    conditions2 = {
      sender_id: recipient_attrs[:recipient_id],
      sender_type: recipient_attrs[:recipient_type],
      recipient: sender
    }

    Conversation.where(conditions1).or(where(conditions2)).take
  end
end


text:
package org.syphr.mythtv.protocol.impl;

import java.io.IOException;
import java.net.URI;

import junit.framework.Assert;

import org.easymock.EasyMock;
import org.junit.Test;

public class Command63DeleteFileTest extends AbstractProtocolTest
{
    private static final URI FILE_PATH = URI.create("uri");
    private static final String STORAGE_GROUP = "storageGroup";

    private Parser parser;

    @Override
    public void setUp()
    {
        super.setUp();

        parser = EasyMock.createMock(Parser.class);
    }

    @Test
    public void testSendSuccessTrue() throws IOException
    {
        Boolean actual = test("1");
        Assert.assertEquals(Boolean.TRUE, actual);
    }

    @Test
    public void testSendSuccessFalse() throws IOException
    {
        Boolean actual = test("0");
        Assert.assertEquals(Boolean.FALSE, actual);
    }

    @Test(expected = IOException.class)
    public void testSendBadResponse() throws IOException
    {
        test("BAD");
    }

    private Boolean test(String response) throws IOException
    {
        setupMocks(response);

        Command63DeleteFile command = getCommand();
        try
        {
            return command.send(getSocketManager());
        }
        finally
        {
            verify();
        }
    }

    private Command63DeleteFile getCommand()
    {
        return new Command63DeleteFile(null, parser, FILE_PATH, STORAGE_GROUP);
    }

    private void setupMocks(String response) throws IOException
    {
        /*
         * Building the message.
         */
        String combined = "COMBINED";
        EasyMock.expect(parser.combineArguments("DELETE_FILE", FILE_PATH.toString(), STORAGE_GROUP)).andReturn(combined);

        /*
         * Sending the message.
         */
        EasyMock.expect(getSocketManager().sendAndWait(combined)).andReturn(response);

        /*
         * Replay.
         */
        EasyMock.replay(getSocketManager(), parser);
    }

    @Override
    protected void verify()
    {
        super.verify();

        EasyMock.verify(parser);
    }
}


text:
<!DOCTYPE html>

    <title>Task Viewer</title>

    <input type="file" name="Task File" id="file-input" accept=".task" autofocus/>

Task information

Problem

Toggle advanced selection

Variables

Select all

Deselect all

            <input type="text" id="select-vars-regex" title="Enter a regular expression to match names">

Select

Deselect

Constraints

Select all

Deselect all

            <input type="text" id="select-cons-regex" title="Enter a regular expression to match names">

Select

Deselect

Refresh problem

Variables

Other task data

        <col width="200">

Integer Parameters

Double parameters

String parameters

Solutions

Statistics


text:
import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';

const Notification = new Mongo.Collection('Notification');

Notification.allow({
  insert: () => false,
  update: () => false,
  remove: () => false,
});

Notification.deny({
  insert: () => true,
  update: () => true,
  remove: () => true,
});

const NotificationSchema = new SimpleSchema({
   message : {
     type: String,
     label:'The message sent to the receipent'
   },
   for: {
     type: String,
     label: 'The person the message for'
   },
   from: {
     type: String,
     label: 'The person sending the message'
   },
   read : {
     type: Boolean,
     label: 'The message flag',
     defaultValue : false,
   },
   date: {
   type: String,
   label: 'date the message was sent',
   autoValue() {
     if (this.isInsert){
       return (new Date()).toISOString();
     }
   },
 },
});

Notification.attachSchema( NotificationSchema );
export default Notification;


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClosedXML.Excel;
using System.IO;

namespace ClosedXML_Examples
{
    class EditingComments : IXLExample
    {

        public void Create(string filePath) {

            // Exercise(@"path/to/test/resources/comments");

        }

        public void Exercise(string basePath)
        {

            // INCOMPLETE

            var book = new XLWorkbook(Path.Combine(basePath, "EditingComments.xlsx"));
            var sheet = book.Worksheet(1);

            // no change
            // A1

            // edit existing comment
            sheet.Cell("B3").Comment.AddNewLine();
            sheet.Cell("B3").Comment.AddSignature();
            sheet.Cell("B3").Comment.AddText("more comment");

            // delete
            //sheet.Cell("C1").DeleteComment();

            // clear contents
            sheet.Cell("D3").Clear(XLClearOptions.Contents);

            // new basic
            sheet.Cell("E1").Comment.AddText("non authored comment");

            // new with author
            sheet.Cell("F3").Comment.AddSignature();
            sheet.Cell("F3").Comment.AddText("comment from author");

            // TODO: merge with cells
            // TODO: resize with cells
            // TODO: visible

            book.SaveAs(Path.Combine(basePath, "EditingComments_modified.xlsx"));
        }
    }
}


text:
package services

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/gravitational/teleport/lib/defaults"
	"github.com/gravitational/teleport/lib/utils"

	"github.com/gravitational/trace"
	"github.com/jonboulle/clockwork"
)

// GithubConnector defines an interface for a Github OAuth2 connector
type GithubConnector interface {
	// Resource is a common interface for all resources
	Resource
	// CheckAndSetDefaults validates the connector and sets some defaults
	CheckAndSetDefaults() error
	// GetClientID returns the connector client ID
	GetClientID() string
	// SetClientID sets the connector client ID
	SetClientID(string)
	// GetClientSecret returns the connector client secret
	GetClientSecret() string
	// SetClientSecret sets the connector client secret
	SetClientSecret(string)
	// GetRedirectURL returns the connector redirect URL
	GetRedirectURL() string
	// SetRedirectURL sets the connector redirect URL
	SetRedirectURL(string)
	// GetTeamsToLogins returns the mapping of Github teams to allowed logins
	GetTeamsToLogins() []TeamMapping
	// SetTeamsToLogins sets the mapping of Github teams to allowed logins
	SetTeamsToLogins([]TeamMapping)
	// MapClaims returns the list of allows logins based on the retrieved claims
	// returns list of logins and kubernetes groups
	MapClaims(GithubClaims) ([]string, []string)
	// GetDisplay returns the connector display name
	GetDisplay() string
	// SetDisplay sets the connector display name
	SetDisplay(string)
}

// NewGithubConnector creates a new Github connector from name and spec
func NewGithubConnector(name string, spec GithubConnectorSpecV3) GithubConnector {
	return &GithubConnectorV3{
		Kind:    KindGithubConnector,
		Version: V3,
		Metadata: Metadata{
			Name:      name,
			Namespace: defaults.Namespace,
		},
		Spec: spec,
	}
}

// GithubConnectorV3 represents a Github connector
type GithubConnectorV3 struct {
	// Kind is a resource kind, for Github connector it is "github"
	Kind string `json:"kind"`
	// Version is resource version
	Version string `json:"version"`
	// Metadata is resource metadata
	Metadata Metadata `json:"metadata"`
	// Spec contains connector specification
	Spec GithubConnectorSpecV3 `json:"spec"`
}

// GithubConnectorSpecV3 is the current Github connector spec
type GithubConnectorSpecV3 struct {
	// ClientID is the Github OAuth app client ID
	ClientID string `json:"client_id"`
	// ClientSecret is the Github OAuth app client secret
	ClientSecret string `json:"client_secret"`
	// RedirectURL is the authorization callback URL
	RedirectURL string `json:"redirect_url"`
	// TeamsToLogins maps Github team memberships onto allowed logins/roles
	TeamsToLogins []TeamMapping `json:"teams_to_logins"`
	// Display is the connector display name
	Display string `json:"display"`
}

// TeamMapping represents a single team membership mapping
type TeamMapping struct {
	// Organization is a Github organization a user belongs to
	Organization string `json:"organization"`
	// Team is a team within the organization a user belongs to
	Team string `json:"team"`
	// Logins is a list of allowed logins for this org/team
	Logins []string `json:"logins,omitempty"`
	// KubeGroups is a list of allowed kubernetes groups for this org/team
	KubeGroups []string `json:"kubernetes_groups,omitempty"`
}

// GithubClaims represents Github user information obtained during OAuth2 flow
type GithubClaims struct {
	// Username is the user's username
	Username string
	// OrganizationToTeams is the user's organization and team membership
	OrganizationToTeams map[string][]string
}

// GetResourceID returns resource ID
func (c *GithubConnectorV3) GetResourceID() int64 {
	return c.Metadata.ID
}

// SetResourceID sets resource ID
func (c *GithubConnectorV3) SetResourceID(id int64) {
	c.Metadata.ID = id
}

// GetName returns the name of the connector
func (c *GithubConnectorV3) GetName() string {
	return c.Metadata.GetName()
}

// SetName sets the connector name
func (c *GithubConnectorV3) SetName(name string) {
	c.Metadata.SetName(name)
}

// Expires returns the connector expiration time
func (c *GithubConnectorV3) Expiry() time.Time {
	return c.Metadata.Expiry()
}

// SetExpiry sets the connector expiration time
func (c *GithubConnectorV3) SetExpiry(expires time.Time) {
	c.Metadata.SetExpiry(expires)
}

// SetTTL sets the connector TTL
func (c *GithubConnectorV3) SetTTL(clock clockwork.Clock, ttl time.Duration) {
	c.Metadata.SetTTL(clock, ttl)
}

// GetMetadata returns the connector metadata
func (c *GithubConnectorV3) GetMetadata() Metadata {
	return c.Metadata
}

// CheckAndSetDefaults verifies the connector is valid and sets some defaults
func (c *GithubConnectorV3) CheckAndSetDefaults() error {
	if err := c.Metadata.CheckAndSetDefaults(); err != nil {
		return trace.Wrap(err)
	}
	return nil
}

// GetClientID returns the connector client ID
func (c *GithubConnectorV3) GetClientID() string {
	return c.Spec.ClientID
}

// SetClientID sets the connector client ID
func (c *GithubConnectorV3) SetClientID(id string) {
	c.Spec.ClientID = id
}

// GetClientSecret returns the connector client secret
func (c *GithubConnectorV3) GetClientSecret() string {
	return c.Spec.ClientSecret
}

// SetClientSecret sets the connector client secret
func (c *GithubConnectorV3) SetClientSecret(secret string) {
	c.Spec.ClientSecret = secret
}

// GetRedirectURL returns the connector redirect URL
func (c *GithubConnectorV3) GetRedirectURL() string {
	return c.Spec.RedirectURL
}

// SetRedirectURL sets the connector redirect URL
func (c *GithubConnectorV3) SetRedirectURL(redirectURL string) {
	c.Spec.RedirectURL = redirectURL
}

// GetTeamsToLogins returns the connector team membership mappings
func (c *GithubConnectorV3) GetTeamsToLogins() []TeamMapping {
	return c.Spec.TeamsToLogins
}

// SetTeamsToLogins sets the connector team membership mappings
func (c *GithubConnectorV3) SetTeamsToLogins(teamsToLogins []TeamMapping) {
	c.Spec.TeamsToLogins = teamsToLogins
}

// GetDisplay returns the connector display name
func (c *GithubConnectorV3) GetDisplay() string {
	return c.Spec.Display
}

// SetDisplay sets the connector display name
func (c *GithubConnectorV3) SetDisplay(display string) {
	c.Spec.Display = display
}

// MapClaims returns a list of logins based on the provided claims,
// returns a list of logins and list of kubernetes groups
func (c *GithubConnectorV3) MapClaims(claims GithubClaims) ([]string, []string) {
	var logins, kubeGroups []string
	for _, mapping := range c.GetTeamsToLogins() {
		teams, ok := claims.OrganizationToTeams[mapping.Organization]
		if !ok {
			// the user does not belong to this organization
			continue
		}
		for _, team := range teams {
			// see if the user belongs to this team
			if team == mapping.Team {
				logins = append(logins, mapping.Logins...)
				kubeGroups = append(kubeGroups, mapping.KubeGroups...)
			}
		}
	}
	return utils.Deduplicate(logins), utils.Deduplicate(kubeGroups)
}

var githubConnectorMarshaler GithubConnectorMarshaler = &TeleportGithubConnectorMarshaler{}

// SetGithubConnectorMarshaler sets Github connector marshaler
func SetGithubConnectorMarshaler(m GithubConnectorMarshaler) {
	marshalerMutex.Lock()
	defer marshalerMutex.Unlock()
	githubConnectorMarshaler = m
}

// GetGithubConnectorMarshaler returns currently set Github connector marshaler
func GetGithubConnectorMarshaler() GithubConnectorMarshaler {
	marshalerMutex.RLock()
	defer marshalerMutex.RUnlock()
	return githubConnectorMarshaler
}

// GithubConnectorMarshaler defines interface for Github connector marshaler
type GithubConnectorMarshaler interface {
	// Unmarshal unmarshals connector from binary representation
	Unmarshal(bytes []byte) (GithubConnector, error)
	// Marshal marshals connector to binary representation
	Marshal(c GithubConnector, opts ...MarshalOption) ([]byte, error)
}

// GetGithubConnectorSchema returns schema for Github connector
func GetGithubConnectorSchema() string {
	return fmt.Sprintf(GithubConnectorV3SchemaTemplate, MetadataSchema, GithubConnectorSpecV3Schema)
}

// TeleportGithubConnectorMarshaler is the default Github connector marshaler
type TeleportGithubConnectorMarshaler struct{}

// UnmarshalGithubConnector unmarshals Github connector from JSON
func (*TeleportGithubConnectorMarshaler) Unmarshal(bytes []byte) (GithubConnector, error) {
	var h ResourceHeader
	if err := json.Unmarshal(bytes, &h); err != nil {
		return nil, trace.Wrap(err)
	}
	switch h.Version {
	case V3:
		var c GithubConnectorV3
		if err := utils.UnmarshalWithSchema(GetGithubConnectorSchema(), &c, bytes); err != nil {
			return nil, trace.Wrap(err)
		}
		if err := c.CheckAndSetDefaults(); err != nil {
			return nil, trace.Wrap(err)
		}
		return &c, nil
	}
	return nil, trace.BadParameter(
		"Github connector resource version %q is not supported", h.Version)
}

// MarshalGithubConnector marshals Github connector to JSON
func (*TeleportGithubConnectorMarshaler) Marshal(c GithubConnector, opts ...MarshalOption) ([]byte, error) {
	return json.Marshal(c)
}

// GithubConnectorV3SchemaTemplate is the JSON schema for a Github connector
const GithubConnectorV3SchemaTemplate = `{
  "type": "object",
  "additionalProperties": false,
  "required": ["kind", "spec", "metadata", "version"],
  "properties": {
    "kind": {"type": "string"},
    "version": {"type": "string", "default": "v3"},
    "metadata": %v,
    "spec": %v
  }
}`

// GithubConnectorSpecV3Schema is the JSON schema for Github connector spec
var GithubConnectorSpecV3Schema = fmt.Sprintf(`{
  "type": "object",
  "additionalProperties": false,
  "required": ["client_id", "client_secret", "redirect_url"],
  "properties": {
    "client_id": {"type": "string"},
    "client_secret": {"type": "string"},
    "redirect_url": {"type": "string"},
    "display": {"type": "string"},
    "teams_to_logins": {
      "type": "array",
      "items": %v
    }
  }
}`, TeamMappingSchema)

// TeamMappingSchema is the JSON schema for team membership mapping
var TeamMappingSchema = `{
  "type": "object",
  "additionalProperties": false,
  "required": ["organization", "team"],
  "properties": {
    "organization": {"type": "string"},
    "team": {"type": "string"},
    "logins": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "kubernetes_groups": {
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  }
}`


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.georgekaraolanis.project4_musicalstructureapp.ListSongsActivity">

    <TextView
        style="@style/text_view_style"
        android:text="@string/label_list_songs"
        android:textSize="@dimen/text_size_label"
        android:gravity="center"/>

    <TextView
        style="@style/text_view_style"
        android:text="@string/info_list_songs"
        android:textSize="@dimen/text_size_info" />

    <Button
        android:id="@+id/search_song_button"
        style="@style/button_style"
        android:text="@string/button_text_search_song"/>

    <Button
        android:id="@+id/play_song_button"
        style="@style/button_style"
        android:text="@string/button_text_now_playing"/>

    <Button
        android:id="@+id/create_playlist_button"
        style="@style/button_style"
        android:text="@string/button_text_create_play_list"/>

</LinearLayout>


text:
{{error}}

      {{article.status}}

    <form role="form" name="articleValidation">

      <fieldset class="form-group"  ng-class="{ 'has-error': articleValidation.id.$invalid }">
        URL концовка (одно слово на английском)
        <input class="form-control"
               id="id"
               name="id"
               ng-model="article.id"
               ng-pattern="/^[A-z,0-9,\-,_]+$/"
               ng-required/>
      </fieldset>
      <nl-editor data="article.body"></nl-editor>

      <button type="submit" class="btn btn-danger"
              ng-class="{ 'disabled': articleValidation.$invalid }"
              ng-click="updateArticle(article)"
              ng-disabled="article.updating">{{article.updating ? 'Saving...' : 'Save'}}
      </button>
      <button type="submit" class="btn btn-danger"
              ng-click="removeArticle()"
              ng-disabled="article.removing">{{article.removing ? 'Deleting...' : 'Delete'}}
      </button>

    </form>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

		    <link rel="stylesheet" type="text/css" href="Styles/branding.css"/>
		    		<title>Copy Assembly</title>
				<meta name="Description" content="Copies the assembly of the selected project to GAC." />

								SharePoint Software Factory

								Recipe Index

								SPSF Deploy and Debug

								Quick Deploy

											Copy Both

											Copy to SharePoint Hive

Copy Assembly

Related Links

Copy Assembly

Copies the assembly of the selected project to GAC.

Authors

Torsten Mandelkow

Version history

1.0 Initial Recipe

						Disclaimer: The views and opinions expressed in this documentation and in SPSF are those of the authors and do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. All trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.

						SharePoint Software Factory, Version 4.1.3.2705, GPLv2, see http://spsf.codeplex.com for more information


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
A. P. de Candolle, Prodr. 2:374. 1825

#### Original name
null

### Remarks
null


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Personalize your workout">
  <meta name="author" content="Kasper Jacobsen">
  <title>Random WOD</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
  <link rel="stylesheet" type="text/css" href="styles.css">


text:
/*       */

// -----------------------------------------------------------------------------
// EXPORTED REDUCER STATE TYPE

// -----------------------------------------------------------------------------
// PRIVATES

const defaultState = {};

// -----------------------------------------------------------------------------
// REDUCER

function byId(state = defaultState, action) {
  if (action.type === 'FETCHED_POST') {
    return Object.assign({}, state,
      { [action.payload.id]: action.payload }
    );
  }

  return state;
}

// -----------------------------------------------------------------------------
// EXPORTED SELECTORS

export function getById(state, id) {
  return state[id];
}

// -----------------------------------------------------------------------------
// EXPORTED REDUCER

export default (byId);