text:
{-# LANGUAGE OverloadedStrings #-}
-- | This is a simple library to query the Linux UPower daemon (via
-- DBus) for battery information.  Currently, it only retrieves
-- information for the first battery it finds.
module System.Information.Battery (
  -- * Types
  BatteryContext,
  BatteryInfo(..),
  BatteryState(..),
  BatteryTechnology(..),
  BatteryType(..),
  -- * Accessors
  batteryContextNew,
  getBatteryInfo
  ) where

import Data.Map ( Map )
import qualified Data.Map as M
import Data.Maybe ( fromMaybe )
import Data.Word
import Data.Int
import DBus
import DBus.Client
import Data.List ( find, isInfixOf )
import Data.Text ( Text )
import qualified Data.Text as T
import Safe ( atMay )

-- | An opaque wrapper around some internal library state
data BatteryContext = BC Client ObjectPath

data BatteryType = BatteryTypeUnknown
                 | BatteryTypeLinePower
                 | BatteryTypeBatteryType
                 | BatteryTypeUps
                 | BatteryTypeMonitor
                 | BatteryTypeMouse
                 | BatteryTypeKeyboard
                 | BatteryTypePda
                 | BatteryTypePhone
                 deriving (Show, Ord, Eq, Enum)

data BatteryState = BatteryStateUnknown
                  | BatteryStateCharging
                  | BatteryStateDischarging
                  | BatteryStateEmpty
                  | BatteryStateFullyCharged
                  | BatteryStatePendingCharge
                  | BatteryStatePendingDischarge
                  deriving (Show, Ord, Eq, Enum)

data BatteryTechnology = BatteryTechnologyUnknown
                       | BatteryTechnologyLithiumIon
                       | BatteryTechnologyLithiumPolymer
                       | BatteryTechnologyLithiumIronPhosphate
                       | BatteryTechnologyLeadAcid
                       | BatteryTechnologyNickelCadmium
                       | BatteryTechnologyNickelMetalHydride
                       deriving (Show, Ord, Eq, Enum)

-- | There are a few fields supported by UPower that aren't exposed
-- here.. could be easily.
data BatteryInfo = BatteryInfo { batteryNativePath :: Text
                               , batteryVendor :: Text
                               , batteryModel :: Text
                               , batterySerial :: Text
                               -- , batteryUpdateTime :: Time
                               , batteryType :: BatteryType
                               , batteryPowerSupply :: Bool
                               , batteryHasHistory :: Bool
                               , batteryHasStatistics :: Bool
                               , batteryOnline :: Bool
                               , batteryEnergy :: Double
                               , batteryEnergyEmpty :: Double
                               , batteryEnergyFull :: Double
                               , batteryEnergyFullDesign :: Double
                               , batteryEnergyRate :: Double
                               , batteryVoltage :: Double
                               , batteryTimeToEmpty :: Int64
                               , batteryTimeToFull :: Int64
                               , batteryPercentage :: Double
                               , batteryIsPresent :: Bool
                               , batteryState :: BatteryState
                               , batteryIsRechargable :: Bool
                               , batteryCapacity :: Double
                               , batteryTechnology :: BatteryTechnology
{-                               , batteryRecallNotice :: Bool
                               , batteryRecallVendor :: Text
                               , batteryRecallUr :: Text
-}
                               }

-- | Find the first power source that is a battery in the list.  The
-- simple heuristic is a substring search on 'BAT'
firstBattery :: [ObjectPath] -> Maybe ObjectPath
firstBattery = find (isInfixOf "BAT" . formatObjectPath)

-- | The name of the power daemon bus
powerBusName :: BusName
powerBusName = "org.freedesktop.UPower"

-- | The base object path
powerBaseObjectPath :: ObjectPath
powerBaseObjectPath = "/org/freedesktop/UPower"

-- | A helper to read the variant contents of a dict with a default
-- value.
readDict :: (IsVariant a) => Map Text Variant -> Text -> a -> a
readDict dict key dflt = fromMaybe dflt $ do
  variant <- M.lookup key dict
  fromVariant variant

-- | Read the variant contents of a dict which is of an unknown integral type.
readDictIntegral :: Map Text Variant -> Text -> Int32 -> Int
readDictIntegral dict key dflt = fromMaybe (fromIntegral dflt) $ do
  v <- M.lookup key dict
  case variantType v of
    TypeWord8   -> return $ fromIntegral (f v :: Word8)
    TypeWord16  -> return $ fromIntegral (f v :: Word16)
    TypeWord32  -> return $ fromIntegral (f v :: Word32)
    TypeWord64  -> return $ fromIntegral (f v :: Word64)
    TypeInt16   -> return $ fromIntegral (f v :: Int16)
    TypeInt32   -> return $ fromIntegral (f v :: Int32)
    TypeInt64   -> return $ fromIntegral (f v :: Int64)
    _           -> Nothing
  where
    f :: (Num a, IsVariant a) => Variant -> a
    f = fromMaybe (fromIntegral dflt) . fromVariant

-- | Query the UPower daemon about information on a specific battery.
-- If some fields are not actually present, they may have bogus values
-- here.  Don't bet anything critical on it.
getBatteryInfo :: BatteryContext -> IO (Maybe BatteryInfo)
getBatteryInfo (BC systemConn battPath) = do
  -- Grab all of the properties of the battery each call with one
  -- message.
  reply <- call_ systemConn (methodCall battPath "org.freedesktop.DBus.Properties" "GetAll")
                             { methodCallDestination = Just "org.freedesktop.UPower"
                             , methodCallBody = [toVariant $ T.pack "org.freedesktop.UPower.Device"]
                             }

  return $ do
    body <- methodReturnBody reply `atMay` 0
    dict <- fromVariant body
    return BatteryInfo { batteryNativePath = readDict dict "NativePath" ""
                       , batteryVendor = readDict dict "Vendor" ""
                       , batteryModel = readDict dict "Model" ""
                       , batterySerial = readDict dict "Serial" ""
                       , batteryType = toEnum $ fromIntegral $ readDictIntegral dict "Type" 0
                       , batteryPowerSupply = readDict dict "PowerSupply" False
                       , batteryHasHistory = readDict dict "HasHistory" False
                       , batteryHasStatistics = readDict dict "HasStatistics" False
                       , batteryOnline = readDict dict "Online" False
                       , batteryEnergy = readDict dict "Energy" 0.0
                       , batteryEnergyEmpty = readDict dict "EnergyEmpty" 0.0
                       , batteryEnergyFull = readDict dict "EnergyFull" 0.0
                       , batteryEnergyFullDesign = readDict dict "EnergyFullDesign" 0.0
                       , batteryEnergyRate = readDict dict "EnergyRate" 0.0
                       , batteryVoltage = readDict dict "Voltage" 0.0
                       , batteryTimeToEmpty = readDict dict "TimeToEmpty" 0
                       , batteryTimeToFull = readDict dict "TimeToFull" 0
                       , batteryPercentage = readDict dict "Percentage" 0.0
                       , batteryIsPresent = readDict dict "IsPresent" False
                       , batteryState = toEnum $ readDictIntegral dict "State" 0
                       , batteryIsRechargable = readDict dict "IsRechargable" True
                       , batteryCapacity = readDict dict "Capacity" 0.0
                       , batteryTechnology =
                         toEnum $ fromIntegral $ readDictIntegral dict "Technology" 0
                       }

-- | Construct a battery context if possible.  This could fail if the
-- UPower daemon is not running.  The context can be used to get
-- actual battery state with 'getBatteryInfo'.
batteryContextNew :: IO (Maybe BatteryContext)
batteryContextNew = do
  systemConn <- connectSystem

  -- First, get the list of devices.  For now, we just get the stats
  -- for the first battery
  reply <- call_ systemConn (methodCall powerBaseObjectPath "org.freedesktop.UPower" "EnumerateDevices")
        { methodCallDestination = Just powerBusName
        }
  return $ do
    body <- methodReturnBody reply `atMay` 0
    powerDevices <- fromVariant body
    battPath <- firstBattery powerDevices
    return $ BC systemConn battPath

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8" ?>
<Settings
      xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://schemas.microsoft.com/2011/01/fabric">

    <Parameter Name="ReplicatorEndpoint" Value="ReplicatorEndpoint" />

</Settings>


text:
CREATE TABLE BPM_CONF_ASSIGN(
	ID BIGINT NOT NULL,
	NAME VARCHAR(50),
	NODE_ID BIGINT,
        CONSTRAINT PK_BPM_CONF_ASSIGN PRIMARY KEY(ID),
        CONSTRAINT FK_BPM_CONF_ASSIGN_NODE FOREIGN KEY(NODE_ID) REFERENCES BPM_CONF_NODE(ID)
) ENGINE=INNODB CHARSET=UTF8;


text:
<?php

namespace Magento\Checkout\Controller\Cart;

use Magento\Framework;
use Magento\Framework\Controller\ResultFactory;

class Configure extends \Magento\Checkout\Controller\Cart
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator
     * @param \Magento\Checkout\Model\Cart $cart
     * @codeCoverageIgnore
     */
    public function __construct(
        Framework\App\Action\Context $context,
        Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator,
        \Magento\Checkout\Model\Cart $cart
    ) {
        parent::__construct(
            $context,
            $scopeConfig,
            $checkoutSession,
            $storeManager,
            $formKeyValidator,
            $cart
        );
    }

    /**
     * Action to reconfigure cart item
     *
     * @return \Magento\Framework\View\Result\Page|\Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        // Extract item and product to configure
        $id = (int)$this->getRequest()->getParam('id');
        $productId = (int)$this->getRequest()->getParam('product_id');
        $quoteItem = null;
        if ($id) {
            $quoteItem = $this->cart->getQuote()->getItemById($id);
        }

        try {
            if (!$quoteItem || $productId != $quoteItem->getProduct()->getId()) {
                $this->messageManager->addError(__("We can't find the quote item."));
                return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('checkout/cart');
            }

            $params = new \Magento\Framework\DataObject();
            $params->setCategoryId(false);
            $params->setConfigureMode(true);
            $params->setBuyRequest($quoteItem->getBuyRequest());

            $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
            $this->_objectManager->get('Magento\Catalog\Helper\Product\View')
                ->prepareAndRender(
                    $resultPage,
                    $quoteItem->getProduct()->getId(),
                    $this,
                    $params
                );
            return $resultPage;
        } catch (\Exception $e) {
            $this->messageManager->addError(__('We cannot configure the product.'));
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            return $this->_goBack();
        }
    }
}


text:
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';

import { baseURI } from './baseuri';
import { process2faReturn } from '../../../2fa/client/callWithTwoFactorRequired';

export const mountArrayQueryParameters = (label, array) => array.reduce((acc, item) => {
	acc += `${ label }[]=${ item }&`;
	return acc;
}, '');

export const APIClient = {
	delete(endpoint, params) {
		return APIClient._jqueryCall('DELETE', endpoint, params);
	},

	get(endpoint, params) {
		return APIClient._jqueryCall('GET', endpoint, params);
	},

	post(endpoint, params, body) {
		if (!body) {
			body = params;
			params = {};
		}

		return APIClient._jqueryCall('POST', endpoint, params, body);
	},

	upload(endpoint, params, formData, xhrOptions) {
		if (!formData) {
			formData = params;
			params = {};
		}

		return APIClient._jqueryFormDataCall(endpoint, params, formData, xhrOptions);
	},

	getCredentials() {
		return {
			'X-User-Id': Meteor._localStorage.getItem(Accounts.USER_ID_KEY),
			'X-Auth-Token': Meteor._localStorage.getItem(Accounts.LOGIN_TOKEN_KEY),
		};
	},

	_generateQueryFromParams(params) {
		let query = '';
		if (params && typeof params === 'object') {
			Object.keys(params).forEach((key) => {
				query += query === '' ? '?' : '&';

				if (Array.isArray(params[key])) {
					const joinedArray = params[key].join(`&${ key }[]=`);
					query += `${ key }[]=${ joinedArray }`;
				} else {
					query += `${ key }=${ params[key] }`;
				}
			});
		}

		return query;
	},

	_jqueryCall(method, endpoint, params, body, headers = {}, dataType) {
		const query = APIClient._generateQueryFromParams(params);

		return new Promise(function _rlRestApiGet(resolve, reject) {
			jQuery.ajax({
				method,
				url: `${ baseURI }api/${ endpoint }${ query }`,
				headers: Object.assign({
					'Content-Type': 'application/json',
					...APIClient.getCredentials(),
				}, headers),
				data: JSON.stringify(body),
				dataType,
				success: function _rlGetSuccess(result) {
					resolve(result);
				},
				error: function _rlGetFailure(xhr, status, errorThrown) {
					APIClient.processTwoFactorError({
						xhr,
						params: [method, endpoint, params, body, headers],
						resolve,
						reject,
						originalCallback() {
							const error = new Error(errorThrown);
							error.xhr = xhr;
							reject(error);
						},
					});
				},
			});
		});
	},

	_jqueryFormDataCall(endpoint, params, formData, { progress = () => {}, error = () => {} } = {}) {
		const ret = { };

		const query = APIClient._generateQueryFromParams(params);

		if (!(formData instanceof FormData)) {
			throw new Error('The formData parameter MUST be an instance of the FormData class.');
		}

		ret.promise = new Promise(function _jqueryFormDataPromise(resolve, reject) {
			ret.xhr = jQuery.ajax({
				xhr() {
					const xhr = new window.XMLHttpRequest();

					xhr.upload.addEventListener('progress', function(evt) {
						if (evt.lengthComputable) {
							const percentComplete = evt.loaded / evt.total;
							progress(percentComplete * 100);
						}
					}, false);

					xhr.upload.addEventListener('error', error, false);

					return xhr;
				},
				url: `${ baseURI }api/${ endpoint }${ query }`,
				headers: APIClient.getCredentials(),
				data: formData,
				processData: false,
				contentType: false,
				type: 'POST',
				success: function _jqueryFormDataSuccess(result) {
					resolve(result);
				},
				error: function _jqueryFormDataError(xhr, status, errorThrown) {
					const error = new Error(errorThrown);
					error.xhr = xhr;
					reject(error);
				},
			});
		});

		return ret;
	},

	processTwoFactorError({ xhr, params, originalCallback, resolve, reject }) {
		if (!xhr.responseJSON || !xhr.responseJSON.errorType) {
			return originalCallback();
		}

		process2faReturn({
			error: xhr.responseJSON,
			originalCallback,
			onCode(code, method) {
				const headers = params[params.length - 1];
				headers['x-2fa-code'] = code;
				headers['x-2fa-method'] = method;
				APIClient._jqueryCall(...params).then(resolve).catch(reject);
			},
		});
	},

	v1: {
		delete(endpoint, params) {
			return APIClient.delete(`v1/${ endpoint }`, params);
		},

		get(endpoint, params) {
			return APIClient.get(`v1/${ endpoint }`, params);
		},

		post(endpoint, params, body) {
			return APIClient.post(`v1/${ endpoint }`, params, body);
		},

		upload(endpoint, params, formData) {
			return APIClient.upload(`v1/${ endpoint }`, params, formData);
		},
	},
};


text:
'use strict';

var grunt = require('grunt');
var exec = require('child_process').exec;

//running tasks with grunt.tasks() caused strange problems, the best way i found to do this
//is to define separate config cases under fixtures and then invoke grunt with the target file
//the target file must be defined under test/fixtures/grunt-config
function runGruntTask (gruntFile, callback) {
  exec('grunt --gruntfile test/fixtures/grunt-config/%s.js'.replace('%s', gruntFile), function (err, sdout, stderr) {
    if(err){throw err;}
    callback();
  });
}

exports.cache_control = {
    tearDown: function (done) {
        grunt.file.delete('test/tmp');
        grunt.file.mkdir('test/tmp');
        done();
    },
    default_options: function(test) {
      test.expect(1);
      //copy fixtures/default.html to tmp because replace is true by default
      grunt.file.copy('test/fixtures/default.html', 'test/tmp/default.html');
      runGruntTask('default', function () {
          test.strictEqual(
              grunt.file.read('test/tmp/default.html'),
              grunt.file.read('test/expected/default.html'),
              "with default options, both links and scripts are appended with v=1.0 and replaced in the same file"
          );
          test.done();
      });
  },
    output_dest_set_replace_is_false_source_is_intact: function (test) {
        test.expect(2);
        var sourceHtml = grunt.file.read('test/fixtures/default.html');
        runGruntTask('output_dest_set_replace_is_false_source_is_intact', function () {
            test.strictEqual(
                sourceHtml,
                grunt.file.read('test/fixtures/default.html'),
                "source html file is left intact if outputDest is set"
            );
            test.strictEqual(
                grunt.file.read('test/tmp/target.html'),
                grunt.file.read('test/expected/default.html'),
                "destination file is processed correctly when outputDest is set"
            );
            test.done();
        });
    },
    //process an already processed file with same options, must remain the same
    process_is_idempotent: function (test) {
        test.expect(1);
        grunt.file.copy('test/expected/default.html', 'test/tmp/default.html');
        runGruntTask('default', function () {
            test.strictEqual(
                grunt.file.read('test/tmp/default.html'),
                grunt.file.read('test/expected/default.html'),
                "process is idempotent if ran on a file with the same options as previous run"
            );
            test.done();
        });
    },
    file_is_updated_with_new_version: function (test) {
        test.expect(1);
        //test/expected/default.html is processed as v=1.0
        grunt.file.copy('test/expected/default.html', 'test/tmp/v2.0.html');
        runGruntTask('file-is-updated-with-new-version', function () {
            test.strictEqual(
                grunt.file.read('test/tmp/v2.0.html'),
                grunt.file.read('test/expected/v2.0.html'),
                "if a file is updated with a new version, that version is set correctly"
            );
            test.done();
        });
    },
    files_in_filesToIgnore_are_left_unprocessed: function (test) {
        test.expect(1);
        grunt.file.copy('test/fixtures/default.html', 'test/tmp/default.html');
        runGruntTask('ignored', function () {
            test.strictEqual(
               grunt.file.read('test/tmp/default.html'),
               grunt.file.read('test/expected/ignored.html'),
                "files in filesToIgnore must be left unprocessed"
            );
            test.done();
        });
    },
    files_matching_ignorePatterns_are_left_unprocessed: function (test) {
        test.expect(1);
        runGruntTask('files-matching-ignorePatterns-are-left-unprocessed', function () {
            test.strictEqual(
                grunt.file.read('test/tmp/default2.html'),
                grunt.file.read('test/expected/default2.html'),
                "files matching any of the patterns defined under ignorePatterns are unprocessed"
            );
            test.done();
        });
    }
};


text:
package me.chanjar.weixin.cp.util.xml;

import com.thoughtworks.xstream.XStream;
import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.cp.bean.*;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class XStreamTransformer {

    protected static final Map<Class, XStream> CLASS_2_XSTREAM_INSTANCE = configXStreamInstance();

    /**
     * xml -> pojo
     */
    @SuppressWarnings("unchecked")
    public static <T> T fromXml(Class<T> clazz, String xml) {
        T object = (T) CLASS_2_XSTREAM_INSTANCE.get(clazz).fromXML(xml);
        return object;
    }

    @SuppressWarnings("unchecked")
    public static <T> T fromXml(Class<T> clazz, InputStream is) {
        T object = (T) CLASS_2_XSTREAM_INSTANCE.get(clazz).fromXML(is);
        return object;
    }

    /**
     * 注册扩展消息的解析器
     *
     * @param clz     类型
     * @param xStream xml解析器
     */
    public static void register(Class clz, XStream xStream) {
        CLASS_2_XSTREAM_INSTANCE.put(clz, xStream);
    }

    /**
     * pojo -> xml
     */
    public static <T> String toXml(Class<T> clazz, T object) {
        return CLASS_2_XSTREAM_INSTANCE.get(clazz).toXML(object);
    }

    private static Map<Class, XStream> configXStreamInstance() {
        Map<Class, XStream> map = new HashMap<>();
        map.put(WxCpXmlMessage.class, config_WxCpXmlMessage());
        map.put(WxCpXmlOutNewsMessage.class, config_WxCpXmlOutNewsMessage());
        map.put(WxCpXmlOutTextMessage.class, config_WxCpXmlOutTextMessage());
        map.put(WxCpXmlOutImageMessage.class, config_WxCpXmlOutImageMessage());
        map.put(WxCpXmlOutVideoMessage.class, config_WxCpXmlOutVideoMessage());
        map.put(WxCpXmlOutVoiceMessage.class, config_WxCpXmlOutVoiceMessage());
        return map;
    }

    private static XStream config_WxCpXmlMessage() {
        XStream xstream = XStreamInitializer.getInstance();
        xstream.processAnnotations(WxCpXmlMessage.class);
        xstream.processAnnotations(WxCpXmlMessage.ScanCodeInfo.class);
        xstream.processAnnotations(WxCpXmlMessage.SendPicsInfo.class);
        xstream.processAnnotations(WxCpXmlMessage.SendPicsInfo.Item.class);
        xstream.processAnnotations(WxCpXmlMessage.SendLocationInfo.class);
        return xstream;
    }

    private static XStream config_WxCpXmlOutImageMessage() {
        XStream xstream = XStreamInitializer.getInstance();
        xstream.processAnnotations(WxCpXmlOutMessage.class);
        xstream.processAnnotations(WxCpXmlOutImageMessage.class);
        return xstream;
    }

    private static XStream config_WxCpXmlOutNewsMessage() {
        XStream xstream = XStreamInitializer.getInstance();
        xstream.processAnnotations(WxCpXmlOutMessage.class);
        xstream.processAnnotations(WxCpXmlOutNewsMessage.class);
        xstream.processAnnotations(WxCpXmlOutNewsMessage.Item.class);
        return xstream;
    }

    private static XStream config_WxCpXmlOutTextMessage() {
        XStream xstream = XStreamInitializer.getInstance();
        xstream.processAnnotations(WxCpXmlOutMessage.class);
        xstream.processAnnotations(WxCpXmlOutTextMessage.class);
        return xstream;
    }

    private static XStream config_WxCpXmlOutVideoMessage() {
        XStream xstream = XStreamInitializer.getInstance();
        xstream.processAnnotations(WxCpXmlOutMessage.class);
        xstream.processAnnotations(WxCpXmlOutVideoMessage.class);
        xstream.processAnnotations(WxCpXmlOutVideoMessage.Video.class);
        return xstream;
    }

    private static XStream config_WxCpXmlOutVoiceMessage() {
        XStream xstream = XStreamInitializer.getInstance();
        xstream.processAnnotations(WxCpXmlOutMessage.class);
        xstream.processAnnotations(WxCpXmlOutVoiceMessage.class);
        return xstream;
    }

}


text:
[instagram-private-api](../../README.md) / [responses](../../modules/responses.md) / TimelineFeedResponseInItem

# Interface: TimelineFeedResponseInItem

[responses](../../modules/responses.md).TimelineFeedResponseInItem

## Table of contents

### Properties

- [duration\_in\_video\_in\_sec](TimelineFeedResponseInItem.md#duration_in_video_in_sec)
- [position](TimelineFeedResponseInItem.md#position)
- [start\_time\_in\_video\_in\_sec](TimelineFeedResponseInItem.md#start_time_in_video_in_sec)
- [user](TimelineFeedResponseInItem.md#user)

## Properties

### duration\_in\_video\_in\_sec

• **duration\_in\_video\_in\_sec**: ``null``

#### Defined in

[src/responses/timeline.feed.response.ts:234](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/timeline.feed.response.ts#L234)

___

### position

• **position**: (`string` \| `number`)[] \| `number`[]

#### Defined in

[src/responses/timeline.feed.response.ts:232](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/timeline.feed.response.ts#L232)

___

### start\_time\_in\_video\_in\_sec

• **start\_time\_in\_video\_in\_sec**: ``null``

#### Defined in

[src/responses/timeline.feed.response.ts:233](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/timeline.feed.response.ts#L233)

___

### user

• **user**: [`TimelineFeedResponseUser`](TimelineFeedResponseUser.md)

#### Defined in

[src/responses/timeline.feed.response.ts:231](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/timeline.feed.response.ts#L231)


text:
class AutocompleteResult;
class ChromeAutocompleteProviderClient;
class Profile;

namespace base {
template <typename Type>
struct DefaultSingletonTraits;
}  // namespace base

// The native part of the Java AutocompleteController class.
class AutocompleteControllerAndroid : public AutocompleteController::Observer,
                                      public KeyedService {
 public:
  AutocompleteControllerAndroid(
      Profile* profile,
      std::unique_ptr<ChromeAutocompleteProviderClient> client);

  AutocompleteControllerAndroid(const AutocompleteControllerAndroid&) = delete;
  AutocompleteControllerAndroid& operator=(
      const AutocompleteControllerAndroid&) = delete;

  // Methods that forward to AutocompleteController:
  void Start(JNIEnv* env,
             const base::android::JavaRef<jstring>& j_text,
             jint j_cursor_pos,
             const base::android::JavaRef<jstring>& j_desired_tld,
             const base::android::JavaRef<jstring>& j_current_url,
             jint j_page_classification,
             bool prevent_inline_autocomplete,
             bool prefer_keyword,
             bool allow_exact_keyword_match,
             bool want_asynchronous_matches);
  void StartPrefetch(JNIEnv* env);
  base::android::ScopedJavaLocalRef<jobject> Classify(
      JNIEnv* env,
      const base::android::JavaParamRef<jstring>& j_text,
      bool focused_from_fakebox);
  void OnOmniboxFocused(
      JNIEnv* env,
      const base::android::JavaParamRef<jstring>& j_omnibox_text,
      const base::android::JavaParamRef<jstring>& j_current_url,
      jint j_page_classification,
      const base::android::JavaParamRef<jstring>& j_current_title);
  void Stop(JNIEnv* env, bool clear_result);
  void ResetSession(JNIEnv* env);

  void OnSuggestionSelected(
      JNIEnv* env,
      jint match_index,
      const jint j_window_open_disposition,
      const base::android::JavaParamRef<jstring>& j_current_url,
      jint j_page_classification,
      jlong elapsed_time_since_first_modified,
      jint completed_length,
      const base::android::JavaParamRef<jobject>& j_web_contents);
  void DeleteMatch(JNIEnv* env, jint match_index);
  void DeleteMatchElement(JNIEnv* env, jint match_index, jint element_index);
  base::android::ScopedJavaLocalRef<jobject>
  UpdateMatchDestinationURLWithAdditionalAssistedQueryStats(
      JNIEnv* env,
      jint match_index,
      jlong elapsed_time_since_input_change,
      const base::android::JavaParamRef<jstring>& jnew_query_text,
      const base::android::JavaParamRef<jobjectArray>& jnew_query_params);
  base::android::ScopedJavaLocalRef<jobject> GetMatchingTabForSuggestion(
      JNIEnv* env,
      jint match_index);

  // KeyedService:
  void Shutdown() override;

  // Pass detected voice matches down to VoiceSuggestionsProvider.
  void SetVoiceMatches(
      JNIEnv* env,
      const base::android::JavaParamRef<jobjectArray>& j_voice_matches,
      const base::android::JavaParamRef<jfloatArray>& j_confidence_scores);

  base::android::ScopedJavaLocalRef<jobject> GetJavaObject() const;

  class Factory : public BrowserContextKeyedServiceFactory {
   public:
    static AutocompleteControllerAndroid* GetForProfile(Profile* profile);
    static Factory* GetInstance();

   protected:
    content::BrowserContext* GetBrowserContextToUse(
        content::BrowserContext* context) const override;

   private:
    friend struct base::DefaultSingletonTraits<Factory>;

    Factory();
    ~Factory() override;

    // BrowserContextKeyedServiceFactory
    KeyedService* BuildServiceInstanceFor(
        content::BrowserContext* profile) const override;
  };

 private:
  ~AutocompleteControllerAndroid() override;

  // AutocompleteController::Observer implementation.
  void OnResultChanged(AutocompleteController* controller,
                       bool default_match_changed) override;

  // Notifies the Java AutocompleteController that suggestions were received
  // based on the text the user typed in last.
  void NotifySuggestionsReceived(
      const AutocompleteResult& autocomplete_result);

  // Prepare renderer process. Called in zero-prefix context.
  // This call may get triggered multiple time during User interaction with the
  // Omnibox - these requests are deduplicated down the call chain.
  void WarmUpRenderProcess() const;

  // Last input we sent to the autocomplete controller.
  AutocompleteInput input_{};

  // Whether we're currently inside a call to Start() that's called
  // from Classify().
  bool inside_synchronous_start_{false};

  // The Profile associated with this instance of AutocompleteControllerAndroid.
  // There should be only one instance of AutocompleteControllerAndroid per
  // Profile. This is orchestrated by AutocompleteControllerFactory java class.
  // Guaranteed to be non-null.
  const raw_ptr<Profile> profile_;

  // Direct reference to AutocompleteController java class. Kept for as long as
  // this instance of AutocompleteControllerAndroid lives: until corresponding
  // Profile gets destroyed.
  // Destruction of Profile triggers destruction of both
  // C++ AutocompleteControllerAndroid and Java AutocompleteController objects.
  // Guaranteed to be non-null.
  const base::android::ScopedJavaGlobalRef<jobject> java_controller_;

  // Associated AutocompleteProviderClient.
  // Guaranteed to be non-null.
  const raw_ptr<ChromeAutocompleteProviderClient> provider_client_;

  // AutocompleteController associated with this client. As this is directly
  // associated with the |provider_client_| and indirectly with |profile_|
  // there is exactly one instance per class.
  // Retained throughout the lifetime of the AutocompleteControllerAndroid.
  // Invalidated only immediately before the AutocompleteControllerAndroid is
  // destroyed.
  std::unique_ptr<AutocompleteController> autocomplete_controller_;

  // Factory used to create asynchronously invoked callbacks.
  // Retained throughout the lifetime of the AutocompleteControllerAndroid.
  const base::WeakPtrFactory<AutocompleteControllerAndroid> weak_ptr_factory_{
      this};
};

#endif  // CHROME_BROWSER_ANDROID_OMNIBOX_AUTOCOMPLETE_CONTROLLER_ANDROID_H_


text:
#include <assert.h>
#include <stdlib.h>
#include "Step.h"
#include "Fullerene.h"
#include "CarbonAllotrope.h"
#include "Debug.h"
#include "DebugMemory.h"

int Step::s_progress_level = 0;
pthread_mutex_t Step::s_mutex;

Step::Step()
  : p_symmetric(false), p_close(false), p_is_tube(false),
    p_maximum_number_of_carbons(60),
    p_gen(0), p_ca(0), p_boundary(), p_number_of_rest_pentagons(0),
    p_all_pentagons(false), p_close_count(0),
    p_ring_next_sequence(0), p_carbon_next_sequence(0), p_bond_next_sequence(0)
{
}

Step::Step(Generator& gen, int maximum_number_of_carbons, bool symmetric, int close)
  : Object(0), p_symmetric(symmetric), p_close(close), p_is_tube(false),
    p_maximum_number_of_carbons(maximum_number_of_carbons), p_gen(&gen),
    p_ca(new CarbonAllotrope()), p_boundary(), p_number_of_rest_pentagons(0),
    p_all_pentagons(true), p_close_count(close),
    p_ring_next_sequence(0), p_carbon_next_sequence(0), p_bond_next_sequence(0)
{
  p_gen->link_up();
  p_ca->link_up();
  if (p_gen->type() == GENERATOR_TYPE_TUBE)
    {
      p_ca->make_equator_by_chiral_characteristic(p_gen->n(), p_gen->m(), p_gen->h());
      p_is_tube = true;
    }
  else
    p_ca->make_symmetric_scrap(p_gen->scrap_no());
  if (!p_symmetric)
    {
      p_boundary.clean();
      p_ca->list_oldest_connected_boundary_carbons(p_boundary);
      p_all_pentagons = true;
      if (p_is_tube)
        p_number_of_rest_pentagons = p_gen->n() + p_gen->m();
    }
#if defined(DEBUG_CARBON_ALLOTROPE_CONSTRUCTION)
  p_ca->print_detail();
#endif
}

Step* Step::p_copy(CarbonAllotrope* ca) const
{
  Step* result = new Step();
  result->p_symmetric = p_symmetric;
  result->p_close = p_close;
  result->p_is_tube = p_is_tube;
  result->p_maximum_number_of_carbons = p_maximum_number_of_carbons;
  result->p_gen = new Generator(*p_gen);
  result->p_gen->link_up();
  result->p_ca = ca;
  result->p_ca->link_up();
  result->p_boundary.copy_from(result->p_ca, p_boundary);
  result->p_number_of_rest_pentagons = p_number_of_rest_pentagons;
  result->p_all_pentagons = p_all_pentagons;
  result->p_close_count = p_close_count;
  result->p_ring_next_sequence = p_ring_next_sequence;
  result->p_carbon_next_sequence = p_carbon_next_sequence;
  result->p_bond_next_sequence = p_bond_next_sequence;
  return result;
}

Step* Step::shallow_copy() const
{
  return p_copy(p_ca);
}

Step* Step::deep_copy() const
{
  return p_copy(p_ca->copy());
}

Step::~Step()
{
  if (p_gen)
    p_gen->link_down();
  if (p_ca)
    p_ca->link_down();
}

bool Step::construction_step(Fullerene*& fullerene)
{
  int No = p_gen->glow_step();
  int num;
  ErrorCode result;
  int progress_level = get_progress_level();
  if (progress_level > 0)
    p_gen->print_progress(progress_level);
  if (p_symmetric)
    result =
      p_ca->fill_n_polygons_around_carbons_closed_to_center_and_pentagons(No, num);
  else
    {
      if (No == 6)
        p_number_of_rest_pentagons--;
      else
        p_all_pentagons = false;
      Carbon* carbon = p_boundary.get_two_rings_carbon_of_minimum_sequence_no();
      assert(carbon);
      result = p_ca->fill_n_polygon_around_carbon(No, carbon, p_boundary);
    }
#if defined(DEBUG_CARBON_ALLOTROPE_CONSTRUCTION)
  p_ca->print_detail();
#endif
#if defined(DEBUG_BOUNDARY_REPRESENTATIONS)
  p_ca->print_boundary_representations();
#endif
  int number_of_carbons = p_ca->number_of_carbons();
  if (p_symmetric)
    {
      p_boundary.clean();
      p_ca->list_oldest_connected_boundary_carbons(p_boundary);
    }
  int number_of_carbons_in_boundary = p_boundary.length();
  if (!p_symmetric && (number_of_carbons_in_boundary == 0))
    {
      if (--p_close_count > 0)
        {
          p_boundary.clean();
          p_ca->list_oldest_connected_boundary_carbons(p_boundary);
          number_of_carbons_in_boundary = p_boundary.length();
          p_all_pentagons = true;
          if (p_is_tube)
            p_number_of_rest_pentagons = p_gen->n() + p_gen->m();
        }
    }
  if ((result != ERROR_CODE_OK) ||
      (number_of_carbons > p_maximum_number_of_carbons) ||
      (p_is_tube && p_all_pentagons && (p_number_of_rest_pentagons <= 0)) ||
      (number_of_carbons_in_boundary == 0))
    {
      MyString buffer;
#if defined(DEBUG_ERRORS)
      printf("************************************************\n");
#endif
      p_gen->get_generator_formula(buffer);
      if (result != ERROR_CODE_OK)
        {
#if defined(DEBUG_ERRORS) || defined(DEBUG_CONSTRUCTION_ALGORITHM)
          printf("* ERROR %s ", (char*)buffer);
          error_handler(result);
#endif
#if defined(DEBUG_ERRORS)
          printf("************************************************\n");
#endif
          fullerene = 0;
          return false;
        }
      else if (number_of_carbons > p_maximum_number_of_carbons)
        {
#if defined(DEBUG_ERRORS) || defined(DEBUG_CONSTRUCTION_ALGORITHM)
          printf("* ERROR %s Too many carbons %d\n", (char*)buffer, number_of_carbons);
#endif
#if defined(DEBUG_ERRORS)
          printf("************************************************\n");
#endif
          fullerene = 0;
          return false;
        }
      else if (p_is_tube && p_all_pentagons && (p_number_of_rest_pentagons <= 0))
        {
#if defined(DEBUG_ERRORS) || defined(DEBUG_CONSTRUCTION_ALGORITHM)
          printf("* ERROR %s Tube height is enlarged\n", (char*)buffer);
#endif
#if defined(DEBUG_ERRORS)
          printf("************************************************\n");
#endif
          fullerene = 0;
          return false;
        }
      else if (number_of_carbons_in_boundary > 0)
        {
#if defined(DEBUG_ERRORS) || defined(DEBUG_CONSTRUCTION_ALGORITHM)
          printf("* ERROR %s Unknown error\n", (char*)buffer);
#endif
#if defined(DEBUG_ERRORS)
          printf("************************************************\n");
#endif
          fullerene = 0;
          return false;
        }
      else
        {
#if defined(DEBUG_ERRORS) || defined(DEBUG_CONSTRUCTION_ALGORITHM)
          printf("* OK    %s generated carbons %d\n", (char*)buffer, number_of_carbons);
#endif
#if defined(DEBUG_ERRORS)
          printf("************************************************\n");
#endif
          fullerene = new Fullerene();
          fullerene->set_carbon_allotrope(p_ca);
          fullerene->set_generator_formula((char*)buffer);
          return false;
        }
    }
  return true;
}

bool Step::is_there_next_branch() const
{
  return p_gen->is_there_next_branch();
}

void Step::next_branch()
{
  p_ring_next_sequence = p_ca->ring_next_sequence;
  p_carbon_next_sequence = p_ca->carbon_next_sequence;
  p_bond_next_sequence = p_ca->bond_next_sequence;
#if defined(DEBUG_CONSTRUCTION_ALGORITHM)
  printf("@@@ Step::next_branch() = %d, %d, %d\n",
         p_ring_next_sequence, p_carbon_next_sequence, p_bond_next_sequence);
#endif
  p_gen->next_branch();
}

void Step::rollback()
{
#if defined(DEBUG_CONSTRUCTION_ALGORITHM)
  printf("@@@ Step::rollback() = %d, %d, %d\n",
         p_ring_next_sequence, p_carbon_next_sequence, p_bond_next_sequence);
#endif
  p_ca->rollback(p_ring_next_sequence, p_carbon_next_sequence, p_bond_next_sequence);
}

void Step::initiate_progress_level(int level)
{
  if (pthread_mutex_init(&s_mutex, 0) != 0)
    {
      fprintf(stderr, "pthread_mutex_init() error\n");
      exit(1);
    }
  set_progress_level(level);
}

int Step::get_progress_level()
{
  if (pthread_mutex_lock(&s_mutex) != 0)
    {
      fprintf(stderr, "pthread_mutex_lock() error\n");
      exit(1);
    }
  int result = s_progress_level;
  if (pthread_mutex_unlock(&s_mutex) != 0)
    {
      fprintf(stderr, "pthread_mutex_unlock() error\n");
      exit(1);
    }
  return result;
}

void Step::set_progress_level(int level)
{
  if (pthread_mutex_lock(&s_mutex) != 0)
    {
      fprintf(stderr, "pthread_mutex_lock() error\n");
      exit(1);
    }
  s_progress_level = level;
  if (pthread_mutex_unlock(&s_mutex) != 0)
    {
      fprintf(stderr, "pthread_mutex_unlock() error\n");
      exit(1);
    }
}

/* Local Variables:	*/
/* mode: c++		*/
/* End:			*/


text:
namespace Livity.Composition.Primitives
{
	public enum ImportCardinality
	{
		One,
		Many
	}
}


text:
package cmd

import (
	"context"
	"strconv"
	"testing"
	"time"

	humanize "github.com/dustin/go-humanize"
)

const ActualSize = 1000

// Test FileInfo.AddObjectPart()
func TestAddObjectPart(t *testing.T) {
	testCases := []struct {
		partNum       int
		expectedIndex int
	}{
		{1, 0},
		{2, 1},
		{4, 2},
		{5, 3},
		{7, 4},
		// Insert part.
		{3, 2},
		// Replace existing part.
		{4, 3},
		// Missing part.
		{6, -1},
	}

	// Setup.
	fi := newFileInfo("test-object", 8, 8)
	fi.Erasure.Index = 1
	if !fi.IsValid() {
		t.Fatalf("unable to get xl meta")
	}

	// Test them.
	for _, testCase := range testCases {
		if testCase.expectedIndex > -1 {
			partNumString := strconv.Itoa(testCase.partNum)
			fi.AddObjectPart(testCase.partNum, "etag."+partNumString, int64(testCase.partNum+humanize.MiByte), ActualSize)
		}

		if index := objectPartIndex(fi.Parts, testCase.partNum); index != testCase.expectedIndex {
			t.Fatalf("%+v: expected = %d, got: %d", testCase, testCase.expectedIndex, index)
		}
	}
}

// Test objectPartIndex(). generates a sample FileInfo data and asserts
// the output of objectPartIndex() with the expected value.
func TestObjectPartIndex(t *testing.T) {
	testCases := []struct {
		partNum       int
		expectedIndex int
	}{
		{2, 1},
		{1, 0},
		{5, 3},
		{4, 2},
		{7, 4},
	}

	// Setup.
	fi := newFileInfo("test-object", 8, 8)
	fi.Erasure.Index = 1
	if !fi.IsValid() {
		t.Fatalf("unable to get xl meta")
	}

	// Add some parts for testing.
	for _, testCase := range testCases {
		partNumString := strconv.Itoa(testCase.partNum)
		fi.AddObjectPart(testCase.partNum, "etag."+partNumString, int64(testCase.partNum+humanize.MiByte), ActualSize)
	}

	// Add failure test case.
	testCases = append(testCases, struct {
		partNum       int
		expectedIndex int
	}{6, -1})

	// Test them.
	for _, testCase := range testCases {
		if index := objectPartIndex(fi.Parts, testCase.partNum); index != testCase.expectedIndex {
			t.Fatalf("%+v: expected = %d, got: %d", testCase, testCase.expectedIndex, index)
		}
	}
}

// Test FileInfo.ObjectToPartOffset().
func TestObjectToPartOffset(t *testing.T) {
	// Setup.
	fi := newFileInfo("test-object", 8, 8)
	fi.Erasure.Index = 1
	if !fi.IsValid() {
		t.Fatalf("unable to get xl meta")
	}

	// Add some parts for testing.
	// Total size of all parts is 5,242,899 bytes.
	for _, partNum := range []int{1, 2, 4, 5, 7} {
		partNumString := strconv.Itoa(partNum)
		fi.AddObjectPart(partNum, "etag."+partNumString, int64(partNum+humanize.MiByte), ActualSize)
	}

	testCases := []struct {
		offset         int64
		expectedIndex  int
		expectedOffset int64
		expectedErr    error
	}{
		{0, 0, 0, nil},
		{1 * humanize.MiByte, 0, 1 * humanize.MiByte, nil},
		{1 + humanize.MiByte, 1, 0, nil},
		{2 + humanize.MiByte, 1, 1, nil},
		// Its valid for zero sized object.
		{-1, 0, -1, nil},
		// Max fffset is always (size - 1).
		{(1 + 2 + 4 + 5 + 7) + (5 * humanize.MiByte) - 1, 4, 1048582, nil},
		// Error if offset is size.
		{(1 + 2 + 4 + 5 + 7) + (5 * humanize.MiByte), 0, 0, InvalidRange{}},
	}

	// Test them.
	for _, testCase := range testCases {
		index, offset, err := fi.ObjectToPartOffset(context.Background(), testCase.offset)
		if err != testCase.expectedErr {
			t.Fatalf("%+v: expected = %s, got: %s", testCase, testCase.expectedErr, err)
		}
		if index != testCase.expectedIndex {
			t.Fatalf("%+v: index: expected = %d, got: %d", testCase, testCase.expectedIndex, index)
		}
		if offset != testCase.expectedOffset {
			t.Fatalf("%+v: offset: expected = %d, got: %d", testCase, testCase.expectedOffset, offset)
		}
	}
}

func TestFindFileInfoInQuorum(t *testing.T) {
	getNFInfo := func(n int, quorum int, t int64, dataDir string) []FileInfo {
		fi := newFileInfo("test", 8, 8)
		fi.AddObjectPart(1, "etag", 100, 100)
		fi.ModTime = time.Unix(t, 0)
		fi.DataDir = dataDir
		fis := make([]FileInfo, n)
		for i := range fis {
			fis[i] = fi
			fis[i].Erasure.Index = i + 1
			quorum--
			if quorum == 0 {
				break
			}
		}
		return fis
	}

	tests := []struct {
		fis            []FileInfo
		modTime        time.Time
		dataDir        string
		expectedErr    error
		expectedQuorum int
	}{
		{
			fis:            getNFInfo(16, 16, 1603863445, "36a21454-a2ca-11eb-bbaa-93a81c686f21"),
			modTime:        time.Unix(1603863445, 0),
			dataDir:        "36a21454-a2ca-11eb-bbaa-93a81c686f21",
			expectedErr:    nil,
			expectedQuorum: 8,
		},
		{
			fis:            getNFInfo(16, 7, 1603863445, "36a21454-a2ca-11eb-bbaa-93a81c686f21"),
			modTime:        time.Unix(1603863445, 0),
			dataDir:        "36a21454-a2ca-11eb-bbaa-93a81c686f21",
			expectedErr:    errErasureReadQuorum,
			expectedQuorum: 8,
		},
		{
			fis:            getNFInfo(16, 16, 1603863445, "36a21454-a2ca-11eb-bbaa-93a81c686f21"),
			modTime:        time.Unix(1603863445, 0),
			dataDir:        "36a21454-a2ca-11eb-bbaa-93a81c686f21",
			expectedErr:    errErasureReadQuorum,
			expectedQuorum: 0,
		},
	}

	for _, test := range tests {
		test := test
		t.Run("", func(t *testing.T) {
			_, err := findFileInfoInQuorum(context.Background(), test.fis, test.modTime, test.dataDir, test.expectedQuorum)
			if err != test.expectedErr {
				t.Errorf("Expected %s, got %s", test.expectedErr, err)
			}
		})
	}
}

func TestTransitionInfoEquals(t *testing.T) {
	inputs := []struct {
		tier            string
		remoteObjName   string
		remoteVersionID string
		status          string
	}{
		{
			tier:            "S3TIER-1",
			remoteObjName:   mustGetUUID(),
			remoteVersionID: mustGetUUID(),
			status:          "complete",
		},
		{
			tier:            "S3TIER-2",
			remoteObjName:   mustGetUUID(),
			remoteVersionID: mustGetUUID(),
			status:          "complete",
		},
	}

	var i uint
	for i = 0; i < 8; i++ {
		fi := FileInfo{
			TransitionTier:      inputs[0].tier,
			TransitionedObjName: inputs[0].remoteObjName,
			TransitionVersionID: inputs[0].remoteVersionID,
			TransitionStatus:    inputs[0].status,
		}
		ofi := fi
		if i&(1<<0) != 0 {
			ofi.TransitionTier = inputs[1].tier
		}
		if i&(1<<1) != 0 {
			ofi.TransitionedObjName = inputs[1].remoteObjName
		}
		if i&(1<<2) != 0 {
			ofi.TransitionVersionID = inputs[1].remoteVersionID
		}
		actual := fi.TransitionInfoEquals(ofi)
		if i == 0 && !actual {
			t.Fatalf("Test %d: Expected FileInfo's transition info to be equal: fi %v ofi %v", i, fi, ofi)
		}
		if i != 0 && actual {
			t.Fatalf("Test %d: Expected FileInfo's transition info to be inequal: fi %v ofi %v", i, fi, ofi)
		}
	}
	fi := FileInfo{
		TransitionTier:      inputs[0].tier,
		TransitionedObjName: inputs[0].remoteObjName,
		TransitionVersionID: inputs[0].remoteVersionID,
		TransitionStatus:    inputs[0].status,
	}
	ofi := FileInfo{}
	if fi.TransitionInfoEquals(ofi) {
		t.Fatalf("Expected to be inequal: fi %v ofi %v", fi, ofi)
	}
}


text:
var Utils     = require("../../utils")
  , DataTypes = require("../../data-types")
  , util      = require("util")

module.exports = (function() {
  var QueryGenerator = {
    addSchema: function(opts) {
      var tableName
      var schema        = (!!opts && !!opts.options && !!opts.options.schema ? opts.options.schema : undefined)
      var schemaDelimiter  = (!!opts && !!opts.options && !!opts.options.schemaDelimiter ? opts.options.schemaDelimiter : undefined)

      if (!!opts && !!opts.tableName) {
        tableName = opts.tableName
      }
      else if (typeof opts === "string") {
        tableName = opts
      }

      if (!schema || schema.toString().trim() === "") {
        return tableName
      }

      return this.quoteIdentifier(schema + (!schemaDelimiter ? '.' : schemaDelimiter) + tableName, false)
    },

    createSchema: function() {
      var query = "SHOW TABLES"
      return Utils._.template(query)({})
    },

    dropSchema: function() {
      var query = "SHOW TABLES"
      return Utils._.template(query)({})
    },

    showSchemasQuery: function() {
      return "SHOW TABLES"
    },

    createTableQuery: function(tableName, attributes, options) {
      options = Utils._.extend({
        engine: 'InnoDB',
        charset: null
      }, options || {})

      var query   = "CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>)<%= comment %> ENGINE=<%= engine %> <%= charset %>"
        , primaryKeys = []
        , foreignKeys = {}
        , attrStr = []

      for (var attr in attributes) {
        if (attributes.hasOwnProperty(attr)) {
          var dataType = attributes[attr]

          if (Utils._.includes(dataType, 'PRIMARY KEY')) {
            primaryKeys.push(attr)
            attrStr.push(this.quoteIdentifier(attr) + " " + dataType.replace(/PRIMARY KEY/, ''))
          } else if (Utils._.includes(dataType, 'REFERENCES')) {
            // MySQL doesn't support inline REFERENCES declarations: move to the end
            var m = dataType.match(/^(.+) (REFERENCES.*)$/)
            attrStr.push(this.quoteIdentifier(attr) + " " + m[1])
            foreignKeys[attr] = m[2]
          } else {
            attrStr.push(this.quoteIdentifier(attr) + " " + dataType)
          }
        }
      }

      var values = {
        table: this.quoteIdentifier(tableName),
        attributes: attrStr.join(", "),
        comment: options.comment && Utils._.isString(options.comment) ? " COMMENT " + this.escape(options.comment) : "",
        engine: options.engine,
        charset: (options.charset ? "DEFAULT CHARSET=" + options.charset : "")
      }
      , pkString = primaryKeys.map(function(pk) { return this.quoteIdentifier(pk) }.bind(this)).join(", ")

      if (pkString.length > 0) {
        values.attributes += ", PRIMARY KEY (" + pkString + ")"
      }

      for (var fkey in foreignKeys) {
        if(foreignKeys.hasOwnProperty(fkey)) {
          values.attributes += ", FOREIGN KEY (" + this.quoteIdentifier(fkey) + ") " + foreignKeys[fkey]
        }
      }

      return Utils._.template(query)(values).trim() + ";"
    },

    dropTableQuery: function(tableName, options) {
      options = options || {}

      var query = "DROP TABLE IF EXISTS <%= table %>;"

      return Utils._.template(query)({
        table: this.quoteIdentifier(tableName)
      })
    },

    renameTableQuery: function(before, after) {
      var query = "RENAME TABLE `<%= before %>` TO `<%= after %>`;"
      return Utils._.template(query)({ before: before, after: after })
    },

    showTablesQuery: function() {
      return 'SHOW TABLES;'
    },

    addColumnQuery: function(tableName, attributes) {
      var query      = "ALTER TABLE `<%= tableName %>` ADD <%= attributes %>;"
        , attrString = []

      for (var attrName in attributes) {
        var definition = attributes[attrName]

        attrString.push(Utils._.template('`<%= attrName %>` <%= definition %>')({
          attrName: attrName,
          definition: definition
        }))
      }

      return Utils._.template(query)({ tableName: tableName, attributes: attrString.join(', ') })
    },

    removeColumnQuery: function(tableName, attributeName) {
      var query = "ALTER TABLE `<%= tableName %>` DROP `<%= attributeName %>`;"
      return Utils._.template(query)({ tableName: tableName, attributeName: attributeName })
    },

    changeColumnQuery: function(tableName, attributes) {
      var query      = "ALTER TABLE `<%= tableName %>` CHANGE <%= attributes %>;"
      var attrString = []

      for (var attrName in attributes) {
        var definition = attributes[attrName]

        attrString.push(Utils._.template('`<%= attrName %>` `<%= attrName %>` <%= definition %>')({
          attrName: attrName,
          definition: definition
        }))
      }

      return Utils._.template(query)({ tableName: tableName, attributes: attrString.join(', ') })
    },

    renameColumnQuery: function(tableName, attrBefore, attributes) {
      var query      = "ALTER TABLE `<%= tableName %>` CHANGE <%= attributes %>;"
      var attrString = []

      for (var attrName in attributes) {
        var definition = attributes[attrName]

        attrString.push(Utils._.template('`<%= before %>` `<%= after %>` <%= definition %>')({
          before: attrBefore,
          after: attrName,
          definition: definition
        }))
      }

      return Utils._.template(query)({ tableName: tableName, attributes: attrString.join(', ') })
    },

    selectQuery: function(tableName, options) {
      var table = null,
          joinQuery = ""

      options            = options || {}
      options.table      = table = Array.isArray(tableName) ? tableName.map(function(t) { return this.quoteIdentifier(t)}.bind(this)).join(", ") : this.quoteIdentifier(tableName)
      options.attributes = options.attributes && options.attributes.map(function(attr){
        if(Array.isArray(attr) && attr.length == 2) {
          return [attr[0], this.quoteIdentifier(attr[1])].join(' as ')
        } else {
          return attr.indexOf(Utils.TICK_CHAR) < 0 ? this.quoteIdentifiers(attr) : attr
        }
      }.bind(this)).join(", ")
      options.attributes = options.attributes || '*'

      if (options.include) {
        var optAttributes = options.attributes === '*' ? [options.table + '.*'] : [options.attributes]

        options.include.forEach(function(include) {
          var attributes = Object.keys(include.daoFactory.attributes).map(function(attr) {
            return this.quoteIdentifier(include.as) + "." + this.quoteIdentifier(attr) + " AS " + this.quoteIdentifier(include.as + "." + attr)
          }.bind(this))

          optAttributes = optAttributes.concat(attributes)

          var table = include.daoFactory.tableName
          var as = include.as
          var tableLeft = ((include.association.associationType === 'BelongsTo') ? include.as : tableName)
          var attrLeft = 'id'
          var tableRight = ((include.association.associationType === 'BelongsTo') ? tableName : include.as)
          var attrRight = include.association.identifier
          joinQuery += " LEFT OUTER JOIN " + this.quoteIdentifier(table) + " AS " + this.quoteIdentifier(as) + " ON " + this.quoteIdentifier(tableLeft) + "." + this.quoteIdentifier(attrLeft) + " = " + this.quoteIdentifier(tableRight) + "." + this.quoteIdentifier(attrRight)

        }.bind(this))

        options.attributes = optAttributes.join(', ')
      }

      var query = "SELECT " + options.attributes + " FROM " + options.table
      query += joinQuery

      if (options.hasOwnProperty('where')) {
        options.where = this.getWhereConditions(options.where, tableName)
        query += " WHERE " + options.where
      }

      if (options.group) {
        options.group = Array.isArray(options.group) ? options.group.map(function(t) { return this.quoteIdentifiers(t)}.bind(this)).join(', ') : this.quoteIdentifiers(options.group)
        query += " GROUP BY " + options.group
      }

      if (options.order) {
        query += " ORDER BY " + options.order
      }

      if (options.limit && !(options.include && (options.limit === 1))) {
        if (options.offset) {
          query += " LIMIT " + options.offset + ", " + options.limit
        } else {
          query += " LIMIT " + options.limit
        }
      }

      query += ";"

      return query
    },

    insertQuery: function(tableName, attrValueHash) {
      attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, this.options.omitNull)

      var table = this.quoteIdentifier(tableName)
      var attributes = Object.keys(attrValueHash).map(function(attr){return this.quoteIdentifier(attr)}.bind(this)).join(",")
      var values = Utils._.values(attrValueHash).map(function(v) { return this.escape(v) }.bind(this)).join(",")

      var query = "INSERT INTO " + table + " (" + attributes + ") VALUES (" + values + ");"

      return query
    },

    bulkInsertQuery: function(tableName, attrValueHashes) {
      var tuples = []

      Utils._.forEach(attrValueHashes, function(attrValueHash) {
        tuples.push("(" +
          Utils._.values(attrValueHash).map(function(v) { return this.escape(v) }.bind(this)).join(",") +
        ")")
      }.bind(this))

      var table      = this.quoteIdentifier(tableName)
      var attributes = Object.keys(attrValueHashes[0]).map(function(attr){return this.quoteIdentifier(attr)}.bind(this)).join(",")

      var query  = "INSERT INTO " + table + " (" + attributes + ") VALUES " + tuples.join(",") + ";"

      return query
    },

    updateQuery: function(tableName, attrValueHash, where) {
      attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, this.options.omitNull)

      var values = []

      for (var key in attrValueHash) {
        var value  = attrValueHash[key]
          , _value = this.escape(value)

        values.push(this.quoteIdentifier(key) + "=" + _value)
      }

      var query = "UPDATE " + this.quoteIdentifier(tableName) +
                  " SET " + values.join(",") +
                  " WHERE " + this.getWhereConditions(where)

      return query
    },

    deleteQuery: function(tableName, where, options) {
      options = options || {}

      var table = this.quoteIdentifier(tableName)
      if (options.truncate === true) {
        // Truncate does not allow LIMIT and WHERE
        return "TRUNCATE " + table
      }

      where = this.getWhereConditions(where)
      var limit = ""

      if(Utils._.isUndefined(options.limit)) {
        options.limit = 1;
      }

      if(!!options.limit) {
        limit = " LIMIT " + this.escape(options.limit)
      }

      return "DELETE FROM " + table + " WHERE " + where + limit
    },

    bulkDeleteQuery: function(tableName, where, options) {
      options = options || {}

      var table = this.quoteIdentifier(tableName)
      where = this.getWhereConditions(where)

      var query = "DELETE FROM " + table + " WHERE " + where

      return query
    },

    incrementQuery: function (tableName, attrValueHash, where) {
      attrValueHash = Utils.removeNullValuesFromHash(attrValueHash, this.options.omitNull)

      var values = []

      for (var key in attrValueHash) {
        var value  = attrValueHash[key]
          , _value = this.escape(value)

        values.push(this.quoteIdentifier(key) + "=" + this.quoteIdentifier(key) + " + " + _value)
      }

      var table = this.quoteIdentifier(tableName)
      values = values.join(",")
      where = this.getWhereConditions(where)

      var query = "UPDATE " + table + " SET " + values + " WHERE " + where

      return query
    },

    addIndexQuery: function(tableName, attributes, options) {
      var transformedAttributes = attributes.map(function(attribute) {
        if(typeof attribute === 'string') {
          return attribute
        } else {
          var result = ""

          if (!attribute.attribute) {
            throw new Error('The following index attribute has no attribute: ' + util.inspect(attribute))
          }

          result += attribute.attribute

          if (attribute.length) {
            result += '(' + attribute.length + ')'
          }

          if (attribute.order) {
            result += ' ' + attribute.order
          }

          return result
        }
      }.bind(this))

      var onlyAttributeNames = attributes.map(function(attribute) {
        return (typeof attribute === 'string') ? attribute : attribute.attribute
      }.bind(this))

      options = Utils._.extend({
        indicesType: null,
        indexName: Utils._.underscored(tableName + '_' + onlyAttributeNames.join('_')),
        parser: null
      }, options || {})

      return Utils._.compact([
        "CREATE", options.indicesType, "INDEX", options.indexName,
        (options.indexType ? ('USING ' + options.indexType) : undefined),
        "ON", tableName, '(' + transformedAttributes.join(', ') + ')',
        (options.parser ? "WITH PARSER " + options.parser : undefined)
      ]).join(' ')
    },

    showIndexQuery: function(tableName, options) {
      var sql = "SHOW INDEX FROM <%= tableName %><%= options %>"
      return Utils._.template(sql)({
        tableName: tableName,
        options: (options || {}).database ? ' FROM ' + options.database : ''
      })
    },

    removeIndexQuery: function(tableName, indexNameOrAttributes) {
      var sql       = "DROP INDEX <%= indexName %> ON <%= tableName %>"
        , indexName = indexNameOrAttributes

      if (typeof indexName !== 'string') {
        indexName = Utils._.underscored(tableName + '_' + indexNameOrAttributes.join('_'))
      }

      return Utils._.template(sql)({ tableName: tableName, indexName: indexName })
    },

    getWhereConditions: function(smth, tableName) {
      var result = null

      if (Utils.isHash(smth)) {
        smth   = Utils.prependTableNameToHash(tableName, smth)
        result = this.hashToWhereConditions(smth)
      } else if (typeof smth === 'number') {
        smth   = Utils.prependTableNameToHash(tableName, { id: smth })
        result = this.hashToWhereConditions(smth)
      } else if (typeof smth === "string") {
        result = smth
      } else if (Array.isArray(smth)) {
        result = Utils.format(smth)
      }

      return result ? result : '1=1'
    },

    hashToWhereConditions: function(hash) {
      var result = []

      for (var key in hash) {
        var value = hash[key]

         //handle qualified key names
        var _key   = this.quoteIdentifiers(key)
          , _value = null

        if (Array.isArray(value)) {
          // is value an array?
          if (value.length === 0) { value = [null] }
          _value = "(" + value.map(function(v) { return this.escape(v) }.bind(this)).join(',') + ")"

          result.push([_key, _value].join(" IN "))
        } else if ((value) && (typeof value == 'object') && !(value instanceof Date)) {
          // is value an object?

          //using as sentinel for join column => value
          _value = this.quoteIdentifiers(value.join)
          result.push([_key, _value].join("="))
        } else {
          _value = this.escape(value)
          result.push((_value == 'NULL') ? _key + " IS NULL" : [_key, _value].join("="))
        }
      }

      return result.join(" AND ")
    },

    attributesToSQL: function(attributes) {
      var result = {}

      for (var name in attributes) {
        var dataType = attributes[name]

        if (Utils.isHash(dataType)) {
          var template

          if (dataType.type.toString() === DataTypes.ENUM.toString()) {
            if (Array.isArray(dataType.values) && (dataType.values.length > 0)) {
              template = "ENUM(" + Utils._.map(dataType.values, function(value) {
                return this.escape(value)
              }.bind(this)).join(", ") + ")"
            } else {
              throw new Error('Values for ENUM haven\'t been defined.')
            }
          } else {
            template = dataType.type.toString();
          }

          if (dataType.hasOwnProperty('allowNull') && (!dataType.allowNull)) {
            template += " NOT NULL"
          }

          if (dataType.autoIncrement) {
            template += " auto_increment"
          }

          if ((dataType.defaultValue !== undefined) && (dataType.defaultValue != DataTypes.NOW)) {
            template += " DEFAULT " + this.escape(dataType.defaultValue)
          }

          if (dataType.unique) {
            template += " UNIQUE"
          }

          if (dataType.primaryKey) {
            template += " PRIMARY KEY"
          }

          if(dataType.references) {
            template += " REFERENCES " + this.quoteIdentifier(dataType.references)

            if(dataType.referencesKey) {
              template += " (" + this.quoteIdentifier(dataType.referencesKey) + ")"
            } else {
              template += " (" + this.quoteIdentifier('id') + ")"
            }

            if(dataType.onDelete) {
              template += " ON DELETE " + dataType.onDelete.toUpperCase()
            }

            if(dataType.onUpdate) {
              template += " ON UPDATE " + dataType.onUpdate.toUpperCase()
            }

          }

          if (dataType.comment && Utils._.isString(dataType.comment) && dataType.comment.length) {
            template += " COMMENT " + Utils.escape(dataType.comment)
          }

          result[name] = template
        } else {
          result[name] = dataType
        }
      }

      return result
    },

    findAutoIncrementField: function(factory) {
      var fields = []

      for (var name in factory.attributes) {
        if (factory.attributes.hasOwnProperty(name)) {
          var definition = factory.attributes[name]

          if (definition && (definition.indexOf('auto_increment') > -1)) {
            fields.push(name)
          }
        }
      }

      return fields
    },

    enableForeignKeyConstraintsQuery: function() {
      var sql = "SET FOREIGN_KEY_CHECKS = 1;"
      return Utils._.template(sql, {})
    },

    disableForeignKeyConstraintsQuery: function() {
      var sql = "SET FOREIGN_KEY_CHECKS = 0;"
      return Utils._.template(sql, {})
    },

    quoteIdentifier: function(identifier, force) {
      return Utils.addTicks(identifier, "`")
    },

    quoteIdentifiers: function(identifiers, force) {
      return identifiers.split('.').map(function(v) { return this.quoteIdentifier(v, force) }.bind(this)).join('.')
    },

    escape: function(value) {
      if (value instanceof Date) {
        value = Utils.toSqlDate(value)
      } else if (typeof value === 'boolean') {
        value = value ? 1 : 0
      }
      return Utils.escape(value)
    }

  }

  return Utils._.extend(Utils._.clone(require("../query-generator")), QueryGenerator)
})()


text:
<script>
    $("document").ready(function()
    {
        //needed because jquery mobile will always try to make ajax calls from links
        //$("a").attr("data-ajax", "false");
        /************************************************************************
         *                                                                      *
         *                        Desktop Version Scripts                       *
         *                                                                      *
         ************************************************************************/

        if ($('#anno').length) {
            document.getElementById('mese').disabled = true;
            document.getElementById('giorno').disabled = true;
        }
        if ($('#annoDT').length) {
            document.getElementById('meseDT').disabled = true;
            document.getElementById('giornoDT').disabled = true;
        }
        if ($('#annoCO').length) {
            document.getElementById('meseCO').disabled = true;
            document.getElementById('giornoCO').disabled = true;
        }
        if ($('#annoNA').length) {
            document.getElementById('meseNA').disabled = true;
            document.getElementById('giornoNA').disabled = true;
        }

        function disableTextFilter(bool)
        {
            if ($('#anno').length) {
                document.getElementById('mese').disabled = bool;
                document.getElementById('giorno').disabled = bool;
            }
            if ($('#annoDT').length) {
                document.getElementById('meseDT').disabled = bool;
                document.getElementById('giornoDT').disabled = bool;
            }
            if ($('#annoCO').length) {
                document.getElementById('meseCO').disabled = bool;
                document.getElementById('giornoCO').disabled = bool;
            }
            if ($('#annoNA').length) {
                document.getElementById('meseNA').disabled = bool;
                document.getElementById('giornoNA').disabled = bool;
            }
        }

        $("#loading").hide();
        $(".lingua").click(function(event)
        {
			var strlang=event.target.id;
			strlang=strlang.substring(0,2);
            $.get("/features/ajax_pages/setlang.php", "lang="+strlang, function(data)
            {
                window.location.reload();
            });
        });

		// Bind enter events on search forms
		$("div.searchform input").keydown(function(e){
				if(e.keyCode==13) if(visualizzaGrafici) aggiornaGrafico(); else applyfilter();
		});
		$("div.searchformDT input").keydown(function(e){
				if(e.keyCode==13) if(visualizzaGrafici) aggiornaGrafico(); else applyfilterDT();
		});
		$("div.searchformCO input").keydown(function(e){
				if(e.keyCode==13) applyfilterCO();
		});
		$("div.searchformNA input" && visualizzaGrafici).keydown(function(e){
				if(e.keyCode==13) if(visualizzaGrafici) aggiornaGrafico(); else applyfilterNA();
		});

        $("#crossreferenceTXT").keydown(function(e){
				if(e.keyCode==13) crossreferenceTXT();
		});

        $("#brandingTXT").keydown(function(e){
				if(e.keyCode==13) brandingTXT();
		});

		// --

		$("#applyfilter").click(function(){applyfilter();});

		function applyfilter(){
           var anno = $("#anno").val();
            $("#anno").val = "";
            var mese = $("#mese").val();
            $("#mese").val = "";
            var giorno = $("#giorno").val();
            $("#giorno").val = "";
            if (anno == "" && mese == "" && giorno == "")
            {
                $("#loading").show();
                $("#tabellafatture").html("");
                document.getElementById('applyfilter').disabled = true;
                document.getElementById('anno').disabled = true;
                document.getElementById('mese').disabled = true;
                document.getElementById('giorno').disabled = true;
                $.post("/features/ajax_pages/getfatture.php", "", function(data, status){
                    $("#loading").hide();
                    $("#tabellafatture").html(data);
                    document.getElementById('applyfilter').disabled = false;
                    document.getElementById('anno').disabled = false;
                    document.getElementById('mese').disabled = false;
                    document.getElementById('giorno').disabled = false;
                });
            }
            else
            {
                if (anno != "" && mese == "" && giorno == "")
                {
                    $("#loading").show();
                    $("#tabellafatture").html("");
                    document.getElementById('applyfilter').disabled = true;
                    document.getElementById('anno').disabled = true;
                    document.getElementById('mese').disabled = true;
                    document.getElementById('giorno').disabled = true;
                    $.post("/features/ajax_pages/getfatture.php", "anno="+anno, function(data, status){
                        $("#loading").hide();
                        $("#tabellafatture").html(data);
                        document.getElementById('applyfilter').disabled = false;
                        document.getElementById('anno').disabled = false;
                        document.getElementById('mese').disabled = false;
                        document.getElementById('giorno').disabled = false;
                    });
                }
                else
                {
                    if (anno != "" && mese != "" && giorno == "")
                    {
                        $("#loading").show();
                        $("#tabellafatture").html("");
                        document.getElementById('applyfilter').disabled = true;
                        document.getElementById('anno').disabled = true;
                        document.getElementById('mese').disabled = true;
                        document.getElementById('giorno').disabled = true;
                        $.post("/features/ajax_pages/getfatture.php", "anno="+anno+"&mese="+mese, function(data, status){
                            $("#loading").hide();
                            $("#tabellafatture").html(data);
                            document.getElementById('applyfilter').disabled = false;
                            document.getElementById('anno').disabled = false;
                            document.getElementById('mese').disabled = false;
                            document.getElementById('giorno').disabled = false;
                        });
                    }
                    else
                    {
                        if (anno != "" && mese != "" && giorno != "")
                        {
                            $("#loading").show();
                            $("#tabellafatture").html("");
                            document.getElementById('applyfilter').disabled = true;
                            document.getElementById('anno').disabled = true;
                            document.getElementById('mese').disabled = true;
                            document.getElementById('giorno').disabled = true;
                            $.post("/features/ajax_pages/getfatture.php", "anno="+anno+"&mese="+mese+"&giorno="+giorno, function(data, status){
                                $("#loading").hide();
                                $("#tabellafatture").html(data);
                                document.getElementById('applyfilter').disabled = false;
                                document.getElementById('anno').disabled = false;
                                document.getElementById('mese').disabled = false;
                                document.getElementById('giorno').disabled = false;
                            });
                        }
                    }
                }
            }
		}

        $("#applyfilterDT").click(function(){applyfilterDT();});
		function applyfilterDT(){
            var anno = $("#annoDT").val();
            $("#annoDT").val = "";
            var mese = $("#meseDT").val();
            $("#meseDT").val = "";
            var giorno = $("#giornoDT").val();
            $("#giornoDT").val = "";
            if (anno == "" && mese == "" && giorno == "")
            {
                document.getElementById('applyfilterDT').disabled = true;
                document.getElementById('annoDT').disabled = true;
                document.getElementById('meseDT').disabled = true;
                document.getElementById('giornoDT').disabled = true;
                $("#loading").show();
                $("#tabelladocumentotrasporto").html("");
                $.post("/features/ajax_pages/getdt.php", "", function(data, status){
                    $("#loading").hide();
                    $("#tabelladocumentotrasporto").html(data);
                    document.getElementById('applyfilterDT').disabled = false;
                    document.getElementById('annoDT').disabled = false;
                    document.getElementById('meseDT').disabled = false;
                    document.getElementById('giornoDT').disabled = false;
                });
            }
            else
            {
                if (anno != "" && mese == "" && giorno == "")
                {
                    $("#loading").show();
                    $("#tabelladocumentotrasporto").html("");
                    document.getElementById('applyfilterDT').disabled = true;
                    document.getElementById('annoDT').disabled = true;
                    document.getElementById('meseDT').disabled = true;
                    document.getElementById('giornoDT').disabled = true;
                    $.post("/features/ajax_pages/getdt.php", "anno="+anno, function(data, status){
                        $("#loading").hide();
                        $("#tabelladocumentotrasporto").html(data);
                        document.getElementById('applyfilterDT').disabled = false;
                        document.getElementById('annoDT').disabled = false;
                        document.getElementById('meseDT').disabled = false;
                        document.getElementById('giornoDT').disabled = false;
                    });
                }
                else
                {
                    if (anno != "" && mese != "" && giorno == "")
                    {
                        $("#loading").show();
                        $("#tabelladocumentotrasporto").html("");
                        document.getElementById('applyfilterDT').disabled = true;
                        document.getElementById('annoDT').disabled = true;
                        document.getElementById('meseDT').disabled = true;
                        document.getElementById('giornoDT').disabled = true;
                        $.post("/features/ajax_pages/getdt.php", "anno="+anno+"&mese="+mese, function(data, status){
                            $("#loading").hide();
                            $("#tabelladocumentotrasporto").html(data);
                            document.getElementById('applyfilterDT').disabled = false;
                            document.getElementById('annoDT').disabled = false;
                            document.getElementById('meseDT').disabled = false;
                            document.getElementById('giornoDT').disabled = false;
                        });
                    }
                    else
                    {
                        if (anno != "" && mese != "" && giorno != "")
                        {
                            $("#loading").show();
                            $("#tabelladocumentotrasporto").html("");
                            document.getElementById('applyfilterDT').disabled = true;
                            document.getElementById('annoDT').disabled = true;
                            document.getElementById('meseDT').disabled = true;
                            document.getElementById('giornoDT').disabled = true;
                            $.post("/features/ajax_pages/getdt.php", "anno="+anno+"&mese="+mese+"&giorno="+giorno, function(data, status){
                                $("#loading").hide();
                                $("#tabelladocumentotrasporto").html(data);
                                document.getElementById('applyfilterDT').disabled = false;
                                document.getElementById('annoDT').disabled = false;
                                document.getElementById('meseDT').disabled = false;
                                document.getElementById('giornoDT').disabled = false;
                            });
                        }
                    }
                }
            }
		}

        $("#applyfilterNA").click(function(){applyfilterNA();});
		function applyfilterNA(){
            var anno = $("#annoNA").val();
            $("#annoNA").val = "";
            var mese = $("#meseNA").val();
            $("#meseNA").val = "";
            var giorno = $("#giornoNA").val();
            $("#giornoNA").val = "";
            if (anno == "" && mese == "" && giorno == "")
            {
                document.getElementById('applyfilterNA').disabled = true;
                document.getElementById('annoNA').disabled = true;
                document.getElementById('meseNA').disabled = true;
                document.getElementById('giornoNA').disabled = true;
                $("#loading").show();
                $("#tabellanoteaccredito").html("");
                $.post("/features/ajax_pages/getna.php", "", function(data, status){
                    $("#loading").hide();
                    $("#tabellanoteaccredito").html(data);
                    document.getElementById('applyfilterNA').disabled = false;
                    document.getElementById('annoNA').disabled = false;
                    document.getElementById('meseNA').disabled = false;
                    document.getElementById('giornoNA').disabled = false;
                });
            }
            else
            {
                if (anno != "" && mese == "" && giorno == "")
                {
                    $("#loading").show();
                    $("#tabellanoteaccredito").html("");
                    document.getElementById('applyfilterNA').disabled = true;
                    document.getElementById('annoNA').disabled = true;
                    document.getElementById('meseNA').disabled = true;
                    document.getElementById('giornoNA').disabled = true;
                    $.post("/features/ajax_pages/getna.php", "anno="+anno, function(data, status){
                        $("#loading").hide();
                        $("#tabellanoteaccredito").html(data);
                        document.getElementById('applyfilterNA').disabled = false;
                        document.getElementById('annoNA').disabled = false;
                        document.getElementById('meseNA').disabled = false;
                        document.getElementById('giornoNA').disabled = false;
                    });
                }
                else
                {
                    if (anno != "" && mese != "" && giorno == "")
                    {
                        $("#loading").show();
                        $("#tabellanoteaccredito").html("");
                        document.getElementById('applyfilterNA').disabled = true;
                        document.getElementById('annoNA').disabled = true;
                        document.getElementById('meseNA').disabled = true;
                        document.getElementById('giornoNA').disabled = true;
                        $.post("/features/ajax_pages/getna.php", "anno="+anno+"&mese="+mese, function(data, status){
                            $("#loading").hide();
                            $("#tabellanoteaccredito").html(data);
                            document.getElementById('applyfilterNA').disabled = false;
                            document.getElementById('annoNA').disabled = false;
                            document.getElementById('meseNA').disabled = false;
                            document.getElementById('giornoNA').disabled = false;
                        });
                    }
                    else
                    {
                        if (anno != "" && mese != "" && giorno != "")
                        {
                            $("#loading").show();
                            $("#tabellanoteaccredito").html("");
                            document.getElementById('applyfilterNA').disabled = true;
                            document.getElementById('annoNA').disabled = true;
                            document.getElementById('meseNA').disabled = true;
                            document.getElementById('giornoNA').disabled = true;
                            $.post("/features/ajax_pages/getna.php", "anno="+anno+"&mese="+mese+"&giorno="+giorno, function(data, status){
                                $("#loading").hide();
                                $("#tabellanoteaccredito").html(data);
                                document.getElementById('applyfilterNA').disabled = false;
                                document.getElementById('annoNA').disabled = false;
                                document.getElementById('meseNA').disabled = false;
                                document.getElementById('giornoNA').disabled = false;
                            });
                        }
                    }
                }
            }
		}

        $("#applyfilterCO").click(function(){applyfilterCO();});

		function applyfilterCO(){
            var anno = $("#annoCO").val();
            $("#annoCO").val = "";
            var mese = $("#meseCO").val();
            $("#meseCO").val = "";
            var giorno = $("#giornoCO").val();
            $("#giornoCO").val = "";
            if (anno == "" && mese == "" && giorno == "")
            {
                $("#loading").show();
                $("#tabellaconford").html("");
                document.getElementById('applyfilterCO').disabled = true;
                document.getElementById('annoCO').disabled = true;
                document.getElementById('meseCO').disabled = true;
                document.getElementById('giornoCO').disabled = true;
                $.post("/features/ajax_pages/getco.php", "", function(data, status){
                    $("#loading").hide();
                    $("#tabellaconford").html(data);
                    document.getElementById('applyfilterCO').disabled = false;
                    document.getElementById('annoCO').disabled = false;
                    document.getElementById('meseCO').disabled = false;
                    document.getElementById('giornoCO').disabled = false;
                });
            }
            else
            {
                if (anno != "" && mese == "" && giorno == "")
                {
                    $("#loading").show();
                    $("#tabellaconford").html("");
                    document.getElementById('applyfilterCO').disabled = true;
                    document.getElementById('annoCO').disabled = true;
                    document.getElementById('meseCO').disabled = true;
                    document.getElementById('giornoCO').disabled = true;
                    $.post("/features/ajax_pages/getco.php", "anno="+anno, function(data, status){
                        $("#loading").hide();
                        $("#tabellaconford").html(data);
                        document.getElementById('applyfilterCO').disabled = false;
                        document.getElementById('annoCO').disabled = false;
                        document.getElementById('meseCO').disabled = false;
                        document.getElementById('giornoCO').disabled = false;
                    });
                }
                else
                {
                    if (anno != "" && mese != "" && giorno == "")
                    {
                        $("#loading").show();
                        $("#tabellaconford").html("");
                        document.getElementById('applyfilterCO').disabled = true;
                        document.getElementById('annoCO').disabled = true;
                        document.getElementById('meseCO').disabled = true;
                        document.getElementById('giornoCO').disabled = true;
                        $.post("/features/ajax_pages/getco.php", "anno="+anno+"&mese="+mese, function(data, status){
                            $("#loading").hide();
                            $("#tabellaconford").html(data);
                            document.getElementById('applyfilterCO').disabled = false;
                            document.getElementById('annoCO').disabled = false;
                            document.getElementById('meseCO').disabled = false;
                            document.getElementById('giornoCO').disabled = false;
                        });
                    }
                    else
                    {
                        if (anno != "" && mese != "" && giorno != "")
                        {
                            $("#loading").show();
                            $("#tabellaconford").html("");
                            document.getElementById('applyfilterCO').disabled = true;
                            document.getElementById('annoCO').disabled = true;
                            document.getElementById('meseCO').disabled = true;
                            document.getElementById('giornoCO').disabled = true;
                            $.post("/features/ajax_pages/getco.php", "anno="+anno+"&mese="+mese+"&giorno="+giorno, function(data, status){
                                $("#loading").hide();
                                $("#tabellaconford").html(data);
                                document.getElementById('applyfilterCO').disabled = false;
                                document.getElementById('annoCO').disabled = false;
                                document.getElementById('meseCO').disabled = false;
                                document.getElementById('giornoCO').disabled = false;
                            });
                        }
                    }
                }
            }
		}

        $("#uhpcertTXT").keyup(function()
        {
            $("#loading").show();
            $("#tabellacertuhppvt").html("");
            var text = $("#uhpcertTXT").val();
            $.post("/features/ajax_pages/getcert.php", "text="+text, function(data, status)
            {
                $("#loading").hide();
                $("#tabellacertuhppvt").html(data);
            });
        });

        $("#crossreferenceBTN").click(function(){crossreferenceTXT();});
        function crossreferenceTXT()
        {
            $("#loading").show();
            $("#tabellatrascodifiche").html("");
            document.getElementById('crossreferenceBTN').disabled = true;
            document.getElementById('crossreferenceTXT').disabled = true;
            var text = $("#crossreferenceTXT").val();
            $.post("/features/ajax_pages/getcrossref.php", "text="+text, function(data, status)
            {
                $("#loading").hide();
                $("#tabellatrascodifiche").html(data);
                document.getElementById('crossreferenceBTN').disabled = false;
                document.getElementById('crossreferenceTXT').disabled = false;
            });
        }

        $("#brandingBTN").click(function(e){brandingTXT();});
        function brandingTXT()
        {
            $("#loading").show();
            $("#tabellamarcature").html("");
            document.getElementById('brandingBTN').disabled = true;
            document.getElementById('brandingTXT').disabled = true;
            var text = $("#brandingTXT").val();
            $.post("/features/ajax_pages/getbrand.php", "text="+text, function(data, status)
            {
                $("#loading").hide();
                $("#tabellamarcature").html(data);
                document.getElementById('brandingBTN').disabled = false;
                document.getElementById('brandingTXT').disabled = false;
            });
        }

        $("#resetBTN").click(function()
        {
            document.getElementById("CDPAR").value = "";
            document.getElementById("CDORD").value = "";
            document.getElementById("NRSERIAL").value = "";
        });

        $("#searchCertPubBTN").click(function()
        {
            var cdpar = $("#CDPAR").val();
            var cdord = $("#CDORD").val();
            var nrserial = $("#NRSERIAL").val();
            if (cdpar == "" || cdord == "" || nrserial == "")
            {
                alert("<?php echo $localizzazione['cert_pub_err_txt'][$_SESSION['lang']] ?>");
            }
            else
            {
                $("#loading").show();
                $("#tabellacertuhppub").html("");
                $.post("/features/ajax_pages/getcertpub.php", "cdpar="+cdpar+"&cdord="+cdord+"&nrserial="+nrserial, function(data, status){
                    $("#loading").hide();
                    $("#tabellacertuhppub").html(data);
                });
            }
        });

        $('.contenitoregrafico').hide();
        $("#aggiornagraficoBTN").hide();
        $('.contenitoregrafico').highcharts({
            chart: {
                plotBackgroundColor: "#2C2F37",
                backgroundColor: "#DFDFDF",
                fontColor: '#FF6600',
                marginBottom: 10,
                width: 700,
                height: 400,
                type: 'pie',
                options3d: {
                    enabled: true,
                    alpha: 45,
                    beta: 0
                }
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    depth: 35,
                    dataLabels: {
                        enabled: true,
                    }
                }
            },
            xAxis: {
                type: 'datetime'
            },
            credits: {
                enabled: false
            },
            title : {
                text : window.location.pathname.slice(1)
            },
            series: [{
               type: "pie",
               data: [29.9, 71.5, 106.4],
               name : 'Importo'
            }]
        });
        var visualizzaGrafici = false;

        $(".annitxt").keydown(function(event)
        {
            var testo = $(".annitxt").val();
            if (testo.length < 4)
            {
                // Allow only backspace and delete and tab and refresh
                if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 116 )
                {
                    // let it happen, don't do anything
                    if ((event.keyCode == 46 || event.keyCode == 8) && testo.length == 1)
                    {
                        disableTextFilter(true);
                    }
                }
                else
                {
                    // Ensure that it is a number and stop the keypress
                    if (!(event.keyCode >= 48 && event.keyCode <= 57) && !(event.keyCode >= 96 && event.keyCode <= 105))
                    {
                        event.preventDefault();
                    }
                    else
                    {
                        disableTextFilter(false);
                    }
                }
            }
            else
            {
                if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 116 )
                {
                    // let it happen, don't do anything
                }
                else
                return false;
            }
        });

        $(".linktoggle").click(function()
        {
            var anno = $(".annitxt").val();
            var mese = $(".mesitxt").val();
            var chart = $('.contenitoregrafico').highcharts();
            if (anno == "")
            {
                alert("<?php echo $localizzazione["grafico_error_no_data"][$_SESSION['lang']]; ?>");
                visualizzaGrafici = false;
                return false;
            }
            if (!visualizzaGrafici)
            {
                $(".tabelladiv").hide();
                $(".contenitoregrafico").show();
                visualizzaGrafici = true;
                $.get("/features/ajax_pages/getgrafico.php", "type="+window.location.pathname.slice(1)+"&anno="+anno+"&mese="+mese, function(dato, success)
                {
                    chart.series[0].setData(eval(dato));
                });
                $(".linktoggle").html("<?php echo $localizzazione["visualizza_tabelle"][$_SESSION['lang']]; ?>'");
                $("#aggiornagraficoBTN").show();
            }
            else
            {
                $(".tabelladiv").show();
                $(".contenitoregrafico").hide();
                visualizzaGrafici = false;
                $(".linktoggle").html("<?php echo $localizzazione["visualizza_grafici"][$_SESSION['lang']]; ?>");
                $("#aggiornagraficoBTN").hide();
            }

        });

        $("#aggiornagraficoBTN").click(function(){aggiornaGrafico();});
        function aggiornaGrafico()
        {
            var anno = $(".annitxt").val();
            var mese = $(".mesitxt").val();
            var chart = $('.contenitoregrafico').highcharts();
            if (anno == "")
            {
                alert("<?php echo $localizzazione["grafico_error_no_data"][$_SESSION['lang']]; ?>");
                return false;
            }
            $.get("/features/ajax_pages/getgrafico.php", "type="+window.location.pathname.slice(1)+"&anno="+anno+"&mese="+mese, function(dato, success)
            {
                chart.series[0].setData(eval(dato));
            });
        }

        /************************************************************************
         *                                                                      *
         *                      Responsive Layout Scripts                       *
         *                                                                      *
         ************************************************************************/
        //Partiamo con un dispositivo mobile o desktop?
        var isInMobileMode = false;
        if ($(window).width() < 1600)
            isInMobileMode = true;

        //variabile booleana necessaria per capire se il menu deve essere visibile o meno
        var clicked = false;
        $(".btn-responsive-menu").click(function()
        {
            $("#mainmenu").toggleClass("show");
            if (clicked)
            {
                //Nasconde Menu
                $(".left-sidebar").removeClass("hidden");
                $(".content").animate({marginLeft: "-=214px"},1000);
                $(".left-sidebar").animate({marginLeft: "-=214"},1000);
                clicked = false;
            }
            else
            {
                //Mostra menu
                $(".left-sidebar").addClass("hidden");
                $(".content").animate({marginLeft: "+=214px"},1000);
                $(".left-sidebar").css("display", "inline-block");
                $(".left-sidebar").animate({marginLeft: "+=214"},1000);
                clicked = true;
            }
        });

        //Questa funzione è come un listener. Se sei su un browser o da mobile guardi il sito con il cellulare girato, cambia in modo dinamico la visualizzazione
        $(window).resize(function() {
            if($(window).width() >= 1600)
            {
                $(".content").css("margin-left", "214px");
                $(".left-sidebar").css("margin-left", "0px");
                $(".left-sidebar").css("display", "block");
                isInMobileMode = false;
            }
            else
            {
                if (!clicked)
                {
                    $(".content").css("margin-left", "0px");
                    $(".left-sidebar").css("margin-left", "-214px");
                    $(".left-sidebar").css("display", "none");
                }
                isInMobileMode = true;
            }
        });

    });

    /************************************************************************
    *                                                                       *
    *                           Login Validation Form                       *
    *                                                                       *
    *************************************************************************/

	function validateform()
	{
		var uname=$.trim($("#user_login").val());
		var upass=$.trim($("#user_pass").val());
		if(uname==""){
			alert("<?php echo $localizzazione['user_obb'][$_SESSION['lang']]; ?>");
			$("#user_login").focus();
			return false;
		}
		if(upass==""){
			alert("<?php echo $localizzazione['pass_obb'][$_SESSION['lang']]; ?>");
			$("#user_pass").focus();
			return false;
		}
	}
</script>