text:
layout: post
title: 什么是 P, NP, NP-complete, NP-hard
category: 科研
tags: Math
keywords: 概念,NPhard
description:
---

###相关概念
NP-hard(non-deterministic polynomial-time hard)

1. P:能在多项式时间内解决
2. NP:不能在多项式时间内解决或不确定能不能在多项式时间内解决,但一旦你找到一个解,只需要多项式时间去验证这个解是正确的
3. NP-hard:如果一个问题是NP-hard,意味着可以将任意NP问题化约到这个问题。如果可以解这个问题,那么可以轻松地解任意NP问题。
4. NPC:NP完全问题,所有NP问题在多项式时间内都能化约(Reducibility)到某一NP问题,这一NP问题就是NPC问题,即解决了此NPC问题,所有NP问题也都解决了。

###资料原文
These refer to how long it takes a program to run.  Problems in class P can be solved with algorithms that run in **polynomial time**.

Say you have an algorithm that finds the smallest integer in an array.  One way to do this is by iterating over all the integers of the array and keeping track of the smallest number you've seen up to that point.  Every time you look at an element, you compare it to the current minimum, and if it's smaller, you update the minimum.

How long does this take?  Let's say there are n elements in the array.  For every element the algorithm has to perform a constant number of operations.  Therefore we can say that the algorithm runs in O(n) time, or that the runtime is a linear function of how many elements are in the array.  So this algorithm runs in **linear time**.

You can also have algorithms that run in **quadratic time** (O(n^2)), **exponential time** (O(2^n)), or even **logarithmic time** (O(log n)).  Binary search (on a balanced tree) runs in logarithmic time because the height of the binary search tree is a logarithmic function of the number of elements in the tree.

If the running time is some polynomial function of the size of the input, for instance if the algorithm runs in linear time or quadratic time or cubic time, then we say the algorithm runs in **polynomial time** and the problem it solves is in class **P**.

###**NP**
Now there are a lot of programs that don't (necessarily) run in polynomial time on a regular computer, but do run in polynomial time on a nondeterministic Turing machine.  These programs solve problems in **NP**, which stands for **nondeterministic polynomial time**.  A nondeterministic Turing machine can do everything a regular computer can and more. This means all problems in P are also in NP.

An equivalent way to define NP is by pointing to the problems that can be verified in polynomial time.  This means there is not necessarily a polynomial-time way to find a solution, but once you have a solution it only takes polynomial time to verify that it is correct.

Some people think P = NP, which means any problem that can be verified in polynomial time can also be solved in polynomial time and vice versa.  If they could prove this, it would revolutionize computer science because people would be able to construct faster algorithms for a lot of important problems.

###**NP-hard**
What does NP-hard mean?  A lot of times you can solve a problem by reducing it to a different problem.  I can reduce Problem B to Problem A if, given a solution to Problem A, I can easily construct a solution to Problem B.  (In this case, "easily" means "in polynomial time.")

If a problem is **NP-hard**, this means I can reduce any problem in NP to that problem.  This means if I can solve that problem, I can easily solve any problem in NP.  If we could solve an NP-hard problem in polynomial time, this would prove P = NP.

###**NP-complete**
A problem is **NP-complete** if the problem is both

- NP-hard, and
- in NP.

###参考资料
【1】[What are P, NP, NP-complete, and NP-hard?](http://www.quora.com/What-are-P-NP-NP-complete-and-NP-hard)


text:
package org.itsnat.droid.impl.xmlinflater.layout.classtree;

import android.content.Context;
import android.view.View;

import org.itsnat.droid.impl.dom.DOMAttr;
import org.itsnat.droid.impl.util.MiscUtil;
import org.itsnat.droid.impl.xmlinflated.layout._IncludeFakeViewGroup_;
import org.itsnat.droid.impl.xmlinflater.layout.AttrLayoutContext;
import org.itsnat.droid.impl.xmlinflater.layout.ClassDescViewMgr;
import org.itsnat.droid.impl.xmlinflater.layout.PendingPostInsertChildrenTasks;
import org.itsnat.droid.impl.xmlinflater.layout.attr.AttrDesc_Include_layout;

/**
 * Created by jmarranz on 30/04/14.
 */
public class ClassDescView_Include extends ClassDescViewBased
{

    public ClassDescView_Include(ClassDescViewMgr classMgr, ClassDescView_widget_FrameLayout parentClass)
    {
        super(classMgr,"include",parentClass);
    }

    @Override
    @SuppressWarnings("unchecked")
    protected Class<View> resolveClass()
    {
        return (Class<View>)MiscUtil.resolveClass(_IncludeFakeViewGroup_.class.getName());
    }

    @Override
    protected boolean setAttributeThisClass(final View view,final DOMAttr attr,final AttrLayoutContext attrCtx)
    {
        // Se redefine totalmente porque necesitamos memorizar los atributos (excepto el layout)
        if (attr.getNamespaceURI() == null && attr.getName().equals("layout"))
            return super.setAttributeThisClass(view, attr, attrCtx);

        ((_IncludeFakeViewGroup_)view).saveAttrib(attr);

        return true; // No los estamos ignorando
    }

    @Override
    protected View createViewObject(int idStyle,PendingPostInsertChildrenTasks pendingPostInsertChildrenTasks,Context ctx)
    {
        return new _IncludeFakeViewGroup_(ctx);
    }

    protected void init()
    {
        super.init();

        addAttrDescNoNS(new AttrDesc_Include_layout(this)); // OJO llamamos a addAttrDescNoNS porque NO tiene namespace
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<title>Column Names In A Result Set</title>

<meta http-equiv="content-type" content="text/html; charset=UTF-8">

Small. Fast. Reliable.
Choose any three.

    About
    Sitemap
    Documentation
    Download
    License
    News
    Developers
    Support

SQLite C Interface

Column Names In A Result Set

const char *sqlite3_column_name(sqlite3_stmt*, int N);
const void *sqlite3_column_name16(sqlite3_stmt*, int N);

These routines return the name assigned to a particular column
in the result set of a SELECT statement.  The sqlite3_column_name()
interface returns a pointer to a zero-terminated UTF-8 string
and sqlite3_column_name16() returns a pointer to a zero-terminated
UTF-16 string.  The first parameter is the prepared statement
that implements the SELECT statement. The second parameter is the
column number.  The leftmost column is number 0.

The returned string pointer is valid until either the prepared statement
is destroyed by sqlite3_finalize() or until the next call to
sqlite3_column_name() or sqlite3_column_name16() on the same column.

If sqlite3_malloc() fails during the processing of either routine
(for example during a conversion from UTF-8 to UTF-16) then a
NULL pointer is returned.

The name of a result column is the value of the "AS" clause for
that column, if there is an AS clause.  If there is no AS clause
then the name of the column is unspecified and may change from
one release of SQLite to the next.

Requirements:
H13721 H13723 H13724 H13725 H13726 H13727

See also lists of
  Objects,
  Constants, and
  Functions.

This page last modified 2009/02/18 18:03:35 UTC


text:
package android.support.v4.content;

import android.content.Intent;

class k
{

    k()
    {
    }

    public static Intent a(String s, String s1)
    {
        return Intent.makeMainSelectorActivity(s, s1);
    }
}


text:
package org.mindinformatics.gwt.domeo.client.ui.popup;

import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.resources.client.CssResource.NotStrict;

public interface CurationPopupResources extends ClientBundle {

	@NotStrict
	@Source("org/mindinformatics/gwt/domeo/client/ui/popup/CurationPopup.css")
	PopupCssResource popupCss();

	public interface PopupCssResource extends CssResource {
		@ClassName("fw_PopupPanel")
		String popupPanel();

		@ClassName("fw_ScrollPanel")
		String scrollPanel();

		@ClassName("fw_containerPanelWithPadding")
		String containerPanelWithPadding();
	}
}


text:
function(event_new)
  set(event_id ${ARGN})
  if(NOT event_id)
    identifier(event)
    ans(event_id)
  endif()

  if(COMMAND ${event_id})
    message(FATAL_ERROR "specified event already exists")
  endif()

  ## curry the event emit function and create a callable from the event
  curry3(${event_id}() => event_emit("${event_id}" /*))
  ans(event)

  callable("${event}")
  ans(event)

  curry3(() => event_addhandler("${event_id}" /*))
  ans(add_handler)

  curry3(() => event_removehandler("${event_id}" /*))
  ans(remove_handler)

  curry3(() => event_clear("${event_id}" /*))
  ans(clear)

  ## set event's properties
  map_set(${event} event_id "${event_id}")
  map_set(${event} handlers)
  map_set(${event} add ${add_handler})
  map_set(${event} remove ${remove_handler})
  map_set(${event} clear ${clear})

  ## register event globally
  events()
  ans(events)
  map_set(${events} "${event_id}" ${event})

  return(${event})
endfunction()

## faster version (does not use curry but a custom implementation)
function(event_new)
  set(event_id ${ARGN})
  if(NOT event_id)
    identifier(event)
    ans(event_id)
  endif()

  if(COMMAND ${event_id})
    message(FATAL_ERROR "specified event already exists")
  endif()

  ## curry the event emit function and create a callable from the event

  function_new()
  ans(add_handler)
  function_new()
  ans(remove_handler)
  function_new()
  ans(clear)
  eval("
    function(${event_id})
      event_emit(\"${event_id}\" \${ARGN})
      return_ans()
    endfunction()
    function(${add_handler})
      event_addhandler(\"${event_id}\" \${ARGN})
      return_ans()
    endfunction()
    function(${remove_handler})
      event_removehandler(\"${event_id}\" \${ARGN})
      return_ans()
    endfunction()
    function(${clear})
      event_clear(\"${event_id}\" \${ARGN})
      return_ans()
    endfunction()

  ")

  callable("${event_id}")
  ans(event)

  ## set event's properties
  map_set(${event} event_id "${event_id}")
  map_set(${event} handlers)
  map_set(${event} add ${add_handler})
  map_set(${event} remove ${remove_handler})
  map_set(${event} clear ${clear})

  ## register event globally
  events()
  ans(events)
  map_set(${events} "${event_id}" ${event})

  return(${event})
endfunction()


text:
using MasterExtensionKit.Core.Exceptions;
using MasterExtensionKit.Core.Strings.Converters;
using MasterExtensionKit.Core.UnitTests._Shared;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace MasterExtensionKit.Core.UnitTests.Strings.Converters
{
	[TestClass]
	public class ToIntegerExtensionsTests
	{
		#region General String Tests

		[TestMethod]
		[ExpectedException(typeof(SourceNullException), "")]
		public void String_Converter_ToInteger_Null_Exception()
		{
			TestStringData.NULL_STRING.ToInteger();
		}

		[TestMethod]
		[ExpectedException(typeof(SourceEmptyException), "")]
		public void String_Converter_ToInteger_Empty_Invalid()
		{
			TestStringData.EMPTY_STRING.ToInteger();
		}

		#endregion

		[TestMethod]
		public void String_Converter_ToInteger_IgnoreErrorTrue_Zero_Valid()
		{
			Assert.AreEqual(TestNumberData.INTEGER_ZERO, TestStringData.INTEGER_ZERO_VALUE.ToInteger());
		}

		[TestMethod]
		public void String_Converter_ToInteger_IgnoreErrorTrue_MaxInteger_Valid()
		{
			Assert.AreEqual(TestNumberData.INTEGER_MAX_VALUE, TestStringData.INTEGER_MAX_VALUE.ToInteger());
		}

		[TestMethod]
		public void String_Converter_ToInteger_IgnoreErrorTrue_MinimumInteger_Valid()
		{
			Assert.AreEqual(TestNumberData.INTEGER_MIN_VALUE, TestStringData.INTEGER_MIN_VALUE.ToInteger());
		}

		[TestMethod]
		public void String_Converter_ToInteger_IgnoreErrorTrue_AlphaOnly_Null()
		{
			Assert.AreEqual(TestNumberData.INTEGER_NULL, TestStringData.ALPHA_ONLY_STRING.ToInteger());
		}

		[TestMethod]
		[ExpectedException(typeof (ConversionFailureException), "Failed to convert string to interger.")]
		public void String_Converter_ToInteger_IgnoreErrorFalse_AlphaOnly_Exception()
		{
			Assert.AreEqual(TestNumberData.INTEGER_NULL, TestStringData.ALPHA_ONLY_STRING.ToInteger(false));
		}

		[TestMethod]
		public void String_Converter_ToInteger_IgnoreErrorTrue_AlphaNumeric_Null()
		{
			Assert.AreEqual(TestNumberData.INTEGER_NULL, TestStringData.ALPHANUMERIC_STIRNG.ToInteger());
		}

		[TestMethod]
		[ExpectedException(typeof (ConversionFailureException), "Failed to convert string to interger.")]
		public void String_Converter_ToInteger_IgnoreErrorFalse_AlphaNumeric_Null()
		{
			Assert.AreEqual(TestNumberData.INTEGER_NULL, TestStringData.ALPHANUMERIC_STIRNG.ToInteger(false));
		}

		[TestMethod]
		public void String_Converter_ToInteger_IgnoreErrorTrue_Decimal_Null()
		{
			Assert.AreEqual(TestNumberData.INTEGER_NULL, TestStringData.DECIMAL_MIN_VALUE.ToInteger());
		}

		[TestMethod]
		[ExpectedException(typeof (ConversionFailureException), "Failed to convert string to interger.")]
		public void String_Converter_ToInteger_IgnoreErrorFalse_Decimal_Null()
		{
			Assert.AreEqual(TestNumberData.INTEGER_NULL, TestStringData.DECIMAL_MIN_VALUE.ToInteger(false));
		}
	}
}


text:
<?php
// Copyright 2011 Toby Zerner, Simon Zerner
// This file is part of esoTalk. Please see the included license file for usage information.

if (!defined("IN_ESOTALK")) exit;

/**
 * Displays the member list page, including the filter bar, the letter scrubber, and the list.
 *
 * @package esoTalk
 */

global $orderBy;
$orderBy = $data["orderBy"];

// Shortcut function to construct a URL to a member list page, while retaining the same orderBy.
function makeURL($startFrom = 0, $searchString = "")
{
	global $orderBy;
	$urlParts = array("members", $orderBy);

	if ($startFrom > 0 or $startFrom[0] == "p" or $searchString) $urlParts[] = $startFrom;
	if ($searchString) $urlParts[] = "?search=$searchString";

	return implode("/", $urlParts);
}

?>

<?php if (ET::$session->isAdmin()): ?>
<a href='<?php echo URL("members/create"); ?>' class='button big' id='createMemberLink'> <?php echo T("Create Member"); ?>
<?php endif; ?>

<?php if (!$data["searchString"] and $data["orderBy"] == "name"): ?>

<?php

// Construct an array of letters, and "#" as the item for special characters and numbers.
$letters = range("a", "z");
array_unshift($letters, "#");

// Work out what letter we are currently viewing by looking at the name of the first member in the results.
$currentLetter = strtolower($data["members"][0]["username"][0]);
if (!in_array($currentLetter, $letters)) $currentLetter = "#";

// Output the letter scrubber items.
foreach ($letters as $letter) {
	$selected = ($currentLetter == $letter) ? " selected" : "";
	$id = $letter == "#" ? 0 : $letter;
	echo "
".strtoupper($letter)."
";
}

?>

<?php endif; ?>

<?php printf(T("%s Members"), number_format($data["countMembers"])); ?>

<?php foreach ($data["orders"] as $k => $v): ?>
<li<?php if ($data["orderBy"] == $k): ?> class='selected'<?php endif; ?>><a href='<?php echo URL("members/$k/".($data["searchString"] ? "?search=".$data["searchString"] : "")); ?>'><?php echo T($v[0]); ?>

<?php endforeach; ?>

<form class='search big' id='memberSearch' action='<?php echo URL(makeURL()); ?>' method='get'>
<fieldset>

<input name='search' type='text' class='text' value='<?php echo $data["searchString"]; ?>' spellcheck='false' placeholder='<?php echo T("Filter by name or group..."); ?>'/>
<?php if ($data["searchString"]): ?><a class='control-reset' href='<?php echo URL(makeURL()); ?>'><?php endif; ?>
</fieldset>
</form>

<?php // If we're searching but there are no search results, show an error.
if ($data["searchString"] and !count($data["members"])): ?>

<?php echo T("message.noSearchResultsMembers"); ?>

<?php else: ?>

<?php if ($data["startFrom"] > 0): ?>

<a href='<?php echo URL(makeURL("p".(ceil($data["startFrom"] / C("esoTalk.members.membersPerPage") + 1) - 1), $data["searchString"])); ?>'>‹ <?php echo T("Previous"); ?>

<?php endif; ?>

<?php $this->renderView("members/list", $data); ?>

<?php if ($data["startFrom"] + C("esoTalk.members.membersPerPage") < $data["countMembers"]): ?>

<a href='<?php echo URL(makeURL("p".(floor($data["startFrom"] / C("esoTalk.members.membersPerPage") + 1) + 1), $data["searchString"])); ?>'><?php echo T("Next"); ?> ›

<?php endif; ?>

<?php endif; ?>


text:
package com.pubnub.api;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static com.pubnub.api.matchers.JSONAssert.assertJSONArrayHas;
import static org.junit.Assert.assertEquals;

public class UnsubscribeTest {
    Pubnub pubnub;
    Pubnub pubnub2;

    String channel;
    String group;

    String random;

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @BeforeClass
    public static void cleanup() throws JSONException, InterruptedException {
        TestHelper.cleanup();
    }

    @Before
    public void setUp() {
        pubnub = new Pubnub("demo", "demo");
        pubnub.setCacheBusting(false);
        pubnub.setUUID("client#1");

        pubnub2 = new Pubnub("demo", "demo");
        pubnub2.setCacheBusting(false);
        pubnub2.setUUID("client#2");

        random = UUID.randomUUID().toString().substring(0, 8);
        channel = "ch6-" + random;
        group = "jtest-" + random;
    }

    @Test
    public void testUnsubscribe()
            throws InterruptedException, PubnubException {
        CountDownLatch latch = new CountDownLatch(1);
        CountDownLatch latch2 = new CountDownLatch(1);

        TestHelper.PresenceCallback presenceCb = new TestHelper.PresenceCallback(latch);

        pubnub.presence(channel, presenceCb);
        pubnub2.subscribe(channel, new TestHelper.SimpleCallback());

        latch.await(10, TimeUnit.SECONDS);

        assertEquals(pubnub2.getUUID(), presenceCb.getUUID());
        assertEquals("join", presenceCb.getAction());

        presenceCb.setLatch(latch2);
        pubnub2.unsubscribe(channel);

        latch2.await(10, TimeUnit.SECONDS);

        assertEquals(pubnub2.getUUID(), presenceCb.getUUID());
        assertEquals("leave", presenceCb.getAction());
    }

    @Test
    public void testUnsubscribeAllForGroup()
            throws PubnubException, InterruptedException, JSONException {
        JSONObject result;

        CountDownLatch latch1 = new CountDownLatch(1);
        TestHelper.SimpleCallback cb1 = new TestHelper.SimpleCallback(latch1);

        // check online
        connectToGroup();

        // check offline
        pubnub2.unsubscribeAll();
        Thread.sleep(3000);

        pubnub.channelGroupHereNow(group, cb1);
        latch1.await(10, TimeUnit.SECONDS);

        result = (JSONObject) cb1.getResponse();
        assertEquals(0, result.getInt("total_occupancy"));
    }

    @Test
    public void testUnsubscribeAllGroupsForGroup() throws PubnubException, InterruptedException, JSONException {
        JSONObject result;

        CountDownLatch latch1 = new CountDownLatch(1);
        TestHelper.SimpleCallback cb1 = new TestHelper.SimpleCallback(latch1);

        // check online
        connectToGroup();

        // check offline
        pubnub2.channelGroupUnsubscribeAllGroups();
        Thread.sleep(3000);

        pubnub.channelGroupHereNow(group, cb1);
        latch1.await(10, TimeUnit.SECONDS);

        result = (JSONObject) cb1.getResponse();
        assertEquals(0, result.getInt("total_occupancy"));
    }

    @Test
    public void testUnsubscribeGroupForGroup()
            throws PubnubException, InterruptedException, JSONException {
        JSONObject result;

        CountDownLatch latch1 = new CountDownLatch(1);
        TestHelper.SimpleCallback cb1 = new TestHelper.SimpleCallback(latch1);

        // check online
        connectToGroup();

        // check offline
        pubnub2.channelGroupUnsubscribe(group);
        Thread.sleep(3000);

        pubnub.channelGroupHereNow(group, cb1);
        latch1.await(10, TimeUnit.SECONDS);

        result = (JSONObject) cb1.getResponse();
        assertEquals(0, result.getInt("total_occupancy"));
    }

    @Test
    public void testUnsubscribeGroupsForGroup()
            throws PubnubException, InterruptedException, JSONException {
        JSONObject result;

        CountDownLatch latch1 = new CountDownLatch(1);
        TestHelper.SimpleCallback cb1 = new TestHelper.SimpleCallback(latch1);

        // check online
        connectToGroup();

        // check offline
        pubnub2.channelGroupUnsubscribe(new String[]{group});
        Thread.sleep(3000);

        pubnub.channelGroupHereNow(group, cb1);
        latch1.await(10, TimeUnit.SECONDS);

        result = (JSONObject) cb1.getResponse();
        assertEquals(0, result.getInt("total_occupancy"));
    }

    private void connectToGroup()
            throws InterruptedException, PubnubException, JSONException {
        CountDownLatch latch1 = new CountDownLatch(1);
        CountDownLatch latch2 = new CountDownLatch(1);
        CountDownLatch latch3 = new CountDownLatch(1);

        TestHelper.SimpleCallback cb1 = new TestHelper.SimpleCallback(latch1);
        TestHelper.SubscribeCallback cb2 = new TestHelper.SubscribeCallback(latch2);
        TestHelper.SimpleCallback cb3 = new TestHelper.SimpleCallback(latch3);

        pubnub.channelGroupAddChannel(group, channel, cb1);
        latch1.await(10, TimeUnit.SECONDS);

        // check online
        pubnub2.channelGroupSubscribe(group, cb2);
        latch2.await(10, TimeUnit.SECONDS);
        Thread.sleep(1000);

        pubnub.channelGroupHereNow(group, cb3);
        latch3.await(10, TimeUnit.SECONDS);

        JSONObject result = (JSONObject) cb3.getResponse();
        JSONArray uuids = result.getJSONObject("channels")
                .getJSONObject(channel)
                .getJSONArray("uuids");

        assertJSONArrayHas(pubnub2.getUUID(), uuids);
    }
}


text:
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

namespace Anuracode.Forms.Controls.Renderers
{
    /// <summary>
    /// Extended entry renderer.
    /// </summary>
    public class ExtendedEntryRenderer : EntryRenderer
    {
        /// <summary>
        /// When element changed.
        /// </summary>
        /// <param name="e">Argument to use.</param>
        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            UpdateBorderThickness();
        }

        /// <summary>
        /// Event when element property changed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if ((this.Element == null) || (this.Control == null))
            {
                return;
            }

            if ((e.PropertyName == ExtendedEntry.HasInvisibleBordersProperty.PropertyName))
            {
                UpdateBorderThickness();
            }
        }

        /// <summary>
        /// Update border thickness.
        /// </summary>
        protected void UpdateBorderThickness()
        {
            if ((this.Element == null) || (this.Control == null))
            {
                return;
            }

            ExtendedEntry extendedEntry = Element as ExtendedEntry;

            if (extendedEntry != null)
            {
                if (extendedEntry.HasInvisibleBorders)
                {
                    this.Control.SetBackgroundColor(Android.Graphics.Color.Transparent);
                }
            }
        }
    }
}


text:
The code of [https://carloscastellanosvera.com](https://carloscastellanosvera.com)

## Want to reach out?

 - GitHub [ccverak](https://github.com/ccverak)
 - Twitter [@ccverak](https://twitter.com/ccverak)
 - LinkedIn [ccverak](https://linkedin.com/in/ccverak)


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Pilosocereus densiareolatus F.Ritter

### Remarks
null


text:
package com.arialyy.aria.core;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import com.arialyy.aria.core.config.AppConfig;
import com.arialyy.aria.core.config.Configuration;
import com.arialyy.aria.core.config.DGroupConfig;
import com.arialyy.aria.core.config.DownloadConfig;
import com.arialyy.aria.core.config.UploadConfig;
import com.arialyy.aria.core.config.XMLReader;
import com.arialyy.aria.util.ALog;
import com.arialyy.aria.util.CommonUtil;
import com.arialyy.aria.util.FileUtil;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;

public class AriaConfig {
  private static final String TAG = "AriaConfig";

  public static final String DOWNLOAD_TEMP_DIR = "/Aria/temp/download/";
  public static final String UPLOAD_TEMP_DIR = "/Aria/temp/upload/";
  public static final String IGNORE_CLASS_KLASS = "shadow$_klass_";
  public static final String IGNORE_CLASS_MONITOR = "shadow$_monitor_";

  private static volatile AriaConfig Instance;
  private static Context APP;
  private DownloadConfig mDConfig;
  private UploadConfig mUConfig;
  private AppConfig mAConfig;
  private DGroupConfig mDGConfig;
  /**
   * 是否已经联网,true 已经联网
   */
  private static boolean isConnectedNet = true;
  private Handler mAriaHandler;

  private AriaConfig(Context context) {
    APP = context.getApplicationContext();
  }

  public static AriaConfig init(Context context) {
    if (Instance == null) {
      synchronized (AriaConfig.class) {
        if (Instance == null) {
          Instance = new AriaConfig(context);
          Instance.initData();
        }
      }
    }
    return Instance;
  }

  public static AriaConfig getInstance() {
    if (Instance == null) {
      ALog.e(TAG, "请使用init()初始化");
    }
    return Instance;
  }

  public Context getAPP() {
    return APP;
  }

  private void initData() {
    initConfig();
    regNetCallBack(APP);
  }

  public DownloadConfig getDConfig() {
    return mDConfig;
  }

  public UploadConfig getUConfig() {
    return mUConfig;
  }

  public AppConfig getAConfig() {
    return mAConfig;
  }

  public DGroupConfig getDGConfig() {
    return mDGConfig;
  }

  public synchronized Handler getAriaHandler() {
    if (mAriaHandler == null) {
      mAriaHandler = new Handler(Looper.getMainLooper());
    }
    return mAriaHandler;
  }

  /**
   * 注册网络监听,只有配置了检查网络{@link AppConfig#isNetCheck()}才会注册事件
   */
  private void regNetCallBack(Context context) {
    isConnectedNet = isNetworkAvailable();
    if (!getAConfig().isNetCheck()) {
      return;
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
      return;
    }
    ConnectivityManager cm =
        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null) {
      return;
    }

    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    NetworkRequest request = builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
        .build();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      cm.registerNetworkCallback(request, new ConnectivityManager.NetworkCallback() {

        @Override public void onLost(Network network) {
          super.onLost(network);
          isConnectedNet = isNetworkAvailable();
          ALog.d(TAG, "onLost, isConnectNet = " + isConnectedNet);
        }

        @Override public void onAvailable(Network network) {
          super.onAvailable(network);
          isConnectedNet = true;
          ALog.d(TAG, "onAvailable, isConnectNet = true");
        }
      });
    }
  }

  public boolean isNetworkAvailable() {
    // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
    ConnectivityManager connectivityManager =
        (ConnectivityManager) getAPP().getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager == null) {

      return false;
    } else {
      // 获取NetworkInfo对象
      NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

      if (networkInfo != null && networkInfo.length > 0) {
        for (NetworkInfo info : networkInfo) {
          // 判断当前网络状态是否为连接状态
          if (info.getState() == NetworkInfo.State.CONNECTED) {
            return true;
          }
        }
      }
    }
    return false;
  }

  public boolean isConnectedNet() {
    return isConnectedNet;
  }

  /**
   * 初始化配置文件
   */
  private void initConfig() {
    mDConfig = Configuration.getInstance().downloadCfg;
    mUConfig = Configuration.getInstance().uploadCfg;
    mAConfig = Configuration.getInstance().appCfg;
    mDGConfig = Configuration.getInstance().dGroupCfg;

    File xmlFile = new File(APP.getFilesDir().getPath() + Configuration.XML_FILE);
    File tempDir = new File(APP.getFilesDir().getPath() + "/temp");
    if (!xmlFile.exists()) {
      loadConfig();
    } else {
      try {
        String md5Code = CommonUtil.getFileMD5(xmlFile);
        File file = new File(APP.getFilesDir().getPath() + "/temp.xml");
        if (file.exists()) {
          file.delete();
        }
        FileUtil.createFileFormInputStream(APP.getAssets().open("aria_config.xml"),
            file.getPath());
        if (!CommonUtil.checkMD5(md5Code, file) || !Configuration.getInstance().configExists()) {
          loadConfig();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    if (tempDir.exists()) {
      File newDir = new File(APP.getFilesDir().getPath() + AriaConfig.DOWNLOAD_TEMP_DIR);
      newDir.mkdirs();
      tempDir.renameTo(newDir);
    }
  }

  /**
   * 加载配置文件
   */
  private void loadConfig() {
    try {
      XMLReader helper = new XMLReader();
      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser parser = factory.newSAXParser();
      parser.parse(APP.getAssets().open("aria_config.xml"), helper);
      FileUtil.createFileFormInputStream(APP.getAssets().open("aria_config.xml"),
          APP.getFilesDir().getPath() + Configuration.XML_FILE);
    } catch (ParserConfigurationException | IOException | SAXException e) {
      ALog.e(TAG, e.toString());
    }
  }
}


text:
th.tablesort-sortable {
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -o-user-select: none;
    user-select: none;
    cursor: pointer;
}

table .tablesort-sortable:after{
    content:"";
    float:right;
    margin-top:7px;
    visibility:hidden;
    border-left:4px solid transparent;
    border-right:4px solid transparent;

    border-top:none;
    border-bottom:4px solid #000;
}

table .tablesort-desc:after{
    border-top:4px solid #000;
    border-bottom:none;
}

table .tablesort-asc,table .tablesort-desc{
    background-color:rgba(141, 192, 219, 0.25);
}

table .tablesort-sortable:hover:after, table .tablesort-asc:after, table .tablesort-desc:after {
    visibility:visible;
}

/*
 * Styling for the table row shown in empty tables
 */

/* The row is always added as the first row in a table
   Hide it by default */
.showIfLast {
    display: none;
}

/* Only show it if it is also the last row of the table. */
.showIfLast:last-child {
    display: table-row;
}

.showIfLast td {
    text-align: center;
}

.showIfLast td:after {
    content: "No data";
}


text:
abstract AbstrModel
abstract AbstrUnivarModel <: AbstrModel
abstract AbstrMultivarModel <: AbstrModel

################
## resimulate ##
################

@doc doc"""
Resimulate data from given model.
"""->
function resimulate(data::AbstractTimenum,
                    mod::AbstrUnivarModel,
                    nPaths::Int = 1)
    ## resimulate data from given model

    ## data must be univariate for univariate models
    nObs, nAss = size(data)
    if nAss != 1
        error("Original data must be univariate for univariate models.")
    end

    ## get returns without NAs
    pureRets = dropna(data.vals[1])
    nRets = size(pureRets, 1)

    simRetsDf = DataFrame()
    noNAInds = !isna(data.vals[1])
    for ii=1:nPaths
        # simulate values
        simVals = simulate(mod, nRets)

        ## fill values into DataArray
        simRetsDa = DataArray(Float64, nObs)
        simRetsDa[noNAInds] = simVals

        ## copy values to DataFrame
        simRetsDf[ii] = simRetsDa
    end

    ## fix names
    modName = string(typeof(mod))
    if nPaths == 1
        colName = symbol(string(names(data.vals)[1],
                                "_sim_",
                                modName))
        rename!(simRetsDf, :x1, colName)
    else
        nams = [symbol(string(names(data.vals)[1],
                              "_sim_",
                              modName,
                              "_",
                              "$ii")) for ii=1:nPaths]
        names!(simRetsDf, nams)
    end
    simRets = Timenum(simRetsDf, idx(data))
    return simRets
end

## function resimulateLogPrices(logPricesTn::Timenum,
##                              mod::AbstrUnivarModel,
##                              nPaths::Int = 1)
##     ## simulate historic log price path again

##     nObs, nAss = size(logPricesTn)

##     # logPricesTn should be only one asset for univariate models
##     if nAss != 1
##         error("Original data must be exactly one asset for univariate models.")
##     end

##     # get logRets
##     logRets = price2ret(logPricesTn, log=true)

##     ## get returns without NAs
##     pureRets = dropna(logRets.vals[1])
##     nRets = size(pureRets, 1)

##     ## fit model to pure returns
##     modFit = estimate(mod, pureRets)

##     simRetsDf = DataFrame()
##     noNAInds = !isna(logRets.vals[1])
##     for ii=1:nPaths
##         # simulate values
##         simVals = simulate(modFit, nRets)

##         ## fill values into DataArray
##         simRetsDa = DataArray(Float64, nObs-1)
##         simRetsDa[noNAInds] = simVals

##         ## copy values to DataFrame
##         simRetsDf[ii] = simRetsDa
##     end

##     ## fix names
##     modName = string(typeof(modFit))
##     if nPaths == 1
##         colName = symbol(string(names(logPricesTn.vals)[1],
##                                 "_sim_",
##                                 modName))
##         rename!(simRetsDf, :x1, colName)
##     else
##         nams = [symbol(string(names(logPricesTn.vals)[1],
##                               "_sim_",
##                               modName,
##                               "_",
##                               "$ii")) for ii=1:nPaths]
##         names!(simRetsDf, nams)
##     end

##     simRets = Timenum(simRetsDf, idx(logRets))
##     simPrices = ret2price(simRets)
##     idx(simPrices)[1] = idx(logPricesTn)[1]

##     return (simRets, simPrices)
## end


text:
import { SuperMap } from '../SuperMap';
import { Util } from '../commontypes/Util';
import { WebPrintingJobLayers } from './WebPrintingJobLayers';
import { WebPrintingJobCustomItems } from './WebPrintingJobCustomItems';

/**
 * @class SuperMap.WebPrintingJobLegendOptions
 * @classdesc Web 打印图例参数类。
 * @version 10.1.0
 * @category iServer WebPrintingJob
 * @param {Object} option - 初始化参数。
 * @param {string} [option.title] - 图例名称。
 * @param {string} [option.picAsUrl] - 图例的图片 url 地址。
 * @param {string} [option.picAsBase64] - 图例的 base64 位图片信息。
 * @param {SuperMap.WebPrintingJobLayers} [option.layers] - 图例的布局业务图层参数类。
 * @param {SuperMap.WebPrintingJobCustomItems} [option.customItems] - 自定义图例元素参数类。
 */
export class WebPrintingJobLegendOptions {
    constructor(option) {
        /**
         * @member {string} SuperMap.WebPrintingJobLegendOptions.prototype.title
         * @description  图例名称。
         */
        this.title = null;
        /**
         * @member {string} [SuperMap.WebPrintingJobLegendOptions.prototype.picAsUrl]
         * @description  图例的图片 url 地址。
         */
        this.picAsUrl = null;
        /**
         * @member {string} [SuperMap.WebPrintingJobLegendOptions.prototype.picAsBase64]
         * @description  图例的 base64 位图片信息。
         */
        this.picAsBase64 = null;
        /**
         * @member {SuperMap.WebPrintingJobLayers} [SuperMap.WebPrintingJobLegendOptions.prototype.layers]
         * @description  图例的布局业务图层参数类。
         */
        this.layers = null;
        /**
         * @member {SuperMap.WebPrintingJobCustomItems} [SuperMap.WebPrintingJobLegendOptions.prototype.customItems]
         * @description  自定义图例元素参数类。
         */
        this.customItems = null;

        this.CLASS_NAME = 'SuperMap.WebPrintingJobLegendOptions';
        Util.extend(this, option);
    }

    /**
     * @function SuperMap.WebPrintingJobLegendOptions.prototype.destroy
     * @description 释放资源,将引用资源的属性置空。
     */
    destroy() {
        this.title = null;
        this.picAsUrl = null;
        this.picAsBase64 = null;
        if (this.layers instanceof WebPrintingJobLayers) {
            this.layers.destroy();
            this.layers = null;
        }
        if (this.customItems instanceof WebPrintingJobCustomItems) {
            this.customItems.destroy();
            this.customItems = null;
        }
    }

    /**
     * @function SuperMap.WebPrintingJobLegendOptions.prototype.toJSON
     * @description 将 SuperMap.WebPrintingJobLegendOptions 对象转化为 JSON 字符串。
     * @returns {string} 返回转换后的 JSON 字符串。
     */
    toJSON() {
        var params = {
            title: this.title || ""
        };
        if (this.picAsUrl) {
            params.picAsUrl = this.picAsUrl;
        } else if (this.picAsBase64) {
            params.picAsBase64 = this.picAsBase64.replace(/^data:.+;base64,/, '');
        } else if (this.customItems) {
            params.customItems = this.customItems;
        }
        return Util.toJSON(params);
    }
}

SuperMap.WebPrintingJobLegendOptions = WebPrintingJobLegendOptions;


text:
require 'rspec'
require_relative '../../../../lib/html_to_haml/tools/html/attribute_handler'

describe HtmlToHaml::Html::AttributeHandler do
  subject { described_class.new }

  context 'empty attributes' do
    it 'generates an empty string' do
      expect(subject.attributes_string).to eq('')
    end
  end

  context 'regular attributes' do
    it 'generates a string that puts regular attributes into a hash string' do
      subject.add_attribute(attr: 'attr1="attribute1"')
      expect(subject.attributes_string).to eq('{ attr1: "attribute1" }')
    end
  end

  context 'ids' do
    it 'generates a string using the # syntax for simple ids' do
      subject.add_attribute(attr: 'id="simple-id"')
      expect(subject.attributes_string).to eq('#simple-id')
    end

    it 'handles single quotes' do
      subject.add_attribute(attr: "id='simple-id'")
      expect(subject.attributes_string).to eq('#simple-id')
    end

    it 'generates a # separated string for an attribute with mutliple simple ids' do
      subject.add_attribute(attr: 'id="simple-id1 simple-id2"')
      expect(subject.attributes_string).to eq('#simple-id1#simple-id2')
    end

    it 'generates a regular attributes string for the id if it is not in quotes' do
      subject.add_attribute(attr: 'id=erb-id')
      expect(subject.attributes_string).to eq('{ id: erb-id }')
    end

    it 'generates a regular attributes string for the id if it has string interpolation in it' do
      subject.add_attribute(attr: 'id="simple-id #{erb-id}"')
      expect(subject.attributes_string).to eq('{ id: "simple-id #{erb-id}" }')
    end
  end

  context 'classes' do
    it 'generates a string using the . syntax for simple classes' do
      subject.add_attribute(attr: 'class="simple-class"')
      expect(subject.attributes_string).to eq('.simple-class')
    end

    it 'handles single quotes' do
      subject.add_attribute(attr: "class='simple-class'")
      expect(subject.attributes_string).to eq('.simple-class')
    end

    it 'generates a . separated string for an attribute with mutliple simple classes' do
      subject.add_attribute(attr: 'class="simple-class1 simple-class2"')
      expect(subject.attributes_string).to eq('.simple-class1.simple-class2')
    end

    it 'generates a regular attributes string for the class if it is not in quotes' do
      subject.add_attribute(attr: 'class=erb-class')
      expect(subject.attributes_string).to eq('{ class: erb-class }')
    end

    it 'generates a regular attributes string for the class if it has string interpolation in it' do
      subject.add_attribute(attr: 'class="simple-class #{erb-class}"')
      expect(subject.attributes_string).to eq('{ class: "simple-class #{erb-class}" }')
    end
  end

  context 'ids, classes and regular attributes' do
    it 'combines the ids, classes and regular attributes in that order' do
      subject.add_attribute(attr: 'id="simple-id"')
      subject.add_attribute(attr: 'class="simple-class"')
      subject.add_attribute(attr: 'attr1="attribute1"')
      expect(subject.attributes_string).to eq('#simple-id.simple-class{ attr1: "attribute1" }')
    end
  end
end


text:
"""
Tests for listing endpoints
"""
from django.test import override_settings
from tests.ozp.cases import APITestCase
from rest_framework import status

from ozpcenter import model_access as generic_model_access
from ozpcenter.scripts import sample_data_generator as data_gen

@override_settings(ES_ENABLED=False)
class ListingSimilarApiTest(APITestCase):

    def setUp(self):
        """
        setUp is invoked before each test method
        """
        self.maxDiff = None

    @classmethod
    def setUpTestData(cls):
        """
        Set up test data for the whole TestCase (only run once for the TestCase)
        """
        data_gen.run()

    def test_get_similar_list_1_categories(self):
        user = generic_model_access.get_profile('wsmith').user
        self.client.force_authenticate(user=user)

        url = '/api/listing/1/similar/'
        response = self.client.get(url, format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        titles = ['{}'.format(i['title']) for i in response.data]

        expected_results = ['Acoustic Guitar',
                            'Bleach',
                            'Electric Guitar',
                            'Electric Piano',
                            'Piano',
                            'Rutebok for Norge',
                            'Sheet music',
                            'Sound Mixer',
                            'Superunknown',
                            'Ten']

        self.assertListEqual(titles, expected_results)

    def test_get_similar_list_2_categories(self):
        user = generic_model_access.get_profile('wsmith').user
        self.client.force_authenticate(user=user)

        url = '/api/listing/2/similar/'
        response = self.client.get(url, format='json')

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        titles = ['{}'.format(i['title']) for i in response.data]

        expected_results = ['Air Mail',
                            'Application programming interface',
                            'Barsoom',
                            'Bass Fishing',
                            'BeiDou Navigation Satellite System',
                            'Bombardier Transportation',
                            'Bourbon',
                            'Cable ferry',
                            'Chain boat navigation',
                            'Chatter Box']

        self.assertListEqual(titles, expected_results)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>fr.fablabmars.model</title>
<meta name="date" content="2015-04-24">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

fr.fablabmars.model

Classes

CardMenu

Contact

Facture

FicheTarifaire

QueryResult

Utilisateur


text:
package org.springframework.context.config;

import org.w3c.dom.Element;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.core.JdkVersion;
import org.springframework.jmx.support.MBeanRegistrationSupport;
import org.springframework.util.StringUtils;

/**
 * Parser for the <context:mbean-export/> element.
 *
 * <p>Registers an instance of
 * {@link org.springframework.jmx.export.annotation.AnnotationMBeanExporter}
 * within the context.
 *
 * @author Juergen Hoeller
 * @author Mark Fisher
 * @since 2.5
 * @see org.springframework.jmx.export.annotation.AnnotationMBeanExporter
 */
class MBeanExportBeanDefinitionParser extends AbstractBeanDefinitionParser {

	private static final String MBEAN_EXPORTER_BEAN_NAME = "mbeanExporter";

	private static final String DEFAULT_DOMAIN_ATTRIBUTE = "default-domain";

	private static final String SERVER_ATTRIBUTE = "server";

	private static final String REGISTRATION_ATTRIBUTE = "registration";

	private static final String REGISTRATION_IGNORE_EXISTING = "ignoreExisting";

	private static final String REGISTRATION_REPLACE_EXISTING = "replaceExisting";

	protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) {
		return MBEAN_EXPORTER_BEAN_NAME;
	}

	protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
		String beanClassName = (JdkVersion.isAtLeastJava15() ?
				"org.springframework.jmx.export.annotation.AnnotationMBeanExporter" :
				"org.springframework.jmx.export.MBeanExporter");
		BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClassName);

		// Mark as infrastructure bean and attach source location.
		builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));

		String defaultDomain = element.getAttribute(DEFAULT_DOMAIN_ATTRIBUTE);
		if (StringUtils.hasText(defaultDomain)) {
			builder.addPropertyValue("defaultDomain", defaultDomain);
		}

		String serverBeanName = element.getAttribute(SERVER_ATTRIBUTE);
		if (StringUtils.hasText(serverBeanName)) {
			builder.addPropertyReference("server", serverBeanName);
		}
		else {
			AbstractBeanDefinition specialServer = MBeanServerBeanDefinitionParser.findServerForSpecialEnvironment();
			if (specialServer != null) {
				builder.addPropertyValue("server", specialServer);
			}
		}

		String registration = element.getAttribute(REGISTRATION_ATTRIBUTE);
		int registrationBehavior = MBeanRegistrationSupport.REGISTRATION_FAIL_ON_EXISTING;
		if (REGISTRATION_IGNORE_EXISTING.equals(registration)) {
			registrationBehavior = MBeanRegistrationSupport.REGISTRATION_IGNORE_EXISTING;
		}
		else if (REGISTRATION_REPLACE_EXISTING.equals(registration)) {
			registrationBehavior = MBeanRegistrationSupport.REGISTRATION_REPLACE_EXISTING;
		}
		builder.addPropertyValue("registrationBehavior", new Integer(registrationBehavior));

		return builder.getBeanDefinition();
	}

}


text:
ppMultiLinePlot::ppMultiLinePlot(ppSessionController* pSessionController) :
    acMultiLinePlot(false, false)
{
    m_pSessionController = pSessionController;

    // Set xAxis visible / invisible:
    HideXAxisLabels(true);
}

void ppMultiLinePlot::InitPlot(const QString& xAxisTitle, const QString& yAxisTitle,
                               AMDTPwrCategory graphCategory, ppDataUtils::GraphViewCategoryType graphType,
                               GraphValuesType valuesType, const QString& unitsStr)
{
    m_graphCategory = graphCategory;
    m_graphType = graphType;
    m_valuesType = valuesType;
    m_unitsStr = unitsStr;

    m_relevantCountersVec.clear();
    ppDataUtils::GetRelevantCounterIdsByGraphType(m_relevantCountersVec, m_graphType, m_pSessionController);

    m_isShown = false;

    GT_IF_WITH_ASSERT(m_pCustomPlot != nullptr)
    {
        m_pCustomPlot->xAxis->setBasePen(QPen(PP_ACTIVE_RANGE_AXES_COLOR, PP_TIMELINE_ACTIVE_RANGE_X_AXIS_WIDTH));
        m_pCustomPlot->xAxis->setTickLabelColor(PP_ACTIVE_RANGE_AXES_COLOR);
        m_pCustomPlot->xAxis->setTicks(false);
        m_pCustomPlot->yAxis->setBasePen(QPen(PP_ACTIVE_RANGE_AXES_COLOR, PP_TIMELINE_ACTIVE_RANGE_Y_AXIS_WIDTH));
        m_pCustomPlot->yAxis->setTickLabelColor(PP_ACTIVE_RANGE_AXES_COLOR);
    }

    // Initialize the plot axes titles:
    InitPlotAxesLabels(xAxisTitle, yAxisTitle);

    InitTrackingToolTip();
}

void ppMultiLinePlot::InitPlotWithSelectedCounters()
{
    QVector<acMultiLinePlotItemData*> graphData;

    PrepareTimeLineSelectedCountersInitData(graphData);

    //if there is new data to set into graph
    if (graphData.size() > 0)
    {
        // add empty graphs to plot
        bool allowReplot = false;
        InitPlotWithEmptyGraphs(graphData, allowReplot);

        // delete data
        for (int i = 0; i < graphData.count(); i++)
        {
            delete graphData[i];
        }

        // init legend
        InitPlotInfoTable();

        // connect the add/remove button to slot
        bool rc = connect(this, SIGNAL(AddRemoveActivated()), this, SLOT(OnAddRemoveCountersAccepted()));
        GT_ASSERT(rc);
    }
}

void ppMultiLinePlot::SetGraphInitializationData()
{
    // this function initializes the data to the existing empty graphs
    QVector<acMultiLinePlotItemData*> graphData;

    // get session time range fom DB
    SamplingTimeRange samplingRange(0, 0);
    m_pSessionController->GetSessionTimeRange(samplingRange);

    // get session counters from DB
    gtVector<int> counterIds;
    ppDataUtils::GetRelevantCounterIdsByGraphType(counterIds, m_graphType, m_pSessionController);

    // if there is counters selected in the session for getting their data
    if (counterIds.size() > 0)
    {
        // get data from dB
        PrepareTimelineDataFromDB(counterIds,
                                  samplingRange,
                                  graphData);
    }

    //if there is new data to set into graph
    if (graphData.size() > 0)
    {
        // add data series to graph
        bool allowReplot = false;
        InitPlotGraphs(graphData, allowReplot);

        // delete data
        for (int i = 0; i < graphData.count(); i++)
        {
            delete graphData[i];
        }

        ResetPlotInfoTable();

        ResetPlotInfoTableColumnWidth();
        SetInfoTableBySpecificTimePoint(samplingRange.m_toTime);
    }
    else
    {
        // hide graph and it's legend:
        m_isShown = false;
    }
}

void ppMultiLinePlot::PrepareTimeLineSelectedCountersInitData(QVector<acMultiLinePlotItemData*>& graphData)
{
    int count = m_relevantCountersVec.size();

    if (m_pSessionController != nullptr)
    {
        for (int i = 0; i < count; i++)
        {
            QString name = m_pSessionController->GetCounterNameById(m_relevantCountersVec[i]);
            QColor color = m_pSessionController->GetColorForCounter(m_relevantCountersVec[i]);
            QString description = m_pSessionController->GetCounterDescription(m_relevantCountersVec[i]);

            QVector<double> keyVec;
            QVector<double> valueVec;
            acMultiLinePlotItemData* graphItem = new acMultiLinePlotItemData(keyVec, valueVec, color, name, description);
            graphData << graphItem;
        }
    }
}

void ppMultiLinePlot::UpdateVisibility()
{
    if (nullptr != GetPlot())
    {
        GetPlot()->setVisible(m_isShown);
    }

    if (GetPlotInfoTable() != nullptr)
    {
        GetPlotInfoTable()->setVisible(m_isShown);
    }
}

void ppMultiLinePlot::UpdatePlotRange(bool isReplotNeeded, SamplingTimeRange samplingRange)
{
    QCPRange currentRange = GetGraphRange();

    if (currentRange.lower != samplingRange.m_fromTime ||
        currentRange.upper != samplingRange.m_toTime)
    {
        ChangeGraphRangeByBothPoints(samplingRange.m_fromTime, samplingRange.m_toTime);

        if (isReplotNeeded)
        {
            Replot();
        }
    }
}

void ppMultiLinePlot::PrepareTimelineDataFromDB(const gtVector<int>& counterIds,
                                                SamplingTimeRange& samplingTimeRange,
                                                QVector<acMultiLinePlotItemData*>& graphData)
{
    int id;
    int numOfValues;
    QString name;
    QString  description;
    acMultiLinePlotItemData* graphItem;
    QVector<double> keyVec;
    QVector<double> valueVec;
    QColor color;

    if (m_pSessionController != nullptr)
    {
        gtMap<int, gtVector<SampledValue>> sampledDataPerCounter;
        m_pSessionController->GetProfilerBL().GetSampledValuesByRange(counterIds, samplingTimeRange, sampledDataPerCounter);

        int countersNum = m_relevantCountersVec.size();

        for (int i = 0; i < countersNum; i++)
        {
            id = m_relevantCountersVec[i];

            GT_IF_WITH_ASSERT(sampledDataPerCounter.count(id) > 0)
            {
                name = m_pSessionController->GetCounterNameById(id);
                color = m_pSessionController->GetColorForCounter(id);
                description = m_pSessionController->GetCounterDescription(id);

                keyVec.clear();
                valueVec.clear();

                numOfValues = sampledDataPerCounter[id].size();

                for (int j = 0; j < numOfValues; j++)
                {
                    keyVec << (sampledDataPerCounter[id])[j].m_sampleTime;
                    valueVec << (sampledDataPerCounter[id])[j].m_sampleValue;
                }

                graphItem = new acMultiLinePlotItemData(keyVec, valueVec, color, name, description);
                graphData << graphItem;
            }
        }
    }
}

void ppMultiLinePlot::PrepareTimelineDataFromNewDataEvent(ppQtEventData pSampledDataPerCounter,
                                                          QVector<acMultiLinePlotItemData*>& graphData)
{
    GT_IF_WITH_ASSERT(nullptr != m_pSessionController)
    {
        int id;
        QString name, description;
        acMultiLinePlotItemData* graphItem;
        QColor color;
        QVector<double> keyVec;
        QVector<double> valueVec;

        int count = m_relevantCountersVec.size();

        for (int i = 0; i < count; i++)
        {
            id = m_relevantCountersVec[i];
            //find the relevant counter in the event data map
            gtMap<int, PPSampledValuesBatch>::const_iterator it = pSampledDataPerCounter->find(id);

            // if not fount in map - bug - the same selected counters should be in the map and in the plot
            GT_IF_WITH_ASSERT(it != pSampledDataPerCounter->end())
            {
                name = m_pSessionController->GetCounterNameById(id);
                color = m_pSessionController->GetColorForCounter(id);
                description = m_pSessionController->GetCounterDescription(id);

                keyVec.clear();
                valueVec.clear();

                keyVec << (*it).second.m_quantizedTime;
                valueVec << (*it).second.m_sampleValues[0];

                graphItem = new acMultiLinePlotItemData(keyVec, valueVec, color, name, description);
                graphData << graphItem;
            }
        }
    }
}

void ppMultiLinePlot::AddNewDataToExistingGraph(ppQtEventData pSampledDataPerCounter, SamplingTimeRange samplingRange, bool bShouldUpdateLastSample)
{
    QVector<double> valVec;

    // in specific event - all counters have the same key (time)
    gtMap<int, PPSampledValuesBatch>::const_iterator it = pSampledDataPerCounter->begin();
    double key = (*it).second.m_quantizedTime;

    if (m_relevantCountersVec.size() > 0)
    {
        GetValueVecFromEventData(pSampledDataPerCounter, valVec);

        // add data to graph
        bool removeOldSamplings = false;
        bool allowReplot = false;
        AddDataToTimeLineGraph(key, valVec, samplingRange.m_fromTime, samplingRange.m_toTime, removeOldSamplings, allowReplot);

        // update lege0-11nd by last point
        if (HasLegend() && bShouldUpdateLastSample)
        {
            ResetPlotInfoTableColumnWidth();
            SetInfoTableBySpecificTimePoint(samplingRange.m_toTime);
        }
    }
}

void ppMultiLinePlot::GetValueVecFromEventData(ppQtEventData pSampledDataPerCounter, QVector<double>& valVec)
{
    GT_IF_WITH_ASSERT(m_pSessionController != nullptr)
    {
        int id;
        int index;
        QString name;
        int countersNum = m_relevantCountersVec.size();

        // add temp data - for finding un-updated data
        for (int i = 0; i < countersNum; i++)
        {
            valVec << -1;
        }

        for (int i = 0; i < countersNum; i++)
        {
            id = m_relevantCountersVec[i];

            // ceck if the id is in the event data map
            GT_IF_WITH_ASSERT(pSampledDataPerCounter->count(id) > 0)
            {
                // get graph index for this counter and set the vector in the index place to the counter value
                name = m_pSessionController->GetCounterNameById(id);
                index = GetGraphIndexByName(name);

                GT_IF_WITH_ASSERT(index > -1 && index < countersNum)
                {
                    valVec[index] = pSampledDataPerCounter->at(id).m_sampleValues[0];
                }
            }
        }
    }
}

void ppMultiLinePlot::OnAddRemoveCountersAccepted()
{
    ppCountersSelectionDialog::OpenCountersSelectionDialog(m_graphCategory);
}

void ppMultiLinePlot::Delete()
{
    // not in destructor because - this destructor called also when layout is deleted.
    // if the layout destructor is called first it will delete this object too, so when we get to this destructor the object will not be exist, and we cant delete it.
    m_pCustomPlot->clearGraphs();
    m_pGraphsVec.clear();
    m_pPlotInfoTable->deleteLater();
    m_pCustomPlot->deleteLater();
}

void ppMultiLinePlot::SetShown(bool isShown, bool shouldUpdateVisibility)
{
    m_isShown = isShown;

    if (shouldUpdateVisibility)
    {
        UpdateVisibility();
    }
}

void ppMultiLinePlot::HideSingleLineGraphFromCumulative(int selectedGraphIndex, bool hideGrpah)
{
    int prevGraphIndex = -1;
    acVectorLineGraph* pTmpGraph = qobject_cast<acVectorLineGraph*>(m_pCustomPlot->graph(selectedGraphIndex));
    GT_IF_WITH_ASSERT(nullptr != pTmpGraph)
    {
        acDataVector* pDataVec = pTmpGraph->VectorData();
        acDataVector* prevDataVec = nullptr;

        //step 1: get the index of the shown graph that comes right below the one we like to remove/add
        for (int i = selectedGraphIndex - 1; i >= 0; i--)
        {
            GT_IF_WITH_ASSERT(i < m_pGraphsVec.count())
            {
                if (!m_pGraphsVec[i]->IsHidden())
                {
                    prevGraphIndex = i;
                    break;
                }
            }
        }

        // step 2: if it is not the first graph shown (first on the bottom of the plot)
        // get the previous (the graphs below it) y values
        if (selectedGraphIndex > 0 && prevGraphIndex > -1)
        {
            pTmpGraph = qobject_cast<acVectorLineGraph*>(m_pCustomPlot->graph(prevGraphIndex));
            GT_IF_WITH_ASSERT(nullptr != pTmpGraph)
            {
                prevDataVec = pTmpGraph->VectorData();
            }
            else
            {
                prevGraphIndex = -1;
            }
        }

        // step 3: get the removed graph (single line graph) y values
        QVector<double> removedGraphVals;

        unsigned int vecSize = pDataVec->size();

        // if it is the first graph (on the bottom of the plot) - get its value
        if (selectedGraphIndex == 0 || prevGraphIndex == -1)
        {
            for (unsigned int i = 0; i < vecSize; i++)
            {
                removedGraphVals << ((*pDataVec)[i]).Value();
            }
        }
        else
        {
            // if not we need to reduce the graphs below it from its value to get its real value
            // (as in cumulative graph the values are also cumulative)
            // for showing (not hiding) the graph we the the oposide thing (add not reduce)
            GT_IF_WITH_ASSERT(nullptr != prevDataVec && nullptr != pDataVec)
            {
                // if the total graph - don't do nothing
                if (selectedGraphIndex < (m_pCustomPlot->graphCount() - 1))
                {
                    for (unsigned int i = 0; i < vecSize; i++)
                    {
                        // if not first - get its value minus/plus the value of shown graph below
                        if (hideGrpah)
                        {
                            removedGraphVals << ((*pDataVec)[i]).Value() - ((*prevDataVec)[i]).Value();
                            ((*pDataVec)[i]).SetValue(((*pDataVec)[i]).Value() - ((*prevDataVec)[i]).Value());
                        }
                        else // show graph
                        {
                            removedGraphVals << ((*pDataVec)[i]).Value();
                            ((*pDataVec)[i]).SetValue(((*pDataVec)[i]).Value() + ((*prevDataVec)[i]).Value());
                        }
                    }
                }
            }
        }

        // step 4: update all graphs data. update graphs values that above the removed/added graph
        // when the graph hidden - we need to reduce its y values from all graphs above it.
        // when the graph is added - we need to add its y values from all graphs above it.
        int numGraphs = m_pCustomPlot->graphCount();

        // only if the total counter exist - dont move it and dont reduce from it as that graph is static even if graphs below it are hidden
        if (m_isLastGraphTotal)
        {
            numGraphs -= 1;
        }

        for (int graphIndex = selectedGraphIndex + 1; graphIndex < numGraphs; graphIndex++)
        {
            // if the graph above not hidden
            if (!m_pGraphsVec[graphIndex]->IsHidden())
            {
                pTmpGraph = qobject_cast<acVectorLineGraph*>(m_pCustomPlot->graph(graphIndex));

                GT_IF_WITH_ASSERT(nullptr != pTmpGraph)
                {
                    pDataVec = pTmpGraph->VectorData();

                    // all graphs data vector is in the same size (same keys)
                    GT_IF_WITH_ASSERT(nullptr != pDataVec && vecSize == pDataVec->size())
                    {
                        for (unsigned int index = 0; index < vecSize; index++)
                        {
                            if (hideGrpah)
                            {
                                ((*pDataVec)[index]).SetValue(((*pDataVec)[index]).Value() - removedGraphVals[index]);
                            }
                            else
                            {
                                ((*pDataVec)[index]).SetValue(((*pDataVec)[index]).Value() + removedGraphVals[index]);
                            }
                        }
                    }
                }
            }
        }

        // step 5: order fill
        OrderGraphChannelFill();
    }
}

void ppMultiLinePlot::SetPowerGraphLegendCheckState(QVector<bool> hiddenStateVec)
{
    // get legend
    acListCtrl* pLegend = GetPlotInfoTable();

    GT_IF_WITH_ASSERT(pLegend != nullptr)
    {
        unsigned int count = hiddenStateVec.count();
        int row = 0;

        // for all graphs - set their check state by the inpout vector
        for (unsigned int graphIndex = 0; graphIndex < count; graphIndex++)
        {
            // get the graph row number in legend
            row = count - 1 - graphIndex;

            GT_IF_WITH_ASSERT(row < pLegend->rowCount())
            {
                // set row related row in legend checked/unchecked
                QTableWidgetItem* pItem = pLegend->item(row, LEGEND_CHECKBOX_COLUMN);

                GT_IF_WITH_ASSERT(pItem != nullptr)
                {
                    if (hiddenStateVec[graphIndex] == true)
                    {
                        pItem->setCheckState(Qt::Unchecked);
                    }
                    else
                    {
                        // set checked only if graph is not disabled
                        if (!IsGraphDisabledAtIndex(graphIndex))
                        {
                            pItem->setCheckState(Qt::Checked);
                        }
                    }
                }
            }
        }
    }
}

void ppMultiLinePlot::ResetPlotInfoTableColumnWidth()
{
    // Sanity check:
    GT_IF_WITH_ASSERT(m_pPlotInfoTable != nullptr)
    {
        m_pPlotInfoTable->resizeColumnToContents(1);
    }
}


text:
package us.codecraft.forger;

/**
 * @author code4crafter@gmail.com
 */
public interface Fooable {

    public String foo();
}


text:
/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
	System.config({
		paths: {
			// paths serve as alias
			'npm:': 'node_modules/'
		},
		// map tells the System loader where to look for things
		map: {
			// our app is within the app folder
			'app': 'app',

			// angular bundles
			'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
			'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
			'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
			'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
			'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
			'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
			'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
			'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',

			// other libraries
			'rxjs':                      'npm:rxjs',
			'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'
		},
		// packages tells the System loader how to load when no filename and/or no extension
		packages: {
			app: {
				defaultExtension: 'js',
				meta: {
					'./*.js': {
						loader: 'systemjs-angular-loader.js'
					}
				}
			},
			rxjs: {
				defaultExtension: 'js'
			}
		}
	});
})(this);


text:
module Rubex
  module AST
    module Statement
      module BeginBlock
        class Begin < Base
          def initialize(statements, tails, location)
            @tails = tails
            super(statements, location)
          end

          def analyse_statement(local_scope)
            local_scope.found_begin_block
            declare_error_state_variable local_scope
            declare_error_klass_variable local_scope
            declare_unhandled_error_variable local_scope
            @block_scope = Rubex::SymbolTable::Scope::BeginBlock.new(
              block_name(local_scope), local_scope
            )
            create_c_function_to_house_statements local_scope.outer_scope
            analyse_tails local_scope
          end

          def generate_code(code, local_scope)
            code.nl
            code << '/* begin-rescue-else-ensure-end block begins: */'
            code.nl
            super
            cb_c_name = local_scope.find(@begin_func.name).c_name
            state_var = local_scope.find(@state_var_name).c_name
            code << "#{state_var} = 0;\n"
            code << "rb_protect(#{cb_c_name}, Qnil, &#{state_var});"
            code.nl
            generate_rescue_else_ensure code, local_scope
          end

          private

          def generate_rescue_else_ensure(code, local_scope)
            err_state_var = local_scope.find(@error_var_name).c_name
            set_error_state_variable err_state_var, code, local_scope
            set_unhandled_error_variable code, local_scope
            generate_rescue_blocks err_state_var, code, local_scope
            generate_else_block code, local_scope
            generate_ensure_block code, local_scope
            generate_rb_jump_tag err_state_var, code, local_scope
            code << "rb_set_errinfo(Qnil);\n"
          end

          def declare_unhandled_error_variable(local_scope)
            @unhandled_err_var_name = 'begin_block_' + local_scope.begin_block_counter.to_s + '_unhandled_error'
            local_scope.declare_var(
              name: @unhandled_err_var_name,
              c_name: Rubex::VAR_PREFIX + @unhandled_err_var_name,
              type: DataType::Int.new
            )
          end

          def set_unhandled_error_variable(code, local_scope)
            n = local_scope.find(@unhandled_err_var_name).c_name
            code << "#{n} = 0;"
            code.nl
          end

          def generate_rb_jump_tag(_err_state_var, code, local_scope)
            state_var = local_scope.find(@state_var_name).c_name
            code << "if (#{local_scope.find(@unhandled_err_var_name).c_name})"
            code.block do
              code << "rb_jump_tag(#{state_var});"
              code.nl
            end
          end

          def generate_ensure_block(code, local_scope)
            ensure_block = @tails.select { |e| e.is_a?(Ensure) }[0]
            ensure_block&.generate_code(code, local_scope)
          end

          # We use a goto statement to jump to the ensure block so that when a
          # condition arises where no error is raised, the ensure statement will
          # be executed, after which rb_jump_tag() will be called.
          def generate_else_block(code, local_scope)
            else_block = @tails.select { |t| t.is_a?(Else) }[0]

            code << 'else'
            code.block do
              state_var = local_scope.find(@state_var_name).c_name
              code << '/* If exception not among those captured in raise */'
              code.nl

              code << "if (#{state_var})"
              code.block do
                code << "#{local_scope.find(@unhandled_err_var_name).c_name} = 1;"
                code.nl
              end

              if else_block
                code << 'else'
                code.block do
                  else_block.generate_code code, local_scope
                end
              end
            end
          end

          def set_error_state_variable(err_state_var, code, _local_scope)
            code << "#{err_state_var} = rb_errinfo();"
            code.nl
          end

          def generate_rescue_blocks(err_state_var, code, local_scope)
            if @tails[0].is_a?(Rescue)
              generate_first_rescue_block err_state_var, code, local_scope

              @tails[1..-1].grep(Rescue).each do |resc|
                else_if_cond = rescue_condition err_state_var, resc, code, local_scope
                code << "else if (#{else_if_cond})"
                code.block do
                  resc.generate_code code, local_scope
                end
              end
            else # no rescue blocks present
              code << "if (0) {}\n"
            end
          end

          def generate_first_rescue_block(err_state_var, code, local_scope)
            code << "if (#{rescue_condition(err_state_var, @tails[0], code, local_scope)})"
            code.block do
              @tails[0].generate_code code, local_scope
            end
          end

          def rescue_condition(err_state_var, resc, code, local_scope)
            resc.error_klass.generate_evaluation_code code, local_scope
            cond = "RTEST(rb_funcall(#{err_state_var}, rb_intern(\"kind_of?\")"
            cond << ", 1, #{resc.error_klass.c_code(local_scope)}))"

            cond
          end

          def declare_error_state_variable(local_scope)
            @state_var_name = 'begin_block_' + local_scope.begin_block_counter.to_s + '_state'
            local_scope.declare_var(
              name: @state_var_name,
              c_name: Rubex::VAR_PREFIX + @state_var_name,
              type: DataType::Int.new
            )
          end

          def declare_error_klass_variable(local_scope)
            @error_var_name = 'begin_block_' + local_scope.begin_block_counter.to_s + '_exec'
            local_scope.declare_var(
              name: @error_var_name,
              c_name: Rubex::VAR_PREFIX + @error_var_name,
              type: DataType::RubyObject.new
            )
          end

          def block_name(local_scope)
            'begin_block_' + local_scope.klass_name + '_' + local_scope.name + '_' +
              local_scope.begin_block_counter.to_s
          end

          def create_c_function_to_house_statements(scope)
            func_name = @block_scope.name
            arg_list = Statement::ArgumentList.new([
                                                     AST::Expression::ArgDeclaration.new(
                                                     { dtype: 'object',
                                                       variables: [{ ident: 'dummy' }] }
                                                     )
                                                   ])
            @begin_func = TopStatement::CFunctionDef.new(
              'object', '', func_name, arg_list, nil, @statements
            )
            arg_list.analyse_statement @block_scope
            add_to_symbol_table @begin_func.name, arg_list, scope
            @begin_func.analyse_statement @block_scope
            @block_scope.upgrade_symbols_to_global
            scope.add_begin_block_callback @begin_func
          end

          def add_to_symbol_table(func_name, arg_list, scope)
            c_name = Rubex::C_FUNC_PREFIX + func_name
            scope.add_c_method(
              name: func_name,
              c_name: c_name,
              extern: false,
              return_type: DataType::RubyObject.new,
              arg_list: arg_list,
              scope: @block_scope
            )
          end

          def analyse_tails(local_scope)
            @tails.each do |tail|
              tail.analyse_statement local_scope
            end
          end
        end
      end
    end
  end
end


text:
layout: page
title: Leadership Minor
comments: true
description: "blank"
keywords: LEAD, CU, Boulder
---

LEAD 1000: Becoming A Leader

LEAD 4000: Leadership In Context And Emerging Challenges: A Capstone


text:
/*************************************************************************/
/*  spin_box.cpp                                                         */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "spin_box.h"

#include "core/input/input.h"
#include "core/math/expression.h"

Size2 SpinBox::get_minimum_size() const {
	Size2 ms = line_edit->get_combined_minimum_size();
	ms.width += last_w;
	return ms;
}

void SpinBox::_value_changed(double) {
	String value = TS->format_number(String::num(get_value(), Math::range_step_decimals(get_step())));
	if (prefix != "") {
		value = prefix + " " + value;
	}
	if (suffix != "") {
		value += " " + suffix;
	}
	line_edit->set_text(value);
}

void SpinBox::_text_entered(const String &p_string) {
	Ref<Expression> expr;
	expr.instance();

	String num = TS->parse_number(p_string);
	// Ignore the prefix and suffix in the expression
	Error err = expr->parse(num.trim_prefix(prefix + " ").trim_suffix(" " + suffix));
	if (err != OK) {
		return;
	}

	Variant value = expr->execute(Array(), nullptr, false);
	if (value.get_type() != Variant::NIL) {
		set_value(value);
	}
	_value_changed(0);
}

LineEdit *SpinBox::get_line_edit() {
	return line_edit;
}

void SpinBox::_line_edit_input(const Ref<InputEvent> &p_event) {
}

void SpinBox::_range_click_timeout() {
	if (!drag.enabled && Input::get_singleton()->is_mouse_button_pressed(MOUSE_BUTTON_LEFT)) {
		bool up = get_local_mouse_position().y < (get_size().height / 2);
		set_value(get_value() + (up ? get_step() : -get_step()));

		if (range_click_timer->is_one_shot()) {
			range_click_timer->set_wait_time(0.075);
			range_click_timer->set_one_shot(false);
			range_click_timer->start();
		}

	} else {
		range_click_timer->stop();
	}
}

void SpinBox::_release_mouse() {
	if (drag.enabled) {
		drag.enabled = false;
		Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_VISIBLE);
		warp_mouse(drag.capture_pos);
	}
}

void SpinBox::_gui_input(const Ref<InputEvent> &p_event) {
	ERR_FAIL_COND(p_event.is_null());

	if (!is_editable()) {
		return;
	}

	Ref<InputEventMouseButton> mb = p_event;

	if (mb.is_valid() && mb->is_pressed()) {
		bool up = mb->get_position().y < (get_size().height / 2);

		switch (mb->get_button_index()) {
			case MOUSE_BUTTON_LEFT: {
				line_edit->grab_focus();

				set_value(get_value() + (up ? get_step() : -get_step()));

				range_click_timer->set_wait_time(0.6);
				range_click_timer->set_one_shot(true);
				range_click_timer->start();

				drag.allowed = true;
				drag.capture_pos = mb->get_position();
			} break;
			case MOUSE_BUTTON_RIGHT: {
				line_edit->grab_focus();
				set_value((up ? get_max() : get_min()));
			} break;
			case MOUSE_BUTTON_WHEEL_UP: {
				if (line_edit->has_focus()) {
					set_value(get_value() + get_step() * mb->get_factor());
					accept_event();
				}
			} break;
			case MOUSE_BUTTON_WHEEL_DOWN: {
				if (line_edit->has_focus()) {
					set_value(get_value() - get_step() * mb->get_factor());
					accept_event();
				}
			} break;
		}
	}

	if (mb.is_valid() && !mb->is_pressed() && mb->get_button_index() == MOUSE_BUTTON_LEFT) {
		//set_default_cursor_shape(CURSOR_ARROW);
		range_click_timer->stop();
		_release_mouse();
		drag.allowed = false;
	}

	Ref<InputEventMouseMotion> mm = p_event;

	if (mm.is_valid() && mm->get_button_mask() & MOUSE_BUTTON_MASK_LEFT) {
		if (drag.enabled) {
			drag.diff_y += mm->get_relative().y;
			float diff_y = -0.01 * Math::pow(ABS(drag.diff_y), 1.8f) * SGN(drag.diff_y);
			set_value(CLAMP(drag.base_val + get_step() * diff_y, get_min(), get_max()));
		} else if (drag.allowed && drag.capture_pos.distance_to(mm->get_position()) > 2) {
			Input::get_singleton()->set_mouse_mode(Input::MOUSE_MODE_CAPTURED);
			drag.enabled = true;
			drag.base_val = get_value();
			drag.diff_y = 0;
		}
	}
}

void SpinBox::_line_edit_focus_exit() {
	// discontinue because the focus_exit was caused by right-click context menu
	if (line_edit->get_menu()->is_visible()) {
		return;
	}

	_text_entered(line_edit->get_text());
}

inline void SpinBox::_adjust_width_for_icon(const Ref<Texture2D> &icon) {
	int w = icon->get_width();
	if ((w != last_w)) {
		line_edit->set_offset(SIDE_LEFT, 0);
		line_edit->set_offset(SIDE_RIGHT, -w);
		last_w = w;
	}
}

void SpinBox::_notification(int p_what) {
	if (p_what == NOTIFICATION_DRAW) {
		Ref<Texture2D> updown = get_theme_icon("updown");

		_adjust_width_for_icon(updown);

		RID ci = get_canvas_item();
		Size2i size = get_size();

		if (is_layout_rtl()) {
			updown->draw(ci, Point2i(0, (size.height - updown->get_height()) / 2));
		} else {
			updown->draw(ci, Point2i(size.width - updown->get_width(), (size.height - updown->get_height()) / 2));
		}

	} else if (p_what == NOTIFICATION_FOCUS_EXIT) {
		//_value_changed(0);
	} else if (p_what == NOTIFICATION_ENTER_TREE) {
		_adjust_width_for_icon(get_theme_icon("updown"));
		_value_changed(0);
	} else if (p_what == NOTIFICATION_EXIT_TREE) {
		_release_mouse();
	} else if (p_what == NOTIFICATION_TRANSLATION_CHANGED) {
		_value_changed(0);
	} else if (p_what == NOTIFICATION_THEME_CHANGED) {
		call_deferred("minimum_size_changed");
		get_line_edit()->call_deferred("minimum_size_changed");
	} else if (p_what == NOTIFICATION_LAYOUT_DIRECTION_CHANGED || p_what == NOTIFICATION_TRANSLATION_CHANGED) {
		update();
	}
}

void SpinBox::set_align(LineEdit::Align p_align) {
	line_edit->set_align(p_align);
}

LineEdit::Align SpinBox::get_align() const {
	return line_edit->get_align();
}

void SpinBox::set_suffix(const String &p_suffix) {
	suffix = p_suffix;
	_value_changed(0);
}

String SpinBox::get_suffix() const {
	return suffix;
}

void SpinBox::set_prefix(const String &p_prefix) {
	prefix = p_prefix;
	_value_changed(0);
}

String SpinBox::get_prefix() const {
	return prefix;
}

void SpinBox::set_editable(bool p_editable) {
	line_edit->set_editable(p_editable);
}

bool SpinBox::is_editable() const {
	return line_edit->is_editable();
}

void SpinBox::apply() {
	_text_entered(line_edit->get_text());
}

void SpinBox::_bind_methods() {
	//ClassDB::bind_method(D_METHOD("_value_changed"),&SpinBox::_value_changed);
	ClassDB::bind_method(D_METHOD("_gui_input"), &SpinBox::_gui_input);
	ClassDB::bind_method(D_METHOD("set_align", "align"), &SpinBox::set_align);
	ClassDB::bind_method(D_METHOD("get_align"), &SpinBox::get_align);
	ClassDB::bind_method(D_METHOD("set_suffix", "suffix"), &SpinBox::set_suffix);
	ClassDB::bind_method(D_METHOD("get_suffix"), &SpinBox::get_suffix);
	ClassDB::bind_method(D_METHOD("set_prefix", "prefix"), &SpinBox::set_prefix);
	ClassDB::bind_method(D_METHOD("get_prefix"), &SpinBox::get_prefix);
	ClassDB::bind_method(D_METHOD("set_editable", "editable"), &SpinBox::set_editable);
	ClassDB::bind_method(D_METHOD("is_editable"), &SpinBox::is_editable);
	ClassDB::bind_method(D_METHOD("apply"), &SpinBox::apply);
	ClassDB::bind_method(D_METHOD("get_line_edit"), &SpinBox::get_line_edit);

	ADD_PROPERTY(PropertyInfo(Variant::INT, "align", PROPERTY_HINT_ENUM, "Left,Center,Right,Fill"), "set_align", "get_align");
	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "editable"), "set_editable", "is_editable");
	ADD_PROPERTY(PropertyInfo(Variant::STRING, "prefix"), "set_prefix", "get_prefix");
	ADD_PROPERTY(PropertyInfo(Variant::STRING, "suffix"), "set_suffix", "get_suffix");
}

SpinBox::SpinBox() {
	line_edit = memnew(LineEdit);
	add_child(line_edit);

	line_edit->set_anchors_and_offsets_preset(Control::PRESET_WIDE);
	line_edit->set_mouse_filter(MOUSE_FILTER_PASS);
	line_edit->set_align(LineEdit::ALIGN_LEFT);

	//connect("value_changed",this,"_value_changed");
	line_edit->connect("text_entered", callable_mp(this, &SpinBox::_text_entered), Vector<Variant>(), CONNECT_DEFERRED);
	line_edit->connect("focus_exited", callable_mp(this, &SpinBox::_line_edit_focus_exit), Vector<Variant>(), CONNECT_DEFERRED);
	line_edit->connect("gui_input", callable_mp(this, &SpinBox::_line_edit_input));

	range_click_timer = memnew(Timer);
	range_click_timer->connect("timeout", callable_mp(this, &SpinBox::_range_click_timeout));
	add_child(range_click_timer);
}


text:
package io.micrometer.core.tck;

import io.micrometer.core.instrument.LongTaskTimer;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.instrument.distribution.CountAtBucket;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
import io.micrometer.core.instrument.internal.DefaultLongTaskTimer;
import io.micrometer.core.instrument.simple.SimpleConfig;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static io.micrometer.core.instrument.MockClock.clock;
import static org.assertj.core.api.Assertions.assertThat;

public class DefaultLongTaskTimerTest {

    @Test
    @DisplayName("supports sending histograms of active task duration")
    void histogram() {
        MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock());
        LongTaskTimer t = LongTaskTimer.builder("my.timer")
                .serviceLevelObjectives(Duration.ofSeconds(10), Duration.ofSeconds(40), Duration.ofMinutes(1))
                .register(registry);

        List<Integer> samples = Arrays.asList(48, 42, 40, 35, 22, 16, 13, 8, 6, 4, 2);
        int prior = samples.get(0);
        for (Integer value : samples) {
            clock(registry).add(prior - value, TimeUnit.SECONDS);
            t.start();
            prior = value;
        }
        clock(registry).add(samples.get(samples.size() - 1), TimeUnit.SECONDS);

        CountAtBucket[] countAtBuckets = t.takeSnapshot().histogramCounts();

        assertThat(countAtBuckets[0].bucket(TimeUnit.SECONDS)).isEqualTo(10);
        assertThat(countAtBuckets[0].count()).isEqualTo(4);

        assertThat(countAtBuckets[1].bucket(TimeUnit.SECONDS)).isEqualTo(40);
        assertThat(countAtBuckets[1].count()).isEqualTo(9);

        assertThat(countAtBuckets[2].bucket(TimeUnit.MINUTES)).isEqualTo(1);
        assertThat(countAtBuckets[2].count()).isEqualTo(11);
    }

    @Test
    void histogramWithMoreBucketsThanActiveTasks() {
        MockClock clock = new MockClock();
        MeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, clock) {
            @Override
            protected LongTaskTimer newLongTaskTimer(Meter.Id id,
                    DistributionStatisticConfig distributionStatisticConfig) {
                // supportsAggregablePercentiles true for using pre-defined histogram
                // buckets
                return new DefaultLongTaskTimer(id, clock, getBaseTimeUnit(), distributionStatisticConfig, true);
            }
        };
        LongTaskTimer ltt = LongTaskTimer.builder("my.ltt").publishPercentileHistogram().register(registry);
        ltt.start();
        clock.add(15, TimeUnit.MINUTES);
        ltt.start();
        clock.add(5, TimeUnit.MINUTES);
        // one task at 20 minutes, one task at 5 minutes
        CountAtBucket[] countAtBuckets = ltt.takeSnapshot().histogramCounts();
        int index = 0;
        while (countAtBuckets[index].bucket(TimeUnit.NANOSECONDS) < Duration.ofMinutes(5).toNanos()) {
            assertThat(countAtBuckets[index++].count()).isZero();
        }
        while (countAtBuckets[index].bucket(TimeUnit.NANOSECONDS) < Duration.ofMinutes(20).toNanos()) {
            assertThat(countAtBuckets[index++].count()).isOne();
        }
        while (index < countAtBuckets.length) {
            assertThat(countAtBuckets[index++].count()).isEqualTo(2);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <subjects>
      <billSubjects>
        <legislativeSubjects>
          <item>
            <name>Congressional committees</name>
          </item>
          <item>
            <name>Senate Special Committee on Aging</name>
          </item>
        </legislativeSubjects>
        <policyArea>
          <name>Congress</name>
        </policyArea>
      </billSubjects>
    </subjects>
    <laws />
    <committeeReports />
    <actions>
      <actionTypeCounts>
        <introducedInSenate>1</introducedInSenate>
        <originalBillReported>1</originalBillReported>
        <referredToCommittee>1</referredToCommittee>
        <reportedToSenate>1</reportedToSenate>
      </actionTypeCounts>
      <actionByCounts>
        <senate>4</senate>
      </actionByCounts>
      <item>
        <actionDate>2017-02-01</actionDate>
        <committee>
          <name>Rules and Administration Committee</name>
          <systemCode>ssra00</systemCode>
        </committee>
        <links>
          <link>
            <url>https://www.congress.gov/congressional-record/volume-163/senate-section/page/S598</url>
            <name>S598</name>
          </link>
        </links>
        <sourceSystem>
          0
          <name>Senate</name>
        </sourceSystem>
        <text>Referred to the Committee on Rules and Administration. (text of measure as introduced: CR S598)</text>
        <type>IntroReferral</type>
      </item>
      <item>
        <actionDate>2017-02-01</actionDate>
        <committee>
          <name>Aging Committee</name>
          <systemCode>spag00</systemCode>
        </committee>
        <links />
        <sourceSystem>
          0
          <name>Senate</name>
        </sourceSystem>
        <text>Special Committee on Aging. Original measure reported to Senate by Senator Collins. Without written report.</text>
        <type>Committee</type>
      </item>
      <item>
        <type>Committee</type>
        <actionDate>2017-02-01</actionDate>
        <text>Special Committee on Aging. Original measure reported to Senate by Senator Collins. Without written report.</text>
        <committee>
          <name>Aging Committee</name>
          <systemCode>spag00</systemCode>
        </committee>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <actionCode>14000</actionCode>
        <links />
      </item>
      <item>
        <type>IntroReferral</type>
        <actionDate>2017-02-01</actionDate>
        <text>Introduced in Senate</text>
        <committee />
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <actionCode>10000</actionCode>
        <links />
      </item>
    </actions>
    <introducedDate>2017-02-01</introducedDate>
    <createDate>2017-02-02T05:28:46Z</createDate>
    <amendments />
    <relatedBills />
    <billNumber>31</billNumber>
    <committees>
      <billCommittees>
        <item>
          <activities>
            <item>
              <name>Referred to</name>
              <date>2017-02-01T21:48:21Z</date>
            </item>
          </activities>
          <type>Standing</type>
          <name>Rules and Administration Committee</name>
          <chamber>Senate</chamber>
          <subcommittees />
          <systemCode>ssra00</systemCode>
        </item>
        <item>
          <activities>
            <item>
              <name>Reported original measure</name>
              <date>2017-02-01T21:47:19Z</date>
            </item>
          </activities>
          <type>Special</type>
          <name>Aging Committee</name>
          <chamber>Senate</chamber>
          <subcommittees />
          <systemCode>spag00</systemCode>
        </item>
      </billCommittees>
    </committees>
    <calendarNumbers />
    <title>An original resolution authorizing the expenditures by the Special Committee on Aging.</title>
    <version>1.0.0</version>
    <titles>
      <item>
        <chamberCode />
        <titleType>Official Title as Introduced</titleType>
        <parentTitleType />
        <chamberName />
        <title>An original resolution authorizing the expenditures by the Special Committee on Aging.</title>
      </item>
      <item>
        <chamberCode />
        <titleType>Display Title</titleType>
        <parentTitleType />
        <chamberName />
        <title>An original resolution authorizing the expenditures by the Special Committee on Aging.</title>
      </item>
    </titles>
    <notes />
    <summaries>
      <billSummaries>
        <item>
          <versionCode>00</versionCode>
          <lastSummaryUpdateDate>2017-03-02T22:53:20Z</lastSummaryUpdateDate>
          <updateDate>2017-02-01T05:00:00Z</updateDate>
          <name>Introduced in Senate</name>
          <actionDesc>Introduced in Senate</actionDesc>
          <text><![CDATA[
Authorizes expenditures by the Senate Special Committee on Aging for the 115th Congress.
]]></text>
          <actionDate>2017-02-01</actionDate>
        </item>
        <item>
          <versionCode>80</versionCode>
          <lastSummaryUpdateDate>2017-03-02T22:53:52Z</lastSummaryUpdateDate>
          <updateDate>2017-02-01T19:00:38Z</updateDate>
          <name>Reported to Senate without amendment</name>
          <actionDesc>Reported to Senate without amendment</actionDesc>
          <text><![CDATA[
(This measure has not been amended since it was introduced. The summary of that version is repeated here.)

Authorizes expenditures by the Senate Special Committee on Aging for the 115th Congress.
]]></text>
          <actionDate>2017-02-01</actionDate>
        </item>
      </billSummaries>
    </summaries>
    <latestAction>
      <actionDate>2017-02-01</actionDate>
      <text>Referred to the Committee on Rules and Administration. (text of measure as introduced: CR S598)</text>
      <links />
    </latestAction>
    <cosponsors />
    <sponsors>
      <item>
        <bioguideId>C001035</bioguideId>
        <identifiers>
          <lisID>1541</lisID>
          <gpoId>8291</gpoId>
          <bioguideId>C001035</bioguideId>
        </identifiers>
        <middleName>MARGARET</middleName>
        <firstName>SUSAN</firstName>
        <fullName>Sen. Collins, Susan M. [R-ME]</fullName>
        <byRequestType />
        <party>R</party>
        <lastName>COLLINS</lastName>
        <state>ME</state>
      </item>
    </sponsors>
    <originChamber>Senate</originChamber>
    <recordedVotes />
    <policyArea>
      <name>Congress</name>
    </policyArea>
    <cboCostEstimates />
    <updateDate>2017-05-04T00:08:47Z</updateDate>
    <congress>115</congress>
    <billType>SRES</billType>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>