text:
package gofogbugz

import (
	"fmt"
	"log"
	"net/http"
	"net/url"
	"runtime"
)

type Scout struct {
	URL                 string
	UserName            string
	Project             string
	Area                string
	Email               string
	ScoutDefaultMessage string
	FriendlyResponse    string
	Prefix              string
	Logger              *log.Logger
}

func Init(s *Scout) {
	std = s
}

func checkInit() {
	if std == nil {
		panic("gofogbugz: Call gofogbugz.Init before using reporting")
	}
}

// Standard reporter
var std *Scout = nil

// Report obtains a stack trace and reports
// it to fogbugz.
// The err string is used as the bug title.
// Remaining fogbugz data is obtained from
// the Scout struct.
func (s *Scout) Report(title string) error {
	// Heavily based on http://play.golang.org/p/65P0tZOZe0
	var n int
	buf := make([]byte, 1<<20) // 1 MB buffer
	for i := 0; ; i++ {
		n = runtime.Stack(buf, true)
		if n < len(buf) {
			buf = buf[:n]
			break
		}
		if len(buf) >= 64<<20 {
			// Filled 64 MB - stop here
			break
		}
		buf = make([]byte, 2*len(buf))
	}
	values := url.Values{
		"ScoutUserName":       {s.UserName},
		"ScoutProject":        {s.Project},
		"ScoutArea":           {s.Area},
		"Description":         {s.Prefix + title},
		"ForceNewBug":         {"0"},
		"Extra":               {string(buf[:n])}, // stack trace
		"Email":               {s.Email},
		"ScoutDefaultMessage": {s.ScoutDefaultMessage},
		"FriendlyResponse":    {s.FriendlyResponse},
	}
	resp, err := http.PostForm(s.URL, values)
	if err != nil {
		log.Print(err)
		return err
	}
	defer resp.Body.Close()
	return nil
}

// Sets the prefix for fogbugz bug reports.
// Suggested value is the application version.
func (s *Scout) SetPrefix(prefix string) {
	s.Prefix = prefix
}

// Fatal is equivalent to l.Print() followed by
// a call to os.Exit(1) reporting the bug to
// fogbugz beforehand.
func (s *Scout) Fatal(v ...interface{}) {
	str := fmt.Sprint(v...)
	s.Report(str)
	s.Logger.Fatal(str)
}

// Fatalf is equivalent to l.Printf() followed by
// a call to os.Exit(1) reporting the bug to
// fogbugz beforehand.
func (s *Scout) Fatalf(format string, v ...interface{}) {
	str := fmt.Sprintf(format, v...)
	s.Report(str)
	s.Logger.Fatal(str)
}

// Fatalln is equivalent to l.Println() followed by
// a call to os.Exit(1) reporting the bug to
// fogbugz beforehand.
func (s *Scout) Fatalln(v ...interface{}) {
	str := fmt.Sprintln(v...)
	s.Report(str)
	s.Logger.Fatal(str)
}

// Panic is equivalent to l.Print() followed by
// a call to panic() reporting the bug to
// fogbugz beforehand.
func (s *Scout) Panic(v ...interface{}) {
	str := fmt.Sprint(v...)
	s.Report(str)
	s.Logger.Panic(str)
}

// Panicf is equivalent to l.Printf() followed by
// a call to panic() reporting the bug to
// fogbugz beforehand.
func (s *Scout) Panicf(format string, v ...interface{}) {
	str := fmt.Sprintf(format, v...)
	s.Report(str)
	s.Logger.Panic(str)
}

// Panicln is equivalent to l.Println() followed by
// a call to panic() reporting the bug to
// fogbugz beforehand.
func (s *Scout) Panicln(v ...interface{}) {
	str := fmt.Sprintln(v...)
	s.Report(str)
	s.Logger.Panic(str)
}

// Print calls l.Print to print to the logger.
// Arguments are handled in the manner of fmt.Print.
// The bug is reported to fogbugz beforehand.
func (s *Scout) Print(v ...interface{}) {
	str := fmt.Sprint(v...)
	s.Report(str)
	s.Logger.Print(str)
}

// Printf calls l.Printf to print to the logger.
// Arguments are handled in the manner of fmt.Printf.
// The bug is reported to fogbugz beforehand.
func (s *Scout) Printf(format string, v ...interface{}) {
	str := fmt.Sprintf(format, v...)
	s.Report(str)
	s.Logger.Print(str)
}

// Println calls l.Println to print to the logger.
// Arguments are handled in the manner of fmt.Println.
// The bug is reported to fogbugz beforehand.
func (s *Scout) Println(format string, v ...interface{}) {
	str := fmt.Sprintln(v...)
	s.Report(str)
	s.Logger.Print(str)
}

// Standard reporter

// Sets the prefix for the standard fogbugz bug reports.
// Suggested value is the application version.
func SetPrefix(prefix string) {
	std.SetPrefix(prefix)
}

// Fatal is equivalent to l.Print() followed by
// a call to os.Exit(1) reporting the bug to
// fogbugz beforehand.
func Fatal(v ...interface{}) {
	checkInit()
	s := fmt.Sprint(v...)
	std.Report(s)
	log.Fatal(s)
}

// Fatalf is equivalent to l.Printf() followed by
// a call to os.Exit(1) reporting the bug to
// fogbugz beforehand.
func Fatalf(format string, v ...interface{}) {
	checkInit()
	s := fmt.Sprintf(format, v...)
	std.Report(s)
	log.Fatal(s)
}

// Fatalln is equivalent to l.Println() followed by
// a call to os.Exit(1) reporting the bug to
// fogbugz beforehand.
func Fatalln(v ...interface{}) {
	checkInit()
	s := fmt.Sprintln(v...)
	std.Report(s)
	log.Fatal(s)
}

// Panic is equivalent to l.Print() followed by
// a call to panic() reporting the bug to
// fogbugz beforehand.
func Panic(v ...interface{}) {
	checkInit()
	s := fmt.Sprint(v...)
	std.Report(s)
	log.Panic(s)
}

// Panicf is equivalent to l.Printf() followed by
// a call to panic() reporting the bug to
// fogbugz beforehand.
func Panicf(format string, v ...interface{}) {
	checkInit()
	s := fmt.Sprintf(format, v...)
	std.Report(s)
	log.Panic(s)
}

// Panicln is equivalent to l.Println() followed by
// a call to panic() reporting the bug to
// fogbugz beforehand.
func Panicln(v ...interface{}) {
	checkInit()
	s := fmt.Sprintln(v...)
	std.Report(s)
	log.Panic(s)
}

// Print calls l.Print to print to the logger.
// Arguments are handled in the manner of fmt.Print.
// The bug is reported to fogbugz beforehand.
func Print(v ...interface{}) {
	checkInit()
	s := fmt.Sprint(v...)
	std.Report(s)
	log.Print(s)
}

// Printf calls l.Print to print to the logger.
// Arguments are handled in the manner of fmt.Printf.
// The bug is reported to fogbugz beforehand.
func Printf(format string, v ...interface{}) {
	checkInit()
	s := fmt.Sprintf(format, v...)
	std.Report(s)
	log.Print(s)
}

// Println calls l.Print to print to the logger.
// Arguments are handled in the manner of fmt.Println.
// The bug is reported to fogbugz beforehand.
func Println(format string, v ...interface{}) {
	checkInit()
	s := fmt.Sprintln(v...)
	std.Report(s)
	log.Print(s)
}


text:
import File = require('vinyl');
import {IAuthOptions} from 'sp-request';

export enum CheckinType {
  minor = 0,
  major = 1,
  overwrite = 2,
  nocheckin = 3
}

export interface ICoreOptions {
  siteUrl: string;
  checkin?: boolean;
  checkinType?: CheckinType;
  checkinMessage?: string;
  notification?: boolean;
  filesMetaData?: IFileMetaData[];
}

export interface IFileMetaData {
  fileName: string;
  updated?: boolean;
  metadata: any;
}

export interface IGlobOptions {
  glob: string | string[];
  folder?: string;
  base?: string;
}

export interface IFileContentOptions {
  fileName: string;
  fileContent: string | Buffer;
  folder: string;
}

export interface IVinylOptions {
  file: File;
  folder?: string;
}

export type FileOptions = IGlobOptions | IFileContentOptions | IVinylOptions;

export interface ISPSaveOptions {
  creds: IAuthOptions;
  files: IFileContentOptions[];
  core: ICoreOptions;
}

export function isGlobOptions(T: FileOptions): T is IGlobOptions {
  return !!(T as IGlobOptions).glob;
}

export function isFileContentOptions(T: FileOptions): T is IFileContentOptions {
  return !!(T as IFileContentOptions).fileContent || (T as IFileContentOptions).fileContent === '';
}

export function isVinylOptions(T: FileOptions): T is IVinylOptions {
  return !!(T as IVinylOptions).file;
}

redpajama_set_name: RedPajamaGithub


text:
package org.libelektra;

import static org.libelektra.ValidationUtil.argNotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nonnull;
import org.libelektra.exception.ConflictingStateException;
import org.libelektra.exception.InstallationException;
import org.libelektra.exception.InterfaceException;
import org.libelektra.exception.InternalException;
import org.libelektra.exception.KeyReleasedException;
import org.libelektra.exception.OutOfMemoryException;
import org.libelektra.exception.PluginMisbehaviorException;
import org.libelektra.exception.ResourceException;
import org.libelektra.exception.SemanticValidationException;
import org.libelektra.exception.SyntacticValidationException;

/**
 * Wraps Elektra errors into the corresponding Java exceptions
 *
 * @see #releaseErrorKey()
 */
public abstract class KDBException extends Exception
{

	protected static final String VALUE_META_KEY_NOT_FOUND = "(unknown)";

	protected static final String MSG_UNKNOWN_ERROR_NUMBER =
		"Sorry, could not map error number '%s'. Please report this incident at https://issues.libelektra.org/";
	protected static final String MSG_MODULE_ERROR_NUMBER = "Sorry, module %s issued error %s:";
	protected static final String MSG_CONFIGFILE = "Configfile: ";
	protected static final String MSG_MOUNTPOINT = "Mountpoint: ";
	protected static final String MSG_DEBUGINFO = "At: %s:%s";

	private static final long serialVersionUID = 1L;

	private final transient Key errorKey;
	private final transient List<WarningEntry> warnings;

	/**
	 * Extracts warnings and error information and maps it to an appropriate
	 * exception
	 *
	 * @param errorKey Key containing {@code error/*} and {@code warnings/*} meta
	 *                 keys
	 * @return {@link KDBException} corresponding to the error information
	 * @throws KeyReleasedException     if this {@code errorKey} has already been
	 *                                  released
	 * @throws IllegalArgumentException if {@code errorKey} is {@code null}
	 */
	@Nonnull public static KDBException getMappedException (Key errorKey)
	{
		argNotNull (errorKey, "Key 'errorKey'");
		String errorNumber = errorKey.getMeta ("error/number").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND);

		if (errorNumber.equals (ResourceException.ERROR_NUMBER))
		{
			return new ResourceException (errorKey);
		}
		if (errorNumber.equals (OutOfMemoryException.ERROR_NUMBER))
		{
			return new OutOfMemoryException (errorKey);
		}
		if (errorNumber.equals (InternalException.ERROR_NUMBER))
		{
			return new InternalException (errorKey);
		}
		if (errorNumber.equals (InterfaceException.ERROR_NUMBER))
		{
			return new InterfaceException (errorKey);
		}
		if (errorNumber.equals (InstallationException.ERROR_NUMBER))
		{
			return new InstallationException (errorKey);
		}
		if (errorNumber.equals (PluginMisbehaviorException.ERROR_NUMBER))
		{
			return new PluginMisbehaviorException (errorKey);
		}
		if (errorNumber.equals (ConflictingStateException.ERROR_NUMBER))
		{
			return new ConflictingStateException (errorKey);
		}
		if (errorNumber.equals (SyntacticValidationException.ERROR_NUMBER))
		{
			return new SyntacticValidationException (errorKey);
		}
		if (errorNumber.equals (SemanticValidationException.ERROR_NUMBER))
		{
			return new SemanticValidationException (errorKey);
		}

		errorKey.setMeta ("error/reason", String.format (MSG_UNKNOWN_ERROR_NUMBER, errorNumber));
		return new InternalException (errorKey);
	}

	/**
	 * @param errorKey Key containing {@code error/*} and {@code warnings/*} meta
	 *                 keys
	 */
	protected KDBException (Key errorKey)
	{
		this.errorKey = errorKey;
		warnings = new ArrayList<> ();

		Optional<String> oWarningsKeyValue = errorKey.getMeta ("warnings").map (Key::getStringAndRelease);
		if (oWarningsKeyValue.isPresent ())
		{
			String lastArrayIndex = oWarningsKeyValue.get ();
			int arraySize = Integer.parseInt (lastArrayIndex.replaceAll ("^#_*", ""));
			for (int i = 0; i <= arraySize; i++)
			{
				warnings.add (new WarningEntry (errorKey, i));
			}
		}
	}

	/**
	 * Release the key backing this {@link KDBException}
	 *
	 * @throws KeyReleasedException if this error key backing this
	 *                              {@link KDBException} has already been released
	 * @apiNote If this exception does not terminate your process, consider
	 *          releasing the backing error key after processing it
	 */
	public void releaseErrorKey ()
	{
		errorKey.release ();
	}

	/**
	 * @return Key containing {@code error/*} and {@code warnings/*} meta keys
	 *         backing this exception
	 */
	@Nonnull public Key getErrorKey ()
	{
		return errorKey;
	}

	/**
	 * @return Elektra error number read from the error key backing this exception
	 * @throws KeyReleasedException if this error key backing this
	 *                              {@link KDBException} has already been released
	 */
	@Nonnull public String getErrorNumber ()
	{
		return errorKey.getMeta ("error/number").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND);
	}

	/**
	 * @return The affected configuration file of the error or if not available
	 *         returns the error key name
	 * @throws KeyReleasedException if this error key backing this
	 *                              {@link KDBException} has already been released
	 */
	@Nonnull public String getConfigFile ()
	{
		return errorKey.getMeta ("error/configfile")
			.map (Key::getStringAndRelease)
			.filter (s -> !s.isEmpty ())
			.orElseGet (errorKey::getName);
	}

	/**
	 * @return Mountpoint of the configuration
	 * @throws KeyReleasedException if this error key backing this
	 *                              {@link KDBException} has already been released
	 */
	@Nonnull public String getMountpoint ()
	{
		return errorKey.getMeta ("error/mountpoint").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND);
	}

	/**
	 * @return Elektra specific debug information in the form of "At: file:line"
	 * @throws KeyReleasedException if this error key backing this
	 *                              {@link KDBException} has already been released
	 */
	@Nonnull public String getDebugInformation ()
	{
		return String.format (MSG_DEBUGINFO,
				      errorKey.getMeta ("error/file").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND),
				      errorKey.getMeta ("error/line").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND));
	}

	/**
	 * @return Module which issued the error
	 * @throws KeyReleasedException if this error key backing this
	 *                              {@link KDBException} has already been released
	 */
	@Nonnull public String getModule ()
	{
		return errorKey.getMeta ("error/module").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND);
	}

	/**
	 * @return Error reason read from the error key backing this exception
	 * @throws KeyReleasedException if this error key backing this
	 *                              {@link KDBException} has already been released
	 */
	@Nonnull public String getReason ()
	{
		return errorKey.getMeta ("error/reason").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND);
	}

	/**
	 * @return The complete error information in a String with config file, mount
	 *         point and debug information as it would be printed in the terminal
	 * @throws KeyReleasedException if this error key backing this
	 *                              {@link KDBException} has already been released
	 */
	@Override public String getMessage ()
	{
		StringBuilder builder = new StringBuilder ();
		builder.append (String.format (MSG_MODULE_ERROR_NUMBER, getModule (), getErrorNumber ())).append ("\n");
		builder.append (getReason ()).append ("\n");
		builder.append (MSG_CONFIGFILE).append (getConfigFile ()).append ("\n");
		errorKey.getMeta ("error/mountpoint")
			.ifPresent (s -> builder.append (MSG_MOUNTPOINT).append (getMountpoint ()).append ("\n"));
		errorKey.getMeta ("error/file").ifPresent (s -> builder.append (getDebugInformation ()).append ("\n"));
		return builder.toString ();
	}

	/**
	 * If an error occurred it may also has important warnings which caused the
	 * error
	 *
	 * @return True if additional warnings were emitted, false otherwise
	 */
	public boolean hasWarnings ()
	{
		return !warnings.isEmpty ();
	}

	/**
	 * @return Additional warnings emitted with the error
	 */
	@Nonnull public List<WarningEntry> getWarnings ()
	{
		return warnings;
	}

	/**
	 * Warning extracted from an error key
	 */
	public static class WarningEntry
	{

		private final String warningNumber;
		private final String reason;
		private final String mountpoint;
		private final String configFile;
		private final String debugInformation;
		private final String module;

		/**
		 * Extracts warning information from the specified {@code key}
		 *
		 * @param key     Key to ectract {@code warnings/*} meta keys from
		 * @param current Warning entry to parse, e.g.: {@code (key, 0)} will search for
		 *                entries with {@code warnings/#0}
		 */
		public WarningEntry (Key key, int current)
		{
			final String warningIndex = Integer.toString (current);
			char[] underscores = new char[warningIndex.length () - 1];
			Arrays.fill (underscores, '_');
			final String warningKeyName = "warnings/#" + new String (underscores) + warningIndex;
			warningNumber =
				key.getMeta (warningKeyName + "/number").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND);
			reason = key.getMeta (warningKeyName + "/reason").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND);
			module = key.getMeta (warningKeyName + "/module").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND);
			debugInformation = String.format (
				MSG_DEBUGINFO,
				key.getMeta (warningKeyName + "/file").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND),
				key.getMeta (warningKeyName + "/line").map (Key::getStringAndRelease).orElse (VALUE_META_KEY_NOT_FOUND));
			mountpoint = key.getMeta (warningKeyName + "/mountpoint")
					     .map (Key::getStringAndRelease)
					     .orElse (VALUE_META_KEY_NOT_FOUND);
			configFile = key.getMeta (warningKeyName + "/configfile")
					     .map (Key::getStringAndRelease)
					     .orElse (VALUE_META_KEY_NOT_FOUND);
		}

		/**
		 * @return Warning number issued by Elektra
		 */
		@Nonnull public String getWarningNumber ()
		{
			return warningNumber;
		}

		/**
		 * @return Warning reason text
		 */
		@Nonnull public String getReason ()
		{
			return reason;
		}

		/**
		 * @return Warning reason mount point
		 */
		@Nonnull public String getMountpoint ()
		{
			return mountpoint;
		}

		/**
		 * @return Warning module
		 */
		@Nonnull public String getModule ()
		{
			return module;
		}

		/**
		 * @return Warning reason configuration file
		 */
		@Nonnull public String getConfigFile ()
		{
			return configFile;
		}

		/**
		 * @return Warning debug information in the form of {@code At: file:line}
		 */
		@Nonnull public String getDebugInformation ()
		{
			return debugInformation;
		}
	}
}


text:
package com.qxcmp.account.auth;

import com.qxcmp.account.event.UserLoginEvent;
import com.qxcmp.config.SystemConfigService;
import com.qxcmp.user.UserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.qxcmp.core.QxcmpSystemConfig.SESSION_TIMEOUT;
import static com.qxcmp.core.QxcmpSystemConfig.SESSION_TIMEOUT_DEFAULT;

/**
 * 认证成功处理器,属于框架基本功能,供平台和前端共同使用
 *

 * 配置在认证过滤器{@link AuthenticationFilter}中,负责对认证成功进行处理
 *

 * 认证成功流程如下:

设置用户最后一次登录日期

 *
 * @author aaric
 */
@Component
@RequiredArgsConstructor
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    private final ApplicationContext applicationContext;
    private final UserService userService;
    private final SystemConfigService systemConfigService;

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

        if (StringUtils.isNotBlank(request.getParameter("callback"))) {
            redirectStrategy.sendRedirect(request, response, request.getParameter("callback"));
        }

        request.getSession().setMaxInactiveInterval(systemConfigService.getInteger(SESSION_TIMEOUT).orElse(SESSION_TIMEOUT_DEFAULT));

        try {
            String userId = request.getParameter("username");
            userService.findById(userId).ifPresent(user -> {
                userService.updateLoginDate(user);
                applicationContext.publishEvent(new UserLoginEvent(user));
            });
        } catch (Exception ignored) {

        }

        super.onAuthenticationSuccess(request, response, authentication);
    }
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("Academy.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Academy.Test")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: Guid("ce85a7a7-5e40-40b7-a07e-5c75fc615c4c")]

// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeMap;

public class AllOne {
    /** Initialize your data structure here. */
    HashMap<String, Integer> keyValue;
    TreeMap<Integer, HashSet<String>> reverse;
    public AllOne() {
        this.keyValue = new HashMap<>();
        this.reverse = new TreeMap<>();
    }

    /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
    public void inc(String key) {
        if (this.keyValue.containsKey(key)) {
            int value = this.keyValue.get(key);
            this.reverse.get(value).remove(key);
            if (this.reverse.get(value).size() == 0){
                this.reverse.remove(value);
            }
            if (!this.reverse.containsKey(value + 1)) {
                this.reverse.put(value + 1, new HashSet<>());
            }
            this.keyValue.put(key, value + 1);
            this.reverse.get(value + 1).add(key);
        } else {
            this.keyValue.put(key, 1);
            if (!this.reverse.containsKey(1)) {
                this.reverse.put(1, new HashSet<>());
            }
            this.reverse.get(1).add(key);
        }
    }

    /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
    public void dec(String key) {
        if (this.keyValue.containsKey(key)) {
            int value = this.keyValue.get(key);
            this.reverse.get(value).remove(key);
            if (this.reverse.get(value).size() == 0) {
                this.reverse.remove(value);
            }
            if (value == 1) {
                this.keyValue.remove(key);
            } else {
                if (!this.reverse.containsKey(value - 1)) {
                    this.reverse.put(value - 1, new HashSet<>());
                }
                this.reverse.get(value - 1).add(key);
                this.keyValue.put(key, value - 1);
            }
        }
    }

    /** Returns one of the keys with maximal value. */
    public String getMaxKey() {
        if (this.keyValue.size() == 0) return "";
        return this.reverse.get(this.reverse.lastKey()).iterator().next();
    }

    /** Returns one of the keys with Minimal value. */
    public String getMinKey() {
        if (this.keyValue.size() == 0) return "";
        return this.reverse.get(this.reverse.firstKey()).iterator().next();
    }
}

/**
 * Your AllOne object will be instantiated and called as such:
 * AllOne obj = new AllOne();
 * obj.inc(key);
 * obj.dec(key);
 * String param_3 = obj.getMaxKey();
 * String param_4 = obj.getMinKey();
 */


text:
from database.engine import command

class Hidden(command.Model):
    __tablename__ = 'hidden'

    id = command.Column(command.Integer(), primary_key=True)
    name = command.Column(command.TEXT(), nullable=False)
    aliases = command.Column(command.ARRAY(command.TEXT()), nullable=True)

    _idx_hidden_command_name = command.Index('index_hidden_name', 'name', unique=True)

class Public(command.Model):
    __tablename__ = 'public'

    id = command.Column(command.Integer(), primary_key=True)
    name = command.Column(command.TEXT(), nullable=False)
    aliases = command.Column(command.ARRAY(command.TEXT()), nullable=True)

    _idx_public_command_name = command.Index('index_public_name', 'name', unique=True)


text:
package feign.okhttp;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import feign.Client;
import feign.Request.HttpMethod;
import okhttp3.*;

/**
 * This module directs Feign's http requests to
 * OkHttp, which enables SPDY and better network
 * control. Ex.
 *
 *

 * GitHub github = Feign.builder().client(new OkHttpClient()).target(GitHub.class,
 * "https://api.github.com");
 */
public final class OkHttpClient implements Client {

  private final okhttp3.OkHttpClient delegate;

  public OkHttpClient() {
    this(new okhttp3.OkHttpClient());
  }

  public OkHttpClient(okhttp3.OkHttpClient delegate) {
    this.delegate = delegate;
  }

  static Request toOkHttpRequest(feign.Request input) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(input.url());

    MediaType mediaType = null;
    boolean hasAcceptHeader = false;
    for (String field : input.headers().keySet()) {
      if (field.equalsIgnoreCase("Accept")) {
        hasAcceptHeader = true;
      }

      for (String value : input.headers().get(field)) {
        requestBuilder.addHeader(field, value);
        if (field.equalsIgnoreCase("Content-Type")) {
          mediaType = MediaType.parse(value);
          if (input.charset() != null) {
            mediaType.charset(input.charset());
          }
        }
      }
    }
    // Some servers choke on the default accept string.
    if (!hasAcceptHeader) {
      requestBuilder.addHeader("Accept", "*/*");
    }

    byte[] inputBody = input.body();
    boolean isMethodWithBody =
        HttpMethod.POST == input.httpMethod() || HttpMethod.PUT == input.httpMethod()
            || HttpMethod.PATCH == input.httpMethod();
    if (isMethodWithBody) {
      requestBuilder.removeHeader("Content-Type");
      if (inputBody == null) {
        // write an empty BODY to conform with okhttp 2.4.0+
        // http://johnfeng.github.io/blog/2015/06/30/okhttp-updates-post-wouldnt-be-allowed-to-have-null-body/
        inputBody = new byte[0];
      }
    }

    RequestBody body = inputBody != null ? RequestBody.create(mediaType, inputBody) : null;
    requestBuilder.method(input.httpMethod().name(), body);
    return requestBuilder.build();
  }

  private static feign.Response toFeignResponse(Response response, feign.Request request)
      throws IOException {
    return feign.Response.builder()
        .status(response.code())
        .reason(response.message())
        .request(request)
        .headers(toMap(response.headers()))
        .body(toBody(response.body()))
        .build();
  }

  private static Map<String, Collection<String>> toMap(Headers headers) {
    return (Map) headers.toMultimap();
  }

  private static feign.Response.Body toBody(final ResponseBody input) throws IOException {
    if (input == null || input.contentLength() == 0) {
      if (input != null) {
        input.close();
      }
      return null;
    }
    final Integer length = input.contentLength() >= 0 && input.contentLength() <= Integer.MAX_VALUE
        ? (int) input.contentLength()
        : null;

    return new feign.Response.Body() {

      @Override
      public void close() throws IOException {
        input.close();
      }

      @Override
      public Integer length() {
        return length;
      }

      @Override
      public boolean isRepeatable() {
        return false;
      }

      @Override
      public InputStream asInputStream() throws IOException {
        return input.byteStream();
      }

      @SuppressWarnings("deprecation")
      @Override
      public Reader asReader() throws IOException {
        return input.charStream();
      }

      @Override
      public Reader asReader(Charset charset) throws IOException {
        return asReader();
      }
    };
  }

  @Override
  public feign.Response execute(feign.Request input, feign.Request.Options options)
      throws IOException {
    okhttp3.OkHttpClient requestScoped;
    if (delegate.connectTimeoutMillis() != options.connectTimeoutMillis()
        || delegate.readTimeoutMillis() != options.readTimeoutMillis()
        || delegate.followRedirects() != options.isFollowRedirects()) {
      requestScoped = delegate.newBuilder()
          .connectTimeout(options.connectTimeoutMillis(), TimeUnit.MILLISECONDS)
          .readTimeout(options.readTimeoutMillis(), TimeUnit.MILLISECONDS)
          .followRedirects(options.isFollowRedirects())
          .build();
    } else {
      requestScoped = delegate;
    }
    Request request = toOkHttpRequest(input);
    Response response = requestScoped.newCall(request).execute();
    return toFeignResponse(response, input).toBuilder().request(input).build();
  }
}


text:
echo "I'm shell script"
#cd ../
echo `pwd`
#gradle -v
#adb mount -o remount /
#adb shell mkdir sdcard/plu | adb push -p /c/Users/zhangqiang/Desktop/newlink-10-10-101.jar sdcard/plu/newlink.jar | adb shell am force-stop com.homelink.newlink | adb shell am start -n com.homelink.newlink/com.homelink.newlink.ui.app.SplashScreenActivity
#adb shell mkdir sdcard/plu | adb push -p /c/Users/zhangqiang/Desktop/newlink-10-10-101.jar sdcard/plu/newlink.jar
#adb shell mkdir sdcard/plu
adb shell rm -rf sdcard/plu
echo $?
#gradle -p /d/learn/TheDemo/MyDemo assembleBaiduDebug


text:
@implementation NSString (SGAddition)

- (NSString*) sg_trimWhitespace
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (NSString *)sg_extensionOfFile
{
    NSArray *splitStrArr = [self componentsSeparatedByString:@"."];

    if (splitStrArr != nil && splitStrArr.count == 2)
        return [splitStrArr lastObject];
    else
        return nil;
}

- (NSString *)sg_nameOfFile
{
    NSArray *splitStrArr = [self componentsSeparatedByString:@"."];

    if (splitStrArr != nil && splitStrArr.count == 2)
        return [splitStrArr firstObject];
    else
        return nil;
}

- (NSString *)sg_stringByTrim {
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    return [self stringByTrimmingCharactersInSet:set];
}

+ (BOOL)sg_isEmpty:(NSString*)str
{
    if(str == nil)
        return YES;

    NSString *trimStr = [str sg_stringByTrim];

    if (trimStr.length == 0) {
        return YES;
    }

    return NO;
}

- (NSString*)sg_limitWithLength:(NSInteger)len
{
    if (self.length <= len) {
        return self;
    }

    return [self substringWithRange:NSMakeRange(0, len)];
}

+ (NSString *)sg_durationInStr:(NSInteger)timeInterval
{
    NSInteger mintues = timeInterval / 60;

    NSInteger mintuePart = mintues % 60;

    NSInteger hourPart   = mintues / 60;

    return [NSString stringWithFormat:@"%02ld:%02ld",hourPart,mintuePart];
}

+ (NSMutableAttributedString*)sg_buildDialogPomoCntAttributeString:(NSInteger)pomoCnt
{
    NSDictionary    *style          = @{
                                        @"sum": @[
                                                [UIFont systemFontOfSize:48.0 weight:UIFontWeightMedium]
                                                ],
                                        @"txt": @[
                                                [UIFont systemFontOfSize:12.0]
                                                ],
                                        };

    NSString *sumStr = [NSString stringWithFormat:@"<sum>%ld</sum><txt>%@</txt>", pomoCnt, NSLocalizedString(@"pomos",@"quantity - pomo")];

    return [[NSMutableAttributedString alloc] initWithAttributedString:[sumStr attributedStringWithStyleBook:style]];
}

+ (NSMutableAttributedString*)sg_buildActiveDaysAttributeString:(NSInteger)days fontWeight:(CGFloat)weight
{
    NSDictionary    *style          = @{
                                        @"sum": @[
                                                [UIFont systemFontOfSize:15.0 weight:weight]
                                                ],
                                        @"txt": @[
                                                [UIFont systemFontOfSize:12.0 weight:weight]
                                                ],
                                        };

    NSString *sumStr = [NSString stringWithFormat:@"<sum>%ld</sum><txt> %@</txt>", days, NSLocalizedString(@"days",@"time")];

    return [[NSMutableAttributedString alloc] initWithAttributedString:[sumStr attributedStringWithStyleBook:style]];
}

+ (NSMutableAttributedString*)sg_buildConsumedTimeAttributeString:(NSInteger)timeInterval fontWeight:(CGFloat)weight
{
    NSInteger mintues = timeInterval/60;

    NSInteger mintuePart = mintues%60;

    NSInteger hourPart   = mintues/60;

    NSDictionary    *style          = @{
                                        @"sum": @[
                                                [UIFont systemFontOfSize:15.0 weight:weight]
                                                ],
                                        @"txt": @[
                                                [UIFont systemFontOfSize:12.0 weight:weight]
                                                ],
                                        };

    NSString *sumStr = [NSString stringWithFormat:@"<sum>%ld</sum><txt> %@</txt> <sum>%ld</sum><txt> %@</txt>", hourPart, NSLocalizedString(@"hrs",@"quantity - mintues"), mintuePart, NSLocalizedString(@"mins",@"quantity - mintues")];

    return [[NSMutableAttributedString alloc] initWithAttributedString:[sumStr attributedStringWithStyleBook:style]];
}

+ (NSMutableAttributedString*)sg_buildCompletedAssignmentAttributeString:(NSInteger)completedCnt fontWeight:(CGFloat)weight
{
    NSDictionary    *style          = @{
                                        @"sum": @[
                                                [UIFont systemFontOfSize:15.0 weight:weight]
                                                ],
                                        @"txt": @[
                                                [UIFont systemFontOfSize:12.0 weight:weight]
                                                ],
                                        };

    NSString *sumStr = [NSString stringWithFormat:@"<sum>%ld</sum><txt> %@</txt>", completedCnt, NSLocalizedString(@"tasks",@"quantity")];

    return [[NSMutableAttributedString alloc] initWithAttributedString:[sumStr attributedStringWithStyleBook:style]];
}

//保留1位小数,去掉无意义的0
+ (NSString*)sg_displayInHour:(CGFloat)seconds
{
    NSString *hourStr = [self sg_displayShortFloat:seconds/kSGSecondsPerHour];

    return [hourStr stringByAppendingString:@"h"];
}

+ (NSString*)sg_displayShortFloat:(CGFloat)floatNum
{
    NSString *floatStr = [NSString stringWithFormat:@"%.1lf",floatNum];

    if ([floatStr containsString:@".0"]) {
        floatStr = [NSString stringWithFormat:@"%.0lf",floatNum];
    }

    return floatStr;
}

+ (NSString*)sg_inspiration:(CGFloat)focusTime
{
    NSAssert(focusTime>=0, @"should greater than zero");

    NSString *msg = nil;

    CGFloat focusMintues = focusTime/kSGSecondsPerMinute;

    if (focusMintues>750) {
        msg = @"宁静致远";
    } else if (focusMintues>500) {
        msg = @"遇见心流";
    } else if (focusMintues>360) {
        msg = @"发奋图强";
    } else if (focusMintues>320) {
        msg = @"高歌猛进";
    } else if (focusMintues>280) {
        msg = @"乘风破浪";
    } else if (focusMintues>240) {
        msg = @"废寝忘食";
    }else if (focusMintues>200) {
        msg = @"披荆斩棘";
    } else if (focusMintues>160) {
        msg = @"只争朝夕";
    } else if (focusMintues>120) {
        msg = @"全力以赴";
    } else if (focusMintues>80) {
        msg = @"心无旁骛";
    } else if (focusMintues>40) {
        msg = @"渐入佳境";
    } else if (focusMintues>0) {
        msg = @"完美开局";
    }

    return msg;
}

@end


text:
package com.googlecode.totallylazy.collections;

import org.junit.Test;

import java.util.Iterator;
import java.util.ListIterator;

import static com.googlecode.totallylazy.collections.ListZipper.zipper;
import static com.googlecode.totallylazy.collections.PersistentList.constructors.list;
import static com.googlecode.totallylazy.matchers.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class ZipperListIteratorTest {
    @Test
    public void canGoForward() throws Exception {
        PersistentList<Character> values = list('a', 'b', 'c', 'd', 'e');
        Iterator<Character> expected = values.iterator();
        ListIterator<Character> listIterator = new ZipperListIterator<Character>(zipper(values));

        for (int i = 0; i < values.size(); i++) {
            assertThat(listIterator.hasNext(), is(expected.hasNext()));
            assertThat(listIterator.next(), is(expected.next()));
        }

        assertThat(listIterator.hasNext(), is(expected.hasNext()));
    }

    @Test
    public void canGoBackwards() throws Exception {
        PersistentList<Character> values = list('a', 'b', 'c', 'd', 'e');
        Iterator<Character> expected = values.reverse().iterator();
        ListIterator<Character> listIterator = new ZipperListIterator<Character>(zipper(values).last());

        for (int i = 0; i < values.size(); i++) {
            assertThat(listIterator.hasPrevious(), is(expected.hasNext()));
            assertThat(listIterator.previous(), is(expected.next()));
        }

        assertThat(listIterator.hasPrevious(), is(expected.hasNext()));
    }

    @Test
    public void canGoBackwardsAndForwards() throws Exception {
        PersistentList<Character> values = list('a', 'b', 'c');
        ListIterator<Character> listIterator = new ZipperListIterator<Character>(zipper(values));

        assertThat(listIterator.next(), is('a'));
        assertThat(listIterator.next(), is('b'));
        assertThat(listIterator.next(), is('c'));
        assertThat(listIterator.previous(), is('c'));
        assertThat(listIterator.next(), is('c'));
        assertThat(listIterator.previous(), is('c'));
        assertThat(listIterator.previous(), is('b'));
        assertThat(listIterator.previous(), is('a'));
    }

    @Test
    public void supportsIndex() throws Exception {
        PersistentList<Character> values = list('a', 'b', 'c');
        ListIterator<Character> listIterator = new ZipperListIterator<Character>(zipper(values));

        assertThat(listIterator.nextIndex(), is(0));
        assertThat(listIterator.previousIndex(), is(-1));

        assertThat(listIterator.next(), is('a'));
        assertThat(listIterator.nextIndex(), is(1));
        assertThat(listIterator.previousIndex(), is(0));

        assertThat(listIterator.next(), is('b'));
        assertThat(listIterator.nextIndex(), is(2));
        assertThat(listIterator.previousIndex(), is(1));

        assertThat(listIterator.next(), is('c'));
        assertThat(listIterator.nextIndex(), is(3));
        assertThat(listIterator.previousIndex(), is(2));

        assertThat(listIterator.previous(), is('c'));
        assertThat(listIterator.nextIndex(), is(2));
        assertThat(listIterator.previousIndex(), is(1));

        assertThat(listIterator.next(), is('c'));
        assertThat(listIterator.nextIndex(), is(3));
        assertThat(listIterator.previousIndex(), is(2));

        assertThat(listIterator.previous(), is('c'));
        assertThat(listIterator.nextIndex(), is(2));
        assertThat(listIterator.previousIndex(), is(1));

        assertThat(listIterator.previous(), is('b'));
        assertThat(listIterator.nextIndex(), is(1));
        assertThat(listIterator.previousIndex(), is(0));

        assertThat(listIterator.previous(), is('a'));
        assertThat(listIterator.nextIndex(), is(0));
        assertThat(listIterator.previousIndex(), is(-1));
    }
}


text:
<?php

namespace SejourBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use SejourBundle\Entity\Sejour;
use SejourBundle\Form\Type\SejourType;
use SejourBundle\Entity\Enfant;
use SejourBundle\Entity\Jour;
use SejourBundle\Entity\Evenement;
use SejourBundle\Entity\Activite;
use SejourBundle\Entity\ProblemesEnfant;
use SejourBundle\Entity\EvenementLies;
use SejourBundle\Entity\AnimSejour;
use SejourBundle\Entity\ForumCategorie;
use SejourBundle\Entity\ForumMessage;
use SejourBundle\Entity\ForumUserMessageVu;
use SejourBundle\Entity\AnimConges;
use SejourBundle\Entity\IdMoment;
use SejourBundle\Entity\Soin;
use SejourBundle\Entity\Traitement;
use SejourBundle\Entity\TraitementJour;
use SejourBundle\Form\Type\ActiviteType;
use SejourBundle\Form\Type\ForumCategorieType;
use SejourBundle\Form\Type\ForumMessageType;
use SejourBundle\Form\Type\AffecterType;
use SejourBundle\Form\Type\ModifierAffectationType;
use SejourBundle\Form\Type\ModifierEvenementType;
use SejourBundle\Form\Type\AjoutFicheType;
use SejourBundle\Form\Type\EnfantType;
use SejourBundle\Form\Type\EvenementType;
use SejourBundle\Form\Type\ProblemesEnfantType;
use SejourBundle\Form\Type\RecruterType;
use SejourBundle\Form\Type\SoinType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Dompdf\Dompdf;
use Dompdf\Options;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;

class JourController extends Controller
{
	public function listeEvenementAction($idSejour, $id, Request $req){
		$repository = $this->getDoctrine()
						  ->getManager()
						  ->getRepository('SejourBundle:Evenement');
		$listEvenements = $repository->findBy(array('jour' => $id));

		$listDef = array();
		foreach($listEvenements as $ev)
		{
			$eve= array(
						'title' => $ev->getActivite()->getNom(),
						'start' => $ev->getJour()->getDate()->format('Y-m-d')."T".$ev->getHeureDebut()->format('H:i'),
						'end' => $ev->getJour()->getDate()->format('Y-m-d')."T".$ev->getHeureFin()->format('H:i'),
						'color' => $ev->getActivite()->getCategorie()->getCouleur(),
						'id' => $ev->getId(),
						);
			array_push($listDef, $eve);
		}

		$encoders = array(new JsonEncoder());
		$normalizers = array(new GetSetMethodNormalizer());
		$serializer = new Serializer($normalizers, $encoders);
		$response = new Response($serializer->serialize($listDef, 'json'));
		$response->headers->set('Content-Type', 'application/json');
		return $response;
	}
	public function modifieEvenementAction($idSejour, $id, Request $req){
		$em = $this->getDoctrine()->getManager();
		$repository = $this->getDoctrine()
						  ->getManager()
						  ->getRepository('SejourBundle:Evenement');
		$repository2 = $this->getDoctrine()
		  ->getManager()
		  ->getRepository('SejourBundle:AnimConges');
		$listEvenements = $repository->findBy(array('jour' => $id));
		$evenement = $req->get('ev');
		$start = new \datetime($req->get('start'));
		$end = new \datetime($req->get('end'));
		$conflits = array();
		$evenementModifie= $repository->findOneById($evenement);

		$listeEvenementJ = $repository->findByJour($evenementModifie->getJour());
		$listeAnim = $evenementModifie->getAnimateurs();

		// Avant de valider la modification d'un évènement il faut vérifier si :
		// 1) Les animateurs prévus sur l'activité ne sont pas en congés à ce moment
		// 2) Les nouveaux horairres ne créent pas de conflits

		foreach($listeAnim as $Anim)
		{
			$CongeAnim = $repository2->findOneBy(array('jour'=>$evenementModifie->getJour(), 'user'=>$Anim));
			$DC = $CongeAnim->getMoment()->getHeureDebut()->format('H:i:s');
			$FC = $CongeAnim->getMoment()->getHeureFin()->format('H:i:s');
			$DE = $start->format('H:i:s');
			$FE = $end->format('H:i:s');
			$Test = ((($DC <= $DE) && ($FC > $DE)) or
					(($DC >= $DE) && ($FC <= $FE)) or
					(($DC < $FE) && ($FC >= $FE)) or
					(($DC <= $DE) && ($FC >= $FE)));
			if( $Test  ) // **** 1 **** Vérification des congés
			{
				array_push($conflits, '
 Problème avec l\'animateur '.$Anim->getPN().' : Conflit avec les congés de l\'animateur (Anim en '.$CongeAnim->getMoment()->getMoment(). ')
');
			}
			// Verif des congés OK !!

			//**** 2 **** Vérification autres événements des animateurs
			else
			{
				foreach($listeEvenementJ as $evJ) // On regarde tous les évènements de la journée
				{
					if($evJ->getId() == $evenementModifie->getId()) // On inhibe l'évènement en cours
					{
						continue;
					}
					else
					{
						$listeAnimAutreEv = $evJ->getAnimateurs();
						foreach($listeAnimAutreEv as $AutreAnim) //On compare chaque animateur
						{
							if($AutreAnim->getId() === $Anim->getId()) //Quand on trouve deux anims identiques, on vérifie que les évènements soient compatibles
							{
								$DC = $evJ->getHeureDebut()->format('H:i:s');
								$FC = $evJ->getHeureFin()->format('H:i:s');
								$DE = $start->format('H:i:s');
								$FE = $end->format('H:i:s');
								$Test2 = ((($DC <= $DE) && ($FC > $DE)) or
										(($DC >= $DE) && ($FC <= $FE)) or
										(($DC < $FE) && ($FC >= $FE)) or
										(($DC <= $DE) && ($FC >= $FE)));
								if( $Test2  ) // **** 1 **** Vérification des congés
								{
									array_push($conflits, '
 Problème avec l\'animateur '.$Anim->getPN().' : Conflit avec les affectations sur une autre activité (Activité '.$evJ->getActivite()->getNom().')
');
								}
							}
						}
					}
				}
			}

		}

		if( count($conflits) === 0 )
		{
			$evenementModifie->setHeureDebut($start);
			$evenementModifie->setHeureFin($end);
			$em->flush();
			$listDef = array();
			$listDef['statut']='ok';
			$listDef['liste']= array();
			foreach($listEvenements as $ev)
			{
				$eve= array(
							'title' => $ev->getActivite()->getNom(),
							'start' => $ev->getJour()->getDate()->format('Y-m-d')."T".$ev->getHeureDebut()->format('H:i'),
							'end' => $ev->getJour()->getDate()->format('Y-m-d')."T".$ev->getHeureFin()->format('H:i'),
							'color' => $ev->getActivite()->getCategorie()->getCouleur(),
							'id' => $ev->getId(),
							);
				array_push($listDef['liste'], $eve);
			}
			$encoders = array(new JsonEncoder());
			$normalizers = array(new GetSetMethodNormalizer());
			$serializer = new Serializer($normalizers, $encoders);
			$response = new Response($serializer->serialize($listDef, 'json'));
			$response->headers->set('Content-Type', 'application/json');
			return $response;
		}
		else
		{
			$rep='
';
			foreach($conflits as $value)
			{
				$rep.=$value;
			}
			$rep.='
';
			return new JsonResponse(array('statut' => 'conflit', 'data'=>$rep));
		}
	}
	public function jourAction($idSejour, $id){
	$this->container->get('sejour.droits')->AllowedUser($idSejour);
    $repository = $this->getDoctrine()
      ->getManager()
      ->getRepository('SejourBundle:Evenement');
	$prevNextJours = $this->prevNextJours($id, $idSejour);

	$repository2 = $this->getDoctrine()
		->getManager()
		->getRepository('SejourBundle:Jour');

	$jour=$repository2->findOneBy(array('sejour'=>$idSejour, 'id'=>$id));

	if(null === $jour)
	{
		throw new NotFoundHttpException("La journée n'existe pas.");
	}

	return $this->render('SejourBundle:Default:jour.html.twig', array(	'Sejour' => $this->getDoctrine()->getManager()->getRepository('SejourBundle:Sejour')->findOneById($idSejour),
																		'jour' => $jour, 'nav'=>$prevNextJours,
																	));
	}
	public function jourAddEventAction($idSejour, $id, Request $request){
	$repository2 = $this->getDoctrine()
	->getManager()
	->getRepository('SejourBundle:Jour');

	$jour=$repository2->find($id);

	$evenement = new Evenement();
	$form   = $this->get('form.factory')->create(EvenementType::class, $evenement, ['Sejour' => $idSejour]);

	if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
	  $em = $this->getDoctrine()->getManager();
	  $evenement->setJour($jour);
	  $em->persist($evenement);
	  $em->flush();
	  $request->getSession()->getFlashBag()->add('notice', 'L\'activité a bien été ajoutée à la journée.');

	  return $this->redirectToRoute('jour_indexjour', array('idSejour' => $idSejour, 'id' => $id));
	}

	return $this->render('SejourBundle:Default:creerevenement.html.twig', array('form' => $form->createView(), 'jour'=> $jour, 'Sejour' => $this->getDoctrine()->getManager()->getRepository('SejourBundle:Sejour')->findOneById($idSejour),));
	}
	public function jourDellEventAction($id, Request $request){
		$repository = $this->getDoctrine()
		  ->getManager()
		  ->getRepository('SejourBundle:Evenement')
		;
		$repository2 = $this->getDoctrine()
		  ->getManager()
		  ->getRepository('SejourBundle:EvenementLies')
		;
		$evenement = $repository->find($id);

		if (null === $evenement) {
		  throw new NotFoundHttpException("L'evenement ".$id." n'existe pas.");
		}
		$em = $this->getDoctrine()->getManager();
		if($evenement->getMoment()==4)
		{
			$Lien=$repository2->findOneBy(array('Jour' => $evenement));
			$M1=$Lien->getMatin1();
			$M2=$Lien->getMatin2();

			$em	->remove($Lien)
				->remove($M1)
				->remove($M2);
			$em->flush();

		}

		$em->remove($evenement);
		$em->flush();

		$request->getSession()->getFlashBag()->add('notice', 'L\'activité a été supprimée.');
		return $this->redirectToRoute('jour_indexjour', array('id' => $evenement->getJour()->getId()));

	}
	public function jourAffecterEnfantAction($idJour, $idEnfant, Request $request){
		$repository2 = $this->getDoctrine()
		->getManager()
		->getRepository('SejourBundle:Jour');

		$jour=$repository2->find($idJour);

		$repository = $this->getDoctrine()
		->getManager()
		->getRepository('SejourBundle:Enfant');

		$repository3 = $this->getDoctrine()
		->getManager()
		->getRepository('SejourBundle:EvenementLies')
		;

		$enfant=$repository->find($idEnfant);
		$form   = $this->get('form.factory')->create(AffecterType::class, null, ['jour' => $idJour]);

		if ($request->isMethod('POST') && $form->handleRequest($request)->isValid())
		{
			$Matin1=$form->get('Matin1')->getData();
			$Matin2=$form->get('Matin2')->getData();
			$AM=$form->get('AM')->getData();
			$Jour12=$form->get('Jour12')->getData();
			$Journee=$form->get('Journee')->getData();
			$em = $this->getDoctrine()->getManager();

			if(($Matin1 || $Matin2 || $AM) && ($Jour12 || $Journee))
			{
				$request->getSession()->getFlashBag()->add('alert', 'Les inscriptions n\'ont pas étés enregistrés (Inscriptions incohérentes)');
				return $this->redirectToRoute('jour_indexjour', array('id' => $idJour));

			}

			if($Matin1)
			{
				$Matin1->addEnfant($enfant);
				$em->persist($Matin1);
				$em->flush();
			}

			if($Matin2)
			{
				$Matin2->addEnfant($enfant);
				$em->persist($Matin2);
				$em->flush();
			}

			if($AM)
			{
				$AM->addEnfant($enfant);
				$em->persist($AM);
				$em->flush();
			}

			if($Jour12)
			{
				$Jour12->addEnfant($enfant);
				$em->persist($Jour12);
				$em->flush();

				$Lien=$repository3->findOneBy(
				array('Jour' => $Jour12));
				$M1=$Lien->getMatin1();
				$M2=$Lien->getMatin2();

				$M1->addEnfant($enfant);
				$em->persist($M1);
				$em->flush();
				$M2->addEnfant($enfant);
				$em->persist($M2);
				$em->flush();
			}

			if($Journee)
			{
				$Journee->addEnfant($enfant);
				$em->persist($Journee);
				$em->flush();
			}

			$request->getSession()->getFlashBag()->add('notice', 'Les inscriptions ont bien été prises en compte !');
			return $this->redirectToRoute('jour_indexjour', array('id' => $idJour));

		}

		return $this->render('SejourBundle:Default:jouraffecter.html.twig', array('form' => $form->createView(),'jour'=> $jour, 'enfant'=> $enfant));
	}
	public function jourModifierEnfantAction($idJour, $idEnfant, Request $request){
		$repository2 = $this->getDoctrine()
		->getManager()
		->getRepository('SejourBundle:Jour');

		$jour=$repository2->find($idJour);

		$repository = $this->getDoctrine()
		->getManager()
		->getRepository('SejourBundle:Enfant');

		$repository3 = $this->getDoctrine()
		->getManager()
		->getRepository('SejourBundle:EvenementLies')
		;

		$enfant=$repository->find($idEnfant);

		$listeEvEnfant = $enfant->getEvenements();
		$Matin1=Null;
		$Matin2=Null;
		$AM=Null;
		$Jour12=Null;
		$Jour=Null;
		foreach( $listeEvEnfant as $EvEnfant)
		{
			if($EvEnfant->getJour()->getId() == $idJour)
			{
				if($EvEnfant->getMoment() == 1)
				{
					$Matin1=$EvEnfant;
				}
				elseif($EvEnfant->getMoment() == 2)
				{
					$Matin2=$EvEnfant;
				}
				elseif($EvEnfant->getMoment() == 3)
				{
					$AM=$EvEnfant;
				}
				elseif($EvEnfant->getMoment() == 4)
				{
					$Jour12=$EvEnfant;
				}
				elseif($EvEnfant->getMoment() == 5)
				{
					$Jour=$EvEnfant;
				}
			}
		}

		$MatinBloque=false;
		if($Matin1)
		{
			$MatinBloque=$Matin1->getEstlie();
		}

		$form   = $this->get('form.factory')->create(ModifierAffectationType::class, null, ['jour' => $idJour, 'Matin1' => $Matin1, 'Matin2' => $Matin2, 'AM'=> $AM, 'Jour12'=> $Jour12, 'Journee'=>$Jour]);

		if ($request->isMethod('POST') && $form->handleRequest($request)->isValid())
		{
			if($MatinBloque === false)
			{
			$NewMatin1=$form->get('Matin1')->getData();
			$NewMatin2=$form->get('Matin2')->getData();
			}
			$NewAM=$form->get('AM')->getData();
			$NewJour12=$form->get('Jour12')->getData();
			$NewJour=$form->get('Journee')->getData();
			$em = $this->getDoctrine()->getManager();

			if($MatinBloque === false)
			{

				if($Matin1 != $NewMatin1)
				{
					if($Matin1)
					{
					$Matin1->removeEnfant($enfant);
					$em->flush();
					}
					if($NewMatin1)
					{
						$NewMatin1->addEnfant($enfant);
						$em->persist($NewMatin1);
						$em->flush();
					}
				}

			if($Matin2 != $NewMatin2)
			{
				if($Matin2)
				{
				$Matin2->removeEnfant($enfant);
				$em->flush();
				}
				if($NewMatin2)
				{
					$NewMatin2->addEnfant($enfant);
					$em->persist($NewMatin2);
					$em->flush();
				}
			}
			}
			if($AM != $NewAM)
			{
				if($AM)
				{
				$AM->removeEnfant($enfant);
				$em->flush();
				}
				if($NewAM)
				{
					$NewAM->addEnfant($enfant);
					$em->persist($NewAM);
					$em->flush();
				}
			}

			if($Jour12 != $NewJour12)
			{
				if($Jour12)
				{
				$Jour12->removeEnfant($enfant);
				$em->flush();

				$Lien=$repository3->findOneBy(
				array('Jour' => $Jour12));
				$M1=$Lien->getMatin1();
				$M2=$Lien->getMatin2();

				$M1->removeEnfant($enfant);
				$em->persist($M1);
				$em->flush();
				$M2->removeEnfant($enfant);
				$em->persist($M2);
				$em->flush();

				}
				if($NewJour12)
				{
					$NewJour12->addEnfant($enfant);
					$em->persist($NewJour12);
					$em->flush();

					$Lien=$repository3->findOneBy(
					array('Jour' => $NewJour12));
					$M1=$Lien->getMatin1();
					$M2=$Lien->getMatin2();

					$M1->addEnfant($enfant);
					$em->persist($M1);
					$em->flush();
					$M2->addEnfant($enfant);
					$em->persist($M2);
					$em->flush();
				}
			}

			if($Jour != $NewJour)
			{
				if($Jour)
				{
				$Jour->removeEnfant($enfant);
				$em->flush();
				}
				if($NewJour)
				{
					$NewJour->addEnfant($enfant);
					$em->persist($NewJour);
					$em->flush();
				}
			}

			$request->getSession()->getFlashBag()->add('notice', 'Les inscriptions ont bien étés modifiés !');
			return $this->redirectToRoute('jour_indexjour', array('id' => $idJour));

		}

		return $this->render('SejourBundle:Default:jourmodifieraffectation.html.twig', array('form' => $form->createView(),'jour'=> $jour, 'enfant'=> $enfant, 'matinbloque'=>$MatinBloque));
	}
	public function jourEditEventAction($id, Request $request){
		$repository = $this->getDoctrine()
		  ->getManager()
		  ->getRepository('SejourBundle:Evenement')
		;

		// On récupère l'entité correspondante à l'id $id
		$evenement = $repository->find($id);
		$jour = $evenement->getJour();

		if (null === $evenement)
		{
			throw new NotFoundHttpException("L'evenement ".$id." n'existe pas.");
		}

		$form = $this->get('form.factory')->create(ModifierEvenementType::class, $evenement);

		if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
			$em = $this->getDoctrine()->getManager();
		  // Inutile de persister ici, Doctrine connait déjà notre annonce
		  $em->flush();

		  $request->getSession()->getFlashBag()->add('notice', 'L\'évènement a bien été modifié');
		   return $this->redirectToRoute('jour_indexjour', array('id' => $jour->getId()));
	}

	return $this->render('SejourBundle:Default:creerevenement.html.twig', array('form' => $form->createView(), 'jour'=> $jour));
    }
	public function jourEvenementAffecterAnimAction($idSejour, $idJour, Request $request){
	$this->verifDroit($idSejour, 'ROLE_DIRECTEUR');
	if( null !==  $request->query->get('ev'))
	{
		$idEvenement =  $request->query->get('ev');
	}
	elseif( null !== $request->get("data")["form[Ev"])
	{
		$idEvenement =  $request->get("data")["form[Ev"];
	}
	else
	{
		$idEvenement = null;
	}

    $repository = $this->getDoctrine()
      ->getManager()
      ->getRepository('SejourBundle:Evenement');
    $repository2 = $this->getDoctrine()
      ->getManager()
      ->getRepository('SejourBundle:Jour');
    $repository3 = $this->getDoctrine()
      ->getManager()
      ->getRepository('SejourBundle:AnimConges');
    $repository4 = $this->getDoctrine()
      ->getManager()
      ->getRepository('UserBundle:User');
	$Evenement = $repository->findOneBy(array('jour'=>$idJour, 'id'=>$idEvenement));
	$listeEvenements = $repository->findBy(array('jour'=>$idJour));
	$Jour = $repository2->findOneBy(array('id'=>$idJour, 'sejour'=>$idSejour));
	if(null === $Jour or null === $Evenement)
	{
		throw new NotFoundHttpException("L'evenement n'existe pas.");
	}

	$listeAnimAff = $Evenement->getAnimateurs();
	$listeAnimAffecter = array();
	foreach($listeAnimAff as $i)
	{
		array_push($listeAnimAffecter, $i);
	}
	$listeAnim = $repository3->findByJour($idJour);
	$listeAnimPossible = array();
	$listeAnimImpossible = array();
	$DebutActi = $Evenement->getHeureDebut();
	$FinActi = $Evenement ->getHeureFin();
	foreach($listeAnim as $Anim)
		{
			$aff = false;
			if($Anim->getMoment()->getConges() === true) // Animateur en congés
			{
				array_push($listeAnimImpossible, $Anim->getUser());
			}
			else // Anim en RC ou travail
			{
				$DC = $Anim->getMoment()->getHeureDebut();
				$FC = $Anim->getMoment()->getHeureFin();
				$DE = $DebutActi;
				$FE = $FinActi;
				$Test = ((($DC <= $DE) && ($FC > $DE)) or
						(($DC >= $DE) && ($FC <= $FE)) or
						(($DC < $FE) && ($FC >= $FE)) or
						(($DC <= $DE) && ($FC >= $FE)));
				if($Anim->getMoment()->getTravail() === false and $Test  ) // RC en même temps que evenement
				{
					array_push($listeAnimImpossible, $Anim->getUser());
				}
				else // Travail ou RC compatible avec l'évènement
				{
					// Ici il faut regarder s'il y a d'autres évènements sur lequel l'animateur est affecté, qui ont lieux en même temps.
					foreach($listeEvenements as $evJour)
					{
						if($evJour === $Evenement) // Si l'ev que l'on regarde est celui en cours, on passe
						{
							continue;
						}
						else //Ici on compare un autre évènement du même jour.
						{
							$LA = $evJour->getAnimateurs(); //récupération de la liste des anim
							foreach($LA as $an)
							{
								if($an !== $Anim->getUser()) //On cherche l'anim en cours
								{
									continue;
								}
								else // Ici on regarde une affectation d'un même anim sur un évènement du même jour. Si les heures ne sont pas compatibles on jette.
								{
									$DebutEv = $evJour->getHeureDebut();
									$FinEv = $evJour->getHeureFin();
									$Test2 = ((($DebutEv <= $DE) && ($FinEv > $DE)) or
									(($DebutEv >= $DE) && ($FinEv <= $FE)) or
									(($DebutEv < $FE) && ($FinEv >= $FE)) or
									(($DebutEv <= $DE) && ($FinEv >= $FE)));
									if($Test2)
									{
										array_push($listeAnimImpossible, $Anim->getUser());
										$aff = true;
										break;
									}

								}
							}
						}
					}
					if ($aff === false)
					{
					array_push($listeAnimPossible, $Anim->getUser());
					}
				}
			}
		}
	$form = $this->createFormBuilder();

	$form->add('Dispo', EntityType::class, array(
			'class' => 'UserBundle:User',
			'choices' => $listeAnimPossible,
			'data' => $listeAnimAff,
			'choice_label'=>'PN',
			'label'=>'Animateurs Disponibles',
			'required'=>true,
			'expanded'=>true,
			'multiple'=>true,
			'disabled'=>false,
			))
		->add('NonDispo', EntityType::class, array(
			'class' => 'UserBundle:User',
			'choices' => $listeAnimImpossible,
			'data' => $listeAnimAff,
			'choice_label'=>'PN',
			'label'=>'Animateurs Indisponibles (repos ou autre activité au même moment)',
			'required'=>false,
			'expanded'=>true,
			'multiple'=>true,
			'disabled'=>true,
			))
		->add('Ev', HiddenType::class, array(
			'data' => $idEvenement));

	$form->add('Affecter les anims',SubmitType::class, array( 'attr' => array('id' => 'formAnimSubmit', 'class' => 'formAnimSubmit')));

	$form = $form->getForm();
	if ($request->isMethod('POST')) {
		$em = $this->getDoctrine()->getManager();
		if(isset($request->get("data")["form[Dispo"]))
		{
			$data = $request->get("data")["form[Dispo"] ;
			$listAnimSelected=array();
			foreach($data as $ani)
			{
				array_push($listAnimSelected, $repository4->findOneById($ani));
			}
			$listAnimEnMoins = array_diff($listeAnimAffecter, $listAnimSelected);
			foreach($listAnimEnMoins as $moins)
			{
				$Evenement->removeAnimateur($moins);
			}

			foreach($data as $ani)
			{
				if(! in_array($repository4->findOneById($ani), $listeAnimAffecter))
				{
					$Evenement->addAnimateur($repository4->findOneById($ani));
				}
			}
		}
		else
		{
			foreach($listeAnimAffecter as $moins)
			{
				$Evenement->removeAnimateur($moins);
			}
		}
		$em->flush();
		return new JsonResponse(array('status' => 'ok'));
	}
	$HTML = $this->renderView('SejourBundle:Default:affecterAnim.html.twig', array('form' => $form->createView(), 'Evenement'=>$Evenement, 'Jour' => $idJour, 'Sejour'=>$idSejour ));

	$encoders = array(new JsonEncoder());
	$normalizers = array(new GetSetMethodNormalizer());
	$serializer = new Serializer($normalizers, $encoders);
	$response = new Response($serializer->serialize($HTML, 'json'));
	$response->headers->set('Content-Type', 'application/json');
	return $response;
	}
	private function prevNextJours($id, $idSejour)
	{
		$repository = $this->getDoctrine()
			->getManager()
			->getRepository('SejourBundle:Jour');

		$jour=$repository->find($id)->getDate();
		$dateDep=$jour;
		$datePrev = $dateDep->modify('-1 day');
		$JourPrev=$repository->findOneBy(array('date'=>$datePrev, 'sejour'=>$idSejour));
		$datePrev = $dateDep->modify('+2 day');
		$JourNext=$repository->findOneBy(array('date'=>$datePrev, 'sejour'=>$idSejour));

		if($JourPrev)
		{
			$JourPrev=$JourPrev->getId();
		}
		if($JourNext)
		{
			$JourNext=$JourNext->getId();
		}
		$datePrev = $dateDep->modify('-1 day');
		return array($JourPrev, $JourNext);
	}
	private function verifDroit($id, $role)
	{
		$this->container->get('sejour.droits')->AllowedUser($id);
		if( !$this->get('security.authorization_checker')->isGranted($role) )
		{
			throw new AccessDeniedException('Tu n\'as pas accès à cette page !');
		}
	}
}


text:
namespace inet {

namespace physicallayer {

Define_Module(IdealObstacleLoss);

IdealObstacleLoss::IdealObstacleLoss()
{
}

void IdealObstacleLoss::initialize(int stage)
{
    if (stage == INITSTAGE_LOCAL) {
        medium = check_and_cast<IRadioMedium *>(getParentModule());
        physicalEnvironment = getModuleFromPar<IPhysicalEnvironment>(par("physicalEnvironmentModule"), this);
    }
}

std::ostream& IdealObstacleLoss::printToStream(std::ostream& stream, int level) const
{
    return stream << "IdealObstacleLoss";
}

bool IdealObstacleLoss::isObstacle(const IPhysicalObject *object, const Coord& transmissionPosition, const Coord& receptionPosition) const
{
    const ShapeBase *shape = object->getShape();
    const Coord& position = object->getPosition();
    const EulerAngles& orientation = object->getOrientation();
    Rotation rotation(orientation);
    const LineSegment lineSegment(rotation.rotateVectorCounterClockwise(transmissionPosition - position), rotation.rotateVectorCounterClockwise(receptionPosition - position));
    Coord intersection1, intersection2, normal1, normal2;
    bool hasIntersections = shape->computeIntersection(lineSegment, intersection1, intersection2, normal1, normal2);
    bool isObstacle = hasIntersections && intersection1 != intersection2;
    if (isObstacle) {
        ObstaclePenetratedEvent event(object, intersection1, intersection2, normal1, normal2, isObstacle ? 1 : 0);
        const_cast<IdealObstacleLoss *>(this)->emit(obstaclePenetratedSignal, &event);
    }
    return isObstacle;
}

double IdealObstacleLoss::computeObstacleLoss(Hz frequency, const Coord& transmissionPosition, const Coord& receptionPosition) const
{
    TotalObstacleLossComputation obstacleLossVisitor(this, transmissionPosition, receptionPosition);
    physicalEnvironment->visitObjects(&obstacleLossVisitor, LineSegment(transmissionPosition, receptionPosition));
    return obstacleLossVisitor.isObstacleFound() ? 0 : 1;
}

IdealObstacleLoss::TotalObstacleLossComputation::TotalObstacleLossComputation(const IdealObstacleLoss *obstacleLoss, const Coord& transmissionPosition, const Coord& receptionPosition) :
    obstacleLoss(obstacleLoss),
    transmissionPosition(transmissionPosition),
    receptionPosition(receptionPosition)
{
}

void IdealObstacleLoss::TotalObstacleLossComputation::visit(const cObject *object) const
{
    if (!isObstacleFound_)
        isObstacleFound_ = obstacleLoss->isObstacle(check_and_cast<const IPhysicalObject *>(object), transmissionPosition, receptionPosition);
}

} // namespace physicallayer

} // namespace inet


text:
.. _overview:

Overview
====================

TreeDict can be thought of as a hierarchical dictionary.  It is
limited in functionality compared to the python built-in dictionary
only in that the branch names and values must be strings that follow
standard python attribute naming rules.  This is to allow the user to
access and set values through attributes, allowing for easy-to-read,
concise parameter specification.

The syntax used to specify branches and leaves in the tree is the same
as that used for accessing attributes, i.e. python names seperated by
periods.  For example, `b1.b2.x` specifies a branch `b1`, sub-branch
`b2`, and value `x`.

Basic Operations
----------------------------------------

All the python operators supported by `dict` are also supported by
`TreeDict`.  These include assignment, membersnhip testing with `in`,
equality testing, iteration, and copying.  These are summarized in the
following table:

+-------------------------+---------------------------------------------+
|  ``k in t``             | True if  `k`  is in  `t`, False otherwise.  |
+-------------------------+---------------------------------------------+
|  ``t[k] = v``           | Sets key `k` to value `v`.                  |
+-------------------------+---------------------------------------------+
|  ``del t[k]``           | Removes key `key` from `t`.                 |
+-------------------------+---------------------------------------------+
| ``t['a.b.x'] = v``,     | Sets key `'x'` on branch `'a.b'` to `v`.    |
| ``t.a.b.x = v``         | `'a.b'` is implicitly created if not        |
|                         | present.                                    |
+-------------------------+---------------------------------------------+
| ``for k in t:``         | Like `dict`, iterates through the keys of   |
|                         | `t`.                                        |
+-------------------------+---------------------------------------------+
| ``t.copy()``,           | Creates a copy of the tree structure.       |
| ``copy(t)``             |                                             |
+-------------------------+---------------------------------------------+
| ``t.copy(deep=True)``,  | Creates a copy of both the tree structure   |
| ``deepcopy(t)``         | and the values.                             |
+-------------------------+---------------------------------------------+

In addition to the above, all the dictionary methods --
:meth:`~treedict.TreeDict.get`, :meth:`~treedict.TreeDict.setdefault`,
:meth:`~treedict.TreeDict.clear`, :meth:`~treedict.TreeDict.copy`,
:meth:`~treedict.TreeDict.pop`, :meth:`~treedict.TreeDict.popitem`,
:meth:`~treedict.TreeDict.update`, :meth:`~treedict.TreeDict.keys`,
:meth:`~treedict.TreeDict.iterkeys`,
:meth:`~treedict.TreeDict.values`,
:meth:`~treedict.TreeDict.itervalues`,
:meth:`~treedict.TreeDict.items` and
:meth:`~treedict.TreeDict.iteritems` -- are implemented.  Each of
these supports optional parameters beyond those of `dict` to work with
the tree-shaped structure, but the default operations are exactly
analagous a `dict` in which the keys are the full path names to the
values.  If these functions are called on a branch, they operate only
on that branch and the branches and values underneath it.  For
example::

    >>> from treedict import TreeDict
    >>> t = TreeDict()
    >>> t.a.b.x = 1
    >>> t.a.c.x = 2
    >>> t.d.y = 3
    >>> t.items()
    [('a.c.x', 2), ('a.b.x', 1), ('d.y', 3)]
    >>> t.a.items()
    [('c.x', 2), ('b.x', 1)]
    >>> t.a.b.items()
    [('x', 1)]

In addition, pickling is supported.

Implicit Branch Creation
----------------------------------------

Branches in the TreeDict are created implicitly as needed.  In the
following code::

    t = TreeDict()
    t.a.b.y = 1
    t.a.b.c.x = 2

the intermediate branches `a`, `b`, and `c` are implicitly created.
Thus, setting options through attributes minimizes unnecessary syntax,
e.g. quotes and brackets (``["..."]``) if one uses python
dictionaries.

Internally, this is done by allowing "dangling" branches -- branches
that are invisible (e.g. ``b in t`` is False if `b` is dangling) to
the API but are tracked internally until they are attached to the
tree.  A dangling branch is attached if a leaf value is assigned to it
or a dangling subbranch is attached.  In the example above, assigning
`1` to `y` attaches the dangling branches `a` and `b`.

Implicitly creating branches in this way allows more natural orderings
on assigning values than what python would normally allow.
Specifically, "forward" references can be made to dangling branches
that are attached much later.  For example::

    t = TreeDict()

    # Action specified at top for clarity
    t.action = t.action_definitions.make_apple_stroudel  # dangling branch

    # Now specify definitions
    t.action_definitions.make_apple_stroudel.action      = "puree"
    t.action_definitions.make_apple_stroudel.ingredients = ["apple", "stroudel"]

    t.action_definitions.make_peach_cobler.action      = "puree"
    t.action_definitions.make_peach_cobler.ingredients = ["peach", "cobler"]

    # Or specify it this way
    pie = t.action_definitions.make_pie
    pie.action  = "puree"
    pie.ingredients = [3.14159265358979323846, 2.7182818284590451]

    # And so on ...

This allows the user to choose an order in defining parameters that
best presents the options.  Specifying more significant options first
(lower levels on the tree), with details coming later (branches and
leaves), allows for more readable and intuitive code.

Tree Structure
----------------------

The tree itself is such that each node has only one parent node, and
each tree has only one root.  Nodes can be detached from their parent
with the :meth:`~treedict.TreeDict.pop` method; these become a new
tree with the detached node becoming the root.  Likewise, trees can be
grafted in usign :meth:`~treedict.TreeDict.attach`.  In addition,
copies of the entire tree, or just a subtree, can be done with
:meth:`~treedict.TreeDict.copy`.

Unattached TreeDict instances within the tree structure are treated
just like any other values.  Thus links within the tree structure are
allowed as leaves can reference other parts of the tree.  To eliminate
these links, one can use :meth:`~treedict.TreeDict.attach` with
``recursive = True`` to turn any such links into branches, copying as
needed.

Examples
-------------------------

After the above introduction, the features of TreeDict are best
learned by browsing the TreeDict API or presenting a few examples

Converting to/from a Dictionary
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A dictionary of keys that follow the branch/leaf naming conventions
(e.g. ``value``, ``branch.value``, ``a12._dlkfjd123.v``) can be
converted to a TreeDict in a number of ways, but the easiest way is
using :meth:`~treedict.TreeDict.update`::

    >>> from treedict import TreeDict
    >>> d = {"x" : 1, "y" : 2, "a.b.x" : 3, "a.b.c.y" : 4}
    >>> t = TreeDict()
    >>> t.update(d)
    >>> print t.makeReport()
    y       = 2
    x       = 1
    a.b.c.y = 4
    a.b.x   = 3

To convert to a dictionary, use :meth:`~treedict.TreeDict.iteritems()`::

    >>> from treedict import TreeDict
    >>> t = TreeDict() ; t.set("x" , 1, "y" , 2, "a.b.x", 3, "a.b.c.y", 4)
    >>> dict(t.iteritems())
    {'y': 2, 'x': 1, 'a.b.c.y': 4, 'a.b.x': 3}

Using Default Program Options
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Setting the default options in a program can be done as follows.  In
``defaults.py``, we could have::

    import treedict

    t = treedict.getTree('default_parameters')
    t.verbose = False
    t.run_mode = t.chug
    t.run_object = "coffee"

    t.chug.action = "drink"
    t.chug.quantity = "lots"

    t.sip.action = "drink"
    t.sip.quantity = "a little"

And then, when we need to access these parameters in another file, we
can do::

    def run(run_parameters):

        t = getTree("default_parameters").copy()
        t.update(parameters)

        # The following will print "drink lots" unless overridden by run_parameters
        print t.run_mode.action, t.run_mode.quantity

Function Caching / Memoization
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

TreeDict can be used to build a simple but effective caching system
for time-consuming functions.  This example reworks the `memoized`
decorator from the python `decorator wiki
<http://wiki.python.org/moin/PythonDecoratorLibrary>`_.  It uses the
:meth:`~treedict.TreeDict.hash` method of TreeDict to accomidate
mutable parameters and TreeDict instances in the arguments::

    from treedict import TreeDict

    class memoized_with_treedict(object):
        """
        Based on 'memoized' python decorator from
        http://wiki.python.org/moin/PythonDecoratorLibrary.
        Decorator that caches a function's return value each time it is
        called.  If called later with the same arguments, the cached value
        is returned, and not re-evaluated.  In this case, TreeDicts are
        both allowed as arguments and used to allow mutable arguments as
        types.
        """

        def __init__(self, func):
            self.func = func
            self.cache = {}

        def __call__(self, *args, **kwargs):

            # Use TreeDict to allow for mutable parameters / kwargs
            kw_t = TreeDict(**kwargs)
            arg_t = TreeDict(args = args)
            cache_key = (self.func.__name__, self.func.__module__, kw_t.hash(), arg_t.hash())

            try:
                return self.cache[cache_key]
            except KeyError:
	        # All exceptions from calling the function are passed on.
                self.cache[cache_key] = value = self.func(*args, **kwargs)
                return value

The fact that :meth:`~treedict.TreeDict.hash` returns a string permits
the use of `shelve <http://docs.python.org/library/shelve.html>`_ to
provide disk-level persistent caching, a possibly useful feature for
time consuming scientific calculations::

    from treedict import TreeDict
    import atexit, shelve

    # Put this somewhere so it is set before any memoized functions
    # are called
    from treedict import getTree
    getTree("global_options").cache_file = "cache.tmp"

    class persistent_memoized(object):
        """
        Based on 'memoized' python decorator from
        http://wiki.python.org/moin/PythonDecoratorLibrary.  Decorator
        that caches a function's return value each time it is called.
        If called later with the same arguments, the cached value is
        returned, and not re-evaluated.  In this case, TreeDicts are
        both allowed as arguments and used to allow mutable arguments
        as types.
        """

        def __init__(self, func):
            self.func = func
            self.cache = None

        def __call__(self, *args, **kwargs):

            # Set here so the cache file doesn't need to be set before
            # this module is imported
            if self.cache is None:
                self.cache = shelve.open(getTree("global_options").cache_file)
                atexit.register(lambda: self.cache.close())

            # Use TreeDict to allow for mutable parameters / kwargs
            kw_t = TreeDict(**kwargs)
            arg_t = TreeDict(args = args)

            # A string-based cache_key allows for use in shelves.
            cache_key = self.func.__name__ + str(self.func.__module__) + kw_t.hash() + arg_t.hash()

            try:
                return self.cache[cache_key]
            except KeyError:
                self.cache[cache_key] = value = self.func(*args, **kwargs)
                return value

Here is an example of how either of these decorates could be used::

    @memoized_with_treedict
    def weird_fibonacci(n, t):
        """
        Fibonacci numbers modified so all results are shifted by t.shift,
        and numbers less than t.start are returned as themselves plus the
        shift.  Demonstrates the use of TreeDict to control options in a
        memoized function.  t.start defaults to 1 and t.shift defaults to 0.
        """

        start = max(1, t.get("start", 1))
        shift = t.get("shift", 0)

        if n <= start:
            return n + shift
        else:
            return weird_fibonacci(n-1, t) + weird_fibonacci(n-2, t) + shift

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

    >>> weird_fibonacci(10, TreeDict(start = 5, shift = 2))
    110
    >>> [weird_fibonacci(i, TreeDict(start = 5, shift = 2)) for i in xrange(10)]
    [2, 3, 4, 5, 6, 7, 15, 24, 41, 67]


text:
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Stage, Layer, Star, Text } from 'react-konva';

function generateShapes() {
  return [...Array(10)].map((_, i) => ({
    id: i.toString(),
    x: Math.random() * window.innerWidth,
    y: Math.random() * window.innerHeight,
    rotation: Math.random() * 180,
    isDragging: false,
  }));
}

const INITIAL_STATE = generateShapes();

const App = () => {
  const [stars, setStars] = React.useState(INITIAL_STATE);

  const handleDragStart = (e) => {
    const id = e.target.id();
    setStars(
      stars.map((star) => {
        return {
          ...star,
          isDragging: star.id === id,
        };
      })
    );
  };
  const handleDragEnd = (e) => {
    setStars(
      stars.map((star) => {
        return {
          ...star,
          isDragging: false,
        };
      })
    );
  };

  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <Text text="Try to drag a star" />
        {stars.map((star) => (
          <Star
            key={star.id}
            id={star.id}
            x={star.x}
            y={star.y}
            numPoints={5}
            innerRadius={20}
            outerRadius={40}
            fill="#89b717"
            opacity={0.8}
            draggable
            rotation={star.rotation}
            shadowColor="black"
            shadowBlur={10}
            shadowOpacity={0.6}
            shadowOffsetX={star.isDragging ? 10 : 5}
            shadowOffsetY={star.isDragging ? 10 : 5}
            scaleX={star.isDragging ? 1.2 : 1}
            scaleY={star.isDragging ? 1.2 : 1}
            onDragStart={handleDragStart}
            onDragEnd={handleDragEnd}
          />
        ))}
      </Layer>
    </Stage>
  );
};

const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);


text:
/**
 * Created by bulanmaster on 21.12.2016.
 */

import React, { Component, PropTypes } from 'react';

class BaseISwitch extends Component {
    constructor(props) {
        super(props);
        this.state = {
            on: props.on,
        };
        this.onClick = this.onClick.bind(this);
    }

    onClick() {
        this.setState({
            on: !this.state.on,
        });
    }

    render() {
        const { skin } = this.props;
        const { on } = this.state;

        return (
            <span
                className={`baseISwitch ${skin}`}
                onClick={this.onClick}
            >
				<span className={`baseISwitch-inner${on ? ' on' : ''}`} />
			</span>
        );
    }
}

BaseISwitch.propTypes = {
    on: PropTypes.bool,
    skin: PropTypes.oneOf([
        'white', 'black'
    ]),
};

BaseISwitch.defaultProps = {
    on: false,
    skin: 'white',
};

export default BaseISwitch;


text:
export default
    ['templateUrl', '$state', '$rootScope', 'Store', 'Empty', '$window', 'BreadCrumbService', 'i18n', '$transitions',
    function(templateUrl, $state, $rootScope, Store, Empty, $window, BreadCrumbService, i18n, $transitions) {
        return {
            restrict: 'E',
            templateUrl: templateUrl('bread-crumb/bread-crumb'),
            link: function(scope) {

                var streamConfig = {}, originalRoute;

                let init = function() {

                    scope.showActivityStreamButton = false;
                    scope.showRefreshButton = false;
                    scope.alwaysShowRefreshButton = false;
                    scope.loadingLicense = true;

                    $transitions.onSuccess({}, function updateActivityStreamButton(trans) {
                        if(trans.from() && !Empty(trans.from().name)) {
                            // Go ahead and attach the from params to the state object so that it can all be stored together

                            trans.from().fromParams = trans.params('from') ? trans.params('from') : {};
                            // Store the state that we're coming from in local storage to be accessed when navigating away from the
                            // activity stream
                            //Store('previous_state', fromState);
                        }

                        streamConfig = (trans.to() && trans.to().data) ? trans.to().data : {};

                        if(streamConfig && streamConfig.activityStream) {
                            scope.loadingLicense = false;
                            scope.activityStreamActive = (trans.to().name === 'activityStream') ? true : false;
                            scope.activityStreamTooltip = (trans.to().name === 'activityStream') ? i18n._('Hide Activity Stream') : i18n._('View Activity Stream');
                            scope.showActivityStreamButton = true;
                        }
                        else {
                            scope.showActivityStreamButton = false;
                        }

                        scope.showRefreshButton = (streamConfig && streamConfig.refreshButton) ? true : false;
                        scope.alwaysShowRefreshButton = (streamConfig && streamConfig.alwaysShowRefreshButton) ? true: false;
                    });

                    scope.loadingLicense = false;
                    scope.activityStreamActive = ($state.current.name === 'activityStream') ? true : false;
                    scope.activityStreamTooltip = ($state.current.name === 'activityStream') ? 'Hide Activity Stream' : 'View Activity Stream';
                    scope.showActivityStreamButton = ((streamConfig && streamConfig.activityStream) || $state.current.name ==='activityStream') ? true : false;

                    function onResize(){
                        BreadCrumbService.truncateCrumbs();
                    }

                    function cleanUp() {
                        angular.element($window).off('resize', onResize);
                    }

                    angular.element($window).on('resize', onResize);
                    scope.$on('$destroy', cleanUp);
                };

                init();

                scope.refresh = function() {
                    $state.go($state.current, {}, {reload: true});
                };

                scope.toggleActivityStream = function() {

                    // If the user is not already on the activity stream then they want to navigate to it
                    if(!scope.activityStreamActive) {
                        var stateGoParams = {};

                        if(streamConfig && streamConfig.activityStream) {
                            if(streamConfig.activityStreamTarget) {
                                stateGoParams.target = streamConfig.activityStreamTarget;
                                let isTemplateTarget = _.includes(['template', 'job_template', 'workflow_job_template'], streamConfig.activityStreamTarget);
                                stateGoParams.activity_search = {
                                    or__object1__in: streamConfig.activityStreamTarget,
                                    or__object2__in: streamConfig.activityStreamTarget,
                                    order_by: '-timestamp',
                                    page_size: '20',
                                };

                                if (isTemplateTarget) {
                                    stateGoParams.activity_search.or__object1__in = 'job_template,workflow_job_template';
                                    stateGoParams.activity_search.or__object2__in = 'job_template,workflow_job_template';
                                }

                                if (streamConfig.activityStreamTarget === 'job') {
                                    stateGoParams.activity_search.or__object1__in = 'job,workflow_approval';
                                    stateGoParams.activity_search.or__object2__in = 'job,workflow_approval';
                                }

                                if (streamConfig.activityStreamTarget && streamConfig.activityStreamId && !streamConfig.noActivityStreamID) {
                                    stateGoParams.activity_search[streamConfig.activityStreamTarget] = $state.params[streamConfig.activityStreamId];
                                }
                            }
                            else {
                                stateGoParams.activity_search = {
                                    order_by: '-timestamp',
                                    page_size: '20',
                                };
                            }
                            if(streamConfig.activityStreamId && !streamConfig.noActivityStreamID) {
                                stateGoParams.id = $state.params[streamConfig.activityStreamId];
                            }
                            if(stateGoParams.target === "custom_inventory_script"){
                                if ($state.params.inventory_script_id !== undefined) {
                                    stateGoParams.activity_search[streamConfig.activityStreamTarget] = $state.params.inventory_script_id;
                                    stateGoParams.id = $state.params.inventory_script_id;
                                }
                            }

                        }
                        originalRoute = $state.current;
                        $state.go('activityStream', stateGoParams);
                    }
                    // The user is navigating away from the activity stream - take them back from whence they came
                    else {
                        if(originalRoute) {
                            $state.go(originalRoute.name, originalRoute.fromParams);
                        }
                        else {
                            // If for some reason something went wrong (like local storage was wiped, etc) take the
                            // user back to the dashboard
                            $state.go('dashboard');
                        }

                    }

                };
            }
        };
    }];