working on it ...

Filters

Explore Public Snippets

Sort by

Found 49k snippets matching: count

    public by cghersi modified Jul 27, 2013  338353  1  6  0

    ASP.NET Performance monitors

    The following XML file can be used to create a new user defined Data Collector Set in the Performance Monitor Tool for Windows servers. It checks the most important performance counters for the right execution of ASP.NET Web applications. The performance counters taken into account are those reported in this article: http://mvolo.com/fix-the-3-hi
    <?xml version="1.0" encoding="UTF-16"?>
    <DataCollectorSet>
    	<Status>0</Status>
    	<Duration>600</Duration>
    	<Description>Genera un rapporto con informazioni dettagliate sullo stato delle risorse hardware locali, sui tempi di risposta del sistema e sui processi eseguiti nel computer locale. Tali informazioni consentono di identificare le possibili cause dei problemi di prestazioni. Per eseguire questo Insieme agenti di raccolta dati, è necessario essere almeno membri del gruppo Administrators locale o di un gruppo equivalente.</Description>
    	<DescriptionUnresolved>Genera un rapporto con informazioni dettagliate sullo stato delle risorse hardware locali, sui tempi di risposta del sistema e sui processi eseguiti nel computer locale. Tali informazioni consentono di identificare le possibili cause dei problemi di prestazioni. Per eseguire questo Insieme agenti di raccolta dati, è necessario essere almeno membri del gruppo Administrators locale o di un gruppo equivalente.</DescriptionUnresolved>
    	<DisplayName>
    	</DisplayName>
    	<DisplayNameUnresolved>
    	</DisplayNameUnresolved>
    	<SchedulesEnabled>-1</SchedulesEnabled>
    	<Keyword>CPU</Keyword>
    	<Keyword>Memory</Keyword>
    	<Keyword>Disk</Keyword>
    	<Keyword>Network</Keyword>
    	<Keyword>Performance</Keyword>
    	<LatestOutputLocation>C:\PerfLogs\Admin\ASP.NET\ZIOJ-PC_20130727-000002</LatestOutputLocation>
    	<Name>ASP.NET</Name>
    	<OutputLocation>C:\PerfLogs\Admin\ASP.NET\ZIOJ-PC_20130727-000003</OutputLocation>
    	<RootPath>%systemdrive%\PerfLogs\Admin\ASP.NET</RootPath>
    	<Segment>0</Segment>
    	<SegmentMaxDuration>0</SegmentMaxDuration>
    	<SegmentMaxSize>0</SegmentMaxSize>
    	<SerialNumber>3</SerialNumber>
    	<Server>
    	</Server>
    	<Subdirectory>
    	</Subdirectory>
    	<SubdirectoryFormat>3</SubdirectoryFormat>
    	<SubdirectoryFormatPattern>yyyyMMdd\-NNNNNN</SubdirectoryFormatPattern>
    	<Task>
    	</Task>
    	<TaskRunAsSelf>0</TaskRunAsSelf>
    	<TaskArguments>
    	</TaskArguments>
    	<TaskUserTextArguments>
    	</TaskUserTextArguments>
    	<UserAccount>SYSTEM</UserAccount>
    	<Security>O:BAG:S-1-5-21-2577573897-3235701343-559641010-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;FR;;;LU)(A;;0x1301ff;;;S-1-5-80-2661322625-712705077-2999183737-3043590567-590698655)(A;ID;FA;;;SY)(A;ID;FA;;;BA)(A;ID;0x1200ab;;;LU)(A;ID;FR;;;AU)(A;ID;FR;;;LS)(A;ID;FR;;;NS)</Security>
    	<StopOnCompletion>0</StopOnCompletion>
    	<TraceDataCollector>
    		<DataCollectorType>1</DataCollectorType>
    		<Name>NT Kernel</Name>
    		<FileName>NtKernel</FileName>
    		<FileNameFormat>0</FileNameFormat>
    		<FileNameFormatPattern>
    		</FileNameFormatPattern>
    		<LogAppend>0</LogAppend>
    		<LogCircular>0</LogCircular>
    		<LogOverwrite>0</LogOverwrite>
    		<LatestOutputLocation>C:\PerfLogs\Admin\ASP.NET\ZIOJ-PC_20130727-000002\NtKernel.etl</LatestOutputLocation>
    		<Guid>{00000000-0000-0000-0000-000000000000}</Guid>
    		<BufferSize>64</BufferSize>
    		<BuffersLost>0</BuffersLost>
    		<BuffersWritten>0</BuffersWritten>
    		<ClockType>1</ClockType>
    		<EventsLost>0</EventsLost>
    		<ExtendedModes>0</ExtendedModes>
    		<FlushTimer>0</FlushTimer>
    		<FreeBuffers>0</FreeBuffers>
    		<MaximumBuffers>200</MaximumBuffers>
    		<MinimumBuffers>0</MinimumBuffers>
    		<NumberOfBuffers>0</NumberOfBuffers>
    		<PreallocateFile>0</PreallocateFile>
    		<ProcessMode>0</ProcessMode>
    		<RealTimeBuffersLost>0</RealTimeBuffersLost>
    		<SessionName>NT Kernel Logger</SessionName>
    		<SessionThreadId>0</SessionThreadId>
    		<StreamMode>1</StreamMode>
    		<TraceDataProvider>
    			<DisplayName>{9E814AAD-3204-11D2-9A82-006008A86939}</DisplayName>
    			<FilterEnabled>0</FilterEnabled>
    			<FilterType>0</FilterType>
    			<Level>
    				<Description>Gli eventi fino a questo livello sono attivati</Description>
    				<ValueMapType>1</ValueMapType>
    				<Value>0</Value>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x0</Value>
    				</ValueMapItem>
    			</Level>
    			<KeywordsAny>
    				<Description>Gli eventi con almeno una delle parole chiave specificate sono attivati</Description>
    				<ValueMapType>2</ValueMapType>
    				<Value>0x10303</Value>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x1</Value>
    				</ValueMapItem>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x2</Value>
    				</ValueMapItem>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x100</Value>
    				</ValueMapItem>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x200</Value>
    				</ValueMapItem>
    				<ValueMapItem>
    					<Key>
    					</Key>
    					<Description>
    					</Description>
    					<Enabled>-1</Enabled>
    					<Value>0x10000</Value>
    				</ValueMapItem>
    			</KeywordsAny>
    			<KeywordsAll>
    				<Description>Gli eventi con tutte le parole chiave specificate sono attivati</Description>
    				<ValueMapType>2</ValueMapType>
    				<Value>0x0</Value>
    			</KeywordsAll>
    			<Properties>
    				<Description>I campi dati aggiuntivi specificati verranno raccolti con ogni evento</Description>
    				<ValueMapType>2</ValueMapType>
    				<Value>0</Value>
    			</Properties>
    			<Guid>{9E814AAD-3204-11D2-9A82-006008A86939}</Guid>
    		</TraceDataProvider>
    	</TraceDataCollector>
    	<PerformanceCounterDataCollector>
    		<DataCollectorType>0</DataCollectorType>
    		<Name>Performance Counter</Name>
    		<FileName>Performance Counter</FileName>
    		<FileNameFormat>1</FileNameFormat>
    		<FileNameFormatPattern>yyyyMMdd</FileNameFormatPattern>
    		<LogAppend>-1</LogAppend>
    		<LogCircular>0</LogCircular>
    		<LogOverwrite>0</LogOverwrite>
    		<LatestOutputLocation>C:\PerfLogs\Admin\ASP.NET\ZIOJ-PC_20130727-000002\Performance Counter20130727.csv</LatestOutputLocation>
    		<DataSourceName>
    		</DataSourceName>
    		<SampleInterval>1</SampleInterval>
    		<SegmentMaxRecords>0</SegmentMaxRecords>
    		<LogFileFormat>0</LogFileFormat>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\% Managed Processor Time (estimated)</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Viewstate MAC Validation Failure</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors During Compilation</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors During Execution</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors During Preprocessing</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors Unhandled During Execution</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors Unhandled During Execution/Sec</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Audit Failure Events Raised</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Error Events Raised</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Error Events Raised/Sec</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Infrastructure Error Events Raised</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Infrastructure Error Events Raised/Sec</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Request Error Events Raised</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Request Error Events Raised/Sec</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors Total</Counter>
    		<Counter>\ASP.NET Apps v4.0.30319(__Total__)\Errors Total/Sec</Counter>
    		<Counter>\ASP.NET v4.0.30319\Error Events Raised</Counter>
    		<Counter>\ASP.NET v4.0.30319\Infrastructure Error Events Raised</Counter>
    		<Counter>\ASP.NET v4.0.30319\Request Error Events Raised</Counter>
    		<Counter>\.NET CLR Exceptions\*</Counter>
    		<Counter>\.NET CLR Memory(_Global_)\% Time in GC</Counter>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\% Tempo processore gestito (stimato)</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errore di convalida MAC ViewState</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errori di compilazione</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errori di esecuzione.</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errori di pre-elaborazione</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errori non gestiti durante l'esecuzione</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Errori non gestiti durante l'esecuzione/sec</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore di controllo generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore generati/sec</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore infrastruttura generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore infrastruttura generati/sec</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore richiesta generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Eventi errore richiesta generati/sec</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Totale errori</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET Apps v4.0.30319(__Total__)\Totale errori/sec</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET v4.0.30319\Eventi errore generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET v4.0.30319\Eventi errore infrastruttura generati</CounterDisplayName>
    		<CounterDisplayName>\ASP.NET v4.0.30319\Eventi errore richiesta generati</CounterDisplayName>
    		<CounterDisplayName>\Eccezioni CLR .NET\*</CounterDisplayName>
    		<CounterDisplayName>\Memoria CLR .NET(_Global_)\Percentuale tempo in GC</CounterDisplayName>
    	</PerformanceCounterDataCollector>
    	<DataManager>
    		<Enabled>-1</Enabled>
    		<CheckBeforeRunning>-1</CheckBeforeRunning>
    		<MinFreeDisk>200</MinFreeDisk>
    		<MaxSize>1024</MaxSize>
    		<MaxFolderCount>100</MaxFolderCount>
    		<ResourcePolicy>0</ResourcePolicy>
    		<ReportFileName>report.html</ReportFileName>
    		<RuleTargetFileName>report.xml</RuleTargetFileName>
    		<EventsFileName>
    		</EventsFileName>
    		<Rules>
    			<Logging level="15" file="rules.log">
    			</Logging>
    			<Import file="%systemroot%\pla\rules\Rules.System.Common.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.Summary.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.Performance.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.CPU.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.Network.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.Disk.xml">
    			</Import>
    			<Import file="%systemroot%\pla\rules\Rules.System.Memory.xml">
    			</Import>
    		</Rules>
    		<ReportSchema>
    			<Report name="systemPerformance" version="1" threshold="100">
    				<Import file="%systemroot%\pla\reports\Report.System.Common.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.Summary.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.Performance.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.CPU.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.Network.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.Disk.xml">
    				</Import>
    				<Import file="%systemroot%\pla\reports\Report.System.Memory.xml">
    				</Import>
    			</Report>
    		</ReportSchema>
    		<FolderAction>
    			<Size>0</Size>
    			<Age>1</Age>
    			<Actions>3</Actions>
    			<SendCabTo>
    			</SendCabTo>
    		</FolderAction>
    		<FolderAction>
    			<Size>0</Size>
    			<Age>56</Age>
    			<Actions>8</Actions>
    			<SendCabTo>
    			</SendCabTo>
    		</FolderAction>
    		<FolderAction>
    			<Size>0</Size>
    			<Age>168</Age>
    			<Actions>26</Actions>
    			<SendCabTo>
    			</SendCabTo>
    		</FolderAction>
    	</DataManager>
    	<Value name="PerformanceMonitorView" type="document">
    		<OBJECT ID="DISystemMonitor" CLASSID="CLSID:C4D2D8E0-D1DD-11CE-940F-008029004347">
    			<PARAM NAME="CounterCount" VALUE="4">
    			</PARAM>
    			<PARAM NAME="Counter00001.Path" VALUE="\Processor(_Total)\% Processor Time">
    			</PARAM>
    			<PARAM NAME="Counter00001.Color" VALUE="255">
    			</PARAM>
    			<PARAM NAME="Counter00001.Width" VALUE="2">
    			</PARAM>
    			<PARAM NAME="Counter00001.LineStyle" VALUE="0">
    			</PARAM>
    			<PARAM NAME="Counter00001.ScaleFactor" VALUE="0">
    			</PARAM>
    			<PARAM NAME="Counter00001.Show" VALUE="1">
    			</PARAM>
    			<PARAM NAME="Counter00001.Selected" VALUE="1">
    			</PARAM>
    			<PARAM NAME="Counter00002.Path" VALUE="\Memory\Pages/sec">
    			</PARAM>
    			<PARAM NAME="Counter00002.Color" VALUE="65280">
    			</PARAM>
    			<PARAM NAME="Counter00002.Width" VALUE="1">
    			</PARAM>
    			<PARAM NAME="Counter00003.Path" VALUE="\PhysicalDisk(_Total)\Avg. Disk sec/Read">
    			</PARAM>
    			<PARAM NAME="Counter00003.Color" VALUE="16711680">
    			</PARAM>
    			<PARAM NAME="Counter00003.Width" VALUE="1">
    			</PARAM>
    			<PARAM NAME="Counter00004.Path" VALUE="\PhysicalDisk(_Total)\Avg. Disk sec/Write">
    			</PARAM>
    			<PARAM NAME="Counter00004.Color" VALUE="55295">
    			</PARAM>
    			<PARAM NAME="Counter00004.Width" VALUE="1">
    			</PARAM>
    		</OBJECT>
    	</Value>
    </DataCollectorSet>
    

    public by cghersi modified Apr 11, 2014  327571  0  6  1

    Retrieve useful information regarding indexes in MS SQL Server

    This script helps the DBA to retrieve valuable information regarding indexes. Here the complete explanation of the output fields: object_type: type of object (will either be "U" for User-Defined Table or "V" for View) database_name: name of the database schema_name: name of the schema object_name: name of the object create_date: date the obje
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
    SET NOCOUNT ON
    SET ANSI_WARNINGS OFF
    SET ARITHABORT OFF
    SET ARITHIGNORE ON
    SET TEXTSIZE 2147483647
    
    
    -----------------------------------------------------------------------------------------------------------------------------
    --	Declarations / Sets: Declare And Set Variables
    -----------------------------------------------------------------------------------------------------------------------------
    
    DECLARE @Database_ID AS SMALLINT
    
    
    SET @Database_ID = DB_ID ()
    
    
    -----------------------------------------------------------------------------------------------------------------------------
    --	Error Trapping: Check If Temp Table(s) Already Exist(s) And Drop If Applicable
    -----------------------------------------------------------------------------------------------------------------------------
    
    IF OBJECT_ID (N'tempdb.dbo.#temp_index_breakdown_keys_filters', N'U') IS NOT NULL
    BEGIN
    
    	DROP TABLE dbo.#temp_index_breakdown_keys_filters
    
    END
    
    
    IF OBJECT_ID (N'tempdb.dbo.#temp_index_breakdown_size_info', N'U') IS NOT NULL
    BEGIN
    
    	DROP TABLE dbo.#temp_index_breakdown_size_info
    
    END
    
    
    -----------------------------------------------------------------------------------------------------------------------------
    --	Table Insert: Insert Index Key, Include Key, And Filter Definition Values Into Temp Table
    -----------------------------------------------------------------------------------------------------------------------------
    
    SELECT
    	 sqI.[object_id]
    	,sqI.index_id
    	,STUFF (CONVERT (NVARCHAR (MAX), sqI.index_key), 1, 2, N'') AS index_key
    	,STUFF (CONVERT (NVARCHAR (MAX), sqI.include_key), 1, 2, N'') AS include_key
    	,sqI.filter_definition
    	,RANK () OVER
    				(
    					ORDER BY
    						 sqI.[object_id]
    						,CONVERT (NVARCHAR (MAX), sqI.index_key)
    						,sqI.filter_definition
    				) AS dupe_rank
    INTO
    	dbo.#temp_index_breakdown_keys_filters
    FROM
    
    	(
    		SELECT
    			 I.[object_id]
    			,I.index_id
    			,(
    				SELECT
    					  N', '
    					+ C.name
    					+ N' • '
    					+ TYPE_NAME (C.user_type_id)
    					+ ISNULL ((N': [ ' + (CASE
    											WHEN C.system_type_id <> C.user_type_id THEN LOWER (TYPE_NAME (C.system_type_id))
    											END) + N' ]'), N'')
    					+ N' '
    					+ (CASE
    							WHEN TY.name NOT IN (N'bigint', N'bit', N'date', N'datetime', N'datetime2', N'datetimeoffset', N'decimal', N'float', N'int', N'money', N'numeric', N'real', N'smalldatetime', N'smallint', N'smallmoney', N'time', N'tinyint') THEN CONVERT (NVARCHAR (30), C.max_length)
    							ELSE CONVERT (NVARCHAR (30), C.max_length) + N' (' + CONVERT (NVARCHAR (30), COLUMNPROPERTY (C.[object_id], C.name, 'Precision')) + N',' + ISNULL (CONVERT (NVARCHAR (30), COLUMNPROPERTY (C.[object_id], C.name, 'Scale')), 0) + N')'
    							END)
    					+ N' '
    					+ (CASE
    							WHEN IC.is_descending_key = 0 THEN N'[A]'
    							WHEN IC.is_descending_key = 1 THEN N'[D]'
    							ELSE N'[N/A]'
    							END) AS [text()]
    				FROM
    					sys.index_columns IC
    					INNER JOIN sys.columns C ON C.[object_id] = IC.[object_id]
    						AND C.column_id = IC.column_id
    					INNER JOIN sys.types TY ON TY.user_type_id = C.user_type_id
    				WHERE
    					IC.is_included_column = 0
    					AND IC.[object_id] = I.[object_id]
    					AND IC.index_id = I.index_id
    				ORDER BY
    					IC.key_ordinal
    				FOR
    					 XML PATH ('')
    					,TYPE
    			 ) AS index_key
    			,(
    				SELECT
    					  N', '
    					+ C.name
    					+ N' • '
    					+ TYPE_NAME (C.user_type_id)
    					+ ISNULL ((N': [ ' + (CASE
    											WHEN C.system_type_id <> C.user_type_id THEN LOWER (TYPE_NAME (C.system_type_id))
    											END) + N' ]'), N'')
    					+ N' '
    					+ (CASE
    							WHEN TY.name NOT IN (N'bigint', N'bit', N'date', N'datetime', N'datetime2', N'datetimeoffset', N'decimal', N'float', N'int', N'money', N'numeric', N'real', N'smalldatetime', N'smallint', N'smallmoney', N'time', N'tinyint') THEN CONVERT (NVARCHAR (30), C.max_length)
    							ELSE CONVERT (NVARCHAR (30), C.max_length) + N' (' + CONVERT (NVARCHAR (30), COLUMNPROPERTY (C.[object_id], C.name, 'Precision')) + N',' + ISNULL (CONVERT (NVARCHAR (30), COLUMNPROPERTY (C.[object_id], C.name, 'Scale')), 0) + N')'
    							END) AS [text()]
    				FROM
    					sys.index_columns IC
    					INNER JOIN sys.columns C ON C.[object_id] = IC.[object_id]
    						AND C.column_id = IC.column_id
    					INNER JOIN sys.types TY ON TY.user_type_id = C.user_type_id
    				WHERE
    					IC.is_included_column = 1
    					AND IC.[object_id] = I.[object_id]
    					AND IC.index_id = I.index_id
    				ORDER BY
    					IC.key_ordinal
    				FOR
    					 XML PATH ('')
    					,TYPE
    			 ) AS include_key
    			,I.filter_definition
    		FROM
    			sys.indexes I
    	) sqI
    
    
    -----------------------------------------------------------------------------------------------------------------------------
    --	Table Insert: Insert Size Values Into Temp Table
    -----------------------------------------------------------------------------------------------------------------------------
    
    SELECT
    	 DDPS.[object_id]
    	,DDPS.index_id
    	,SUM (CASE
    			WHEN DDPS.index_id < 2 THEN DDPS.row_count
    			END) AS [rows]
    	,SUM (DDPS.reserved_page_count) AS total_pages
    	,SUM (DDPS.used_page_count) AS used_pages
    	,SUM (CASE
    			WHEN DDPS.index_id < 2 THEN DDPS.in_row_data_page_count + DDPS.lob_used_page_count + DDPS.row_overflow_used_page_count
    			ELSE DDPS.lob_used_page_count + DDPS.row_overflow_used_page_count
    			END) AS data_pages
    INTO
    	dbo.#temp_index_breakdown_size_info
    FROM
    	sys.dm_db_partition_stats DDPS
    GROUP BY
    	 DDPS.[object_id]
    	,DDPS.index_id
    
    
    -----------------------------------------------------------------------------------------------------------------------------
    --	Main Query: Final Display / Output
    -----------------------------------------------------------------------------------------------------------------------------
    
    SELECT
    	 (CASE
    		WHEN sqBAQ.row_filter = 1 THEN sqBAQ.[type]
    		ELSE ''
    		END) AS object_type
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN DB_NAME ()
    		ELSE ''
    		END) AS [database_name]
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN SCHEMA_NAME (sqBAQ.[schema_id])
    		ELSE ''
    		END) AS [schema_name]
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN OBJECT_NAME (sqBAQ.[object_id])
    		ELSE ''
    		END) AS [object_name]
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN sqBAQ.create_date
    		ELSE ''
    		END) AS create_date
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN caMDKL.modify_date
    		ELSE ''
    		END) AS modify_date
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN REVERSE (SUBSTRING (REVERSE (CONVERT (VARCHAR (25), CONVERT (MONEY, sqBAQ.[rows]), 1)), 4, 22))
    		ELSE ''
    		END) AS [rows]
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN CONVERT (VARCHAR (25), CONVERT (MONEY, (sqBAQ.total_pages * 8) / 1024.0), 1)
    		ELSE ''
    		END) AS total_mb
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN CONVERT (VARCHAR (25), CONVERT (MONEY, (sqBAQ.used_pages * 8) / 1024.0), 1)
    		ELSE ''
    		END) AS used_mb
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN CONVERT (VARCHAR (25), CONVERT (MONEY, (sqBAQ.unused_pages * 8) / 1024.0), 1)
    		ELSE ''
    		END) AS unused_mb
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN CONVERT (VARCHAR (25), CONVERT (MONEY, (sqBAQ.data_pages * 8) / 1024.0), 1)
    		ELSE ''
    		END) AS data_mb
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN CONVERT (VARCHAR (25), CONVERT (MONEY, (sqBAQ.index_pages * 8) / 1024.0), 1)
    		ELSE ''
    		END) AS index_mb
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN CONVERT (VARCHAR (6), CONVERT (DECIMAL (5, 2), ISNULL (((sqBAQ.data_pages + .0) / sqBAQ.used_pages) * 100, 0)))
    		ELSE ''
    		END) AS pct_data
    	,(CASE
    		WHEN sqBAQ.row_filter = 1 THEN CONVERT (VARCHAR (6), CONVERT (DECIMAL (5, 2), ISNULL (((sqBAQ.index_pages + .0) / sqBAQ.used_pages) * 100, 0)))
    		ELSE ''
    		END) AS pct_index
    	,sqBAQ.type_desc AS index_type
    	,ISNULL (sqBAQ.index_name, '') AS index_name
    	,(CASE
    		WHEN sqBAQ.type_desc = N'HEAP' THEN ''
    		WHEN sqBAQ.is_primary_key = 0 AND sqBAQ.is_unique = 0 THEN REPLICATE ('.', 6)
    		WHEN sqBAQ.is_system_named = 0 THEN 'No'
    		WHEN sqBAQ.is_system_named = 1 THEN 'Yes'
    		ELSE ''
    		END) AS system_named
    	,(CASE
    		WHEN sqBAQ.is_primary_key = 1 THEN 'Yes'
    		ELSE ''
    		END) AS is_pk
    	,(CASE
    		WHEN sqBAQ.is_unique_constraint = 1 THEN 'C'
    		WHEN sqBAQ.is_unique = 1 THEN 'I'
    		ELSE ''
    		END) AS [unique]
    	,(CASE
    		WHEN sqBAQ.is_disabled = 1 THEN 'Yes'
    		ELSE ''
    		END) AS [disabled]
    	,(CASE
    		WHEN sqBAQ.is_hypothetical = 1 THEN 'Yes'
    		ELSE ''
    		END) AS hypothetical
    	,REVERSE (SUBSTRING (REVERSE (CONVERT (VARCHAR (23), CONVERT (MONEY, sqCC.total_columns), 1)), 4, 23)) AS total_columns
    	,(CASE
    		WHEN sqBAQ.type_desc = N'HEAP' THEN ''
    		ELSE REVERSE (SUBSTRING (REVERSE (CONVERT (VARCHAR (23), CONVERT (MONEY, caMDKL.[index_columns]), 1)), 4, 23))
    		END) AS [index_columns]
    	,(CASE
    		WHEN sqBAQ.type_desc = N'HEAP' THEN ''
    		ELSE REVERSE (SUBSTRING (REVERSE (CONVERT (VARCHAR (23), CONVERT (MONEY, caMDKL.include_columns), 1)), 4, 23))
    		END) AS include_columns
    	,(CASE
    		WHEN sqBAQ.type_desc = N'HEAP' THEN ''
    		ELSE REVERSE (SUBSTRING (REVERSE (CONVERT (VARCHAR (23), CONVERT (MONEY, (caMDKL.[index_columns] / sqCC.total_columns) * 100), 1)), 1, 23))
    		END) AS index_pct_of_columns
    	,(CASE
    		WHEN sqBAQ.type_desc = N'HEAP' THEN ''
    		ELSE REVERSE (SUBSTRING (REVERSE (CONVERT (VARCHAR (23), CONVERT (MONEY, (caMDKL.include_columns / sqCC.total_columns) * 100), 1)), 1, 23))
    		END) AS include_pct_of_columns
    	,(CASE
    		WHEN sqBAQ.type_desc = N'HEAP' THEN ''
    		ELSE REVERSE (SUBSTRING (REVERSE (CONVERT (VARCHAR (23), CONVERT (MONEY, ((caMDKL.[index_columns] + caMDKL.include_columns) / sqCC.total_columns) * 100), 1)), 1, 23))
    		END) AS total_pct_of_columns
    	,CONVERT (VARCHAR (25), CONVERT (MONEY, (ISNULL (sqBAQ.individual_index_pages, 0) * 8) / 1024.0), 1) AS key_mb
    	,CONVERT (VARCHAR (6), CONVERT (DECIMAL (5, 2), ISNULL (((sqBAQ.individual_index_pages + .0) / sqBAQ.index_pages) * 100, 0))) AS key_mb_pct
    	,(CASE
    		WHEN sqBAQ.type_desc = N'HEAP' THEN ''
    		ELSE REVERSE (SUBSTRING (REVERSE (CONVERT (VARCHAR (25), CONVERT (MONEY, sqKL.total_max_length), 1)), 4, 22))
    		END) AS max_key_size_bytes
    	,(CASE
    		WHEN sqKL.total_max_length > 900 THEN 'Yes'
    		ELSE ''
    		END) AS over_key_size_limit
    	,ISNULL (ttIBKF.index_key, N'') AS index_key
    	,ISNULL (ttIBKF.include_key, N'') AS include_key
    	,ISNULL (ttIBKF.filter_definition, N'') AS filter_definition
    	,(CASE
    		WHEN sqED02.dupe_id IS NOT NULL THEN CONVERT (VARCHAR (20), sqED02.dupe_id) + ' - [' + CONVERT (VARCHAR (11), sqED02.total_dupes) + ']'
    		ELSE ''
    		END) AS dupe_id
    	,sqBAQ.is_unused AS unused
    	,ISNULL (CONVERT (VARCHAR (10), STATS_DATE (sqBAQ.[object_id], sqBAQ.index_id), 23), '') AS statistics_date
    	,(CASE
    		WHEN sqBAQ.[allow_row_locks] = 0 THEN 'No'
    		WHEN sqBAQ.[allow_row_locks] = 1 THEN 'Yes'
    		ELSE ''
    		END) AS row_locks
    	,(CASE
    		WHEN sqBAQ.[allow_page_locks] = 0 THEN 'No'
    		WHEN sqBAQ.[allow_page_locks] = 1 THEN 'Yes'
    		ELSE ''
    		END) AS page_locks
    	,(CASE
    		WHEN sqBAQ.[ignore_dup_key] = 0 THEN 'No'
    		WHEN sqBAQ.[ignore_dup_key] = 1 THEN 'Yes'
    		ELSE ''
    		END) AS ignore_dupes
    	,(CASE
    		WHEN sqBAQ.no_recompute = 0 THEN 'Yes'
    		WHEN sqBAQ.no_recompute = 1 THEN 'No'
    		ELSE ''
    		END) AS auto_stats
    	,(CASE
    		WHEN sqBAQ.is_padded = 0 THEN 'No'
    		WHEN sqBAQ.is_padded = 1 THEN 'Yes'
    		ELSE ''
    		END) AS padded
    	,(CASE
    		WHEN sqBAQ.fill_factor = 0 THEN 100
    		ELSE sqBAQ.fill_factor
    		END) AS fill_factor
    	,(CASE
    		WHEN sqBAQ.user_seeks > 0 THEN CONVERT (VARCHAR (20), sqBAQ.user_seeks)
    		ELSE ''
    		END) AS user_seeks
    	,(CASE
    		WHEN sqBAQ.user_scans > 0 THEN CONVERT (VARCHAR (20), sqBAQ.user_scans)
    		ELSE ''
    		END) AS user_scans
    	,(CASE
    		WHEN sqBAQ.user_lookups > 0 THEN CONVERT (VARCHAR (20), sqBAQ.user_lookups)
    		ELSE ''
    		END) AS user_lookups
    	,(CASE
    		WHEN sqBAQ.user_updates > 0 THEN CONVERT (VARCHAR (20), sqBAQ.user_updates)
    		ELSE ''
    		END) AS user_updates
    	,ISNULL (CONVERT (VARCHAR (10), sqBAQ.last_user_seek, 23), '') AS last_user_seek
    	,ISNULL (CONVERT (VARCHAR (10), sqBAQ.last_user_scan, 23), '') AS last_user_scan
    	,ISNULL (CONVERT (VARCHAR (10), sqBAQ.last_user_lookup, 23), '') AS last_user_lookup
    	,ISNULL (CONVERT (VARCHAR (10), sqBAQ.last_user_update, 23), '') AS last_user_update
    	,(CASE
    		WHEN sqBAQ.system_seeks > 0 THEN CONVERT (VARCHAR (20), sqBAQ.system_seeks)
    		ELSE ''
    		END) AS system_seeks
    	,(CASE
    		WHEN sqBAQ.system_scans > 0 THEN CONVERT (VARCHAR (20), sqBAQ.system_scans)
    		ELSE ''
    		END) AS system_scans
    	,(CASE
    		WHEN sqBAQ.system_lookups > 0 THEN CONVERT (VARCHAR (20), sqBAQ.system_lookups)
    		ELSE ''
    		END) AS system_lookups
    	,(CASE
    		WHEN sqBAQ.system_updates > 0 THEN CONVERT (VARCHAR (20), sqBAQ.system_updates)
    		ELSE ''
    		END) AS system_updates
    	,ISNULL (CONVERT (VARCHAR (10), sqBAQ.last_system_seek, 23), '') AS last_system_seek
    	,ISNULL (CONVERT (VARCHAR (10), sqBAQ.last_system_scan, 23), '') AS last_system_scan
    	,ISNULL (CONVERT (VARCHAR (10), sqBAQ.last_system_lookup, 23), '') AS last_system_lookup
    	,ISNULL (CONVERT (VARCHAR (10), sqBAQ.last_system_update, 23), '') AS last_system_update
    FROM
    
    	(
    		SELECT
    			 O.[type]
    			,O.[schema_id]
    			,O.[object_id]
    			,CONVERT (VARCHAR (10), O.create_date, 23) AS create_date
    			,CONVERT (VARCHAR (10), O.modify_date, 23) AS modify_date
    			,sqDDPS.[rows]
    			,sqDDPS.total_pages
    			,sqDDPS.used_pages
    			,(CASE
    				WHEN sqDDPS.total_pages > sqDDPS.used_pages THEN sqDDPS.total_pages - sqDDPS.used_pages
    				ELSE 0
    				END) AS unused_pages
    			,sqDDPS.data_pages
    			,(CASE
    				WHEN sqDDPS.used_pages > sqDDPS.data_pages THEN sqDDPS.used_pages - sqDDPS.data_pages
    				ELSE 0
    				END) AS index_pages
    			,sqI.type_desc
    			,sqI.name AS index_name
    			,sqI.is_system_named
    			,sqI.is_primary_key
    			,sqI.is_unique
    			,sqI.is_disabled
    			,sqI.is_hypothetical
    			,sqI.individual_index_pages
    			,sqI.is_unused
    			,sqI.[allow_row_locks]
    			,sqI.[allow_page_locks]
    			,sqI.[ignore_dup_key]
    			,sqI.no_recompute
    			,sqI.is_padded
    			,sqI.fill_factor
    			,sqI.user_seeks
    			,sqI.user_scans
    			,sqI.user_lookups
    			,sqI.user_updates
    			,sqI.last_user_seek
    			,sqI.last_user_scan
    			,sqI.last_user_lookup
    			,sqI.last_user_update
    			,sqI.system_seeks
    			,sqI.system_scans
    			,sqI.system_lookups
    			,sqI.system_updates
    			,sqI.last_system_seek
    			,sqI.last_system_scan
    			,sqI.last_system_lookup
    			,sqI.last_system_update
    			,sqI.is_unique_constraint
    			,sqI.index_id
    			,sqI.row_filter
    		FROM
    			sys.objects O
    			INNER JOIN
    
    				(
    					SELECT
    						 ttIBSI.[object_id]
    						,SUM (ttIBSI.[rows]) AS [rows]
    						,SUM (ttIBSI.total_pages) AS total_pages
    						,SUM (ttIBSI.used_pages) AS used_pages
    						,SUM (ttIBSI.data_pages) AS data_pages
    					FROM
    						dbo.#temp_index_breakdown_size_info ttIBSI
    					GROUP BY
    						ttIBSI.[object_id]
    				) sqDDPS ON sqDDPS.[object_id] = O.[object_id]
    
    			INNER JOIN
    
    				(
    					SELECT
    						 I.[object_id]
    						,I.type_desc
    						,I.name
    						,KC.is_system_named
    						,I.is_primary_key
    						,I.is_unique
    						,I.is_disabled
    						,I.is_hypothetical
    						,(CASE
    							WHEN ttIBSI.used_pages > ttIBSI.data_pages THEN ttIBSI.used_pages - ttIBSI.data_pages
    							END) AS individual_index_pages
    						,(CASE
    							WHEN I.[type] = 0 THEN ''
    							WHEN I.[type] = 1 THEN REPLICATE ('.', 6)
    							WHEN I.is_primary_key = 1 THEN REPLICATE ('.', 6)
    							WHEN I.is_unique = 1 THEN REPLICATE ('.', 6)
    							WHEN EXISTS
    
    								(
    									SELECT
    										*
    									FROM
    										sys.index_columns IC
    										INNER JOIN sys.foreign_key_columns FKC ON FKC.parent_object_id = IC.[object_id]
    											AND FKC.parent_column_id = IC.column_id
    									WHERE
    										IC.[object_id] = I.[object_id]
    										AND IC.index_id = I.index_id
    								) THEN REPLICATE ('.', 6)
    
    							WHEN DDIUS.[object_id] IS NOT NULL THEN (CASE
    																		WHEN DDIUS.user_seeks + DDIUS.user_scans + DDIUS.user_lookups + DDIUS.user_updates = 0 THEN 'Y/N'
    																		ELSE 'No'
    																		END)
    							ELSE 'Yes'
    							END) AS is_unused
    						,I.[allow_row_locks]
    						,I.[allow_page_locks]
    						,I.[ignore_dup_key]
    						,S.no_recompute
    						,I.is_padded
    						,I.fill_factor
    						,DDIUS.user_seeks
    						,DDIUS.user_scans
    						,DDIUS.user_lookups
    						,DDIUS.user_updates
    						,DDIUS.last_user_seek
    						,DDIUS.last_user_scan
    						,DDIUS.last_user_lookup
    						,DDIUS.last_user_update
    						,DDIUS.system_seeks
    						,DDIUS.system_scans
    						,DDIUS.system_lookups
    						,DDIUS.system_updates
    						,DDIUS.last_system_seek
    						,DDIUS.last_system_scan
    						,DDIUS.last_system_lookup
    						,DDIUS.last_system_update
    						,I.is_unique_constraint
    						,I.index_id
    						,ROW_NUMBER () OVER
    											(
    												PARTITION BY
    													I.[object_id]
    												ORDER BY
    													 I.is_primary_key DESC
    													,(CASE
    														WHEN I.[type] = 0 THEN 'Z'
    														ELSE 'A'
    														END)
    													,I.[type]
    													,I.name
    											) AS row_filter
    					FROM
    						sys.indexes I
    						INNER JOIN dbo.#temp_index_breakdown_size_info ttIBSI ON ttIBSI.[object_id] = I.[object_id]
    							AND ttIBSI.index_id = I.index_id
    						LEFT JOIN sys.key_constraints KC ON KC.parent_object_id = I.[object_id]
    							AND KC.unique_index_id = I.index_id
    						LEFT JOIN sys.stats S ON S.[object_id] = I.[object_id]
    							AND S.stats_id = I.index_id
    						LEFT JOIN master.sys.dm_db_index_usage_stats DDIUS ON DDIUS.[object_id] = I.[object_id]
    							AND DDIUS.index_id = I.index_id
    							AND DDIUS.database_id = @Database_ID
    				) sqI ON sqI.[object_id] = O.[object_id]
    
    		WHERE
    			O.[type] IN ('U', 'V')
    			AND O.is_ms_shipped = 0
    			AND NOT
    
    				(
    					SCHEMA_NAME (O.[schema_id]) = N'dbo'
    					AND O.name = N'sysdiagrams'
    					AND O.[type] = 'U'
    				)
    
    	) sqBAQ
    
    	INNER JOIN
    
    		(
    			SELECT
    				 C.[object_id]
    				,COUNT (*) + .0 AS total_columns
    			FROM
    				sys.columns C
    			GROUP BY
    				C.[object_id]
    		) sqCC ON sqCC.[object_id] = sqBAQ.[object_id]
    
    	LEFT JOIN dbo.#temp_index_breakdown_keys_filters ttIBKF ON ttIBKF.[object_id] = sqBAQ.[object_id]
    		AND ttIBKF.index_id = sqBAQ.index_id
    	LEFT JOIN
    
    		(
    			SELECT
    				 IC.[object_id]
    				,IC.index_id
    				,SUM (C.max_length) AS total_max_length
    			FROM
    				sys.index_columns IC
    				INNER JOIN sys.columns C ON C.[object_id] = IC.[object_id]
    					AND C.column_id = IC.column_id
    			WHERE
    				IC.is_included_column = 0
    			GROUP BY
    				 IC.[object_id]
    				,IC.index_id
    		) sqKL ON sqKL.[object_id] = sqBAQ.[object_id] AND sqKL.index_id = sqBAQ.index_id
    
    	LEFT JOIN
    
    		(
    			SELECT
    				 sqED01.dupe_rank
    				,sqED01.total_dupes
    				,ROW_NUMBER () OVER
    									(
    										ORDER BY
    											(SELECT NULL)
    									) AS dupe_id
    			FROM
    
    				(
    					SELECT
    						 ttIBKF.dupe_rank
    						,COUNT (*) AS total_dupes
    					FROM
    						dbo.#temp_index_breakdown_keys_filters ttIBKF
    					GROUP BY
    						ttIBKF.dupe_rank
    					HAVING
    						COUNT (*) > 1
    				) sqED01
    
    		) sqED02 ON sqED02.dupe_rank = ttIBKF.dupe_rank
    
    	CROSS APPLY
    
    		(
    			SELECT
    				 (CASE
    					WHEN sqBAQ.modify_date = sqBAQ.create_date THEN REPLICATE ('.', 18)
    					ELSE sqBAQ.modify_date
    					END) AS modify_date
    				,LEN (ttIBKF.index_key) - LEN (REPLACE (ttIBKF.index_key, '•', '')) AS [index_columns]
    				,ISNULL (LEN (ttIBKF.include_key) - LEN (REPLACE (ttIBKF.include_key, '•', '')), 0) AS include_columns
    		) caMDKL
    
    ORDER BY
    	 sqBAQ.[type]
    	,SCHEMA_NAME (sqBAQ.[schema_id])
    	,OBJECT_NAME (sqBAQ.[object_id])
    	,sqBAQ.row_filter
    
    
    -----------------------------------------------------------------------------------------------------------------------------
    --	Cleanup: Drop Any Remaining Temp Tables
    -----------------------------------------------------------------------------------------------------------------------------
    
    IF OBJECT_ID (N'tempdb.dbo.#temp_index_breakdown_keys_filters', N'U') IS NOT NULL
    BEGIN
    
    	DROP TABLE dbo.#temp_index_breakdown_keys_filters
    
    END
    
    
    IF OBJECT_ID (N'tempdb.dbo.#temp_index_breakdown_size_info', N'U') IS NOT NULL
    BEGIN
    
    	DROP TABLE dbo.#temp_index_breakdown_size_info
    
    END

    public by mirage3d modified Mar 16, 2016  289560  7  4  0

    Get localised country list from Cocoa in Swift

    import Cocoa
    
    let currentLocale = NSLocale.currentLocale()
    let countryCodes = NSLocale.ISOCountryCodes()
    let countryNames = countryCodes.map { currentLocale.displayNameForKey(NSLocaleCountryCode, value: $0) }
    	.filter { $0 != nil }
    	.sort(<)

    public by Fabax modified Feb 6, 2013  181095  0  4  0

    Char count

    Char count: charCount.js
     * 	Character Count Plugin - jQuery plugin
     * 	Dynamic character count for text areas and input fields
     *	written by Alen Grakalic	
     *	http://cssglobe.com/post/7161/jquery-plugin-simplest-twitterlike-dynamic-character-count-for-textareas
     *
     *	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
     *	Dual licensed under the MIT (MIT-LICENSE.txt)
     *	and GPL (GPL-LICENSE.txt) licenses.
     *
     *	Built for jQuery library
     *	http://jquery.com
     *
     */
     
    (function($) {
    
    	$.fn.charCount = function(options){
    	  
    		// default configuration properties
    		var defaults = {	
    			allowed: 140,		
    			warning: 25,
    			css: 'counter',
    			counterElement: 'span',
    			cssWarning: 'warning',
    			cssExceeded: 'exceeded',
    			counterText: ''
    		}; 
    			
    		var options = $.extend(defaults, options); 
    		
    		function calculate(obj){
    			var count = $(obj).val().length;
    			var available = options.allowed - count;
    			if(available <= options.warning && available >= 0){
    				$(obj).next().addClass(options.cssWarning);
    			} else {
    				$(obj).next().removeClass(options.cssWarning);
    			}
    			if(available < 0){
    				$(obj).next().addClass(options.cssExceeded);
    			} else {
    				$(obj).next().removeClass(options.cssExceeded);
    			}
    			$(obj).next().html(options.counterText + available);
    		};
    				
    		this.each(function() {  			
    			$(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');
    			calculate(this);
    			$(this).keyup(function(){calculate(this)});
    			$(this).change(function(){calculate(this)});
    		});
    	  
    	};
    
    })(jQuery);
    
    
    

    public by fabio.nosenzo modified Feb 9, 2016  2392  3  6  -1

    Count unique values excel formula

    General formula to calculate unique values with MS Excel
    //replace the values "*****" with your data range
    
    SUM(IF(FREQUENCY(IF(LEN(*****)>0,MATCH(*****,*****,0),""), IF(LEN(*****)>0,MATCH(*****,*****,0),""))>0,1))
    
    // remember to insert formula as an array formula with ctrl+shift+enter

    public by Peter Johnson a.k.a. insertcoffee modified Apr 29, 2015  78154  0  3  0

    Pelias category counts - OSM planet Apr 29 - 2015

    Pelias category counts - OSM planet Apr 29 - 2015: cat-counts.json
    {
      "took": 344,
      "timed_out": false,
      "_shards": {
        "total": 40,
        "successful": 40,
        "failed": 0
      },
      "hits": {
        "total": 165113284,
        "max_score": 0,
        "hits": [
          
        ]
      },
      "aggregations": {
        "popular": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "retail",
              "doc_count": 2035329
            },
            {
              "key": "food",
              "doc_count": 1052789
            },
            {
              "key": "education",
              "doc_count": 1012070
            },
            {
              "key": "transport",
              "doc_count": 999489
            },
            {
              "key": "recreation",
              "doc_count": 913755
            },
            {
              "key": "nightlife",
              "doc_count": 622372
            },
            {
              "key": "transport:public",
              "doc_count": 618726
            },
            {
              "key": "professional",
              "doc_count": 532643
            },
            {
              "key": "religion",
              "doc_count": 505962
            },
            {
              "key": "government",
              "doc_count": 439336
            },
            {
              "key": "entertainment",
              "doc_count": 438220
            },
            {
              "key": "health",
              "doc_count": 359072
            },
            {
              "key": "accomodation",
              "doc_count": 294060
            },
            {
              "key": "finance",
              "doc_count": 184095
            },
            {
              "key": "transport:rail",
              "doc_count": 121378
            },
            {
              "key": "transport:station",
              "doc_count": 93877
            },
            {
              "key": "transport:air",
              "doc_count": 69042
            },
            {
              "key": "food:regional",
              "doc_count": 41614
            },
            {
              "key": "transport:air:aerodrome",
              "doc_count": 41028
            },
            {
              "key": "food:pizza",
              "doc_count": 31708
            },
            {
              "key": "food:burger",
              "doc_count": 30856
            },
            {
              "key": "food:cuisine:italian",
              "doc_count": 25551
            },
            {
              "key": "transport:bus",
              "doc_count": 21524
            },
            {
              "key": "food:cuisine:chinese",
              "doc_count": 16937
            },
            {
              "key": "food:coffee_shop",
              "doc_count": 13232
            },
            {
              "key": "food:sandwich",
              "doc_count": 11735
            },
            {
              "key": "food:cuisine:german",
              "doc_count": 10021
            },
            {
              "key": "food:cuisine:japanese",
              "doc_count": 8048
            },
            {
              "key": "food:cuisine:mexican",
              "doc_count": 7967
            },
            {
              "key": "food:cuisine:indian",
              "doc_count": 7397
            },
            {
              "key": "food:kebab",
              "doc_count": 7280
            },
            {
              "key": "food:cuisine:american",
              "doc_count": 7203
            },
            {
              "key": "transport:taxi",
              "doc_count": 7138
            },
            {
              "key": "food:cuisine:french",
              "doc_count": 6603
            },
            {
              "key": "food:chicken",
              "doc_count": 6556
            },
            {
              "key": "food:cuisine:asian",
              "doc_count": 6527
            },
            {
              "key": "food:ice_cream",
              "doc_count": 6345
            },
            {
              "key": "food:cuisine:greek",
              "doc_count": 6028
            },
            {
              "key": "transport:sea",
              "doc_count": 5795
            },
            {
              "key": "food:cuisine:thai",
              "doc_count": 4291
            },
            {
              "key": "food:cuisine:international",
              "doc_count": 4203
            },
            {
              "key": "food:sushi",
              "doc_count": 4122
            },
            {
              "key": "food:fish_and_chips",
              "doc_count": 3505
            },
            {
              "key": "food:cuisine:turkish",
              "doc_count": 2660
            },
            {
              "key": "food:steak",
              "doc_count": 2343
            },
            {
              "key": "food:seafood",
              "doc_count": 2315
            },
            {
              "key": "food:cuisine:spanish",
              "doc_count": 2177
            },
            {
              "key": "food:fish",
              "doc_count": 1414
            },
            {
              "key": "food:cuisine:vietnamese",
              "doc_count": 1400
            },
            {
              "key": "food:noodle",
              "doc_count": 1236
            },
            {
              "key": "food:vegetarian",
              "doc_count": 1164
            },
            {
              "key": "food:cuisine:korean",
              "doc_count": 796
            },
            {
              "key": "food:barbecue",
              "doc_count": 746
            },
            {
              "key": "food:donut",
              "doc_count": 740
            },
            {
              "key": "food:friture",
              "doc_count": 740
            },
            {
              "key": "food:cuisine:bavarian",
              "doc_count": 736
            },
            {
              "key": "food:mediterranean",
              "doc_count": 673
            },
            {
              "key": "food:cake",
              "doc_count": 460
            },
            {
              "key": "food:crepe",
              "doc_count": 421
            },
            {
              "key": "food:cuisine:lebanese",
              "doc_count": 362
            },
            {
              "key": "food:curry",
              "doc_count": 314
            },
            {
              "key": "food:cuisine:russian",
              "doc_count": 287
            },
            {
              "key": "food:tapas",
              "doc_count": 272
            },
            {
              "key": "food:bagel",
              "doc_count": 233
            },
            {
              "key": "food:pasta",
              "doc_count": 225
            },
            {
              "key": "food:cuisine:portuguese",
              "doc_count": 218
            },
            {
              "key": "food:sausage",
              "doc_count": 204
            },
            {
              "key": "food:pancake",
              "doc_count": 203
            },
            {
              "key": "food:cuisine:polish",
              "doc_count": 191
            },
            {
              "key": "food:cuisine:african",
              "doc_count": 190
            },
            {
              "key": "food:cuisine:croatian",
              "doc_count": 171
            },
            {
              "key": "food:cuisine:arab",
              "doc_count": 167
            },
            {
              "key": "food:cuisine:malagasy",
              "doc_count": 158
            },
            {
              "key": "food:cuisine:balkan",
              "doc_count": 154
            },
            {
              "key": "food:vegan",
              "doc_count": 153
            },
            {
              "key": "food:cuisine:brazilian",
              "doc_count": 151
            },
            {
              "key": "food:cuisine:caribbean",
              "doc_count": 146
            },
            {
              "key": "food:cuisine:argentinian",
              "doc_count": 136
            },
            {
              "key": "food:cuisine:hungarian",
              "doc_count": 132
            },
            {
              "key": "food:savory_pancakes",
              "doc_count": 108
            },
            {
              "key": "food:cuisine:peruvian",
              "doc_count": 96
            },
            {
              "key": "food:couscous",
              "doc_count": 79
            },
            {
              "key": "food:pie",
              "doc_count": 78
            },
            {
              "key": "food:sub",
              "doc_count": 78
            },
            {
              "key": "food:cuisine:czech",
              "doc_count": 77
            },
            {
              "key": "food:fried_food",
              "doc_count": 69
            },
            {
              "key": "food:cuisine:basque",
              "doc_count": 66
            },
            {
              "key": "food:cuisine:latin_american",
              "doc_count": 54
            },
            {
              "key": "food:cuisine:danish",
              "doc_count": 48
            },
            {
              "key": "food:cuisine:cantonese",
              "doc_count": 44
            },
            {
              "key": "food:cuisine:australian",
              "doc_count": 38
            },
            {
              "key": "food:dessert",
              "doc_count": 37
            },
            {
              "key": "food:empanada",
              "doc_count": 31
            },
            {
              "key": "food:cuisine:pakistani",
              "doc_count": 30
            },
            {
              "key": "food:cuisine:iranian",
              "doc_count": 29
            },
            {
              "key": "food:cuisine:gaucho",
              "doc_count": 27
            },
            {
              "key": "food:wings",
              "doc_count": 27
            },
            {
              "key": "food:cuisine:sichuan",
              "doc_count": 10
            },
            {
              "key": "food:cuisine:mineira",
              "doc_count": 8
            },
            {
              "key": "food:gyro",
              "doc_count": 8
            },
            {
              "key": "food:bougatsa",
              "doc_count": 5
            },
            {
              "key": "food:cuisine:baiana",
              "doc_count": 5
            },
            {
              "key": "food:cuisine:okinawa_ryori",
              "doc_count": 4
            },
            {
              "key": "food:cuisine:capixaba",
              "doc_count": 3
            },
            {
              "key": "food:cuisine:belarusian",
              "doc_count": 2
            },
            {
              "key": "food:cuisine:hunan",
              "doc_count": 2
            },
            {
              "key": "food:cuisine:shandong",
              "doc_count": 2
            }
          ]
        }
      }
    }
    
    

    public by zonaro modified Nov 25, 2015  2636  1  7  0

    Count Rows of DataReader

    Simple function to count rows of a OleDbDataReader, returns positive integer or -1 if error
    public static int CountRows(this OleDbDataReader Reader)
           {
               int cnt = 0;try{ while (Reader.Read()) { cnt++; } return cnt; }catch (Exception) { return -1; }
           }
    

    public by marksimon232 modified Jun 23, 2014  6927  3  7  1

    Array reference guide for Swift

    Below are the different examples on Swift Arrays.
    //1.Creating an empty array
    var empty = [];
         
    //2.Create an initialized array
    var names=["Mark","Kelly","Susan"]
    var names2:String[] = ["Mark","Kelly","Susan"] //with explicit type convention
     
    var numbers = [1,2,4,5,6,7,8]
     
    //3.Get the count of an array
    println(numbers.count)
     
     
    //4. Iterate through each element in array
    //Method 1
    for (var i=0;i<numbers.count;i++)
    {
            println(numbers[i])
    }
     
    //Method 2
    for num in numbers
    {
            println(num)
    }
     
    //Method 3
    for (index,value)  in enumerate(numbers)
    {
            println("Index \(index): value  \(value)")
    }
     
     
     
    //5.Create sub array with index range
     var subnumbers = numbers[2..4] //4,5
        subnumbers = numbers[2...4] //4,5,6
     
         
    //6.To add an element
    numbers.append(10);
     
    //7.To insert at specific index
    numbers.insert(12,atIndex: 5)
     
    //8.Remove element at index
    var removed = numbers.removeAtIndex(0)
     
    //9.Remve last element
    var removed = numbers.removeLast()

    public by lauhin modified Mar 24, 2016  4893  3  6  0

    Count chars in a String in Java

    Count chars in Strings or letters in words in Java using the Spring framework
    import org.springframework.util.StringUtils;
    
    int occurance = StringUtils.countOccurrencesOf("012405802569015014", "0"); //returns 5
    int occurance = StringUtils.countOccurrencesOf("hello world", "l"); //returns 3

    public by te777 modified Sep 24, 2016  2995  3  5  0

    Hackerrank Count Strings solution python

    Hackerrank Count Strings solution python
    '''
    Created on Aug 7, 2016
    
    AutomataTheory.py
    
    @author: Siddharthasahu @ https://github.com/siddharthasahu/automata-from-regex
    
    Automata build from from regex to DFA taken from there. Count Strings (Matrix class) added
    '''
    # You can test with input " 1 ((((ab)|a)*)|(((aa)|(bb))*)) 368046388 "
    
    #The result of the code executed in main should be 198110437 with the test input
    
    #import fileinput
    #from os import popen
    #import time
    #import sys, traceback
    
    class Automata:
        """class to represent an Automata"""
    
        def __init__(self, language = set(['a', 'b'])):
            self.states = set()
            self.startstate = None
            self.finalstates = []
            self.transitions = dict()
            self.language = language
    
        @staticmethod
        def epsilon():
            return ":e:"
    
        def setstartstate(self, state):
            self.startstate = state
            self.states.add(state)
    
        def addfinalstates(self, state):
            if isinstance(state, int):
                state = [state]
            for s in state:
                if s not in self.finalstates:
                    self.finalstates.append(s)
    
        def addtransition(self, fromstate, tostate, inp):
            if isinstance(inp, str):
                inp = set([inp])
            self.states.add(fromstate)
            self.states.add(tostate)
            if fromstate in self.transitions:
                if tostate in self.transitions[fromstate]:
                    self.transitions[fromstate][tostate] = self.transitions[fromstate][tostate].union(inp)
                else:
                    self.transitions[fromstate][tostate] = inp
            else:
                self.transitions[fromstate] = {tostate : inp}
    
        def addtransition_dict(self, transitions):
            for fromstate, tostates in transitions.items():
                for state in tostates:
                    self.addtransition(fromstate, state, tostates[state])
    
        def gettransitions(self, state, key):
            if isinstance(state, int):
                state = [state]
            trstates = set()
            for st in state:
                if st in self.transitions:
                    for tns in self.transitions[st]:
                        if key in self.transitions[st][tns]:
                            trstates.add(tns)
            return trstates
    
        def getEClose(self, findstate):
            allstates = set()
            states = set([findstate])
            while len(states)!= 0:
                state = states.pop()
                allstates.add(state)
                if state in self.transitions:
                    for tns in self.transitions[state]:
                        if Automata.epsilon() in self.transitions[state][tns] and tns not in allstates:
                            states.add(tns)
            return allstates
    
        def display(self):
            print ("states:", self.states)
            print ("start state: ", self.startstate)
            print ("final states:", self.finalstates)
            print ("transitions:")
            for fromstate, tostates in self.transitions.items():
                for state in tostates:
                    for char in tostates[state]:
                        print ("  ",fromstate, "->", state, "on '"+char+"'",)
                print
    
        def getPrintText(self):
            text = "language: {" + ", ".join(self.language) + "}\n"
            text += "states: {" + ", ".join(map(str,self.states)) + "}\n"
            text += "start state: " + str(self.startstate) + "\n"
            text += "final states: {" + ", ".join(map(str,self.finalstates)) + "}\n"
            text += "transitions:\n"
            linecount = 5
            for fromstate, tostates in self.transitions.items():
                for state in tostates:
                    for char in tostates[state]:
                        text += "    " + str(fromstate) + " -> " + str(state) + " on '" + char + "'\n"
                        linecount +=1
            return [text, linecount]
    
        def newBuildFromNumber(self, startnum):
            translations = {}
            for i in list(self.states):
                translations[i] = startnum
                startnum += 1
            rebuild = Automata(self.language)
            rebuild.setstartstate(translations[self.startstate])
            rebuild.addfinalstates(translations[self.finalstates[0]])
            for fromstate, tostates in self.transitions.items():
                for state in tostates:
                    rebuild.addtransition(translations[fromstate], translations[state], tostates[state])
            return [rebuild, startnum]
    
        def newBuildFromEquivalentStates(self, equivalent, pos):
            # Added "sorted" next line
            rebuild = Automata(sorted(self.language))
            for fromstate, tostates in self.transitions.items():
                for state in tostates:
                    rebuild.addtransition(pos[fromstate], pos[state], tostates[state])
            rebuild.setstartstate(pos[self.startstate])
            for s in self.finalstates:
                rebuild.addfinalstates(pos[s])
            return rebuild
    
        def getDotFile(self):
            dotFile = "digraph DFA {\nrankdir=LR\n"
            if len(self.states) != 0:
                dotFile += "root=s1\nstart [shape=point]\nstart->s%d\n" % self.startstate
                for state in self.states:
                    if state in self.finalstates:
                        dotFile += "s%d [shape=doublecircle]\n" % state
                    else:
                        dotFile += "s%d [shape=circle]\n" % state
                for fromstate, tostates in self.transitions.items():
                    for state in tostates:
                        for char in tostates[state]:
                            dotFile += 's%d->s%d [label="%s"]\n' % (fromstate, state, char)
            dotFile += "}"
            return dotFile
    
    class BuildAutomata:
        """class for building e-nfa basic structures"""
    
        @staticmethod
        def basicstruct(inp):
            state1 = 1
            state2 = 2
            basic = Automata()
            basic.setstartstate(state1)
            basic.addfinalstates(state2)
            basic.addtransition(1, 2, inp)
            return basic
    
        @staticmethod
        def plusstruct(a, b):
            [a, m1] = a.newBuildFromNumber(2)
            [b, m2] = b.newBuildFromNumber(m1)
            state1 = 1
            state2 = m2
            plus = Automata()
            plus.setstartstate(state1)
            plus.addfinalstates(state2)
            plus.addtransition(plus.startstate, a.startstate, Automata.epsilon())
            plus.addtransition(plus.startstate, b.startstate, Automata.epsilon())
            plus.addtransition(a.finalstates[0], plus.finalstates[0], Automata.epsilon())
            plus.addtransition(b.finalstates[0], plus.finalstates[0], Automata.epsilon())
            plus.addtransition_dict(a.transitions)
            plus.addtransition_dict(b.transitions)
            return plus
    
        @staticmethod
        def dotstruct(a, b):
            [a, m1] = a.newBuildFromNumber(1)
            [b, m2] = b.newBuildFromNumber(m1)
            state1 = 1
            state2 = m2-1
            dot = Automata()
            dot.setstartstate(state1)
            dot.addfinalstates(state2)
            dot.addtransition(a.finalstates[0], b.startstate, Automata.epsilon())
            dot.addtransition_dict(a.transitions)
            dot.addtransition_dict(b.transitions)
            return dot
    
        @staticmethod
        def starstruct(a):
            [a, m1] = a.newBuildFromNumber(2)
            state1 = 1
            state2 = m1
            star = Automata()
            star.setstartstate(state1)
            star.addfinalstates(state2)
            star.addtransition(star.startstate, a.startstate, Automata.epsilon())
            star.addtransition(star.startstate, star.finalstates[0], Automata.epsilon())
            star.addtransition(a.finalstates[0], star.finalstates[0], Automata.epsilon())
            star.addtransition(a.finalstates[0], a.startstate, Automata.epsilon())
            star.addtransition_dict(a.transitions)
            return star
    
    
    class DFAfromNFA:
        """class for building dfa from e-nfa and minimise it"""
    
        def __init__(self, nfa):
            self.buildDFA(nfa)
            self.minimise()
    
        def getDFA(self):
            return self.dfa
        
        def getAllStates(self):
            return self.allstates
        
        def getTransitions(self):
            return self.trstates
    
        def getMinimisedDFA(self):
            return self.minDFA
    
        def displayDFA(self):
            self.dfa.display()
    
        def displayMinimisedDFA(self):
            self.minDFA.display()
    
        def buildDFA(self, nfa):
            allstates = dict()
            eclose = dict()
            count = 1
            state1 = nfa.getEClose(nfa.startstate)
            eclose[nfa.startstate] = state1
            dfa = Automata(nfa.language)
            dfa.setstartstate(count)
            states = [[state1, count]]
            allstates[count] = state1
            count +=  1
            while len(states) != 0:
                [state, fromindex] = states.pop()
                # Next line was originally "for char in dfa.language:"
                # But returned "char" in random order, since dfa.language is a set,
                # so dfa.finalstates result was not consistent
                for char in sorted(dfa.language):
                    trstates = nfa.gettransitions(state, char)
                    for s in list(trstates)[:]:
                        if s not in eclose:
                            eclose[s] = nfa.getEClose(s)
                        trstates = trstates.union(eclose[s])
                    if len(trstates) != 0:
                        if trstates not in allstates.values():
                            states.append([trstates, count])
                            allstates[count] = trstates
                            toindex = count
                            count +=  1
                        else:
                            toindex = [k for k, v in allstates.items() if v  ==  trstates][0]
                        dfa.addtransition(fromindex, toindex, char)
       
            for value, state in allstates.items():
                if nfa.finalstates[0] in state:
                    dfa.addfinalstates(value)
     
            self.dfa = dfa
            self.allstates = allstates
            self.trstates = trstates 
    
        def acceptsString(self, string):
            currentstate = self.dfa.startstate
            for ch in string:
                if ch==":e:":
                    continue
                st = list(self.dfa.gettransitions(currentstate, ch))
                if len(st) == 0:
                    return False
                currentstate = st[0]
            if currentstate in self.dfa.finalstates:
                return True
            return False
    
        def minimise(self):
            states = list(self.dfa.states)
            n = len(states)
            unchecked = dict()
            count = 1
            distinguished = []
            equivalent = dict(zip(range(len(states)), [{s} for s in states]))
            pos = dict(zip(states,range(len(states))))
            for i in range(n-1):
                for j in range(i+1, n):
                    if not ([states[i], states[j]] in distinguished or [states[j], states[i]] in distinguished):
                        eq = 1
                        toappend = []
                        # Added "sorted" next line
                        for char in sorted(self.dfa.language):
                            s1 = self.dfa.gettransitions(states[i], char)
                            s2 = self.dfa.gettransitions(states[j], char)
                            if len(s1) != len(s2):
                                eq = 0
                                break
                            if len(s1) > 1:
                                raise BaseException("Multiple transitions detected in DFA")
                            elif len(s1) == 0:
                                continue
                            s1 = s1.pop()
                            s2 = s2.pop()
                            if s1 != s2:
                                if [s1, s2] in distinguished or [s2, s1] in distinguished:
                                    eq = 0
                                    break
                                else:
                                    toappend.append([s1, s2, char])
                                    eq = -1
                        if eq == 0:
                            distinguished.append([states[i], states[j]])
                        elif eq == -1:
                            s = [states[i], states[j]]
                            s.extend(toappend)
                            unchecked[count] = s
                            count += 1
                        else:
                            p1 = pos[states[i]]
                            p2 = pos[states[j]]
                            if p1 != p2:
                                st = equivalent.pop(p2)
                                for s in st:
                                    pos[s] = p1
                                equivalent[p1] = equivalent[p1].union(st)
            newFound = True
            while newFound and len(unchecked) > 0:
                newFound = False
                toremove = set()
                for p, pair in list(unchecked.items()):  #.items():
                    for tr in pair[2:]:
                        if [tr[0], tr[1]] in distinguished or [tr[1], tr[0]] in distinguished:
                            unchecked.pop(p)
                            distinguished.append([pair[0], pair[1]])
                            newFound = True
                            break
            for pair in unchecked.values():
                p1 = pos[pair[0]]
                p2 = pos[pair[1]]
                if p1 != p2:
                    st = equivalent.pop(p2)
                    for s in st:
                        pos[s] = p1
                    equivalent[p1] = equivalent[p1].union(st)
            if len(equivalent) == len(states):
                self.minDFA = self.dfa
            else:
                self.minDFA = self.dfa.newBuildFromEquivalentStates(equivalent, pos)
    
    class NFAfromRegex:
        """class for building e-nfa from regular expressions"""
    
        def __init__(self, regex):
            self.star = '*'
            # Next line was originally "self.plus = '+'
            # Changed to '|' to fit aplication of regex for program
            self.plus = '|'
            self.dot = '.'
            self.openingBracket = '('
            self.closingBracket = ')'
            self.operators = [self.plus, self.dot]
            self.regex = regex
            self.alphabet = [chr(i) for i in range(65,91)]
            self.alphabet.extend([chr(i) for i in range(97,123)])
            self.alphabet.extend([chr(i) for i in range(48,58)])
            self.buildNFA()
    
        def getNFA(self):
            return self.nfa
    
        def displayNFA(self):
            self.nfa.display()
    
        def buildNFA(self):
            language = set()
            self.stack = []
            self.automata = []
            previous = "::e::"
            for char in self.regex:
                if char in self.alphabet:
                    language.add(char)
                    if previous != self.dot and (previous in self.alphabet or previous in [self.closingBracket,self.star]):
                        self.addOperatorToStack(self.dot)
                    self.automata.append(BuildAutomata.basicstruct(char))
                elif char  ==  self.openingBracket:
                    if previous != self.dot and (previous in self.alphabet or previous in [self.closingBracket,self.star]):
                        self.addOperatorToStack(self.dot)
                    self.stack.append(char)
                elif char  ==  self.closingBracket:
                    if previous in self.operators:
                        raise BaseException("Error processing '%s' after '%s'" % (char, previous))
                    while(1):
                        if len(self.stack) == 0:
                            raise BaseException("Error processing '%s'. Empty stack" % char)
                        o = self.stack.pop()
                        if o == self.openingBracket:
                            break
                        elif o in self.operators:
                            self.processOperator(o)
                elif char == self.star:
                    if previous in self.operators or previous  == self.openingBracket or previous == self.star:
                        raise BaseException("Error processing '%s' after '%s'" % (char, previous))
                    self.processOperator(char)
                elif char in self.operators:
                    if previous in self.operators or previous  == self.openingBracket:
                        raise BaseException("Error processing '%s' after '%s'" % (char, previous))
                    else:
                        self.addOperatorToStack(char)
                else:
                    raise BaseException("Symbol '%s' is not allowed" % char)
                previous = char
            while len(self.stack) != 0:
                op = self.stack.pop()
                self.processOperator(op)
            if len(self.automata) > 1:
                print (self.automata)
                raise BaseException("Regex could not be parsed successfully")
            self.nfa = self.automata.pop()
            self.nfa.language = language
    
        def addOperatorToStack(self, char):
            while(1):
                if len(self.stack) == 0:
                    break
                top = self.stack[len(self.stack)-1]
                if top == self.openingBracket:
                    break
                if top == char or top == self.dot:
                    op = self.stack.pop()
                    self.processOperator(op)
                else:
                    break
            self.stack.append(char)
    
        def processOperator(self, operator):
            if len(self.automata) == 0:
                raise BaseException("Error processing operator '%s'. Stack is empty" % operator)
            if operator == self.star:
                a = self.automata.pop()
                self.automata.append(BuildAutomata.starstruct(a))
            elif operator in self.operators:
                if len(self.automata) < 2:
                    raise BaseException("Error processing operator '%s'. Inadequate operands" % operator)
                a = self.automata.pop()
                b = self.automata.pop()
                if operator == self.plus:
                    self.automata.append(BuildAutomata.plusstruct(b,a))
                elif operator == self.dot:
                    self.automata.append(BuildAutomata.dotstruct(b,a))
    
    """def drawGraph(automata, file = ""):
        From https://github.com/max99x/automata-editor/blob/master/util.py
        f = popen(r"dot -Tpng -o graph%s.png" % file, 'w')
        try:
            f.write(automata.getDotFile())
        except:
            raise BaseException("Error creating graph")
        finally:
            f.close()"""
    
    def isInstalled(program):
        """From http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python"""
        import os
        def is_exe(fpath):
            return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
        fpath, fname = os.path.split(program)
        if fpath:
            if is_exe(program) or is_exe(program+".exe"):
                return True
        else:
            for path in os.environ["PATH"].split(os.pathsep):
                exe_file = os.path.join(path, program)
                if is_exe(exe_file) or is_exe(exe_file+".exe"):
                    return True
        return False
    
    class Matrix:
        
        def __init__(self, DFA, allstates, transitions, length):
            self.length = length
            self.DFA = DFA
            self.allstates = allstates
            dim = 0
     
            for value, _state in allstates.items():
                if value != 0:
                    dim += 1
            dim += 1
            self.dim = dim
            self.matrix= self.createMatrix( self.DFA, self.allstates, transitions, self.dim)
            
        def getDim(self):
            return self.dim
            
        def createMatrix(self, DFA, allstates, transitions, dim):
     
            matrix = [[0]*(dim) for _ in range(dim)]
            for from_state, to_state in transitions.items():
                for to_state, _char in to_state.items():
                    matrix[from_state-1][to_state-1] = 1 
           
            return matrix   
            
        def count_paths(self, DFA, dim, length):
            modulo = 1000000007
            result = Matrix.pow2(self, length, self.matrix, dim, modulo)
            count = 0
                  
            for i in range(dim):
                for j in range(dim):
                    if i == 0:
                        for k in DFA.finalstates:
                            k -= 1
                            if j == k:
                                count += result[i][j]
                                
            return count % modulo
    
        def copy(self, dim):
            my_matrix = [[0]*(dim) for _ in range(dim)]
            for i in range(dim):
                for j in range(dim):
                    my_matrix[i][j] = self.matrix[i][j]
                    
            return my_matrix
    
        def printMatrix(self, matrix, dim):
            for i in range(dim):
                print(matrix[i])
    
        def pow2(self, power, matrix, dim, mod=None):
            
            result1 = [[0]*(dim) for _ in range(dim)]
            for i in range(dim):
                result1[i][i] = 1
            while power > 0:
                if power & 1:
                    result1 = Matrix.mat_square_mult(self, result1, matrix, dim, mod);
                power >>= 1;
                if power > 0:
                    matrix = Matrix.mat_square_mult(self, matrix, matrix, dim, mod);
            matrix = result1 
                   
            return matrix
    
        def mat_square_mult(self, matrix, other, dim, mod=None):
            result = [[0]*(dim) for _ in range(dim)]
            for i in range(dim):
                for j in range(dim):
                    index = 0
                    for k in range(dim):
                        index += (matrix[i][k] * other[k][j]) % mod
    
                        result[i][j] = index
            return result
    
    def count_strings(regex, length):
    
        nfaObj = NFAfromRegex(regex)
        nfa = nfaObj.getNFA()
        dfaObj = DFAfromNFA(nfa)
        dfa = dfaObj.getDFA()
        #minDFA = dfaObj.getMinimisedDFA()
        #print ("\nNFA: ")
        #nfaObj.displayNFA()
        #print ("\nDFA: ")
        #dfaObj.displayDFA()
        #print ("\nMinimised DFA: ")
        #dfaObj.displayMinimisedDFA()
        #result = None
        transitions = dfa.transitions
        allstates = dfaObj.getAllStates()
        resultObj = Matrix(dfa, allstates, transitions, length) 
        dim = resultObj.getDim()
        result = Matrix.count_paths(resultObj, dfa, dim, length)
        
        #The result should be 198110437 for the test input
    
        
        print (result)
        
        
        
    def main():
        
        cases = int(input().strip())
        for _i in range(cases):
            in_line = input().strip().split()
            regex = in_line[0]
            length = int(in_line[1])
            count_strings(regex, length)
        
    if __name__  ==  '__main__':
        main()
    • Public Snippets
    • Channels Snippets