text:
<?php

namespace cli;

use cli\arguments\Argument;
use cli\arguments\HelpScreen;
use cli\arguments\InvalidArguments;
use cli\arguments\Lexer;

/**
 * Parses command line arguments.
 */
class Arguments implements \ArrayAccess {
	protected $_flags = array();
	protected $_options = array();
	protected $_strict = false;
	protected $_input = array();
	protected $_invalid = array();
	protected $_parsed;
	protected $_lexer;

	/**
	 * Initializes the argument parser. If you wish to change the default behaviour
	 * you may pass an array of options as the first argument. Valid options are
	 * `'help'` and `'strict'`, each a boolean.
	 *
	 * `'help'` is `true` by default, `'strict'` is false by default.
	 *
	 * @param  array  $options  An array of options for this parser.
	 */
	public function __construct($options = array()) {
		$options += array(
			'strict' => false,
			'input'  => array_slice($_SERVER['argv'], 1)
		);

		$this->_input = $options['input'];
		$this->setStrict($options['strict']);

		if (isset($options['flags'])) {
			$this->addFlags($options['flags']);
		}
		if (isset($options['options'])) {
			$this->addOptions($options['options']);
		}
	}

	/**
	 * Get the list of arguments found by the defined definitions.
	 *
	 * @return array
	 */
	public function getArguments() {
		if (!isset($this->_parsed)) {
			$this->parse();
		}
		return $this->_parsed;
	}

	public function getHelpScreen() {
		return new HelpScreen($this);
	}

	/**
	 * Encodes the parsed arguments as JSON.
	 *
	 * @return string
	 */
	public function asJSON() {
		return json_encode($this->_parsed);
	}

	/**
	 * Returns true if a given argument was parsed.
	 *
	 * @param mixed  $offset  An Argument object or the name of the argument.
	 * @return bool
	 */
	public function offsetExists($offset) {
		if ($offset instanceOf Argument) {
			$offset = $offset->key;
		}

		return array_key_exists($offset, $this->_parsed);
	}

	/**
	 * Get the parsed argument's value.
	 *
	 * @param mixed  $offset  An Argument object or the name of the argument.
	 * @return mixed
	 */
	public function offsetGet($offset) {
		if ($offset instanceOf Argument) {
			$offset = $offset->key;
		}

		if (isset($this->_parsed[$offset])) {
			return $this->_parsed[$offset];
		}
	}

	/**
	 * Sets the value of a parsed argument.
	 *
	 * @param mixed  $offset  An Argument object or the name of the argument.
	 * @param mixed  $value   The value to set
	 */
	public function offsetSet($offset, $value) {
		if ($offset instanceOf Argument) {
			$offset = $offset->key;
		}

		$this->_parsed[$offset] = $value;
	}

	/**
	 * Unset a parsed argument.
	 *
	 * @param mixed  $offset  An Argument object or the name of the argument.
	 */
	public function offsetUnset($offset) {
		if ($offset instanceOf Argument) {
			$offset = $offset->key;
		}

		unset($this->_parsed[$offset]);
	}

	/**
	 * Adds a flag (boolean argument) to the argument list.
	 *
	 * @param mixed  $flag  A string representing the flag, or an array of strings.
	 * @param array  $settings  An array of settings for this flag.
	 * @setting string  description  A description to be shown in --help.
	 * @setting bool    default  The default value for this flag.
	 * @setting bool    stackable  Whether the flag is repeatable to increase the value.
	 * @setting array   aliases  Other ways to trigger this flag.
	 * @return $this
	 */
	public function addFlag($flag, $settings = array()) {
		if (is_string($settings)) {
			$settings = array('description' => $settings);
		}
		if (is_array($flag)) {
			$settings['aliases'] = $flag;
			$flag = array_shift($settings['aliases']);
		}
		if (isset($this->_flags[$flag])) {
			$this->_warn('flag already exists: ' . $flag);
			return $this;
		}

		$settings += array(
			'default'     => false,
			'stackable'   => false,
			'description' => null,
			'aliases'     => array()
		);

		$this->_flags[$flag] = $settings;
		return $this;
	}

	/**
	 * Add multiple flags at once. The input array should be keyed with the
	 * primary flag character, and the values should be the settings array
	 * used by {addFlag}.
	 *
	 * @param array  $flags  An array of flags to add
	 * @return $this
	 */
	public function addFlags($flags) {
		foreach ($flags as $flag => $settings) {
			if (is_numeric($flag)) {
				$this->_warn('No flag character given');
				continue;
			}

			$this->addFlag($flag, $settings);
		}

		return $this;
	}

	/**
	 * Adds an option (string argument) to the argument list.
	 *
	 * @param mixed  $option  A string representing the option, or an array of strings.
	 * @param array  $settings  An array of settings for this option.
	 * @setting string  description  A description to be shown in --help.
	 * @setting bool    default  The default value for this option.
	 * @setting array   aliases  Other ways to trigger this option.
	 * @return $this
	 */
	public function addOption($option, $settings = array()) {
		if (is_string($settings)) {
			$settings = array('description' => $settings);
		}
		if (is_array($option)) {
			$settings['aliases'] = $option;
			$option = array_shift($settings['aliases']);
		}
		if (isset($this->_options[$option])) {
			$this->_warn('option already exists: ' . $option);
			return $this;
		}

		$settings += array(
			'default'     => null,
			'description' => null,
			'aliases'     => array()
		);

		$this->_options[$option] = $settings;
		return $this;
	}

	/**
	 * Add multiple options at once. The input array should be keyed with the
	 * primary option string, and the values should be the settings array
	 * used by {addOption}.
	 *
	 * @param array  $options  An array of options to add
	 * @return $this
	 */
	public function addOptions($options) {
		foreach ($options as $option => $settings) {
			if (is_numeric($option)) {
				$this->_warn('No option string given');
				continue;
			}

			$this->addOption($option, $settings);
		}

		return $this;
	}

	/**
	 * Enable or disable strict mode. If strict mode is active any invalid
	 * arguments found by the parser will throw `cli\arguments\InvalidArguments`.
	 *
	 * Even if strict is disabled, invalid arguments are logged and can be
	 * retrieved with `cli\Arguments::getInvalidArguments()`.
	 *
	 * @param bool  $strict  True to enable, false to disable.
	 * @return $this
	 */
	public function setStrict($strict) {
		$this->_strict = (bool)$strict;
		return $this;
	}

	/**
	 * Get the list of invalid arguments the parser found.
	 *
	 * @return array
	 */
	public function getInvalidArguments() {
		return $this->_invalid;
	}

	/**
	 * Get a flag by primary matcher or any defined aliases.
	 *
	 * @param mixed  $flag  Either a string representing the flag or an
	 *                      cli\arguments\Argument object.
	 * @return array
	 */
	public function getFlag($flag) {
		if ($flag instanceOf Argument) {
			$obj  = $flag;
			$flag = $flag->value;
		}

		if (isset($this->_flags[$flag])) {
			return $this->_flags[$flag];
		}

		foreach ($this->_flags as $master => $settings) {
			if (in_array($flag, (array)$settings['aliases'])) {
				if (isset($obj)) {
					$obj->key = $master;
				}

				$cache[$flag] =& $settings;
				return $settings;
			}
		}
	}

	public function getFlags() {
		return $this->_flags;
	}

	public function hasFlags() {
		return !empty($this->_flags);
	}

	/**
	 * Returns true if the given argument is defined as a flag.
	 *
	 * @param mixed  $argument  Either a string representing the flag or an
	 *                          cli\arguments\Argument object.
	 * @return bool
	 */
	public function isFlag($argument) {
		return (null !== $this->getFlag($argument));
	}

	/**
	 * Returns true if the given flag is stackable.
	 *
	 * @param mixed  $flag  Either a string representing the flag or an
	 *                      cli\arguments\Argument object.
	 * @return bool
	 */
	public function isStackable($flag) {
		$settings = $this->getFlag($flag);

		return isset($settings) && (true === $settings['stackable']);
	}

	/**
	 * Get an option by primary matcher or any defined aliases.
	 *
	 * @param mixed  $option Either a string representing the option or an
	 *                       cli\arguments\Argument object.
	 * @return array
	 */
	public function getOption($option) {
		if ($option instanceOf Argument) {
			$obj = $option;
			$option = $option->value;
		}

		if (isset($this->_options[$option])) {
			return $this->_options[$option];
		}

		foreach ($this->_options as $master => $settings) {
			if (in_array($option, (array)$settings['aliases'])) {
				if (isset($obj)) {
					$obj->key = $master;
				}

				return $settings;
			}
		}
	}

	public function getOptions() {
		return $this->_options;
	}

	public function hasOptions() {
		return !empty($this->_options);
	}

	/**
	 * Returns true if the given argument is defined as an option.
	 *
	 * @param mixed  $argument  Either a string representing the option or an
	 *                          cli\arguments\Argument object.
	 * @return bool
	 */
	public function isOption($argument) {
		return (null != $this->getOption($argument));
	}

	/**
	 * Parses the argument list with the given options. The returned argument list
	 * will use either the first long name given or the first name in the list
	 * if a long name is not given.
	 *
	 * @return array
	 * @throws arguments\InvalidArguments
	 */
	public function parse() {
		$this->_invalid = array();
		$this->_parsed = array();
		$this->_lexer = new Lexer($this->_input);

		$this->_applyDefaults();

		foreach ($this->_lexer as $argument) {
			if ($this->_parseFlag($argument)) {
				continue;
			}
			if ($this->_parseOption($argument)) {
				continue;
			}

			array_push($this->_invalid, $argument->raw);
		}

		if ($this->_strict && !empty($this->_invalid)) {
			throw new InvalidArguments($this->_invalid);
		}
	}

	/**
	 * This applies the default values, if any, of all of the
	 * flags and options, so that if there is a default value
	 * it will be available.
	 */
	private function _applyDefaults() {
		foreach($this->_flags as $flag => $settings) {
			$this[$flag] = $settings['default'];
		}

		foreach($this->_options as $option => $settings) {
			// If the default is 0 we should still let it be set.
			if (!empty($settings['default']) || $settings['default'] === 0) {
				$this[$option] = $settings['default'];
			}
		}
	}

	private function _warn($message) {
		trigger_error('[' . __CLASS__ .'] ' . $message, E_USER_WARNING);
	}

	private function _parseFlag($argument) {
		if (!$this->isFlag($argument)) {
			return false;
		}

		if ($this->isStackable($argument)) {
			if (!isset($this[$argument])) {
				$this[$argument->key] = 0;
			}

			$this[$argument->key] += 1;
		} else {
			$this[$argument->key] = true;
		}

		return true;
	}

	private function _parseOption($option) {
		if (!$this->isOption($option)) {
			return false;
		}

		// Peak ahead to make sure we get a value.
		if ($this->_lexer->end() || !$this->_lexer->peek->isValue) {
			$optionSettings = $this->getOption($option->key);

			if (empty($optionSettings['default']) && $optionSettings !== 0) {
				// Oops! Got no value and no default , throw a warning and continue.
				$this->_warn('no value given for ' . $option->raw);
				$this[$option->key] = null;
			} else {
				// No value and we have a default, so we set to the default
				$this[$option->key] = $optionSettings['default'];
			}
			return true;
		}

		// Store as array and join to string after looping for values
		$values = array();

		// Loop until we find a flag in peak-ahead
		foreach ($this->_lexer as $value) {
			array_push($values, $value->raw);

			if (!$this->_lexer->end() && !$this->_lexer->peek->isValue) {
				break;
			}
		}

		$this[$option->key] = join($values, ' ');
		return true;
	}
}


text:
Autolink
========
Extension to detect and automatically link URLs which appear on the screen and in the scrollback area.

redpajama_set_name: RedPajamaGithub


text:
package org.arp.config;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.xml.ws.BindingProvider;

import org.tempuri.Dinamica;
import org.tempuri.DinamicaSoap;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.name.Named;
import com.google.inject.name.Names;

public class DinamicaModule extends AbstractModule {

    @Provides
    DinamicaSoap getDinamicaSoapClient(@Named("dinamica.endpoint") String endpoint) {
        DinamicaSoap port = new Dinamica().getDinamicaSoap();
        BindingProvider bp = (BindingProvider) port;
        bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpoint);
        return port;
    }

    @Override
    protected void configure() {
        String configLocation = System.getProperty("configLocation", "conf/app.properties");
        Properties prop = new Properties();
        try (InputStream is = new FileInputStream(configLocation)) {
            prop.load(is);
            Names.bindProperties(binder(), prop);
        } catch (IOException e) {
            this.addError(e);
        }
    }

}


text:
using MatterHackers.Agg;
using MatterHackers.Agg.PlatformAbstract;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PrinterCommunication;
using MatterHackers.MatterControl.PrintLibrary;
using MatterHackers.MatterControl.PrintLibrary.Provider;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.VectorMath;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace MatterHackers.MatterControl
{
	using Agg.Font;
	using System.Reflection;
	using System.Text.RegularExpressions;
	using SettingsManagement;
	using PrintHistory;
	using Agg.Image;
	using System.Net;

	public class OemProfileDictionary : Dictionary<string, Dictionary<string, PublicDevice>>
	{
	}

	public class PublicDevice
	{
		public string DeviceToken { get; set; }
		public string ProfileToken { get; set; }
		public string ShortProfileID { get; set; }
		public string CacheKey => this.ShortProfileID + ProfileManager.ProfileExtension;
	}

	public abstract class ApplicationView : GuiWidget
	{
		public abstract void CreateAndAddChildren();
	}

	public class TouchscreenView : ApplicationView
	{
		private FlowLayoutWidget TopContainer;
		private TouchscreenTabView touchscreenTabView;
		private QueueDataView queueDataView;
		private GuiWidget menuSeparator;
		private PrintProgressBar progressBar;
		private bool topIsHidden = false;

		public TouchscreenView()
		{
			CreateAndAddChildren();
			this.AnchorAll();
		}

		public void ToggleTopContainer()
		{
			topIsHidden = !topIsHidden;
			progressBar.WidgetIsExtended = !progressBar.WidgetIsExtended;

			//To do - Animate this (KP)
			this.menuSeparator.Visible = this.TopContainer.Visible;
			this.TopContainer.Visible = !this.TopContainer.Visible;
		}

		public override void CreateAndAddChildren()
		{
			topIsHidden = false;
			this.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;

			FlowLayoutWidget container = new FlowLayoutWidget(FlowDirection.TopToBottom);
			container.AnchorAll();

			TopContainer = new FlowLayoutWidget(FlowDirection.TopToBottom);
			TopContainer.HAnchor = HAnchor.ParentLeftRight;

			if (!UserSettings.Instance.IsTouchScreen)
			{
#if !__ANDROID__
				// The application menu bar, which is suppressed on Android
				ApplicationMenuRow menuRow = new ApplicationMenuRow();
				TopContainer.AddChild(menuRow);
#endif
			}

			menuSeparator = new GuiWidget();
			menuSeparator.Height = 12;
			menuSeparator.HAnchor = HAnchor.ParentLeftRight;
			menuSeparator.MinimumSize = new Vector2(0, 12);
			menuSeparator.Visible = false;

			queueDataView = new QueueDataView();
			TopContainer.AddChild(new ActionBarPlus(queueDataView));

			container.AddChild(TopContainer);

			progressBar = new PrintProgressBar();

			container.AddChild(progressBar);
			container.AddChild(menuSeparator);
			touchscreenTabView = new TouchscreenTabView(queueDataView);

			container.AddChild(touchscreenTabView);
			this.AddChild(container);
		}
	}

	public class DesktopView : ApplicationView
	{
		private WidescreenPanel widescreenPanel;

		public DesktopView()
		{
			CreateAndAddChildren();
			this.AnchorAll();
		}

		public override void CreateAndAddChildren()
		{
			this.BackgroundColor = ActiveTheme.Instance.PrimaryBackgroundColor;

			var container = new FlowLayoutWidget(FlowDirection.TopToBottom);
			container.AnchorAll();

			if (!UserSettings.Instance.IsTouchScreen)
			{
#if !__ANDROID__
				// The application menu bar, which is suppressed on Android
				var menuRow = new ApplicationMenuRow();
				container.AddChild(menuRow);
#endif
			}

			var menuSeparator = new GuiWidget()
			{
				BackgroundColor = new RGBA_Bytes(200, 200, 200),
				Height = 2,
				HAnchor = HAnchor.ParentLeftRight,
				Margin = new BorderDouble(3, 6, 3, 3)
			};
			container.AddChild(menuSeparator);

			widescreenPanel = new WidescreenPanel();
			container.AddChild(widescreenPanel);

			using (new PerformanceTimer("ReloadAll", "AddChild"))
			{
				this.AddChild(container);
			}
		}
	}

	public class ApplicationController
	{
		public Action RedeemDesignCode;
		public Action EnterShareCode;

		private static ApplicationController globalInstance;
		public RootedObjectEventHandler AdvancedControlsPanelReloading = new RootedObjectEventHandler();
		public RootedObjectEventHandler CloudSyncStatusChanged = new RootedObjectEventHandler();
		public RootedObjectEventHandler DoneReloadingAll = new RootedObjectEventHandler();
		public RootedObjectEventHandler PluginsLoaded = new RootedObjectEventHandler();

		public static Action SignInAction;
		public static Action SignOutAction;

		public static Action WebRequestFailed;
		public static Action WebRequestSucceeded;

#if DEBUG
		public const string EnvironmentName = "TestEnv_";
#else
		public const string EnvironmentName = "";
#endif

		/// <summary>
		/// Allows application components to hook initial SystemWindow Load event without an existing Widget instance
		/// </summary>
		public static event EventHandler Load;

		public static Func<string, Task<Dictionary<string, string>>> GetProfileHistory;
		public static Func<PrinterInfo,string, Task<PrinterSettings>> GetPrinterProfileAsync;
		public static Func<string, IProgress<SyncReportType>,Task> SyncPrinterProfiles;
		public static Func<Task<OemProfileDictionary>> GetPublicProfileList;
		public static Func<string, Task<PrinterSettings>> DownloadPublicProfileAsync;

		public SlicePresetsWindow EditMaterialPresetsWindow { get; set; }

		public SlicePresetsWindow EditQualityPresetsWindow { get; set; }

		public ApplicationView MainView;

		public event EventHandler ApplicationClosed;

		private EventHandler unregisterEvents;

		static int applicationInstanceCount = 0;
		public static int ApplicationInstanceCount
		{
			get
			{
				if (applicationInstanceCount == 0)
				{
					Assembly mcAssembly = Assembly.GetEntryAssembly();
					if (mcAssembly != null)
					{
						string applicationName = Path.GetFileNameWithoutExtension(mcAssembly.Location).ToUpper();
						Process[] p1 = Process.GetProcesses();
						foreach (System.Diagnostics.Process pro in p1)
						{
							try
							{
								if (pro?.ProcessName != null
								   && pro.ProcessName.ToUpper().Contains(applicationName))
								{
									applicationInstanceCount++;
								}
							}
							catch
							{
							}
						}
					}
				}

				return applicationInstanceCount;
			}
		}

		public ApplicationController()
		{
			// Name = "MainSlidePanel";
			ActiveTheme.ThemeChanged.RegisterEvent((s, e) => ReloadAll(), ref unregisterEvents);

			// Remove consumed ClientToken from running list on shutdown
			ApplicationClosed += (s, e) => ApplicationSettings.Instance.ReleaseClientToken();
		}

		public void StartSignIn()
		{
			if (PrinterConnectionAndCommunication.Instance.PrinterIsPrinting
				|| PrinterConnectionAndCommunication.Instance.PrinterIsPaused)
			{
				// can't sign in while printing
				UiThread.RunOnIdle(() =>
					StyledMessageBox.ShowMessageBox(null, "Please wait until the print has finished and try again.".Localize(), "Can't sign in while printing".Localize())
				);
			}
			else // do the regular sign in
			{
				SignInAction?.Invoke();
			}
		}

		private static TypeFace monoSpacedTypeFace = null;
		public static TypeFace MonoSpacedTypeFace
		{
			get
			{
				if (monoSpacedTypeFace == null)
				{
					monoSpacedTypeFace = TypeFace.LoadFrom(StaticData.Instance.ReadAllText(Path.Combine("Fonts", "LiberationMono.svg")));
				}

				return monoSpacedTypeFace;
			}
		}

		/// <summary>
		/// Requests fresh content from online services, falling back to cached content if offline
		/// </summary>
		/// <param name="collector">The custom collector function to load the content</param>
		/// <returns></returns>
		public async static Task<T> LoadCacheableAsync<T>(string cacheKey, string cacheScope, Func<Task<T>> collector, string staticDataFallbackPath = null) where T : class
		{
			string cachePath = CacheablePath(cacheScope, cacheKey);

			try
			{
				// Try to update the document
				T item = await collector();
				if (item != null)
				{
					// update cache on success
					File.WriteAllText(cachePath, JsonConvert.SerializeObject(item, Formatting.Indented));
					return item;
				}
			}
			catch
			{
				// Fall back to preexisting cache if failed
			}

			try
			{
				if (File.Exists(cachePath))
				{
					// Load from cache and deserialize
					return JsonConvert.DeserializeObject<T>(File.ReadAllText(cachePath));
				}
			}
			catch
			{
				// Fall back to StaticData
			}

			try
			{
				if (staticDataFallbackPath != null
					&& StaticData.Instance.FileExists(staticDataFallbackPath))
				{
					return JsonConvert.DeserializeObject<T>(StaticData.Instance.ReadAllText(staticDataFallbackPath));
				}
			}
			catch
			{
				return default(T);
			}

			return default(T);
		}

		private static string cacheDirectory = Path.Combine(ApplicationDataStorage.ApplicationUserDataPath, "data", "temp", "cache");

		public static string CacheablePath(string cacheScope, string cacheKey)
		{
			string scopeDirectory = Path.Combine(cacheDirectory, cacheScope);

			// Ensure directory exists
			Directory.CreateDirectory(scopeDirectory);

			string cachePath = Path.Combine(scopeDirectory, cacheKey);
			return cachePath;
		}

		public void StartSignOut()
		{
			if (PrinterConnectionAndCommunication.Instance.PrinterIsPrinting
				|| PrinterConnectionAndCommunication.Instance.PrinterIsPaused)
			{
				// can't log out while printing
				UiThread.RunOnIdle(() =>
					StyledMessageBox.ShowMessageBox(null, "Please wait until the print has finished and try again.".Localize(), "Can't log out while printing".Localize())
				);
			}
			else // do the regular log out
			{
				bool allowShowingSignOutWarning = true;
				if (allowShowingSignOutWarning)
				{
					// Warn on sign out that no access to user printers and cloud library put a 'Don't remind me again' check box
					StyledMessageBox.ShowMessageBox((clickedSignOut) =>
					{
						if (clickedSignOut)
						{
							SignOutAction?.Invoke();
						}
					}, "Are you sure you want to sign out? You will not have access to your printer profiles or cloud library.".Localize(), "Sign Out?".Localize(), StyledMessageBox.MessageType.YES_NO, "Sign Out".Localize(), "Cancel".Localize());
				}
				else // just run the sign out event
				{
					SignOutAction?.Invoke();
				}
			}
		}

		bool pendingReloadRequest = false;
		public void ReloadAll()
		{
			if (pendingReloadRequest || MainView == null)
			{
				return;
			}

			pendingReloadRequest = true;

			UiThread.RunOnIdle(() =>
			{
				using (new QuickTimer($"ReloadAll_{reloadCount++}:"))
				{
					// give the widget a chance to hear about the close before they are actually closed.
					PopOutManager.SaveIfClosed = false;

					WidescreenPanel.PreChangePanels.CallEvents(this, null);
					MainView?.CloseAllChildren();
					using (new QuickTimer("ReloadAll_AddElements"))
					{
						MainView?.CreateAndAddChildren();
					}
					PopOutManager.SaveIfClosed = true;
					this.DoneReloadingAll?.CallEvents(null, null);
				}

				pendingReloadRequest = false;
			});
		}

		static int reloadCount = 0;

		public void OnApplicationClosed()
		{
			ApplicationClosed?.Invoke(null, null);
		}

		static void LoadOemOrDefaultTheme()
		{
			ActiveTheme.SuspendEvents();

			// if not check for the oem color and use it if set
			// else default to "Blue - Light"
			string oemColor = OemSettings.Instance.ThemeColor;
			if (string.IsNullOrEmpty(oemColor))
			{
				ActiveTheme.Instance = ActiveTheme.GetThemeColors("Blue - Light");
			}
			else
			{
				ActiveTheme.Instance = ActiveTheme.GetThemeColors(oemColor);
			}

			ActiveTheme.ResumeEvents();
		}

		public static ApplicationController Instance
		{
			get
			{
				if (globalInstance == null)
				{
					//using (new PerformanceTimer("Startup", "AppController Instance"))
					{
						globalInstance = new ApplicationController();

						// Set the default theme colors
						LoadOemOrDefaultTheme();

						// Accessing any property on ProfileManager will run the static constructor and spin up the ProfileManager instance
						bool na = ProfileManager.Instance.IsGuestProfile;

						if (UserSettings.Instance.DisplayMode == ApplicationDisplayType.Touchscreen)
						{
							// make sure that on touchscreen (due to lazy tabs) we initialize our stating parts and queue
							var temp = new LibraryProviderSQLite(null, null, null, null);
							// and make sure we have the check for print recovery wired up needed for lazy tabs.
							var temp2 = PrintHistoryData.Instance;
							// now bulid the ui
							globalInstance.MainView = new TouchscreenView();
						}
						else
						{
							globalInstance.MainView = new DesktopView();
						}

						ActiveSliceSettings.ActivePrinterChanged.RegisterEvent((s, e) => ApplicationController.Instance.ReloadAll(), ref globalInstance.unregisterEvents);
					}
				}
				return globalInstance;
			}
		}

		public void ReloadAdvancedControlsPanel()
		{
			AdvancedControlsPanelReloading.CallEvents(this, null);
		}

		public LibraryDataView CurrentLibraryDataView = null;
		public void SwitchToPurchasedLibrary()
		{
			if (CurrentLibraryDataView?.CurrentLibraryProvider?.GetRootProvider() != null)
			{
				// Switch to the purchased library
				LibraryProviderSelector libraryProviderSelector = CurrentLibraryDataView.CurrentLibraryProvider.GetRootProvider() as LibraryProviderSelector;
				if (libraryProviderSelector != null)
				{
					LibraryProvider purchaseProvider = libraryProviderSelector.GetPurchasedLibrary();
					UiThread.RunOnIdle(() =>
					{
						CurrentLibraryDataView.CurrentLibraryProvider = purchaseProvider;
					});
				}
			}
		}

		public void SwitchToSharedLibrary()
		{
			// Switch to the shared library
			if (CurrentLibraryDataView?.CurrentLibraryProvider?.GetRootProvider() != null)
			{
				LibraryProviderSelector libraryProviderSelector = CurrentLibraryDataView.CurrentLibraryProvider.GetRootProvider() as LibraryProviderSelector;
				if (libraryProviderSelector != null)
				{
					LibraryProvider sharedProvider = libraryProviderSelector.GetSharedLibrary();
					UiThread.RunOnIdle(() =>
					{
						CurrentLibraryDataView.CurrentLibraryProvider = sharedProvider;
					});
				}
			}
		}

		public void ChangeCloudSyncStatus(bool userAuthenticated, string reason = "")
		{
			UserSettings.Instance.set(UserSettingsKey.CredentialsInvalid, userAuthenticated ? "false" : "true");
			UserSettings.Instance.set(UserSettingsKey.CredentialsInvalidReason, userAuthenticated ? "" : reason);

			CloudSyncStatusChanged.CallEvents(this, new CloudSyncEventArgs() { IsAuthenticated = userAuthenticated });

			// Only fire UserChanged if it actually happened - prevents runaway positive feedback loop
			if (!string.IsNullOrEmpty(AuthenticationData.Instance.ActiveSessionUsername)
				&& AuthenticationData.Instance.ActiveSessionUsername != AuthenticationData.Instance.LastSessionUsername)
			{
				// only set it if it is an actual user name
				AuthenticationData.Instance.LastSessionUsername = AuthenticationData.Instance.ActiveSessionUsername;
			}

			UserChanged();
		}

		// Called after every startup and at the completion of every authentication change
		public void UserChanged()
		{
			ProfileManager.ReloadActiveUser();

			// Ensure SQLite printers are imported
			ProfileManager.Instance.EnsurePrintersImported();

			var guest = ProfileManager.Load("guest");

			// If profiles.json was created, run the import wizard to pull in any SQLite printers
			if (guest?.Profiles?.Any() == true
				&& !ProfileManager.Instance.IsGuestProfile
				&& !ProfileManager.Instance.PrintersImported)
			{
				// Show the import printers wizard
				WizardWindow.Show<CopyGuestProfilesToUser>("/CopyGuestProfiles", "Copy Printers");
			}
		}

		public class CloudSyncEventArgs : EventArgs
		{
			public bool IsAuthenticated { get; set; }
		}

		public void OnLoadActions()
		{
			Load?.Invoke(this, null);

			// Pushing this after load fixes that empty printer list
			ApplicationController.Instance.UserChanged();

			if (!System.IO.File.Exists(@"/storage/sdcard0/Download/LaunchTestPrint.stl"))
			{
				bool showAuthWindow = WizardWindow.ShouldShowAuthPanel?.Invoke() ?? false;
                if (showAuthWindow)
                {
					if (ApplicationSettings.Instance.get(ApplicationSettingsKey.SuppressAuthPanel) != "True")
					{
						//Launch window to prompt user to sign in
						UiThread.RunOnIdle(() => WizardWindow.ShowPrinterSetup());
					}
                }
                else
                {
                    //If user in logged in sync before checking to prompt to create printer
                    if (ApplicationController.SyncPrinterProfiles == null)
                    {
                        RunSetupIfRequired();
                    }
                    else
                    {
                        ApplicationController.SyncPrinterProfiles.Invoke("ApplicationController.OnLoadActions()", null).ContinueWith((task) =>
                        {
                            RunSetupIfRequired();
                        });
                    }
                }

				if (OsInformation.OperatingSystem == OSType.Android)
				{
					// show this last so it is on top
					if (UserSettings.Instance.get("SoftwareLicenseAccepted") != "true")
					{
						UiThread.RunOnIdle(() => WizardWindow.Show<LicenseAgreementPage>("SoftwareLicense", "Software License Agreement"));
					}
				}
			}
			else
			{
				StartPrintingTest();
			}

			if (ActiveSliceSettings.Instance.PrinterSelected
				&& ActiveSliceSettings.Instance.GetValue<bool>(SettingsKey.auto_connect))
			{
				UiThread.RunOnIdle(() =>
				{
					//PrinterConnectionAndCommunication.Instance.HaltConnectionThread();
					PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter();
				}, 2);
			}
		}

        private static void RunSetupIfRequired()
        {
            ApplicationController.Instance.ReloadAdvancedControlsPanel();
            if (!ProfileManager.Instance.ActiveProfiles.Any())
            {
                // Start the setup wizard if no profiles exist
                UiThread.RunOnIdle(() => WizardWindow.ShowPrinterSetup());
            }
        }

        private EventHandler unregisterEvent;
		public void StartPrintingTest()
		{
			QueueData.Instance.RemoveAll();
			QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem("LaunchTestPrint", @"/storage/sdcard0/Download/LaunchTestPrint.stl")));
			PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter();

			PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent((sender, e) =>
			{
				if (PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Connected)
				{
					PrinterConnectionAndCommunication.Instance.PrintActivePartIfPossible();
				}
			}, ref unregisterEvent);
		}

		public void ReloadLibrarySelectorUI()
		{
			LibraryProviderSelector.Reload();
		}

		public void ReloadLibraryUI()
		{
			PrintLibraryWidget.Reload();
		}

		/// <summary>
		/// Download an image from the web into the specified ImageBuffer
		/// </summary>
		/// <param name="uri"></param>
		public void DownloadToImageAsync(ImageBuffer imageToLoadInto, string uriToLoad, bool scaleToImageX, IRecieveBlenderByte scalingBlender = null)
		{
			if (scalingBlender == null)
			{
				scalingBlender = new BlenderBGRA();
			}

			WebClient client = new WebClient();
			client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) =>
			{
				try // if we get a bad result we can get a target invocation exception. In that case just don't show anything
				{
					// scale the loaded image to the size of the target image
					byte[] raw = e.Result;
					Stream stream = new MemoryStream(raw);
					ImageBuffer unScaledImage = new ImageBuffer(10, 10);
					if (scaleToImageX)
					{
						StaticData.Instance.LoadImageData(stream, unScaledImage);
						// If the source image (the one we downloaded) is more than twice as big as our dest image.
						while (unScaledImage.Width > imageToLoadInto.Width * 2)
						{
							// The image sampler we use is a 2x2 filter so we need to scale by a max of 1/2 if we want to get good results.
							// So we scale as many times as we need to to get the Image to be the right size.
							// If this were going to be a non-uniform scale we could do the x and y separately to get better results.
							ImageBuffer halfImage = new ImageBuffer(unScaledImage.Width / 2, unScaledImage.Height / 2, 32, scalingBlender);
							halfImage.NewGraphics2D().Render(unScaledImage, 0, 0, 0, halfImage.Width / (double)unScaledImage.Width, halfImage.Height / (double)unScaledImage.Height);
							unScaledImage = halfImage;
						}

						double finalScale = imageToLoadInto.Width / (double)unScaledImage.Width;
						imageToLoadInto.Allocate(imageToLoadInto.Width, (int)(unScaledImage.Height * finalScale), imageToLoadInto.Width * (imageToLoadInto.BitDepth / 8), imageToLoadInto.BitDepth);
						imageToLoadInto.NewGraphics2D().Render(unScaledImage, 0, 0, 0, finalScale, finalScale);
					}
					else
					{
						StaticData.Instance.LoadImageData(stream, imageToLoadInto);
					}
					imageToLoadInto.MarkImageChanged();
				}
				catch
				{
				}
			};

			try
			{
				client.DownloadDataAsync(new Uri(uriToLoad));
			}
			catch
			{
			}
		}

	}

	public class SyncReportType
	{
		public string actionLabel;
		public double percComplete;
	}
}


text:
package com.twitter.util.jackson

import com.twitter.io.{Buf, ClasspathResource}
import com.twitter.util.Try
import java.io.{File, InputStream}

/**
 * Uses an instance of a [[ScalaObjectMapper]] configured to not perform any type of validation.
 * Inspired by [[https://www.scala-lang.org/api/2.12.6/scala-parser-combinators/scala/util/parsing/json/JSON$.html]].
 *
 * @note This is only intended for use from Scala (not Java).
 *
 * @see [[ScalaObjectMapper]]
 */
object JSON {
  private final val Mapper: ScalaObjectMapper =
    ScalaObjectMapper.builder.withNoValidation.objectMapper

  /** Simple utility to parse a JSON string into an Option[T] type. */
  def parse[T: Manifest](input: String): Option[T] =
    Try(Mapper.parse[T](input)).toOption

  /** Simple utility to parse a JSON [[Buf]] into an Option[T] type. */
  def parse[T: Manifest](input: Buf): Option[T] =
    Try(Mapper.parse[T](input)).toOption

  /**
   * Simple utility to parse a JSON [[InputStream]] into an Option[T] type.
   * @note the caller is responsible for managing the lifecycle of the given [[InputStream]].
   */
  def parse[T: Manifest](input: InputStream): Option[T] =
    Try(Mapper.parse[T](input)).toOption

  /**
   * Simple utility to load a JSON file and parse contents into an Option[T] type.
   *
   * @note the caller is responsible for managing the lifecycle of the given [[File]].
   */
  def parse[T: Manifest](f: File): Option[T] =
    Try(Mapper.underlying.readValue[T](f)).toOption

  /** Simple utility to write a value as a JSON encoded String. */
  def write(any: Any): String =
    Mapper.writeValueAsString(any)

  /** Simple utility to pretty print a JSON encoded String from the given instance. */
  def prettyPrint(any: Any): String =
    Mapper.writePrettyString(any)

  object Resource {

    /**
     * Simple utility to load a JSON resource from the classpath and parse contents into an Option[T] type.
     *
     * @note `name` resolution to locate the resource is governed by [[java.lang.Class#getResourceAsStream]]
     */
    def parse[T: Manifest](name: String): Option[T] = {
      ClasspathResource.load(name) match {
        case Some(inputStream) =>
          try {
            JSON.parse[T](inputStream)
          } finally {
            inputStream.close()
          }
        case _ => None
      }
    }
  }
}


text:
package com.codeborne.selenide.ex;

import org.assertj.core.api.WithAssertions;
import org.junit.jupiter.api.Test;

import java.util.List;

import static com.codeborne.selenide.Mocks.mockCollection;
import static java.util.Arrays.asList;

final class TextsSizeMismatchTest implements WithAssertions {
  private final List<String> actualTexts = asList("Niff", "Naff", "Nuff%");
  private final List<String> expectedTexts = asList("Piff", "Paff", "Puff'\"bro");

  @Test
  void errorMessage() {
    TextsSizeMismatch textsMismatch = new TextsSizeMismatch(mockCollection(".characters"),
      actualTexts,
      expectedTexts,
      null, 9000);

    assertThat(textsMismatch).hasMessage(String.format("Texts size mismatch%n" +
      "Actual: [Niff, Naff, Nuff%%], List size: 3%n" +
      "Expected: [Piff, Paff, Puff'\"bro], List size: 3%n" +
      "Collection: .characters%n" +
      "Timeout: 9 s."));
  }

  @Test
  void errorMessage_withExplanation() {
    TextsSizeMismatch textsMismatch = new TextsSizeMismatch(mockCollection(".characters"),
      actualTexts,
      expectedTexts,
      "we expect favorite characters", 9000);

    assertThat(textsMismatch).hasMessage(String.format("Texts size mismatch%n" +
      "Actual: [Niff, Naff, Nuff%%], List size: 3%n" +
      "Expected: [Piff, Paff, Puff'\"bro], List size: 3%n" +
      "Because: we expect favorite characters%n" +
      "Collection: .characters%n" +
      "Timeout: 9 s."));
  }
}


text:
Parse.Cloud.beforeSave("TestObject", function(request, response) {
  if (!request.object.get("foo")) {
    response.error("foo must be set");
  } else {
    response.success();
  }
});


text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <link href='https://fonts.googleapis.com/css?family=Chivo:900' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/github-dark.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">

    <title>angelteers</title>

Samantha的博客

          View on GitHub

世界平和

Knowing yourself is the height of wisdom!

So just be a happy person!

命运善妒,曾吝啬赋予世人恒久的平静,总猝不及防地把人一下子塞进过山车,任你怎么恐惧挣扎也不肯轻易停下来,非要把圆满的颠簸成支离破碎的,再命你耗尽半生去拼补。

          This page was generated by GitHub Pages. Tactile theme by Jason Long.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 103: 358 (2008)

#### Original name
Gymnopus amarus Murrill

### Remarks
null


text:
@interface MessageTextBubbleView : UIButton<MessageBubbleInterface>

@end


text:
VERSION  := 0.12.0rc1
TARGET   := node_exporter
GOFLAGS  := -ldflags "-X main.Version=$(VERSION)"

include Makefile.COMMON


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// serialization stuff
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using System.Runtime.Serialization;

namespace OpenAsset.RestClient.Library.Noun
{
    [JsonObject(MemberSerialization.OptIn)]
    public class User : Base.BaseNoun
    {
        #region private serializable properties
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore), BaseNounProperty]
        protected string username;
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore), BaseNounProperty]
        protected string full_name;
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore), BaseNounProperty]
        protected int? alive;
        // User Sharing extra values
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore), NestedNounProperty, VersionImplemented("8.1.11")]
        protected int? can_modify;
        #endregion

        #region Accessors
        public virtual string UserName
        {
            get { return username; }
            set { username = value; }
        }

        public virtual string FullName
        {
            get { return full_name; }
            set { full_name = value; }
        }

        public virtual bool Alive
        {
            get { return (alive ?? default(int)) != 0 ? true : false; }
            set { alive = value ? 1 : 0; }
        }

        public virtual bool CanModify
        {
            get { return can_modify != 0; }
            set { can_modify = value ? 1 : 0; }
        }
        #endregion
    }
}


text:
namespace System.Xml.Schema {

    using System.Text;
    using System.Collections;
    using System.Diagnostics;
    using System.Xml.XPath;
    using MS.Internal.Xml.XPath;

    internal class CompiledIdentityConstraint {
        internal XmlQualifiedName name = XmlQualifiedName.Empty;
        private ConstraintRole role;
        private Asttree selector;
        private Asttree[] fields;
        internal XmlQualifiedName refer = XmlQualifiedName.Empty;

        public enum ConstraintRole {
            Unique,
            Key,
            Keyref
        }

        public ConstraintRole Role {
            get { return this.role; }
        }

        public Asttree Selector {
            get { return this.selector; }
        }

        public Asttree[] Fields {
            get { return this.fields; }
        }

        public static readonly CompiledIdentityConstraint Empty = new CompiledIdentityConstraint();

        private CompiledIdentityConstraint() {}

        public CompiledIdentityConstraint(XmlSchemaIdentityConstraint constraint, XmlNamespaceManager nsmgr) {
            this.name = constraint.QualifiedName;

            //public Asttree (string xPath, bool isField, XmlNamespaceManager nsmgr)
            try {
                this.selector = new Asttree(constraint.Selector.XPath, false, nsmgr);
            }
            catch (XmlSchemaException e) {
                e.SetSource(constraint.Selector);
                throw e;
            }
            XmlSchemaObjectCollection fields = constraint.Fields;
            Debug.Assert(fields.Count > 0);
            this.fields = new Asttree[fields.Count];
            for(int idxField = 0; idxField < fields.Count; idxField ++) {
                try {
                    this.fields[idxField] = new Asttree(((XmlSchemaXPath)fields[idxField]).XPath, true, nsmgr);
                }
                catch (XmlSchemaException e) {
                    e.SetSource(constraint.Fields[idxField]);
                    throw e;
                }
            }
            if (constraint is XmlSchemaUnique) {
                this.role = ConstraintRole.Unique;
            }
            else if (constraint is XmlSchemaKey) {
                this.role = ConstraintRole.Key;
            }
            else {             // XmlSchemaKeyref
                this.role = ConstraintRole.Keyref;
                this.refer = ((XmlSchemaKeyref)constraint).Refer;
            }
        }
    }

}


text:
package eu.mosaic_cloud.platform.implementation.v2.configuration;

import eu.mosaic_cloud.platform.v2.configuration.Configuration;
import eu.mosaic_cloud.platform.v2.configuration.ConfigurationIdentifier;

/**
 * Utility functions used for handling configurations.
 *
 * @author Georgiana Macariu
 */
public final class ConfigUtils
{
	private ConfigUtils () {}

	/**
	 * Resolves a configuration parameter given its relative specification.
	 *
	 * @param <T>
	 *            the type of the parameter
	 * @param configuration
	 *            the configuration to which the parameter belongs
	 * @param identifier
	 *            the relative identifier of the parameter
	 * @param valueClass
	 *            the class object representing the type of the parameter
	 * @param defaultValue
	 *            a default value to give to the parameter if it is not found in the given configuration
	 * @return the value of the parameter
	 */
	public static <T extends Object> T resolveParameter (final Configuration configuration, final String identifier, final Class<T> valueClass, final T defaultValue) {
		T retValue;
		if (configuration == null) {
			retValue = defaultValue;
		} else {
			if (valueClass.isEnum ()) {
				final String retName = configuration.getParameter (ConfigurationIdentifier.resolveRelative (identifier), String.class).getValue (((Enum<?>) defaultValue).name ());
				retValue = (T) Enum.valueOf ((Class) valueClass, retName.toUpperCase ());
			} else {
				retValue = configuration.getParameter (ConfigurationIdentifier.resolveRelative (identifier), valueClass).getValue (defaultValue);
			}
		}
		return retValue;
	}
}


text:
"""
Test variable expansion of '<!()' syntax commands.
"""

import os

import TestGyp

test = TestGyp.TestGyp(format='gypd')

expect = test.read('commands.gyp.stdout')

# Set $HOME so that gyp doesn't read the user's actual
# ~/.gyp/include.gypi file, which may contain variables
# and other settings that would change the output.
os.environ['HOME'] = test.workpath()

test.run_gyp('commands.gyp',
             '--debug', 'variables', '--debug', 'general',
             stdout=expect)

# Verify the commands.gypd against the checked-in expected contents.
#
# Normally, we should canonicalize line endings in the expected
# contents file setting the Subversion svn:eol-style to native,
# but that would still fail if multiple systems are sharing a single
# workspace on a network-mounted file system.  Consequently, we
# massage the Windows line endings ('\r\n') in the output to the
# checked-in UNIX endings ('\n').

contents = test.read('commands.gypd').replace('\r\n', '\n')
expect = test.read('commands.gypd.golden')
if not test.match(contents, expect):
  print "Unexpected contents of `commands.gypd'"
  self.diff(expect, contents, 'commands.gypd ')
  test.fail_test()

test.pass_test()


text:
#ifndef AVCODEC_MSRLEDEC_H
#define AVCODEC_MSRLEDEC_H

#include "avcodec.h"
#include "bytestream.h"

/**
 * Decode stream in MS RLE format into frame.
 *
 * @param avctx     codec context
 * @param pic       destination frame
 * @param depth     bit depth
 * @param gb        input bytestream context
 */
int ff_msrle_decode(AVCodecContext *avctx, AVPicture *pic,
                    int depth, GetByteContext *gb);

#endif /* AVCODEC_MSRLEDEC_H */


text:
package org.usfirst.frc.team2141.robot.commands;

import org.usfirst.frc.team2141.robot.Robot;

import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class Elevator_ShiftDown extends Command {

	public Elevator_ShiftDown() {
		// Use requires() here to declare subsystem dependencies
		// eg. requires(chassis);
		requires(Robot.pneumatics);
	}

	// Called just before this Command runs the first time
	protected void initialize() {
	}

	// Called repeatedly when this Command is scheduled to run
	protected void execute() {
		Robot.pneumatics.setGearboxToLow();
	}

	// Make this return true when this Command no longer needs to run execute()
	protected boolean isFinished() {
		return true;
	}

	// Called once after isFinished returns true
	protected void end() {

	}

	// Called when another command which requires one or more of the same
	// subsystems is scheduled to run
	protected void interrupted() {
	}
}


text:
#ifndef CLUSTERREDUCTIONINSTANCE_H
#define CLUSTERREDUCTIONINSTANCE_H

#define NUMBER_OF_REDUCTION_RULES 6

#include "ClusterEditingInstance.h"
#include "CplexInformer.h"
#include "Globals.h"
#include "WorkingCopyInstance.h"

#include "reductionRules/HeavyEdgeRule3in1.h"
#include "reductionRules/CriticalCliqueRule.h"
#include "reductionRules/AlmostCliqueRule.h"
#include "reductionRules/SimilarNeighborhoodRule.h"
#include "reductionRules/MergingRule.h"
#include "reductionRules/ParameterDependentReductionRule.h"
#include "reductionRules/CliqueRule.h"

#include <lemon/connectivity.h>

#include <iostream>
#include <bitset>

namespace ysk {

class ClusterReductionInstance {
public:
  ClusterReductionInstance(ClusterEditingInstance* inst,
                           std::bitset<NUMBER_OF_REDUCTION_RULES> active,
                           double multiplicativeFactor,
                           bool conserveMultipleSolutions)
    : _lastSuccessRule(-1)
    , _currentRule(0)
    , _instance(inst)
    , _active(active)
    , _multiplicativeFactor(multiplicativeFactor)
    , _conserveMultipleSolutions(conserveMultipleSolutions)
  {
  }

  int applyReductionRules(yskLib::CplexInformer* informer);

  ClusterEditingInstance* getInstance();

  int computeConnectedComponents(WorkingCopyGraph::NodeMap<int>& connectedComps);

  void computeChildInstances(std::vector<ClusterReductionInstance*>& childInstances);

  bool operator < (const ClusterReductionInstance& c) const{ return (_instance->getSize() < c._instance->getSize());}

private:
  int _lastSuccessRule;
  int _currentRule;
  ClusterEditingInstance* _instance;
  std::bitset<NUMBER_OF_REDUCTION_RULES> _active;
  double _multiplicativeFactor;
  bool _conserveMultipleSolutions;

};

} // namespace ysk

#endif /* CLUSTERREDUCTIONINSTANCE_H */


text:
#ifndef __EventMachine__H_
#define __EventMachine__H_

#ifdef BUILD_FOR_RUBY
  #include <ruby.h>
  #ifdef HAVE_RB_THREAD_FD_SELECT
    #define EmSelect rb_thread_fd_select
  #else
    // ruby 1.9.1 and below
    #define EmSelect rb_thread_select
  #endif

  #ifdef HAVE_RB_THREAD_CALL_WITHOUT_GVL
   #include <ruby/thread.h>
  #endif

  #ifdef HAVE_RB_WAIT_FOR_SINGLE_FD
    #include <ruby/io.h>
  #endif

  #if defined(HAVE_RBTRAP)
    #include <rubysig.h>
  #elif defined(HAVE_RB_ENABLE_INTERRUPT)
    extern "C" {
      void rb_enable_interrupt(void);
      void rb_disable_interrupt(void);
    }

    #define TRAP_BEG rb_enable_interrupt()
    #define TRAP_END do { rb_disable_interrupt(); rb_thread_check_ints(); } while(0)
  #else
    #define TRAP_BEG
    #define TRAP_END
  #endif

  // 1.9.0 compat
  #ifndef RUBY_UBF_IO
    #define RUBY_UBF_IO RB_UBF_DFL
  #endif
  #ifndef RSTRING_PTR
    #define RSTRING_PTR(str) RSTRING(str)->ptr
  #endif
  #ifndef RSTRING_LEN
    #define RSTRING_LEN(str) RSTRING(str)->len
  #endif
  #ifndef RSTRING_LENINT
    #define RSTRING_LENINT(str) RSTRING_LEN(str)
  #endif
#else
  #define EmSelect select
#endif

#if !defined(HAVE_RB_FDSET_T)
#define fd_check(n) (((n) < FD_SETSIZE) ? 1 : 0*fprintf(stderr, "fd %d too large for select\n", (n)))
// These definitions are cribbed from include/ruby/intern.h in Ruby 1.9.3,
// with this change: any macros that read or write the nth element of an
// fdset first call fd_check to make sure n is in bounds.
typedef fd_set rb_fdset_t;
#define rb_fd_zero(f) FD_ZERO(f)
#define rb_fd_set(n, f) do { if (fd_check(n)) FD_SET((n), (f)); } while(0)
#define rb_fd_clr(n, f) do { if (fd_check(n)) FD_CLR((n), (f)); } while(0)
#define rb_fd_isset(n, f) (fd_check(n) ? FD_ISSET((n), (f)) : 0)
#define rb_fd_copy(d, s, n) (*(d) = *(s))
#define rb_fd_dup(d, s) (*(d) = *(s))
#define rb_fd_resize(n, f)  ((void)(f))
#define rb_fd_ptr(f)  (f)
#define rb_fd_init(f) FD_ZERO(f)
#define rb_fd_init_copy(d, s) (*(d) = *(s))
#define rb_fd_term(f) ((void)(f))
#define rb_fd_max(f)  FD_SETSIZE
#define rb_fd_select(n, rfds, wfds, efds, timeout)  \
  select(fd_check((n)-1) ? (n) : FD_SETSIZE, (rfds), (wfds), (efds), (timeout))
#define rb_thread_fd_select(n, rfds, wfds, efds, timeout)  \
  rb_thread_select(fd_check((n)-1) ? (n) : FD_SETSIZE, (rfds), (wfds), (efds), (timeout))
#endif

class EventableDescriptor;
class InotifyDescriptor;
struct SelectData_t;

/********************
class EventMachine_t
********************/

class EventMachine_t
{
	public:
		static int GetMaxTimerCount();
		static void SetMaxTimerCount (int);

		static int GetSimultaneousAcceptCount();
		static void SetSimultaneousAcceptCount (int);

	public:
		EventMachine_t (EMCallback);
		virtual ~EventMachine_t();

		void Run();
		void ScheduleHalt();
		void SignalLoopBreaker();
		const unsigned long InstallOneshotTimer (int);
		const unsigned long ConnectToServer (const char *, int, const char *, int);
		const unsigned long ConnectToUnixServer (const char *);

		const unsigned long CreateTcpServer (const char *, int);
		const unsigned long OpenDatagramSocket (const char *, int);
		const unsigned long CreateUnixDomainServer (const char*);
		const unsigned long AttachSD (int);
		const unsigned long OpenKeyboard();
		//const char *Popen (const char*, const char*);
		const unsigned long Socketpair (char* const*);

		void Add (EventableDescriptor*);
		void Modify (EventableDescriptor*);
		void Deregister (EventableDescriptor*);

		const unsigned long AttachFD (int, bool);
		int DetachFD (EventableDescriptor*);

		void ArmKqueueWriter (EventableDescriptor*);
		void ArmKqueueReader (EventableDescriptor*);

		void SetTimerQuantum (int);
		static void SetuidString (const char*);
		static int SetRlimitNofile (int);

		pid_t SubprocessPid;
		int SubprocessExitStatus;

		int GetConnectionCount();
		float GetHeartbeatInterval();
		int SetHeartbeatInterval(float);

		const unsigned long WatchFile (const char*);
		void UnwatchFile (int);
		void UnwatchFile (const unsigned long);

		#ifdef HAVE_KQUEUE
		void _HandleKqueueFileEvent (struct kevent*);
		void _RegisterKqueueFileEvent(int);
		#endif

		const unsigned long WatchPid (int);
		void UnwatchPid (int);
		void UnwatchPid (const unsigned long);

		#ifdef HAVE_KQUEUE
		void _HandleKqueuePidEvent (struct kevent*);
		#endif

		uint64_t GetCurrentLoopTime() { return MyCurrentLoopTime; }

		// Temporary:
		void _UseEpoll();
		void _UseKqueue();

		bool UsingKqueue() { return bKqueue; }
		bool UsingEpoll() { return bEpoll; }

		void QueueHeartbeat(EventableDescriptor*);
		void ClearHeartbeat(uint64_t, EventableDescriptor*);

		uint64_t GetRealTime();

	private:
		void _RunOnce();
		void _RunTimers();
		void _UpdateTime();
		void _AddNewDescriptors();
		void _ModifyDescriptors();
		void _InitializeLoopBreaker();
		void _CleanupSockets();

		void _RunSelectOnce();
		void _RunEpollOnce();
		void _RunKqueueOnce();

		void _ModifyEpollEvent (EventableDescriptor*);
		void _DispatchHeartbeats();
		timeval _TimeTilNextEvent();
		void _CleanBadDescriptors();

	public:
		void _ReadLoopBreaker();
		void _ReadInotifyEvents();
		int NumCloseScheduled;

	private:
		enum {
			MaxEpollDescriptors = 64*1024,
			MaxEvents = 4096
		};
		int HeartbeatInterval;
		EMCallback EventCallback;

		class Timer_t: public Bindable_t {
		};

		multimap<uint64_t, Timer_t> Timers;
		multimap<uint64_t, EventableDescriptor*> Heartbeats;
		map<int, Bindable_t*> Files;
		map<int, Bindable_t*> Pids;
		vector<EventableDescriptor*> Descriptors;
		vector<EventableDescriptor*> NewDescriptors;
		set<EventableDescriptor*> ModifiedDescriptors;

		uint64_t NextHeartbeatTime;

		int LoopBreakerReader;
		int LoopBreakerWriter;
		#ifdef OS_WIN32
		struct sockaddr_in LoopBreakerTarget;
		#endif

		timeval Quantum;

		uint64_t MyCurrentLoopTime;

		#ifdef OS_WIN32
		unsigned TickCountTickover;
		unsigned LastTickCount;
		#endif

		#ifdef OS_DARWIN
		mach_timebase_info_data_t mach_timebase;
		#endif

	private:
		bool bTerminateSignalReceived;
		SelectData_t *SelectData;

		bool bEpoll;
		int epfd; // Epoll file-descriptor
		#ifdef HAVE_EPOLL
		struct epoll_event epoll_events [MaxEvents];
		#endif

		bool bKqueue;
		int kqfd; // Kqueue file-descriptor
		#ifdef HAVE_KQUEUE
		struct kevent Karray [MaxEvents];
		#endif

		InotifyDescriptor *inotify; // pollable descriptor for our inotify instance
};

/*******************
struct SelectData_t
*******************/

struct SelectData_t
{
	SelectData_t();
	~SelectData_t();

	int _Select();
	void _Clear();

	int maxsocket;
	rb_fdset_t fdreads;
	rb_fdset_t fdwrites;
	rb_fdset_t fderrors;
	timeval tv;
	int nSockets;
};

#endif // __EventMachine__H_


text:
$( document ).ready( function()
{
	if ( $( '#isRunning' ).val() == 'true' )
	{
		$( '.scheduling' ).attr( 'disabled', 'disabled' );
	}
	else
	{
		$( '.scheduling' ).removeAttr( 'disabled' );
	}

	if ( $( '#dataMartStrategy' ).val() == 'disabled' )
	{
		$( '.dataMart' ).attr( 'disabled', 'disabled' );
	}
} );

function submitSchedulingForm()
{
	$( '.scheduling' ).removeAttr( 'disabled' );
	$( '#schedulingForm' ).submit();
}

function toggleDataMart()
{
	if ( $( '#dataMartStrategy' ).val() == 'never' )
	{
		$( '.dataMart' ).attr( 'disabled', 'disabled' );
	}
	else
	{
		$( '.dataMart' ).removeAttr( 'disabled' );
	}
}

function toggleMoreOptions()
{
	$( "#moreOptionsLink" ).toggle();
	$( "#moreOptionsDiv" ).toggle();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="@color/skyblue" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <solid android:color="@color/skyblue" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <stroke android:width="2dp" android:color="@color/white" />
        </shape>
    </item>
</selector>


text:
//============================================================================
//
// Copyright (C) 2006-2022 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
//============================================================================
package org.talend.components.common.datastore;

import org.talend.daikon.properties.Properties;

/**
 * Placeholder for DatastoreProperties.
 */
public interface DatastoreProperties extends Properties {
}


text:
"""form base classes for aloha-editor integration"""

import floppyforms as forms

from djaloha.widgets import AlohaInput
from django.utils.encoding import smart_unicode

class DjalohaForm(forms.Form):
    """Base class for form with aloha editor"""

    def __init__(self, model_class, lookup, field_name, data=None, field_value=None, *args, **kwargs):
        super(DjalohaForm, self).__init__(data, *args, **kwargs)

        self._model_class = model_class
        self._lookup = lookup
        self._field_name = field_name

        model_name = "__".join(
            (model_class.__module__.split('.')[-2], model_class.__name__)
        )

        lookup_str = "__".join([k + "__" + unicode(v).strip('"\'') for (k, v) in lookup.items()])

        self._form_field = "__".join(
            ("djaloha", model_name, lookup_str, field_name)
        )

        self.fields[self._form_field] = forms.CharField(
            required=False,
            initial=field_value,
            widget=AlohaInput()
        )

    def save(self):
        """save associated object"""
        value = smart_unicode(self.cleaned_data[self._form_field])
        obj = self._model_class.objects.get_or_create(**self._lookup)[0]
        setattr(obj, self._field_name, value)
        obj.save()

    def as_is(self):
        """return html without parent tag"""
        return self._html_output(
            normal_row=u'%(field)s',
            error_row=u'%s',
            row_ender='',
            help_text_html=u'',
            errors_on_separate_row=True
        )


text:
var should = typeof require == 'function' ? require('should') : window.should;
var $ = typeof require == 'function' ? require('../dollar.template') : window.$;

describe('dollar.template', function() {
  it('interpolate', function() {
    var compiled = $.template('hello <%= name %>!');

    var result = compiled({name: 'moe'});
    result.should.equal('hello moe!');
  });

  it('escape', function() {
    var template = $.template('<%- value %>');

    var result = template({value: '


text:
namespace blink {

class LayoutPoint;
class LayoutTableCell;
class LayoutTableSection;
struct PaintInfo;

class TableSectionPainter {
public:
    TableSectionPainter(LayoutTableSection& layoutTableSection) : m_layoutTableSection(layoutTableSection) { }

    void paint(const PaintInfo&, const LayoutPoint&);

private:
    void paintObject(const PaintInfo&, const LayoutPoint&);
    void paintCell(LayoutTableCell*, const PaintInfo&, const LayoutPoint&);

    LayoutTableSection& m_layoutTableSection;
};

} // namespace blink

#endif // TableSectionPainter_h


text:
<APIProxy revision="1" name="xmltojson">
</APIProxy>


text:
using System;
using System.Text.Json;
using Azure.Core;

namespace Azure.Communication.ShortCodes.Models
{
    public partial class CompanyInformation : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            if (Optional.IsDefined(Url))
            {
                writer.WritePropertyName("url");
                writer.WriteStringValue(Url.AbsoluteUri);
            }
            if (Optional.IsDefined(Address))
            {
                writer.WritePropertyName("address");
                writer.WriteStringValue(Address);
            }
            if (Optional.IsDefined(ContactInformation))
            {
                writer.WritePropertyName("contactInformation");
                writer.WriteObjectValue(ContactInformation);
            }
            if (Optional.IsDefined(CustomerCareInformation))
            {
                writer.WritePropertyName("customerCareInformation");
                writer.WriteObjectValue(CustomerCareInformation);
            }
            writer.WriteEndObject();
        }

        internal static CompanyInformation DeserializeCompanyInformation(JsonElement element)
        {
            Optional<string> name = default;
            Optional<Uri> url = default;
            Optional<string> address = default;
            Optional<ContactInformation> contactInformation = default;
            Optional<CustomerCareInformation> customerCareInformation = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("url"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    url = new Uri(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("address"))
                {
                    address = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("contactInformation"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    contactInformation = ContactInformation.DeserializeContactInformation(property.Value);
                    continue;
                }
                if (property.NameEquals("customerCareInformation"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    customerCareInformation = CustomerCareInformation.DeserializeCustomerCareInformation(property.Value);
                    continue;
                }
            }
            return new CompanyInformation(name.Value, url.Value, address.Value, contactInformation.Value, customerCareInformation.Value);
        }
    }
}


text:
public class Test {

    public Object get() {
        return new Object() {
            public boolean equals(Object obj) {
                return someMethod(this);
            }

            private boolean someMethod(Object o) {
                <selection>return false;  //To change body of created methods use File | Settings | File Templates.<caret></selection>
            }
        };
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Weapons
{
    public class Sight : WeaponAccessory
    {
        public Sight(Weapon weapon)
            : base(weapon)
        {
            this.Weapon.Price += 100;
            this.Weapon.Weight += 0.100;
        }

        public override string Describe()
        {
            return base.Describe();
        }
    }
}


text:
package com.jin.uitoolkit.util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

public class PixelUtil {
    private static int screenWidth = 0;
    private static int screenHeight = 0;

    public static int dp2px(Context context, float value) {
        final float scale = context.getResources().getDisplayMetrics().densityDpi;
        return (int) (value * (scale / 160) + 0.5f);
    }

    public static int px2dp(Context context, float value) {
        final float scale = context.getResources().getDisplayMetrics().densityDpi;
        return (int) ((value * 160) / scale + 0.5f);
    }

    public static int sp2px(Context context, float value) {
        Resources r;
        if (context == null) {
            r = Resources.getSystem();
        } else {
            r = context.getResources();
        }
        float spvalue = value * r.getDisplayMetrics().scaledDensity;
        return (int) (spvalue + 0.5f);
    }

    public static int px2sp(Context context, float value) {
        final float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (value / scale + 0.5f);
    }

    public static int getScreenHeight(Context c) {
        if (screenHeight == 0) {
            WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            screenHeight = size.y;
        }

        return screenHeight;
    }

    public static int getScreenWidth(Context c) {
        if (screenWidth == 0) {
            WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            screenWidth = size.x;
        }

        return screenWidth;
    }

    public static Point getScreenMetrics(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int h_screen = dm.heightPixels;
        return new Point(w_screen, h_screen);

    }
}


text:
try:
    import ujson as json
except ImportError:
    import json  # type: ignore[no-redef]

from base64 import b64decode
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, no_type_check

try:
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric.padding import MGF1, OAEP
    from cryptography.hazmat.primitives.ciphers import Cipher
    from cryptography.hazmat.primitives.ciphers.algorithms import AES
    from cryptography.hazmat.primitives.ciphers.modes import CBC
    from cryptography.hazmat.primitives.hashes import SHA1, SHA256, SHA512, Hash

    CRYPTO_INSTALLED = True
except ImportError:
    default_backend = None
    MGF1, OAEP, Cipher, AES, CBC = (None, None, None, None, None)  # type: ignore[misc]
    SHA1, SHA256, SHA512, Hash = (None, None, None, None)  # type: ignore[misc]

    CRYPTO_INSTALLED = False

from telegram import TelegramError, TelegramObject
from telegram.utils.types import JSONDict

if TYPE_CHECKING:
    from telegram import Bot

class TelegramDecryptionError(TelegramError):
    """Something went wrong with decryption."""

    __slots__ = ('_msg',)

    def __init__(self, message: Union[str, Exception]):
        super().__init__(f"TelegramDecryptionError: {message}")
        self._msg = str(message)

    def __reduce__(self) -> Tuple[type, Tuple[str]]:
        return self.__class__, (self._msg,)

@no_type_check
def decrypt(secret, hash, data):
    """
    Decrypt per telegram docs at https://core.telegram.org/passport.

    Args:
        secret (:obj:`str` or :obj:`bytes`): The encryption secret, either as bytes or as a
            base64 encoded string.
        hash (:obj:`str` or :obj:`bytes`): The hash, either as bytes or as a
            base64 encoded string.
        data (:obj:`str` or :obj:`bytes`): The data to decrypt, either as bytes or as a
            base64 encoded string.
        file (:obj:`bool`): Force data to be treated as raw data, instead of trying to
            b64decode it.

    Raises:
        :class:`TelegramDecryptionError`: Given hash does not match hash of decrypted data.

    Returns:
        :obj:`bytes`: The decrypted data as bytes.

    """
    if not CRYPTO_INSTALLED:
        raise RuntimeError(
            'To use Telegram Passports, PTB must be installed via `pip install '
            'python-telegram-bot[passport]`.'
        )
    # Make a SHA512 hash of secret + update
    digest = Hash(SHA512(), backend=default_backend())
    digest.update(secret + hash)
    secret_hash_hash = digest.finalize()
    # First 32 chars is our key, next 16 is the initialisation vector
    key, init_vector = secret_hash_hash[:32], secret_hash_hash[32 : 32 + 16]
    # Init a AES-CBC cipher and decrypt the data
    cipher = Cipher(AES(key), CBC(init_vector), backend=default_backend())
    decryptor = cipher.decryptor()
    data = decryptor.update(data) + decryptor.finalize()
    # Calculate SHA256 hash of the decrypted data
    digest = Hash(SHA256(), backend=default_backend())
    digest.update(data)
    data_hash = digest.finalize()
    # If the newly calculated hash did not match the one telegram gave us
    if data_hash != hash:
        # Raise a error that is caught inside telegram.PassportData and transformed into a warning
        raise TelegramDecryptionError(f"Hashes are not equal! {data_hash} != {hash}")
    # Return data without padding
    return data[data[0] :]

@no_type_check
def decrypt_json(secret, hash, data):
    """Decrypts data using secret and hash and then decodes utf-8 string and loads json"""
    return json.loads(decrypt(secret, hash, data).decode('utf-8'))

class EncryptedCredentials(TelegramObject):
    """Contains data required for decrypting and authenticating EncryptedPassportElement. See the
    Telegram Passport Documentation for a complete description of the data decryption and
    authentication processes.

    Objects of this class are comparable in terms of equality. Two objects of this class are
    considered equal, if their :attr:`data`, :attr:`hash` and :attr:`secret` are equal.

    Note:
        This object is decrypted only when originating from
        :obj:`telegram.PassportData.decrypted_credentials`.

    Args:
        data (:class:`telegram.Credentials` or :obj:`str`): Decrypted data with unique user's
            nonce, data hashes and secrets used for EncryptedPassportElement decryption and
            authentication or base64 encrypted data.
        hash (:obj:`str`): Base64-encoded data hash for data authentication.
        secret (:obj:`str`): Decrypted or encrypted secret used for decryption.
        **kwargs (:obj:`dict`): Arbitrary keyword arguments.

    Attributes:
        data (:class:`telegram.Credentials` or :obj:`str`): Decrypted data with unique user's
            nonce, data hashes and secrets used for EncryptedPassportElement decryption and
            authentication or base64 encrypted data.
        hash (:obj:`str`): Base64-encoded data hash for data authentication.
        secret (:obj:`str`): Decrypted or encrypted secret used for decryption.

    """

    __slots__ = (
        'hash',
        'secret',
        'bot',
        'data',
        '_id_attrs',
        '_decrypted_secret',
        '_decrypted_data',
    )

    def __init__(self, data: str, hash: str, secret: str, bot: 'Bot' = None, **_kwargs: Any):
        # Required
        self.data = data
        self.hash = hash
        self.secret = secret

        self._id_attrs = (self.data, self.hash, self.secret)

        self.bot = bot
        self._decrypted_secret = None
        self._decrypted_data: Optional['Credentials'] = None

    @property
    def decrypted_secret(self) -> str:
        """
        :obj:`str`: Lazily decrypt and return secret.

        Raises:
            telegram.TelegramDecryptionError: Decryption failed. Usually due to bad
                private/public key but can also suggest malformed/tampered data.
        """
        if self._decrypted_secret is None:
            if not CRYPTO_INSTALLED:
                raise RuntimeError(
                    'To use Telegram Passports, PTB must be installed via `pip install '
                    'python-telegram-bot[passport]`.'
                )
            # Try decrypting according to step 1 at
            # https://core.telegram.org/passport#decrypting-data
            # We make sure to base64 decode the secret first.
            # Telegram says to use OAEP padding so we do that. The Mask Generation Function
            # is the default for OAEP, the algorithm is the default for PHP which is what
            # Telegram's backend servers run.
            try:
                self._decrypted_secret = self.bot.private_key.decrypt(
                    b64decode(self.secret),
                    OAEP(mgf=MGF1(algorithm=SHA1()), algorithm=SHA1(), label=None),  # skipcq
                )
            except ValueError as exception:
                # If decryption fails raise exception
                raise TelegramDecryptionError(exception) from exception
        return self._decrypted_secret

    @property
    def decrypted_data(self) -> 'Credentials':
        """
        :class:`telegram.Credentials`: Lazily decrypt and return credentials data. This object
            also contains the user specified nonce as
            `decrypted_data.nonce`.

        Raises:
            telegram.TelegramDecryptionError: Decryption failed. Usually due to bad
                private/public key but can also suggest malformed/tampered data.
        """
        if self._decrypted_data is None:
            self._decrypted_data = Credentials.de_json(
                decrypt_json(self.decrypted_secret, b64decode(self.hash), b64decode(self.data)),
                self.bot,
            )
        return self._decrypted_data

class Credentials(TelegramObject):
    """
    Attributes:
        secure_data (:class:`telegram.SecureData`): Credentials for encrypted data
        nonce (:obj:`str`): Bot-specified nonce
    """

    __slots__ = ('bot', 'nonce', 'secure_data')

    def __init__(self, secure_data: 'SecureData', nonce: str, bot: 'Bot' = None, **_kwargs: Any):
        # Required
        self.secure_data = secure_data
        self.nonce = nonce

        self.bot = bot

    @classmethod
    def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['Credentials']:
        """See :meth:`telegram.TelegramObject.de_json`."""
        data = cls._parse_data(data)

        if not data:
            return None

        data['secure_data'] = SecureData.de_json(data.get('secure_data'), bot=bot)

        return cls(bot=bot, **data)

class SecureData(TelegramObject):
    """
    This object represents the credentials that were used to decrypt the encrypted data.
    All fields are optional and depend on fields that were requested.

    Attributes:
        personal_details (:class:`telegram.SecureValue`, optional): Credentials for encrypted
            personal details.
        passport (:class:`telegram.SecureValue`, optional): Credentials for encrypted passport.
        internal_passport (:class:`telegram.SecureValue`, optional): Credentials for encrypted
            internal passport.
        driver_license (:class:`telegram.SecureValue`, optional): Credentials for encrypted
            driver license.
        identity_card (:class:`telegram.SecureValue`, optional): Credentials for encrypted ID card
        address (:class:`telegram.SecureValue`, optional): Credentials for encrypted
            residential address.
        utility_bill (:class:`telegram.SecureValue`, optional): Credentials for encrypted
            utility bill.
        bank_statement (:class:`telegram.SecureValue`, optional): Credentials for encrypted
            bank statement.
        rental_agreement (:class:`telegram.SecureValue`, optional): Credentials for encrypted
            rental agreement.
        passport_registration (:class:`telegram.SecureValue`, optional): Credentials for encrypted
            registration from internal passport.
        temporary_registration (:class:`telegram.SecureValue`, optional): Credentials for encrypted
            temporary registration.
    """

    __slots__ = (
        'bot',
        'utility_bill',
        'personal_details',
        'temporary_registration',
        'address',
        'driver_license',
        'rental_agreement',
        'internal_passport',
        'identity_card',
        'bank_statement',
        'passport',
        'passport_registration',
    )

    def __init__(
        self,
        personal_details: 'SecureValue' = None,
        passport: 'SecureValue' = None,
        internal_passport: 'SecureValue' = None,
        driver_license: 'SecureValue' = None,
        identity_card: 'SecureValue' = None,
        address: 'SecureValue' = None,
        utility_bill: 'SecureValue' = None,
        bank_statement: 'SecureValue' = None,
        rental_agreement: 'SecureValue' = None,
        passport_registration: 'SecureValue' = None,
        temporary_registration: 'SecureValue' = None,
        bot: 'Bot' = None,
        **_kwargs: Any,
    ):
        # Optionals
        self.temporary_registration = temporary_registration
        self.passport_registration = passport_registration
        self.rental_agreement = rental_agreement
        self.bank_statement = bank_statement
        self.utility_bill = utility_bill
        self.address = address
        self.identity_card = identity_card
        self.driver_license = driver_license
        self.internal_passport = internal_passport
        self.passport = passport
        self.personal_details = personal_details

        self.bot = bot

    @classmethod
    def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['SecureData']:
        """See :meth:`telegram.TelegramObject.de_json`."""
        data = cls._parse_data(data)

        if not data:
            return None

        data['temporary_registration'] = SecureValue.de_json(
            data.get('temporary_registration'), bot=bot
        )
        data['passport_registration'] = SecureValue.de_json(
            data.get('passport_registration'), bot=bot
        )
        data['rental_agreement'] = SecureValue.de_json(data.get('rental_agreement'), bot=bot)
        data['bank_statement'] = SecureValue.de_json(data.get('bank_statement'), bot=bot)
        data['utility_bill'] = SecureValue.de_json(data.get('utility_bill'), bot=bot)
        data['address'] = SecureValue.de_json(data.get('address'), bot=bot)
        data['identity_card'] = SecureValue.de_json(data.get('identity_card'), bot=bot)
        data['driver_license'] = SecureValue.de_json(data.get('driver_license'), bot=bot)
        data['internal_passport'] = SecureValue.de_json(data.get('internal_passport'), bot=bot)
        data['passport'] = SecureValue.de_json(data.get('passport'), bot=bot)
        data['personal_details'] = SecureValue.de_json(data.get('personal_details'), bot=bot)

        return cls(bot=bot, **data)

class SecureValue(TelegramObject):
    """
    This object represents the credentials that were used to decrypt the encrypted value.
    All fields are optional and depend on the type of field.

    Attributes:
        data (:class:`telegram.DataCredentials`, optional): Credentials for encrypted Telegram
            Passport data. Available for "personal_details", "passport", "driver_license",
            "identity_card", "identity_passport" and "address" types.
        front_side (:class:`telegram.FileCredentials`, optional): Credentials for encrypted
            document's front side. Available for "passport", "driver_license", "identity_card"
            and "internal_passport".
        reverse_side (:class:`telegram.FileCredentials`, optional): Credentials for encrypted
            document's reverse side. Available for "driver_license" and "identity_card".
        selfie (:class:`telegram.FileCredentials`, optional): Credentials for encrypted selfie
            of the user with a document. Can be available for "passport", "driver_license",
            "identity_card" and "internal_passport".
        translation (List[:class:`telegram.FileCredentials`], optional): Credentials for an
            encrypted translation of the document. Available for "passport", "driver_license",
            "identity_card", "internal_passport", "utility_bill", "bank_statement",
            "rental_agreement", "passport_registration" and "temporary_registration".
        files (List[:class:`telegram.FileCredentials`], optional): Credentials for encrypted
            files. Available for "utility_bill", "bank_statement", "rental_agreement",
            "passport_registration" and "temporary_registration" types.

    """

    __slots__ = ('data', 'front_side', 'reverse_side', 'selfie', 'files', 'translation', 'bot')

    def __init__(
        self,
        data: 'DataCredentials' = None,
        front_side: 'FileCredentials' = None,
        reverse_side: 'FileCredentials' = None,
        selfie: 'FileCredentials' = None,
        files: List['FileCredentials'] = None,
        translation: List['FileCredentials'] = None,
        bot: 'Bot' = None,
        **_kwargs: Any,
    ):
        self.data = data
        self.front_side = front_side
        self.reverse_side = reverse_side
        self.selfie = selfie
        self.files = files
        self.translation = translation

        self.bot = bot

    @classmethod
    def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['SecureValue']:
        """See :meth:`telegram.TelegramObject.de_json`."""
        data = cls._parse_data(data)

        if not data:
            return None

        data['data'] = DataCredentials.de_json(data.get('data'), bot=bot)
        data['front_side'] = FileCredentials.de_json(data.get('front_side'), bot=bot)
        data['reverse_side'] = FileCredentials.de_json(data.get('reverse_side'), bot=bot)
        data['selfie'] = FileCredentials.de_json(data.get('selfie'), bot=bot)
        data['files'] = FileCredentials.de_list(data.get('files'), bot=bot)
        data['translation'] = FileCredentials.de_list(data.get('translation'), bot=bot)

        return cls(bot=bot, **data)

    def to_dict(self) -> JSONDict:
        """See :meth:`telegram.TelegramObject.to_dict`."""
        data = super().to_dict()

        data['files'] = [p.to_dict() for p in self.files]
        data['translation'] = [p.to_dict() for p in self.translation]

        return data

class _CredentialsBase(TelegramObject):
    """Base class for DataCredentials and FileCredentials."""

    __slots__ = ('hash', 'secret', 'file_hash', 'data_hash', 'bot')

    def __init__(self, hash: str, secret: str, bot: 'Bot' = None, **_kwargs: Any):
        self.hash = hash
        self.secret = secret

        # Aliases just be be sure
        self.file_hash = self.hash
        self.data_hash = self.hash

        self.bot = bot

class DataCredentials(_CredentialsBase):
    """
    These credentials can be used to decrypt encrypted data from the data field in
    EncryptedPassportData.

    Args:
        data_hash (:obj:`str`): Checksum of encrypted data
        secret (:obj:`str`): Secret of encrypted data

    Attributes:
        hash (:obj:`str`): Checksum of encrypted data
        secret (:obj:`str`): Secret of encrypted data
    """

    __slots__ = ()

    def __init__(self, data_hash: str, secret: str, **_kwargs: Any):
        super().__init__(data_hash, secret, **_kwargs)

    def to_dict(self) -> JSONDict:
        """See :meth:`telegram.TelegramObject.to_dict`."""
        data = super().to_dict()

        del data['file_hash']
        del data['hash']

        return data

class FileCredentials(_CredentialsBase):
    """
    These credentials can be used to decrypt encrypted files from the front_side,
    reverse_side, selfie and files fields in EncryptedPassportData.

    Args:
        file_hash (:obj:`str`): Checksum of encrypted file
        secret (:obj:`str`): Secret of encrypted file

    Attributes:
        hash (:obj:`str`): Checksum of encrypted file
        secret (:obj:`str`): Secret of encrypted file
    """

    __slots__ = ()

    def __init__(self, file_hash: str, secret: str, **_kwargs: Any):
        super().__init__(file_hash, secret, **_kwargs)

    def to_dict(self) -> JSONDict:
        """See :meth:`telegram.TelegramObject.to_dict`."""
        data = super().to_dict()

        del data['data_hash']
        del data['hash']

        return data


text:
using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Remoting.Messaging;

using KnownObjects;
using Belikov.GenuineChannels;
using Belikov.GenuineChannels.BroadcastEngine;
using Belikov.GenuineChannels.DotNetRemotingLayer;
using Belikov.GenuineChannels.Logbook;

namespace Server
{
	/// <summary>
	/// Server.
	/// </summary>
	class Server
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			try
			{
				// setup remoting
				System.Configuration.ConfigurationSettings.GetConfig("DNS");
				GenuineGlobalEventProvider.GenuineChannelsGlobalEvent += new GenuineChannelsGlobalEventHandler(GenuineChannelsEventHandler);
				RemotingConfiguration.Configure("Server.exe.config");
				//GlobalLoggerContainer.Logger = new BinaryLog(@"c:\tmp\server.log");

				// bind the business object
				RemotingServices.Marshal(new OperationProvider(), "OperationProvider.rem");

				Console.WriteLine("Server has been started. Press enter to exit.");
				Console.ReadLine();
			}
			catch(Exception ex)
			{
				Console.WriteLine("Exception: {0}. Stack trace: {1}.", ex.Message, ex.StackTrace);
			}
		}

		/// <summary>
		/// Catches Genuine Channels events and removes client session when
		/// user disconnects.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public static void GenuineChannelsEventHandler(object sender, GenuineEventArgs e)
		{
			if (e.SourceException == null)
				Console.WriteLine("Global event: {0}\r\nUrl: {1}", e.EventType,
					e.HostInformation == null ? "<not specified>" : e.HostInformation.ToString());
			else
				Console.WriteLine("Global event: {0}\r\nUrl: {1}\r\nException: {2}", e.EventType,
					e.HostInformation == null ? "<not specified>" : e.HostInformation.ToString(),
					e.SourceException);
		}

	}
}


text:
package com.jjjx.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.util.regex.Pattern;

import static com.baidu.location.h.j.p;
import static io.rong.imlib.statistics.UserData.name;

/**
 * Created by AMing on 17/5/12.
 * Company RongCloud
 */

public class CacheTask {
    private final static String JX_SP = "JxSp";
    private SharedPreferences preferences;
    private boolean isCacheValid;

    private static class SingleTonHolder {
        private static CacheTask sIns = new CacheTask();
    }

    /**
     * 获取实例
     *
     * @return
     */
    public static CacheTask getInstance() {
        return SingleTonHolder.sIns;
    }

    private CacheTask() {

    }

    public void init(Context context) {
        preferences = context.getApplicationContext().getSharedPreferences(JX_SP, Context.MODE_PRIVATE);
    }

    /**
     * 保存登录基本信息
     *
     * @param userId   用户 id
     * @param account  账号
     * @param password 密码
     * @param token    token
     */
    public void cacheLoginInfo(@NonNull String userId, @NonNull String account, @NonNull String password, @NonNull String token) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("userId", userId);
        editor.putString("account", account);
        editor.putString("password", password);
        editor.putString("token", token);
        editor.apply();
    }

    /**
     * 保存 token 到 SharedPreferences
     *
     * @param token
     */
    public void cacheToken(@NonNull String token) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("token", token);
        editor.apply();
    }

    public void cacheName(String name) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("name", name);
        editor.apply();
    }

    public void cacheLoginLng(String lng) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("lng", lng);
        editor.apply();
    }

    public void cacheLoginLat(String lat) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("lat", lat);
        editor.apply();
    }

    public String getLoginLng() {
        return preferences.getString("lng", null);
    }

    public String getLoginLat() {
        return preferences.getString("lat", null);
    }

    public String getName() {
        return preferences.getString("name", null);
    }

    public void cacheSex(String sex) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("sex", sex);
        editor.apply();
    }

    public void cacheCity(String city) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("city", city);
        editor.apply();
    }

    public String getCity() {
        return preferences.getString("city", null);
    }

    public String getSex() {
        return preferences.getString("sex", null);
    }

    public void cachePortrait(String portrait) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("portrait", portrait);
        editor.apply();
    }

    public String getPortrait() {
        return preferences.getString("portrait", null);
    }

    public void cacheLearnYear(String learnYear) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("learnYear", learnYear);
        editor.apply();
    }

    public String getLearnYear() {
        return preferences.getString("learnYear", null);
    }

    public void cacheMainClass(String mainClass) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("mainClass", mainClass);
        editor.apply();
    }

    public String getMainClass() {
        return preferences.getString("mainClass", null);
    }

    public void cacheTeacherAmount(String teacherAmount) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("teacherAmount", teacherAmount);
        editor.apply();
    }

    public String getAeacherAmount() {
        return preferences.getString("teacherAmount", null);
    }

    public void cacheAverageAge(String averageAge) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("averageAge", averageAge);
        editor.apply();
    }

    public String getAverageAge() {
        return preferences.getString("averageAge", null);
    }

    public void cacheUserId(@NonNull String userId) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("userId", userId);
        editor.apply();
    }

    public void cacheAccount(@NonNull String account) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("account", account);
        editor.apply();
    }

    public void cachePwd(@NonNull String password) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("password", password);
        editor.apply();
    }

    public void cacheRole(String role) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("userRole", role);
        editor.apply();
    }

    public boolean isLogin() {
        return (!TextUtils.isEmpty(preferences.getString("userId", "")));
    }

    /**
     * 获取用户 id
     *
     * @return
     */
    public String getUserId() {
        return preferences.getString("userId", null);
    }

    public String getUserRole() {
        return preferences.getString("userRole", "1");
    }

    /**
     * 获取 token
     *
     * @return
     */
    public String getToken() {
        return preferences.getString("token", null);
    }

    /**
     * 获取账号
     *
     * @return
     */
    public String getAccount() {
        return preferences.getString("account", null);
    }

    /**
     * 获取密码
     *
     * @return
     */
    public String getPassword() {
        return preferences.getString("password", null);
    }

    /**
     * 清除 SharedPreferences
     */
    public void clearAllCache() {
        preferences.edit().remove("userId").apply();
        preferences.edit().remove("token").apply();
        preferences.edit().remove("account").apply();
        preferences.edit().remove("password").apply();
        preferences.edit().remove("userRole").apply();
        preferences.edit().remove("name").apply();
        preferences.edit().remove("sex").apply();
        preferences.edit().remove("portrait").apply();
        preferences.edit().remove("averageAge").apply();
        preferences.edit().remove("teacherAmount").apply();
    }
}


text:
-- MySQL dump 10.15  Distrib 10.0.10-MariaDB, for debian-linux-gnu (x86_64)
--
-- Host: localhost    Database: simpleRoles
-- ------------------------------------------------------
-- Server version	10.0.10-MariaDB-1~saucy-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

-- Table structure for table `role`
--

DROP TABLE IF EXISTS `role`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(128) NOT NULL,
  `description` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idxRole` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `user_roles`
--

DROP TABLE IF EXISTS `user_roles`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_roles` (
  `role_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  UNIQUE KEY `role_id` (`role_id`,`user_id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `user_roles_ibfk_1` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE CASCADE,
  CONSTRAINT `user_roles_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `users`
--

DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(256) NOT NULL,
  `username` varchar(64) NOT NULL,
  `ref` text DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `idxUserName` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2014-11-02 20:34:12