Programs & Examples On #Sql server 2005

Use this tag for questions specific to the 2005 version of Microsoft's SQL Server.

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

As you have to use WITH (NOLOCK) for each table it might be annoying to write it in every FROM or JOIN clause. However it has a reason why it is called a "dirty" read. So you really should know when you do one, and not set it as default for the session scope. Why?

Forgetting a WITH (NOLOCK) might not affect your program in a very dramatic way, however doing a dirty read where you do not want one can make the difference in certain circumstances.

So use WITH (NOLOCK) if the current data selected is allowed to be incorrect, as it might be rolled back later. This is mostly used when you want to increase performance, and the requirements on your application context allow it to take the risk that inconsistent data is being displayed. However you or someone in charge has to weigh up pros and cons of the decision of using WITH (NOLOCK).

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

Advantages of SQL Server 2008 over SQL Server 2005?

  • Transparent Data Encryption. The ability to encrypt an entire database.
  • Backup Encryption. Executed at backup time to prevent tampering.
  • External Key Management. Storing Keys separate from the data.
  • Auditing. Monitoring of data access.
  • Data Compression. Fact Table size reduction and improved performance.
  • Resource Governor. Restrict users or groups from consuming high levels or resources.
  • Hot Plug CPU. Add CPUs on the fly.
  • Performance Studio. Collection of performance monitoring tools.
  • Installation improvements. Disk images and service pack uninstall options.
  • Dynamic Development. New ADO and Visual Studio options as well as Dot Net 3.
  • Entity Data Services. Line Of Business (LOB) framework and Entity Query Language (eSQL)
  • LINQ. Development query language for access multiple types of data such as SQL and XML.
  • Data Synchronizing. Development of frequently disconnected applications.
  • Large UDT. No size restriction on UDT.
  • Dates and Times. New data types: Date, Time, Date Time Offset.
  • File Stream. New data type VarBinary(Max) FileStream for managing binary data.
  • Table Value Parameters. The ability to pass an entire table to a stored procedure.
  • Spatial Data. Data type for storing Latitude, Longitude, and GPS entries.
  • Full Text Search. Native Indexes, thesaurus as metadata, and backup ability.
  • SQL Server Integration Service. Improved multiprocessor support and faster lookups.
  • MERGE. TSQL command combining Insert, Update, and Delete.
  • SQL Server Analysis Server. Stack improvements, faster block computations.
  • SQL Server Reporting Server. Improved memory management and better rendering.
  • Microsoft Office 2007. Use OFFICE as an SSRS template. SSRS to WORD.
  • SQL 2000 Support Ends. Mainstream Support for SQL 2000 is coming to an end.

(Good intro article part 1, part 2, part 3. As for compelling reasons, that depends on what you are using SQL server for. Do you need hierarchical data types? Do you currently store files in the database and want to switch over to SQL Server's new filestream feature? Could you use more disk space by turning on data compression?

And let's not forget the ability to MERGE data.

How to determine total number of open/active connections in ms sql server 2005

SELECT
[DATABASE] = DB_NAME(DBID), 
OPNEDCONNECTIONS =COUNT(DBID),
[USER] =LOGINAME
FROM SYS.SYSPROCESSES
GROUP BY DBID, LOGINAME
ORDER BY DB_NAME(DBID), LOGINAME

Specific Time Range Query in SQL Server

select * from table where 
(dtColumn between #3/1/2009# and #3/31/2009#) and 
(hour(dtColumn) between 6 and 22) and 
(weekday(dtColumn, 1) between 2 and 4) 

How to parse string into date?

CONVERT(DateTime, ExpireDate, 121) AS ExpireDate

will do what is needed, result:

2012-04-24 00:00:00.000

What is the best way to create and populate a numbers table?

I know this thread is old and answered, but there is a way to squeeze a little extra performance out of Method 7:

Instead of this (essentially method 7 but with some ease of use polish):

DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM sys.objects s1       --use sys.columns if you don't get enough rows returned to generate all the numbers you need
    CROSS JOIN sys.objects s2 --use sys.co
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'

Try this:

DECLARE @BIT AS BIT = 0
IF OBJECT_ID('tempdb..#TALLY') IS NOT NULL
  DROP TABLE #TALLY
DECLARE @RunDate datetime
SET @RunDate=GETDATE()
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO #TALLY
    FROM        (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T32]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T64]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T128]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T256]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T512]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T1024]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T2048]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T4096]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T8192]
    CROSS JOIN  (SELECT @BIT [X] UNION ALL SELECT @BIT) [T16384]
ALTER TABLE #TALLY ADD PRIMARY KEY(Number)
PRINT CONVERT(varchar(20),datediff(ms,@RunDate,GETDATE()))+' milliseconds'

On my server this takes ~10 ms as opposed to the ~16-20 ms when selecting from sys.objects. It also has the added benefit of not being dependent on how many objects are in sys.objects. While it's pretty safe, it's technically a dependency and the other one goes faster anyway. I think the speed boost is down to using BITs if you change:

DECLARE @BIT AS BIT = 0

to:

DECLARE @BIT AS BIGINT = 0

It adds ~8-10 ms to the total time on my server. That said, when you scale up to 1,000,000 records BIT vs BIGINT doesn't appreciably affect my query anymore, but it still runs around ~680ms vs ~730ms from sys.objects.

Watching variables in SSIS during debug

Drag the variable from Variables pane to Watch pane and voila!

Calculate execution time of a SQL query?

Well, If you really want to do it in your DB there is a more accurate way as given in MSDN:

SET STATISTICS TIME ON

You can read this information from your application as well.

How to use the divide function in the query?

Assuming all of these columns are int, then the first thing to sort out is converting one or more of them to a better data type - int division performs truncation, so anything less than 100% would give you a result of 0:

select (100.0 * (SPGI09_EARLY_OVER_T – SPGI09_OVER_WK_EARLY_ADJUST_T)) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)
from 
CSPGI09_OVERSHIPMENT 

Here, I've mutiplied one of the numbers by 100.0 which will force the result of the calculation to be done with floats rather than ints. By choosing 100, I'm also getting it ready to be treated as a %.

I was also a little confused by your bracketing - I think I've got it correct - but you had brackets around single values, and then in other places you had a mix of operators (- and /) at the same level, and so were relying on the precedence rules to define which operator applied first.

How to convert Varchar to Int in sql server 2008?

There are two type of convert method in SQL.

CAST and CONVERT have similar functionality. CONVERT is specific to SQL Server, and allows for a greater breadth of flexibility when converting between date and time values, fractional numbers, and monetary signifiers. CAST is the more ANSI-standard of the two functions.

Using Convert

Select convert(int,[Column1])

Using Cast

Select cast([Column1] as int)

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

SET STATISTICS TIME ON

SELECT * 

FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;

SET STATISTICS TIME OFF;

And see the message tab it will look like this:

SQL Server Execution Times:

   CPU time = 0 ms,  elapsed time = 10 ms.

(778 row(s) affected)

SQL Server parse and compile time: 

   CPU time = 0 ms, elapsed time = 0 ms.

Convert varchar to uniqueidentifier in SQL Server

It would make for a handy function. Also, note I'm using STUFF instead of SUBSTRING.

create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
    -- just in case it came in with 0x prefix or dashes...
    set @s = replace(replace(@s,'0x',''),'-','')
    -- inject dashes in the right places
    set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
    return cast(@s as uniqueidentifier)
end

SQL Server ORDER BY date and nulls last

Use desc and multiply by -1 if necessary. Example for ascending int ordering with nulls last:

select * 
from
(select null v union all select 1 v union all select 2 v) t
order by -t.v desc

Drop primary key using script in SQL Server database

simply click

'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'

and run the below query is :

Query:alter Table 'TableName' drop constraint PK__TableName__30242045

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

Parse usable Street Address, City, State, Zip from a string

I've done this in the past.

Either do it manually, (build a nice gui that helps the user do it quickly) or have it automated and check against a recent address database (you have to buy that) and manually handle errors.

Manual handling will take about 10 seconds each, meaning you can do 3600/10 = 360 per hour, so 4000 should take you approximately 11-12 hours. This will give you a high rate of accuracy.

For automation, you need a recent US address database, and tweak your rules against that. I suggest not going fancy on the regex (hard to maintain long-term, so many exceptions). Go for 90% match against the database, do the rest manually.

Do get a copy of Postal Addressing Standards (USPS) at http://pe.usps.gov/cpim/ftp/pubs/Pub28/pub28.pdf and notice it is 130+ pages long. Regexes to implement that would be nuts.

For international addresses, all bets are off. US-based workers would not be able to validate.

Alternatively, use a data service. I have, however, no recommendations.

Furthermore: when you do send out the stuff in the mail (that's what it's for, right?) make sure you put "address correction requested" on the envelope (in the right place) and update the database. (We made a simple gui for the front desk person to do that; the person who actually sorts through the mail)

Finally, when you have scrubbed data, look for duplicates.

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

Bud, disable selinux or add the following to your RedHat/CentOS Server:

setsebool -P httpd_can_network_connect_db 1
setsebool -P httpd_can_network_connect 1

Best always!

Simulation of CONNECT BY PRIOR of Oracle in SQL Server

@Alex Martelli's answer is great! But it work only for one element at time (WHERE name = 'Joan') If you take out the WHERE clause, the query will return all the root rows together...

I changed a little bit for my situation, so it can show the entire tree for a table.

table definition:

CREATE TABLE [dbo].[mar_categories] ( 
    [category]  int IDENTITY(1,1) NOT NULL,
    [name]      varchar(50) NOT NULL,
    [level]     int NOT NULL,
    [action]    int NOT NULL,
    [parent]    int NULL,
    CONSTRAINT [XPK_mar_categories] PRIMARY KEY([category])
)

(level is literally the level of a category 0: root, 1: first level after root, ...)

and the query:

WITH n(category, name, level, parent, concatenador) AS 
(
    SELECT category, name, level, parent, '('+CONVERT(VARCHAR (MAX), category)+' - '+CONVERT(VARCHAR (MAX), level)+')' as concatenador
    FROM mar_categories
    WHERE parent is null
        UNION ALL
    SELECT m.category, m.name, m.level, m.parent, n.concatenador+' * ('+CONVERT (VARCHAR (MAX), case when ISNULL(m.parent, 0) = 0 then 0 else m.category END)+' - '+CONVERT(VARCHAR (MAX), m.level)+')' as concatenador
    FROM mar_categories as m, n
    WHERE n.category = m.parent
)
SELECT distinct * FROM n ORDER BY concatenador asc

(You don't need to concatenate the level field, I did just to make more readable)

the answer for this query should be something like:

sql return

I hope it helps someone!

now, I'm wondering how to do this on MySQL... ^^

How to change a table name using an SQL query?

rename table name :

RENAME TABLE old_tableName TO new_tableName;

for example:

RENAME TABLE company_name TO company_master;

Received an invalid column length from the bcp client for colid 6

I faced a similar kind of issue while passing a string to Database table using SQL BulkCopy option. The string i was passing was of 3 characters whereas the destination column length was varchar(20). I tried trimming the string before inserting into DB using Trim() function to check if the issue was due to any space (leading and trailing) in the string. After trimming the string, it worked fine.

You can try text.Trim()

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Cast the result as TIME and the result will be in time format for duration of the interval.

select CAST(job_end - job_start) AS TIME(0)) from tableA

How to connect to SQL Server from another computer?

If you want to connect to SQL server remotly you need to use a software - like Sql Server Management studio.

The computers doesn't need to be on the same network - but they must be able to connect each other using a communication protocol like tcp/ip, and the server must be set up to support incoming connection of the type you choose.

if you want to connect to another computer (to browse files ?) you use other tools, and not sql server (you can map a drive and access it through there ect...)

To Enable SQL connection using tcp/ip read this article:

For Sql Express: express For Sql 2008: 2008

Make sure you enable access through the machine firewall as well.

You might need to install either SSMS or Toad on the machine your using to connect to the server. both you can download from their's company web site.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

SQL, How to Concatenate results?

This one automatically excludes the trailing comma, unlike most of the other answers.

DECLARE @csv VARCHAR(1000)

SELECT @csv = COALESCE(@csv + ',', '') + ModuleValue
FROM Table_X
WHERE ModuleID = @ModuleID

(If the ModuleValue column isn't already a string type then you might need to cast it to a VARCHAR.)

Alter table add multiple columns ms sql

Alter table Hotels 
Add  
{ 
 HasPhotoInReadyStorage  bit, 
 HasPhotoInWorkStorage  bit, 
 HasPhotoInMaterialStorage bit, 
 HasHotelPhotoInReadyStorage  bit, 
 HasHotelPhotoInWorkStorage  bit, 
 HasHotelPhotoInMaterialStorage bit, 
 HasReporterData  bit, 
 HasMovieInReadyStorage  bit, 
 HasMovieInWorkStorage  bit, 
 HasMovieInMaterialStorage bit 
}; 

Above you are using {, }.

Also, you are missing commas:

ALTER TABLE Regions 
ADD ( HasPhotoInReadyStorage  bit, 
 HasPhotoInWorkStorage  bit, 
 HasPhotoInMaterialStorage bit <**** comma needed here
 HasText  bit); 

You need to remove the brackets and make sure all columns have a comma where necessary.

Datetime in where clause

You don't say which database you are using but in MS SQL Server it would be

WHERE DateField = {d '2008-12-20'}

If it is a timestamp field then you'll need a range:

WHERE DateField BETWEEN {ts '2008-12-20 00:00:00'} AND {ts '2008-12-20 23:59:59'}

Foreign key referencing a 2 columns primary key in SQL Server

I had the same problem and I think I have the solution.

If your field Application in table Library has a foreign key that references a field in another table (named Application I would bet), then your field Application in table Library has to have a foreign key to table Application too.

After that you can do your composed foreign key.

Excuse my poor english, and sorry if I'm wrong.

Use a LIKE statement on SQL Server XML Datatype

Yet another option is to cast the XML as nvarchar, and then search for the given string as if the XML vas a nvarchar field.

SELECT * 
FROM Table
WHERE CAST(Column as nvarchar(max)) LIKE '%TEST%'

I love this solution as it is clean, easy to remember, hard to mess up, and can be used as a part of a where clause.

EDIT: As Cliff mentions it, you could use:

...nvarchar if there's characters that don't convert to varchar

SET versus SELECT when assigning variables?

Quote, which summarizes from this article:

  1. SET is the ANSI standard for variable assignment, SELECT is not.
  2. SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  3. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  4. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)
  5. As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

Because TRUNCATE TABLE is a DDL command, it cannot check to see whether the records in the table are being referenced by a record in the child table.

This is why DELETE works and TRUNCATE TABLE doesn't: because the database is able to make sure that it isn't being referenced by another record.

SSIS Connection Manager Not Storing SQL Password

Try storing the connection string along with the password in a variable and assign the variable in the connection string using expression.I also faced the same issue and I solved like dis.

How do I view the SSIS packages in SQL Server Management Studio?

Came across SSIS package that schedule to run as sql job, you can identify where the SSIS package located by looking at the sql job properties; SQL job -> properties -> Steps (from select a page on left side) -> select job (from job list) -> edit -> job step properties shows up this got all the configuration for SSIS package, including its original path, in my case its under “MSDB”

Now connect to sql integration services; - open sql management studio - select server type to “integration services” - enter server name - you will see your SSIS package under “stored packages”

to edit the package right click and export to “file system” you’ll get file with extension .dtx it can be open in visual studio, I used the version visual studio 2012

How to strip HTML tags from a string in SQL Server?

There is a UDF that will do that described here:

User Defined Function to Strip HTML

CREATE FUNCTION [dbo].[udf_StripHTML] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX) AS
BEGIN
    DECLARE @Start INT
    DECLARE @End INT
    DECLARE @Length INT
    SET @Start = CHARINDEX('<',@HTMLText)
    SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
    SET @Length = (@End - @Start) + 1
    WHILE @Start > 0 AND @End > 0 AND @Length > 0
    BEGIN
        SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
        SET @Start = CHARINDEX('<',@HTMLText)
        SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
        SET @Length = (@End - @Start) + 1
    END
    RETURN LTRIM(RTRIM(@HTMLText))
END
GO

Edit: note this is for SQL Server 2005, but if you change the keyword MAX to something like 4000, it will work in SQL Server 2000 as well.

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

There are a few misunderstandings in the discussion above.

First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.

As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:

 IF @@TRANCOUNT > 0
      ROLLBACK TRANSACTION @transaction

Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)

This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.

As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.

Extreme wait-time when taking a SQL Server database offline

There is most likely a connection to the DB from somewhere (a rare example: asynchronous statistic update)

To find connections, use sys.sysprocesses

USE master
SELECT * FROM sys.sysprocesses WHERE dbid = DB_ID('MyDB')

To force disconnections, use ROLLBACK IMMEDIATE

USE master
ALTER DATABASE MyDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE

How to find sum of multiple columns in a table in SQL Server 2005?

You must also be aware of null records:

SELECT  (ISNULL(Val1,0) + ISNULL(Val2,0) + ISNULL(Val3,0)) as 'Total'
FROM Emp

Usage of ISNULL:

ISNULL(col_Name, replace value)

How can I make a SQL temp table with primary key and auto-incrementing field?

If you're just doing some quick and dirty temporary work, you can also skip typing out an explicit CREATE TABLE statement and just make the temp table with a SELECT...INTO and include an Identity field in the select list.

select IDENTITY(int, 1, 1) as ROW_ID,
       Name
into #tmp
from (select 'Bob' as Name union all
      select 'Susan' as Name union all
      select 'Alice' as Name) some_data

select *
from #tmp

How to identify all stored procedures referring a particular table

A non-query way would be to use the Sql Server Management Studio.

Locate the table, right click and choose "View dependencies".

EDIT

But, as the commenters said, it is not very reliable.

What does collation mean?

Besides the "accented letters are sorted differently than unaccented ones" in some Western European languages, you must take into account the groups of letters, which sometimes are sorted differently, also.

Traditionally, in Spanish, "ch" was considered a letter in its own right, same with "ll" (both of which represent a single phoneme), so a list would get sorted like this:

  • caballo
  • cinco
  • coche
  • charco
  • chocolate
  • chueco
  • dado
  • (...)
  • lámpara
  • luego
  • llanta
  • lluvia
  • madera

Notice all the words starting with single c go together, except words starting with ch which go after them, same with ll-starting words which go after all the words starting with a single l. This is the ordering you'll see in old dictionaries and encyclopedias, sometimes even today by very conservative organizations.

The Royal Academy of the Language changed this to make it easier for Spanish to be accomodated in the computing world. Nevertheless, ñ is still considered a different letter than n and goes after it, and before o. So this is a correctly ordered list:

  • Namibia
  • número
  • ñandú
  • ñú
  • obra
  • ojo

By selecting the correct collation, you get all this done for you, automatically :-)

SQL Server query - Selecting COUNT(*) with DISTINCT

Count all the DISTINCT program names by program type and push number

SELECT COUNT(DISTINCT program_name) AS Count,
  program_type AS [Type] 
FROM cm_production 
WHERE push_number=@push_number 
GROUP BY program_type

DISTINCT COUNT(*) will return a row for each unique count. What you want is COUNT(DISTINCT <expression>): evaluates expression for each row in a group and returns the number of unique, non-null values.

Executing a stored procedure within a stored procedure

Inline Stored procedure we using as per our need. Example like different Same parameter with different values we have to use in queries..

Create Proc SP1
(
 @ID int,
 @Name varchar(40)
 -- etc parameter list, If you don't have any parameter then no need to pass.
 )

  AS
  BEGIN

  -- Here we have some opereations

 -- If there is any Error Before Executing SP2 then SP will stop executing.

  Exec SP2 @ID,@Name,@SomeID OUTPUT 

 -- ,etc some other parameter also we can use OutPut parameters like 

 -- @SomeID is useful for some other operations for condition checking insertion etc.

 -- If you have any Error in you SP2 then also it will stop executing.

 -- If you want to do any other operation after executing SP2 that we can do here.

END

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

You want to put the ISNULL inside of the COUNT function, not outside:

Not GOOD: ISNULL(COUNT(field), 0)

GOOD: COUNT(ISNULL(field, 0))

Way to insert text having ' (apostrophe) into a SQL table

yes, sql server doesn't allow to insert single quote in table field due to the sql injection attack. so we must replace single appostrophe by double while saving.

(he doesn't work for me) must be => (he doesn''t work for me)

What represents a double in sql server?

float

Or if you want to go old-school:

real

You can also use float(53), but it means the same thing as float.

("real" is equivalent to float(24), not float/float(53).)

The decimal(x,y) SQL Server type is for when you want exact decimal numbers rather than floating point (which can be approximations). This is in contrast to the C# "decimal" data type, which is more like a 128-bit floating point number.

MSSQL's float type is equivalent to the 64-bit double type in .NET. (My original answer from 2011 said there could be a slight difference in mantissa, but I've tested this in 2020 and they appear to be 100% compatible in their binary representation of both very small and very large numbers -- see https://dotnetfiddle.net/wLX5Ox for my test).

To make things more confusing, a "float" in C# is only 32-bit, so it would be more equivalent in SQL to the real/float(24) type in MSSQL than float/float(53).

In your specific use case... All you need is 5 places after the decimal point to represent latitude and longitude within about one-meter precision, and you only need up to three digits before the decimal point for the degrees. Float(24) or decimal(8,5) will best fit your needs in MSSQL, and using float in C# is good enough, you don't need double. In fact, your users will probably thank you for rounding to 5 decimal places rather than having a bunch of insignificant digits coming along for the ride.

Datatype for storing ip address in SQL Server

Thanks RBarry. I'm putting together an IP block allocation system and storing as binary is the only way to go.

I'm storing the CIDR representation (ex: 192.168.1.0/24) of the IP block in a varchar field, and using 2 calculated fields to hold the binary form of the start and end of the block. From there, I can run fast queries to see if a given block as already been allocated or is free to assign.

I modified your function to calculate the ending IP Address like so:

CREATE FUNCTION dbo.fnDisplayIPv4End(@block AS VARCHAR(18)) RETURNS BINARY(4)
AS
BEGIN
    DECLARE @bin AS BINARY(4)
    DECLARE @ip AS VARCHAR(15)
    DECLARE @size AS INT

    SELECT @ip = Left(@block, Len(@block)-3)
    SELECT @size = Right(@block, 2)

    SELECT @bin = CAST( CAST( PARSENAME( @ip, 4 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 3 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 2 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 1 ) AS INTEGER) AS BINARY(1))

    SELECT @bin = CAST(@bin + POWER(2, 32-@size) AS BINARY(4))
    RETURN @bin
END;
go

SQL Server CASE .. WHEN .. IN statement

Thanks for the Answer I have modified the statements to look like below

SELECT
     AlarmEventTransactionTable.TxnID,
     CASE 
    WHEN DeviceID IN('7', '10', '62', '58', '60',
            '46', '48', '50', '137', '139',
             '141', '145', '164') THEN '01'
    WHEN DeviceID IN('8', '9', '63', '59', '61',
            '47', '49', '51', '138', '140',
            '142', '146', '165') THEN '02'
             ELSE 'NA' END AS clocking,
     AlarmEventTransactionTable.DateTimeOfTxn
FROM
     multiMAXTxn.dbo.AlarmEventTransactionTable

Rounding SQL DateTime to midnight

I usually do

SELECT *
FROM MyTable
WHERE CONVERT(VARCHAR, MyTable.dateField, 101) = CONVERT(VARCHAR, GETDATE(), 101)

if you are using SQL SERVER 2008, you can do

SELECT *
FROM MyTable
WHERE CAST(MyTable.dateField AS DATE) = CAST(GETDATE() AS DATE)

Hope this helps

Is the LIKE operator case-sensitive with MSSQL Server?

You can change from the property of every item.

case sensitive

How can a LEFT OUTER JOIN return more records than exist in the left table?

LEFT OUTER JOIN just like INNER JOIN (normal join) will return as many results for each row in left table as many matches it finds in the right table. Hence you can have a lot of results - up to N x M, where N is number of rows in left table and M is number of rows in right table.

It's the minimum number of results is always guaranteed in LEFT OUTER JOIN to be at least N.

Installation of SQL Server Business Intelligence Development Studio

This worked for me:

Start /wait setup.exe /qb  ADDLOCAL=SQL_DTS,Client_Components,Connectivity,SQL_Tools90,SQL_WarehouseDevWorkbench,SQLXML,Tools_Legacy,SQL_Documentation,SQL_BooksOnline

Based off this TechNet Article:

https://technet.microsoft.com/en-us/library/ms144259(v=sql.90).aspx

SQL Server String or binary data would be truncated

The issue is quite simple: one or more of the columns in the source query contains data that exceeds the length of its destination column. A simple solution would be to take your source query and execute Max(Len( source col )) on each column. I.e.,

Select Max(Len(TextCol1))
    , Max(Len(TextCol2))
    , Max(Len(TextCol3))
    , ...
From ...

Then compare those lengths to the data type lengths in your destination table. At least one, exceeds its destination column length.

If you are absolutely positive that this should not be the case and do not care if it is not the case, then another solution is to forcibly cast the source query columns to their destination length (which will truncate any data that is too long):

Select Cast(TextCol1 As varchar(...))
    , Cast(TextCol2 As varchar(...))
    , Cast(TextCol3 As varchar(...))
    , ...
From ...

How to query values from xml nodes?

if you have only one xml in your table, you can convert it in 2 steps:

CREATE TABLE Batches( 
   BatchID int,
   RawXml xml 
)

declare @xml xml=(select top 1 RawXml from @Batches)

SELECT  --b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)

Getting result of dynamic SQL into a variable for sql-server

this could be a solution?

declare @step2cmd nvarchar(200)
DECLARE @rcount NUMERIC(18,0)   
set @step2cmd = 'select count(*) from uat.ap.ztscm_protocollo' --+ @nometab
EXECUTE @rcount=sp_executesql @step2cmd
select @rcount

Create a date from day month and year with T-SQL

Assuming y, m, d are all int, how about:

CAST(CAST(y AS varchar) + '-' + CAST(m AS varchar) + '-' + CAST(d AS varchar) AS DATETIME)

Please see my other answer for SQL Server 2012 and above

Average of multiple columns

Select Req_ID, sum(R1+R2+R3+R4+R5)/5 as Average
from Request
Group by Req_ID;

How to export SQL Server 2005 query to CSV

I think the simplest way to do this is from Excel.

  1. Open a new Excel file.
  2. Click on the Data tab
  3. Select Other Data Sources
  4. Select SQL Server
  5. Enter your server name, database, table name, etc.

If you have a newer version of Excel you could bring the data in from PowerPivot and then insert this data into a table.

SELECT FOR UPDATE with SQL Server

You cannot have snapshot isolation and blocking reads at the same time. The purpose of snapshot isolation is to prevent blocking reads.

How to get calendar Quarter from a date in TSQL

Using the function MONTH which returns the month as a number, we can easily calculate the quarter.

select date, CEILING((MONTH(date) * 4) / 12) quarter from dual

Get top first record from duplicate records having no unique identity

YOur best bet is to fix the datbase design and add the identioty column to the table. Why do you havea table without one in the first place? Especially one with duplicate records! Clearly the database itself needs redesigning.

And why do you have to have this in a view, why isn't your solution with the temp table a valid solution? Views are not usually a really good thing to do to a perfectly nice database.

How to get number of rows inserted by a transaction

I found the answer to may previous post. Here it is.

CREATE TABLE #TempTable (id int) 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 1,2 

INSERT INTO @TestTable (col1, col2) OUTPUT INSERTED.id INTO #TempTable select 3,4 

SELECT * FROM #TempTable --this select will chage @@ROWCOUNT value

SQL Server Restore Error - Access is Denied

The backup creator had MSSql version 10 installed, so when he took the backup it also stores the original file path (to be able to restore it in same location), but I had version 11, so it could not find the destination directory.

So I changed the output file directory to C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\, and it was able to restore the database successfully.

Source

Insert all values of a table into another table in SQL

The insert statement actually has a syntax for doing just that. It's a lot easier if you specify the column names rather than selecting "*" though:

INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table
-- optionally WHERE ...

I'd better clarify this because for some reason this post is getting a few down-votes.

The INSERT INTO ... SELECT FROM syntax is for when the table you're inserting into ("new_table" in my example above) already exists. As others have said, the SELECT ... INTO syntax is for when you want to create the new table as part of the command.

You didn't specify whether the new table needs to be created as part of the command, so INSERT INTO ... SELECT FROM should be fine if your destination table already exists.

SQL query to select dates between two dates

select * from test 
     where CAST(AddTime as datetime) between '2013/4/4' and '2014/4/4'

-- if data type is different

get DATEDIFF excluding weekends using sql server

I just want to share the code I created that might help you.

DECLARE @MyCounter int = 0, @TempDate datetime, @EndDate datetime;
SET @TempDate = DATEADD(d,1,'2017-5-27')
SET @EndDate = '2017-6-3'

WHILE @TempDate <= @EndDate
    BEGIN
    IF DATENAME(DW,@TempDate) = 'Sunday' OR DATENAME(DW,@TempDate) = 'Saturday'
        SET @MyCounter = @MyCounter
    ELSE IF @TempDate not in ('2017-1-1', '2017-1-16', '2017-2-20', '2017-5-29', '2017-7-4', '2017-9-4', '2017-10-9', '2017-11-11', '2017-12-25')
        SET @MyCounter = @MyCounter + 1

    SET @TempDate = DATEADD(d,1,@TempDate)
    CONTINUE

END
PRINT @MyCounter
PRINT @TempDate

If you do have a holiday table, you can also use that so that you don't have to list all the holidays in the ELSE IF section of the code. You can also create a function for this code and use the function whenever you need it in your query.

I hope this might help too.

CASE IN statement with multiple values

You can return the same value from several matches:

SELECT
  CASE c.Number
    WHEN '1121231' THEN 1
    WHEN '31242323' THEN 1
    WHEN '234523' THEN 2
    WHEN '2342423' THEN 2
  END AS Test
FROM tblClient c

This will probably result in the same execution plan as Martins suggestion, so it's more a matter of how you want to write it.

How do you specify a different port number in SQL Management Studio?

You'll need the SQL Server Configuration Manager. Go to Sql Native Client Configuration, Select Client Protocols, Right Click on TCP/IP and set your default port there.

SQL update query using joins

Try like this...

Update t1.Column1 = value 
from tbltemp as t1 
inner join tblUser as t2 on t2.ID = t1.UserID 
where t1.[column1]=value and t2.[Column1] = value;

How to install SQL Server 2005 Express in Windows 8

Microsoft SQL Server 2005 Express Edition Service Pack 4 on Windows Server 2012 R2

Those steps are based on previous howto from https://stackoverflow.com/users/2385/eduardo-molteni

  1. download SQLEXPR.EXE
  2. run SQLEXPR.EXE
  3. copy c:\generated_installation_dir to inst.bak
  4. quit install
  5. run inst.bak/setuip/sqlncli_x64.msi
  6. run SQLEXPR.EXE
  7. enjoy!

This works with Microsoft SQL Server 2005 Express Edition Service Pack 4 http://www.microsoft.com/en-us/download/details.aspx?id=184

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd-mmm-yy format.

select 
cast(DAY(getdate()) as varchar)+'-'+left(DATEname(m,getdate()),3)+'-'+  
Right(Year(getdate()),2)

How to change identity column values programmatically?

You can insert new rows with modified values and then delete old rows. Following example change ID to be same as foreign key PersonId

SET IDENTITY_INSERT [PersonApiLogin] ON

INSERT INTO [PersonApiLogin](
       [Id]
      ,[PersonId]
      ,[ApiId]
      ,[Hash]
      ,[Password]
      ,[SoftwareKey]
      ,[LoggedIn]
      ,[LastAccess])
SELECT [PersonId]
      ,[PersonId]
      ,[ApiId]
      ,[Hash]
      ,[Password]
      ,[SoftwareKey]
      ,[LoggedIn]
      ,[LastAccess]
FROM [db304].[dbo].[PersonApiLogin]
GO

DELETE FROM [PersonApiLogin]
WHERE [PersonId] <> ID
GO
SET IDENTITY_INSERT [PersonApiLogin] OFF
GO

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

SELECT Id   'PatientId',
       ISNULL(CONVERT(varchar(50),ParentId),'')  'ParentId'
FROM Patients

ISNULL always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar), you'd best make sure that's the type of the first argument.


COALESCE is usually a better function to use than ISNULL, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier has higher precedence than varchar, so that doesn't help.

(It's also generally preferred because it extends to more than two arguments)

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

Follow the below steps to avoid (cannot convert between unicode and non-unicode string data types) this error

i) Add the Data conversion Transformation tool to your DataFlow.
ii) To open the DataFlow Conversion and select [string DT_STR] datatype.
iii) Then go to Destination flow, select Mapping.
iv) change your i/p name to copy of the name.

Pass table as parameter into sql server UDF

To obtain the column count on a table, use this:

select count(id) from syscolumns where id = object_id('tablename')

and to pass a table to a function, try XML as show here:

create function dbo.ReadXml (@xmlMatrix xml)
returns table
as
return
( select
t.value('./@Salary', 'integer') as Salary,
t.value('./@Age', 'integer') as Age
from @xmlMatrix.nodes('//row') x(t)
)
go

declare @source table
( Salary integer,
age tinyint
)
insert into @source
select 10000, 25 union all
select 15000, 27 union all
select 12000, 18 union all
select 15000, 36 union all
select 16000, 57 union all
select 17000, 44 union all
select 18000, 32 union all
select 19000, 56 union all
select 25000, 34 union all
select 7500, 29
--select * from @source

declare @functionArgument xml

select @functionArgument =
( select
Salary as [row/@Salary],
Age as [row/@Age]
from @source
for xml path('')
)
--select @functionArgument as [@functionArgument]

select * from readXml(@functionArgument)

/* -------- Sample Output: --------
Salary Age
----------- -----------
10000 25
15000 27
12000 18
15000 36
16000 57
17000 44
18000 32
19000 56
25000 34
7500 29
*/

SQL query, store result of SELECT in local variable

Isn't this a much simpler solution, if I correctly understand the question, of course.

I want to load email addresses that are in a table called "spam" into a variable.

select email from spam

produces the following list, say:

.accountant
.bid
.buiilldanything.com
.club
.cn
.cricket
.date
.download
.eu

To load into the variable @list:

declare @list as varchar(8000)
set @list += @list (select email from spam)

@list may now be INSERTed into a table, etc.

I hope this helps.

To use it for a .csv file or in VB, spike the code:

declare @list as varchar(8000)
set @list += @list (select '"'+email+',"' from spam)
print @list

and it produces ready-made code to use elsewhere:

".accountant,"
".bid,"
".buiilldanything.com,"
".club,"
".cn,"
".cricket,"
".date,"
".download,"
".eu,"

One can be very creative.

Thanks

Nico

T-SQL Substring - Last 3 Characters

Because more ways to think about it are always good:

select reverse(substring(reverse(columnName), 1, 3))

How to delete all rows from all tables in a SQL Server database?

Here is a solution that:

  1. Drops constraints (thanks to this post)
  2. Iterates through INFORMATION_SCHEMA.TABLES for a particular database
  3. SELECTS tables based on some search criteria
  4. Deletes all the data from those tables
  5. Re-adds constraints
  6. Allows for ignoring of certain tables such as sysdiagrams and __RefactorLog

I initially tried EXECUTE sp_MSforeachtable 'TRUNCATE TABLE ?', but that deleted my diagrams.

USE <DB name>;
GO

-- Disable all constraints in the database
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

declare @catalog nvarchar(250);
declare @schema nvarchar(250);
declare @tbl nvarchar(250);
DECLARE i CURSOR LOCAL FAST_FORWARD FOR select
                                        TABLE_CATALOG,
                                        TABLE_SCHEMA,
                                        TABLE_NAME
                                        from INFORMATION_SCHEMA.TABLES
                                        where
                                        TABLE_TYPE = 'BASE TABLE'
                                        AND TABLE_NAME != 'sysdiagrams'
                                        AND TABLE_NAME != '__RefactorLog'

OPEN i;
FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE @sql NVARCHAR(MAX) = N'DELETE FROM [' + @catalog + '].[' + @schema + '].[' + @tbl + '];'
        /* Make sure these are the commands you want to execute before executing */
        PRINT 'Executing statement: ' + @sql
        -- EXECUTE sp_executesql @sql
        FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
    END
CLOSE i;
DEALLOCATE i;

-- Re-enable all constraints again
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

Check if table exists in SQL Server

If you need to work on different databases:

DECLARE @Catalog VARCHAR(255)
SET @Catalog = 'MyDatabase'

DECLARE @Schema VARCHAR(255)
SET @Schema = 'dbo'

DECLARE @Table VARCHAR(255)
SET @Table = 'MyTable'

IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES   
    WHERE TABLE_CATALOG = @Catalog 
      AND TABLE_SCHEMA = @Schema 
      AND TABLE_NAME = @Table))
BEGIN
   --do stuff
END

database attached is read only

If SQL Server Service is running as Local System, than make sure that the folder containing databases should have FULL CONTROL PERMISSION for the Local System account.

This worked for me.

How to detect if a stored procedure already exists

From SQL Server 2016 CTP3 you can use new DIE statements instead of big IF wrappers

Syntax:

DROP { PROC | PROCEDURE } [ IF EXISTS ] { [ schema_name. ] procedure } [ ,...n ]

Query:

DROP PROCEDURE IF EXISTS usp_name

More info here

SQL query to group by day

actually this depends on what DBMS you are using but in regular SQL convert(varchar,DateColumn,101) will change the DATETIME format to date (one day)

so:

SELECT 
    sum(amount) 
FROM 
    sales 
GROUP BY 
    convert(varchar,created,101)

the magix number 101 is what date format it is converted to

Querying data by joining two tables in two database on different servers

If a linked server is not allowed by your dba, you can use OPENROWSET. Books Online will provide the syntax you need.

If Else If In a Sql Server Function

ALTER FUNCTION [dbo].[fnTally] (@SchoolId nvarchar(50))
    RETURNS nvarchar(3)
AS BEGIN 

    DECLARE @Final nvarchar(3)
    SELECT @Final = CASE 
        WHEN yes_ans > no_ans  AND yes_ans > na_ans THEN 'Yes'
        WHEN no_ans  > yes_ans AND no_ans  > na_ans THEN 'No'
        WHEN na_ans  > yes_ans AND na_ans  > no_ans THEN 'N/A' END
    FROM dbo.qrc_maintally
    WHERE school_id = @SchoolId

Return @Final
End

As you can see, this simplifies the code a lot. It also makes other errors in your code more obvious: you're returning an nvarchar, but declared the function to return an int (corrected in the code above).

Turn off constraints temporarily (MS SQL)

Disabling and Enabling All Foreign Keys

CREATE PROCEDURE pr_Disable_Triggers_v2
    @disable BIT = 1
AS
    DECLARE @sql VARCHAR(500)
        ,   @tableName VARCHAR(128)
        ,   @tableSchema VARCHAR(128)

    -- List of all tables
    DECLARE triggerCursor CURSOR FOR
        SELECT  t.TABLE_NAME AS TableName
            ,   t.TABLE_SCHEMA AS TableSchema
        FROM    INFORMATION_SCHEMA.TABLES t
        ORDER BY t.TABLE_NAME, t.TABLE_SCHEMA

    OPEN    triggerCursor
    FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema
    WHILE ( @@FETCH_STATUS = 0 )
    BEGIN

        SET @sql = 'ALTER TABLE ' + @tableSchema + '.[' + @tableName + '] '
        IF @disable = 1
            SET @sql = @sql + ' DISABLE TRIGGER ALL'
        ELSE
            SET @sql = @sql + ' ENABLE TRIGGER ALL'

        PRINT 'Executing Statement - ' + @sql
        EXECUTE ( @sql )

        FETCH NEXT FROM triggerCursor INTO @tableName, @tableSchema

    END

    CLOSE triggerCursor
    DEALLOCATE triggerCursor

First, the foreignKeyCursor cursor is declared as the SELECT statement that gathers the list of foreign keys and their table names. Next, the cursor is opened and the initial FETCH statement is executed. This FETCH statement will read the first row's data into the local variables @foreignKeyName and @tableName. When looping through a cursor, you can check the @@FETCH_STATUS for a value of 0, which indicates that the fetch was successful. This means the loop will continue to move forward so it can get each successive foreign key from the rowset. @@FETCH_STATUS is available to all cursors on the connection. So if you are looping through multiple cursors, it is important to check the value of @@FETCH_STATUS in the statement immediately following the FETCH statement. @@FETCH_STATUS will reflect the status for the most recent FETCH operation on the connection. Valid values for @@FETCH_STATUS are:

0 = FETCH was successful
-1 = FETCH was unsuccessful
-2 = the row that was fetched is missing

Inside the loop, the code builds the ALTER TABLE command differently depending on whether the intention is to disable or enable the foreign key constraint (using the CHECK or NOCHECK keyword). The statement is then printed as a message so its progress can be observed and then the statement is executed. Finally, when all rows have been iterated through, the stored procedure closes and deallocates the cursor.

see Disabling Constraints and Triggers from MSDN Magazine

how to insert datetime into the SQL Database table?

if you got actuall time in mind GETDATE() would be the function what you looking for

Insert multiple rows WITHOUT repeating the "INSERT INTO ..." part of the statement?

Using INSERT INTO ... VALUES syntax like in Daniel Vassallo's answer there is one annoying limitation:

From MSDN

The maximum number of rows that can be constructed by inserting rows directly in the VALUES list is 1000

The easiest way to omit this limitation is to use derived table like:

INSERT INTO dbo.Mytable(ID, Name)
SELECT ID, Name 
FROM (
   VALUES (1, 'a'),
          (2, 'b'),
          --...
          -- more than 1000 rows
)sub (ID, Name);

LiveDemo


This will work starting from SQL Server 2008+

Get the list of stored procedures created and / or modified on a particular date?

For SQL Server 2012:

SELECT name, modify_date, create_date, type
FROM sys.procedures
WHERE name like '%XXX%' 
ORDER BY modify_date desc

Subtract minute from DateTime in SQL Server 2005

SELECT DATEADD(minute, -15, '2000-01-01 08:30:00'); 

The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like

SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00'); 

where @h is the hour part of your string and @m is the minute part of your string

EDIT:

Here is a better way:

SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)

SQL Server error on update command - "A severe error occurred on the current command"

In my case,I was using SubQuery and had a same problem. I realized that the problem is from memory leakage.

Restarting MSSQL service cause to flush tempDb resource and free huge amount of memory. so this was solve the problem.

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

How to update data in one table from corresponding data in another table in SQL Server 2005

update test1 t1, test2 t2
set t2.deptid = t1.deptid
where t2.employeeid = t1.employeeid

you can not use from keyword for the mysql

When restoring a backup, how do I disconnect all active connections?

I ran across this problem while automating a restore proccess in SQL Server 2008. My (successfull) approach was a mix of two of the answers provided.

First, I run across all the connections of said database, and kill them.

DECLARE @SPID int = (SELECT TOP 1 SPID FROM sys.sysprocess WHERE dbid = db_id('dbName'))
While @spid Is Not Null
Begin
        Execute ('Kill ' + @spid)
        Select @spid = top 1 spid from master.dbo.sysprocesses
        where dbid = db_id('dbName')
End

Then, I set the database to a single_user mode

ALTER DATABASE dbName SET SINGLE_USER

Then, I run the restore...

RESTORE DATABASE and whatnot

Kill the connections again

(same query as above)

And set the database back to multi_user.

ALTER DATABASE dbName SET MULTI_USER

This way, I ensure that there are no connections holding up the database before setting to single mode, since the former will freeze if there are.

Find duplicate records in a table using SQL Server

Select EventID,count() as cnt from dbo.EventInstances group by EventID having count() > 1

How do I change the owner of a SQL Server database?

to change the object owner try the following

EXEC sp_changedbowner 'sa'

that however is not your problem, to see diagrams the Da Vinci Tools objects have to be created (you will see tables and procs that start with dt_) after that

How to copy a huge table data into another table in SQL Server

I have been working with our DBA to copy an audit table with 240M rows to another database.

Using a simple select/insert created a huge tempdb file.

Using a the Import/Export wizard worked but copied 8M rows in 10min

Creating a custom SSIS package and adjusting settings copied 30M rows in 10Min

The SSIS package turned out to be the fastest and most efficent for our purposes

Earl

How to get Time from DateTime format in SQL?

If you want date something in this style: Oct 23 2013 10:30AM

Use this

SELECT CONVERT(NVARCHAR(30),getdate(), 100)

convert() method takes 3 parameters

  1. datatype
  2. Column/Value
  3. Style: Available styles are from 100 to 114. You can choose within range from. Choose one by one to change the date format.

How to save select query results within temporary table?

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

DECODE( ) function in SQL Server

Just for completeness (because nobody else posted the most obvious answer):

Oracle:

DECODE(PC_SL_LDGR_CODE, '02', 'DR', 'CR')

MSSQL (2012+):

IIF(PC_SL_LDGR_CODE='02', 'DR', 'CR')

The bad news:

DECODE with more than 4 arguments would result in an ugly IIF cascade

Multi-dimensional arrays in Bash

This works thanks to 1. "indirect expansion" with ! which adds one layer of indirection, and 2. "substring expansion" which behaves differently with arrays and can be used to "slice" them as described https://stackoverflow.com/a/1336245/317623

# Define each array and then add it to the main one
SUB_0=("name0" "value 0")
SUB_1=("name1" "value;1")
MAIN_ARRAY=(
  SUB_0[@]
  SUB_1[@]
)

# Loop and print it.  Using offset and length to extract values
COUNT=${#MAIN_ARRAY[@]}
for ((i=0; i<$COUNT; i++))
do
  NAME=${!MAIN_ARRAY[i]:0:1}
  VALUE=${!MAIN_ARRAY[i]:1:1}
  echo "NAME ${NAME}"
  echo "VALUE ${VALUE}"
done

It's based off of this answer here

curl_init() function not working

For Windows, if anybody is interested, uncomment the following line (by removing the ;) from php.ini

;extension=php_curl.dll

Restart apache server.

Stored procedure return into DataSet in C# .Net

You can declare SqlConnection and SqlCommand instances at global level so that you can use it through out the class. Connection string is in Web.Config.

SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();

Now you can use the below method to pass values to Stored Procedure and get the DataSet.

public DataSet GetDataSet(string paramValue)
{
    sqlcomm.Connection = sqlConn;
    using (sqlConn)
    {
        try
        {
            using (SqlDataAdapter da = new SqlDataAdapter())
            {  
                // This will be your input parameter and its value
                sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);

                // You can retrieve values of `output` variables
                var returnParam = new SqlParameter
                {
                    ParameterName = "@Error",
                    Direction = ParameterDirection.Output,
                    Size = 1000
                };
                sqlcomm.Parameters.Add(returnParam);
                // Name of stored procedure
                sqlcomm.CommandText = "StoredProcedureName";
                da.SelectCommand = sqlcomm;
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                DataSet ds = new DataSet();
                da.Fill(ds);                            
            }
        }
        catch (SQLException ex)
        {
            Console.WriteLine("SQL Error: " + ex.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
    return new DataSet();
}

The following is the sample of connection string in config file

<connectionStrings>
    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
         providerName="System.Data.SqlClient" />
</connectionStrings>

How to send a Post body in the HttpClient request in Windows Phone 8?

I implemented it in the following way. I wanted a generic MakeRequest method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string> object to house the content to be submitted, and then set the HttpRequestMessage Content property with it:

Generic method to call the API:

    private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
    {
        using (var client = new HttpClient())
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");

            if (postParams != null)
                requestMessage.Content = new FormUrlEncodedContent(postParams);   // This is where your content gets added to the request body


            HttpResponseMessage response = client.SendAsync(requestMessage).Result;

            string apiResponse = response.Content.ReadAsStringAsync().Result;
            try
            {
                // Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
                if (apiResponse != "")
                    return JsonConvert.DeserializeObject<T>(apiResponse);
                else
                    throw new Exception();
            }
            catch (Exception ex)
            {
                throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
            }
        }
    }

Call the method:

    public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
    { 
        // Here you create your parameters to be added to the request content
        var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
        // make a POST request to the "cards" endpoint and pass in the parameters
        return MakeRequest<CardInformation>("POST", "cards", postParams);
    }

MySQL SELECT last few days?

WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL '-3' DAY);

use quotes on the -3 value

TempData keep() vs peek()

Just finished understanding Peek and Keep and had same confusion initially. The confusion arises becauses TempData behaves differently under different condition. You can watch this video which explains the Keep and Peek with demonstration https://www.facebook.com/video.php?v=689393794478113

Tempdata helps to preserve values for a single request and CAN ALSO preserve values for the next request depending on 4 conditions”.

If we understand these 4 points you would see more clarity.Below is a diagram with all 4 conditions, read the third and fourth point which talks about Peek and Keep.

enter image description here

Condition 1 (Not read):- If you set a “TempData” inside your action and if you do not read it in your view then “TempData” will be persisted for the next request.

Condition 2 ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request.

string str = TempData["MyData"];

Even if you are displaying it’s a normal read like the code below.

@TempData["MyData"];

Condition 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted.

@TempData["MyData"];
TempData.Keep("MyData");

Condition 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request.

string str = TempData.Peek("Td").ToString();

Reference :- http://www.codeproject.com/Articles/818493/MVC-Tempdata-Peek-and-Keep-confusion

SQL Server 2005 Using CHARINDEX() To split a string

    USE [master]
    GO
    /******  this function returns Pakistan where as if you want to get ireland simply replace (SELECT SUBSTRING(@NEWSTRING,CHARINDEX('$@$@$',@NEWSTRING)+5,LEN(@NEWSTRING))) with
SELECT @NEWSTRING = (SELECT SUBSTRING(@NEWSTRING, 0,CHARINDEX('$@$@$',@NEWSTRING)))******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE FUNCTION [dbo].[FN_RETURN_AFTER_SPLITER] 
    (  
     @SPLITER varchar(max))
    RETURNS VARCHAR(max)
    AS 
    BEGIN

    --declare @testString varchar(100),
    DECLARE @NEWSTRING VARCHAR(max) 
    -- set @teststring = '@ram?eez(ali)'
     SET @NEWSTRING = @SPLITER ; 

    SELECT @NEWSTRING = (SELECT SUBSTRING(@NEWSTRING,CHARINDEX('$@$@$',@NEWSTRING)+5,LEN(@NEWSTRING)))
    return @NEWSTRING 
    END
    --select [dbo].[FN_RETURN_AFTER_SPLITER]  ('Ireland$@$@$Pakistan')

jQuery see if any or no checkboxes are selected

You can use something like this

if ($("#formID input:checkbox:checked").length > 0)
{
    // any one is checked
}
else
{
   // none is checked
}

make: *** [ ] Error 1 error

Sometimes you will get lots of compiler outputs with many warnings and no line of output that says "error: you did something wrong here" but there was still an error. An example of this is a missing header file - the compiler says something like "no such file" but not "error: no such file", then it exits with non-zero exit code some time later (perhaps after many more warnings). Make will bomb out with an error message in these cases!

android.app.Application cannot be cast to android.app.Activity

You can also try this one.

override fun registerWith( registry: PluginRegistry) {
        GeneratedPluginRegistrant.registerWith(registry as FlutterEngine)       
    //registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin")
    }

I think this one is far better solution than creating a new class.

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I had the same problem with a different and simple solution.

Problem

I installed PHP 5.6 following the accepted answer to this question on Ask Ubuntu. After using Virtualmin to switch a particular virtual server from PHP 5.5 to PHP 5.6, I received a 500 Internal Server Error and had the same entries in the apache error log:

[Tue Jul 03 16:15:22.131051 2018] [fcgid:warn] [pid 24262] (104)Connection reset by peer: [client 10.20.30.40:23700] mod_fcgid: error reading data from FastCGI server
[Tue Jul 03 16:15:22.131101 2018] [core:error] [pid 24262] [client 10.20.30.40:23700] End of script output before headers: index.php

Cause

Simple: I didn't install the php5.6-cgi packet.

Fix

Installing the packet and reloading apache solved the problem:

  • sudo apt-get install php5.6-cgi if you are using PHP 5.6

  • sudo apt-get install php5-cgi if you are using a different PHP 5 version

  • sudo apt-get install php7.0-cgi if you are using PHP 7

Then use service apache2 reload to apply the configuration.

Removing "http://" from a string

Try this out:

$url = 'http://techcrunch.com/startups/'; $url = str_replace(array('http://', 'https://'), '', $url); 

EDIT:

Or, a simple way to always remove the protocol:

$url = 'https://www.google.com/'; $url = preg_replace('@^.+?\:\/\/@', '', $url); 

Making an array of integers in iOS

C array:

NSInteger array[6] = {1, 2, 3, 4, 5, 6};

Objective-C Array:

NSArray *array = @[@1, @2, @3, @4, @5, @6];
// numeric values must in that case be wrapped into NSNumbers

Swift Array:

var array = [1, 2, 3, 4, 5, 6]

This is correct too:

var array = Array(1...10)

NB: arrays are strongly typed in Swift; in that case, the compiler infers from the content that the array is an array of integers. You could use this explicit-type syntax, too:

var array: [Int] = [1, 2, 3, 4, 5, 6]

If you wanted an array of Doubles, you would use :

var array = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] // implicit type-inference

or:

var array: [Double] = [1, 2, 3, 4, 5, 6] // explicit type

Prevent PDF file from downloading and printing

if you want to provide a solution, well, there just isn't one. You would have to be able stop the user running a program that can access the buffers in the GPU to prevent them grabbing a screen shot. Anything displayed on the screen can be captured.

If you decide to send a file where the contents are not accessible online, then you need to rely on the security that the end product/application uses. This will also be completely breakable for an extremely determined pserson.

The last option is to send printed documents in the post. The old fashioned way using a good courier service. Costs go up, time delays are inevitble - but you get exactly what you are after. A solution is not without its costs.

Always happy to point out the obvious :)

How to cast from List<Double> to double[] in Java?

With , you can do it this way.

double[] arr = frameList.stream().mapToDouble(Double::doubleValue).toArray(); //via method reference
double[] arr = frameList.stream().mapToDouble(d -> d).toArray(); //identity function, Java unboxes automatically to get the double value

What it does is :

  • get the Stream<Double> from the list
  • map each double instance to its primitive value, resulting in a DoubleStream
  • call toArray() to get the array.

What is the difference between bool and Boolean types in C#

Note that Boolean will only work were you have using System; (which is usually, but not necessarily, included) (unless you write it out as System.Boolean). bool does not need using System;

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

An interesting challenge would be to write the shortest function to do this. Recursion to the rescue!

function r(a,b){return a>b?[]:[a].concat(r(++a,b))}

Tends to be slow on large ranges, but luckily quantum computers are just around the corner.

An added bonus is that it's obfuscatory. Because we all know how important it is to hide our code from prying eyes.

To truly and utterly obfuscate the function, do this:

function r(a,b){return (a<b?[a,b].concat(r(++a,--b)):a>b?[]:[a]).sort(function(a,b){return a-b})}

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

How do I vertically align text in a div?

If you need to use with the min-height property you must add this CSS on:

.outerContainer .innerContainer {
    height: 0;
    min-height: 100px;
}

How to use CMAKE_INSTALL_PREFIX

But do remember to place it BEFORE PROJECT(< project_name>) command, otherwise it will not work!

My first week of using cmake - after some years of GNU autotools - so I am still learning (better then writing m4 macros), but I think modifying CMAKE_INSTALL_PREFIX after setting project is the better place.

CMakeLists.txt

cmake_minimum_required (VERSION 2.8)

set (CMAKE_INSTALL_PREFIX /foo/bar/bubba)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
project (BarkBark)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")
set (CMAKE_INSTALL_PREFIX /foo/bar/bubba)
message("CIP = ${CMAKE_INSTALL_PREFIX} (should be /foo/bar/bubba")

First run (no cache)

CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- The C compiler identification is GNU 4.4.7
-- etc, etc,...
CIP = /usr/local (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- Configuring done
-- Generating done

Second run

CIP = /foo/bar/bubba (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
CIP = /foo/bar/bubba (should be /foo/bar/bubba
-- Configuring done
-- Generating done

Let me know if I am mistaken, I have a lot of learning to do. It's fun.

What's the difference between Apache's Mesos and Google's Kubernetes

Both projects aim to make it easier to deploy & manage applications inside containers in your datacenter or cloud.

In order to deploy applications on top of Mesos, one can use Marathon or Kubernetes for Mesos.

Marathon is a cluster-wide init and control system for running Linux services in cgroups and Docker containers. Marathon has a number of different canary deploy features and is a very mature project.

Marathon runs on top of Mesos, which is a highly scalable, battle tested and flexible resource manager. Marathon is proven to scale and runs in many production environments.

The Mesos and Mesosphere technology stack provides a cloud-like environment for running existing Linux workloads, but it also provides a native environment for building new distributed systems.

Mesos is a distributed systems kernel, with a full API for programming directly against the datacenter. It abstracts underlying hardware (e.g. bare metal or VMs) away and just exposes the resources. It contains primitives for writing distributed applications (e.g. Spark was originally a Mesos App, Chronos, etc.) such as Message Passing, Task Execution, etc. Thus, entirely new applications are made possible. Apache Spark is one example for a new (in Mesos jargon called) framework that was built originally for Mesos. This enabled really fast development - the developers of Spark didn't have to worry about networking to distribute tasks amongst nodes as this is a core primitive in Mesos.

To my knowledge, Kubernetes is not used inside Google in production deployments today. For production, Google uses Omega/Borg, which is much more similar to the Mesos/Marathon model. However the great thing about using Mesos as the foundation is that both Kubernetes and Marathon can run on top of it.

More resources about Marathon:

https://mesosphere.github.io/marathon/

Video: https://www.youtube.com/watch?v=hZNGST2vIds

Java LinkedHashMap get first or last entry

Perhaps something like this :

LinkedHashMap<Integer, String> myMap;

public String getFirstKey() {
  String out = null;
  for (int key : myMap.keySet()) {
    out = myMap.get(key);
    break;
  }
  return out;
}

public String getLastKey() {
  String out = null;
  for (int key : myMap.keySet()) {
    out = myMap.get(key);
  }
  return out;
}

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

How to join two tables by multiple columns in SQL?

No, just include the different fields in the "ON" clause of 1 inner join statement:

SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
    AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

Passing ArrayList from servlet to JSP

In the servlet code, with the instruction request.setAttribute("servletName", categoryList), you save your list in the request object, and use the name "servletName" for refering it.
By the way, using then name "servletName" for a list is quite confusing, maybe it's better call it "list" or something similar: request.setAttribute("list", categoryList)
Anyway, suppose you don't change your serlvet code, and store the list using the name "servletName". When you arrive to your JSP, it's necessary to retrieve the list from the request, and for that you just need the request.getAttribute(...) method.

<%  
// retrieve your list from the request, with casting 
ArrayList<Category> list = (ArrayList<Category>) request.getAttribute("servletName");

// print the information about every category of the list
for(Category category : list) {
    out.println(category.getId());
    out.println(category.getName());
    out.println(category.getMainCategoryId());
}
%>

addEventListener in Internet Explorer

EDIT

I wrote a snippet that emulate the EventListener interface and the ie8 one, is callable even on plain objects: https://github.com/antcolag/iEventListener/blob/master/iEventListener.js

OLD ANSWER

this is a way for emulate addEventListener or attachEvent on browsers that don't support one of those
hope will help

(function (w,d) {  // 
    var
        nc  = "", nu    = "", nr    = "", t,
        a   = "addEventListener",
        n   = a in w,
        c   = (nc = "Event")+(n?(nc+= "", "Listener") : (nc+="Listener","") ),
        u   = n?(nu = "attach", "add"):(nu = "add","attach"),
        r   = n?(nr = "detach","remove"):(nr = "remove","detach")
/*
 * the evtf function, when invoked, return "attach" or "detach" "Event" functions if we are on a new browser, otherwise add "add" or "remove" "EventListener"
 */
    function evtf(whoe){return function(evnt,func,capt){return this[whoe]((n?((t = evnt.split("on"))[1] || t[0]) : ("on"+evnt)),func, (!n && capt? (whoe.indexOf("detach") < 0 ? this.setCapture() : this.removeCapture() ) : capt  ))}}
    w[nu + nc] = Element.prototype[nu + nc] = document[nu + nc] = evtf(u+c) // (add | attach)Event[Listener]
    w[nr + nc] = Element.prototype[nr + nc] = document[nr + nc] = evtf(r+c) // (remove | detach)Event[Listener]

})(window, document)

How can I check out a GitHub pull request with git?

I prefer to fetch and checkout without creating a local branch and to be in HEAD detached state. It allows me quickly to check the pull request without polluting my local machine with unnecessary local branches.

git fetch upstream pull/ID/head && git checkout FETCH_HEAD

where ID is a pull request ID and upstream where is original pull request has been created (it could be origin, for example).

I hope it helps.

How to restart a windows service using Task Scheduler

Instead of using a bat file, you can simply create a Scheduled Task. Most of the time you define just one action. In this case, create two actions with the NET command. The first one to stop the service, the second one to start the service. Give them a STOP and START argument, followed by the service name.

In this example we restart the Printer Spooler service.

NET STOP "Print Spooler" 
NET START "Print Spooler"

enter image description here

enter image description here

Note: unfortunately NET RESTART <service name> does not exist.

PHP Warning: Unknown: failed to open stream

Check dos and unix file format. This problem is seen on linux platforms if dos file format is used. Use doc2unix command like below and then retry it should work dos2unix *.php

This solution for below problem

Wed Nov 12 07:50:19 2014] [error] [client IP1] PHP Warning: Unknown: failed to
    open stream: Permission denied in Unknown on line 0
[Wed Nov 12 07:50:19 2014] [error] [client IP1] PHP Fatal error: Unknown: Failed
    opening required '/var/www/html/index.php' (include_path='.:/usr/share/pear:
    /usr/share/php') in Unknown on line 0

How can I access the MySQL command line with XAMPP for Windows?

  1. Open the XAMPP control panel.
  2. Click Shell.
  3. Type mysql --user=your_user_name --password=your_password.

How can I select all options of multi-select select box on click?

For jQuery versions 1.6+ then

$('#select_all').click( function() {
    $('#countries option').prop('selected', true);
});

Or for older versions:

$('#select_all').click( function() {
    $('#countries option').attr('selected', 'selected');
});

LIVE DEMO

Increment variable value by 1 ( shell programming)

you can use bc as it can also do floats

var=$(echo "1+2"|bc)

Remove xticks in a matplotlib plot?

Here is an alternative solution that I found on the matplotlib mailing list:

import matplotlib.pylab as plt

x = range(1000)
ax = plt.axes()
ax.semilogx(x, x)
ax.xaxis.set_ticks_position('none') 

graph

Initialising an array of fixed size in python

An easy solution is x = [None]*length, but note that it initializes all list elements to None. If the size is really fixed, you can do x=[None,None,None,None,None] as well. But strictly speaking, you won't get undefined elements either way because this plague doesn't exist in Python.

Python read JSON file and modify

try this script:

with open("data.json") as f:
    data = json.load(f)
    data["id"] = 134
    json.dump(data, open("data.json", "w"), indent = 4)

the result is:

{
    "name":"mynamme",
    "id":134
}

Just the arrangement is different, You can solve the problem by converting the "data" type to a list, then arranging it as you wish, then returning it and saving the file, like that:

index_add = 0
with open("data.json") as f:
    data = json.load(f)
    data_li = [[k, v] for k, v in data.items()]
    data_li.insert(index_add, ["id", 134])
    data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
    json.dump(data, open("data.json", "w"), indent = 4)

the result is:

{
    "id":134,
    "name":"myname"
}

you can add if condition in order not to repeat the key, just change it, like that:

index_add = 0
n_k = "id"
n_v = 134
with open("data.json") as f:
    data = json.load(f)
    if n_k in data:
        data[n_k] = n_v
    else:
       data_li = [[k, v] for k, v in data.items()]
       data_li.insert(index_add, [n_k, n_v])
       data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
    json.dump(data, open("data.json", "w"), indent = 4)

DateTime format to SQL format using C#

try this below

DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");

How do I overload the square-bracket operator in C#?

If you're using C# 6 or later, you can use expression-bodied syntax for get-only indexer:

public object this[int i] => this.InnerList[i];

Find records from one table which don't exist in another

SELECT Call.ID, Call.date, Call.phone_number 
FROM Call 
LEFT OUTER JOIN Phone_Book 
  ON (Call.phone_number=Phone_book.phone_number) 
  WHERE Phone_book.phone_number IS NULL

Should remove the subquery, allowing the query optimiser to work its magic.

Also, avoid "SELECT *" because it can break your code if someone alters the underlying tables or views (and it's inefficient).

FCM getting MismatchSenderId

You will have a server key something like this AIzaSyDiTEVq4Li1pj7IyraRlyRU9adc-49-KVY available in the Settings section of firebase console console.firebase.google.com/project/project-XXXXXXXXXXXXX/settings/cloudmessaging.

Specify the correct key with your code and try again.

How to Specify Eclipse Proxy Authentication Credentials?

I struggle with this constantly, as it seems it is a different solution every time a new version of Eclipse is released. Here is a solution that doesn't involve displaying your password in the .ini file.

In Eclipse go to Window > Preferences > General > security Secure Storage

In the Password tab click on the "Change Password" button Fill in the security questions. Don't make them to hard. Finish

Now go to Window > Preferences > General > Network connections. Choose "Manual" from drop down. Double click "HTTP" option and enter the Host, Port, Username and Password. Finish

Now go to Window > Preferences > General > security Secure Storage

In the Password tab click on the "Recover Password" button Fill in the security questions. Finish

Eclipse now stores your username and password

Replacing last character in a String with java

i want to replace last ',' with space

if (fieldName.endsWith(",")) {
    fieldName = fieldName.substring(0, fieldName.length() - 1) + " ";
}

If you want to remove the trailing comma, simply get rid of the + " ".

Mockito - difference between doReturn() and when()

Continuing this answer, There is another difference that if you want your method to return different values for example when it is first time called, second time called etc then you can pass values so for example...

PowerMockito.doReturn(false, false, true).when(SomeClass.class, "SomeMethod", Matchers.any(SomeClass.class));

So it will return false when the method is called in same test case and then it will return false again and lastly true.

Bat file to run a .exe at the command prompt

Just put that line in the bat file...

Alternatively you can even make a shortcut for svcutil.exe, then add the arguments in the 'target' window.

SQL Server Management Studio missing

Did you include "Management Tools" as a chosen option during setup?

enter image description here

Ensure this option is selected, and SQL Server Management Studio will be installed on the machine.

How to change Apache Tomcat web server port number

You need to edit the Tomcat/conf/server.xml and change the connector port. The connector setting should look something like this:

<Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

Just change the connector port from default 8080 to another valid port number.

What is the proper #include for the function 'sleep()'?

sleep is a non-standard function.

  • On UNIX, you shall include <unistd.h>.
  • On MS-Windows, Sleep is rather from <windows.h>.

In every case, check the documentation.

How update the _id of one MongoDB Document?

In case, you want to rename _id in same collection (for instance, if you want to prefix some _ids):

db.someCollection.find().snapshot().forEach(function(doc) { 
   if (doc._id.indexOf("2019:") != 0) {
       print("Processing: " + doc._id);
       var oldDocId = doc._id;
       doc._id = "2019:" + doc._id; 
       db.someCollection.insert(doc);
       db.someCollection.remove({_id: oldDocId});
   }
});

if (doc._id.indexOf("2019:") != 0) {... needed to prevent infinite loop, since forEach picks the inserted docs, even throught .snapshot() method used.

Remove Backslashes from Json Data in JavaScript

Your string is invalid, but assuming it was valid, you'd have to do:

var finalData = str.replace(/\\/g, "");

When you want to replace all the occurences with .replace, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.

Cheers

OperationalError: database is locked

Just close (stop) and open (start) the database. This solved my problem.

How to run mysql command on bash?

This one worked, double quotes when $user and $password are outside single quotes. Single quotes when inside a single quote statement.

mysql --user="$user" --password="$password" --database="$user" --execute='DROP DATABASE '$user'; CREATE DATABASE '$user';'

How can I insert multiple rows into oracle with a sequence value?

insert into TABLE_NAME
(COL1,COL2)
WITH
data AS
(
    select 'some value'    x from dual
    union all
    select 'another value' x from dual
)
SELECT my_seq.NEXTVAL, x 
FROM data
;

I think that is what you want, but i don't have access to oracle to test it right now.

Php, wait 5 seconds before executing an action

or:

usleep(NUMBER_OF_MICRO_SECONDS);

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Using this HTML:

<div id="myElement" style="position: absolute">This stays at the top</div>

This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.

$(window).scroll(function() {
    $('#myElement').css('top', $(this).scrollTop() + "px");
});

As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's debounce/throttle plugin to reduce overhead.

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

https://cdn.rawgit.com is shutting down. Thus, one of the alternate options can be used. JSDeliver is a free cdn that can be used.

// load any GitHub release, commit, or branch

// note: we recommend using npm for projects that support it

https://cdn.jsdelivr.net/gh/user/repo@version/file

// load jQuery v3.2.1

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

// use a version range instead of a specific version

https://cdn.jsdelivr.net/gh/jquery/[email protected]/dist/jquery.min.js

https://cdn.jsdelivr.net/gh/jquery/jquery@3/dist/jquery.min.js

// omit the version completely to get the latest one

// you should NOT use this in production

https://cdn.jsdelivr.net/gh/jquery/jquery/dist/jquery.min.js

// add ".min" to any JS/CSS file to get a minified version

// if one doesn't exist, we'll generate it for you

https://cdn.jsdelivr.net/gh/jquery/[email protected]/src/core.min.js

// add / at the end to get a directory listing

https://cdn.jsdelivr.net/gh/jquery/jquery/

ref - https://www.jsdelivr.com/?docs=gh

How to download Visual Studio 2017 Community Edition for offline installation?

  • Saved the "vs_professional.exe" in my user Download directory, didn't work in any other disk or path.
  • Installed the certificate, without the reboot.
  • Executed the customized (2 languages and some workloads) command from administrative Command Prompt window targetting an offline root folder on a secondary disk "E:\vs2017offline".

Never thought MS could distribute this way, I understand that people downloading Visual Studio should have advanced knowledge of computers and OS but this is like a jump in time to 30 years back.

AttributeError: Module Pip has no attribute 'main'

To verify whether is your pip installation problem, try using easy_install to install an earlier version of pip:

easy_install pip==9.0.1

If this succeed, pip should be working now. Then you can go ahead to install any other version of pip you want with:

pip install pip==10....

Or you can just stay with version 9.0.1, as your project requires version >= 9.0.

Try building your project again.

how to display full stored procedure code?

Normally speaking you'd use a DB manager application like pgAdmin, browse to the object you're interested in, and right click your way to "script as create" or similar.

Are you trying to do this... without a management app?

How to check if an item is selected from an HTML drop down list?

Well you missed quotation mark around your string selectcard it should be "selectcard"

if (card.value == selectcard)

should be

if (card.value == "selectcard")

Here is complete code for that

function validate()
{
 var ddl = document.getElementById("cardtype");
 var selectedValue = ddl.options[ddl.selectedIndex].value;
    if (selectedValue == "selectcard")
   {
    alert("Please select a card type");
   }
}

JS Fiddle Demo

Deleting specific rows from DataTable

I'm seeing various bits and pieces of the right answer here, but let me bring it all together and explain a couple of things.

First of all, AcceptChanges should only be used to mark the entire transaction on a table as being validated and committed. Which means if you are using the DataTable as a DataSource for binding to, for example, an SQL server, then calling AcceptChanges manually will guarantee that that the changes never get saved to the SQL server.

What makes this issue more confusing is that there are actually two cases in which the exception is thrown and we have to prevent both of them.

1. Modifying an IEnumerable's Collection

We can't add or remove an index to the collection being enumerated because doing so may affect the enumerator's internal indexing. There are two ways to get around this: either do your own indexing in a for loop, or use a separate collection (that is not modified) for the enumeration.

2. Attempting to Read a Deleted Entry

Since DataTables are transactional collections, entries can be marked for deletion but still appear in the enumeration. Which means that if you ask a deleted entry for the column "name" then it will throw an exception. Which means we must check to see whether dr.RowState != DataRowState.Deleted before querying a column.

Putting it all together

We could get messy and do all of that manually, or we can let the DataTable do all the work for us and make the statement look and at more like an SQL call by doing the following:

string name = "Joe";
foreach(DataRow dr in dtPerson.Select($"name='{name}'"))
    dr.Delete();

By calling DataTable's Select function, our query automatically avoids already deleted entries in the DataTable. And since the Select function returns an array of matches, the collection we are enumerating over is not modified when we call dr.Delete(). I've also spiced up the Select expression with string interpolation to allow for variable selection without making the code noisy.

How do I create a new column from the output of pandas groupby().sum()?

You want to use transform this will return a Series with the index aligned to the df so you can then add it as a new column:

In [74]:

df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
   Data2  Data3        Date   Sym  Data4
0     11      5  2015-05-08  aapl     55
1      8      8  2015-05-07  aapl    108
2     10      6  2015-05-06  aapl     66
3     15      1  2015-05-05  aapl    121
4    110     50  2015-05-08  aaww     55
5     60    100  2015-05-07  aaww    108
6    100     60  2015-05-06  aaww     66
7     40    120  2015-05-05  aaww    121

Passing a string array as a parameter to a function java

I believe this should be the way this is done...

public void function(String [] array){
....
}

And the calling will be done like...

public void test(){
    String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k","l","k"};
    function(stringArray);
}

Checking if type == list in python

This seems to work for me:

>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

If you don't want to change your Java version (I don't), you can temporarily change the version in your shell:

First run

/usr/libexec/java_home -V

Then pick a major version if you have it installed, otherwise install it first:

export JAVA_HOME=`/usr/libexec/java_home -v 1.8`

Now you can run sdkmanager.

Set textbox to readonly and background color to grey in jquery

As per you question this is what you can do

HTML

<textarea id='sample'>Area adskds;das;dsald da'adslda'daladhkdslasdljads</textarea>

JS/Jquery

$(function () {
    $('#sample').attr('readonly', 'true'); // mark it as read only
    $('#sample').css('background-color' , '#DEDEDE'); // change the background color
});

or add a class in you css with the required styling

$('#sample').addClass('yourclass');

DEMO

Let me know if the requirement was different

How to make custom dialog with rounded corners in android

I made a new way without having a background drawable is that make it have CardView as parent and give it a app:cardCornerRadius="20dp" and then add this in the java class dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

It's another way to make it .

Why does ENOENT mean "No such file or directory"?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This happens when Elasticsearch thinks the disk is running low on space so it puts itself into read-only mode.

By default Elasticsearch's decision is based on the percentage of disk space that's free, so on big disks this can happen even if you have many gigabytes of free space.

The flood stage watermark is 95% by default, so on a 1TB drive you need at least 50GB of free space or Elasticsearch will put itself into read-only mode.

For docs about the flood stage watermark see https://www.elastic.co/guide/en/elasticsearch/reference/6.2/disk-allocator.html.

The right solution depends on the context - for example a production environment vs a development environment.

Solution 1: free up disk space

Freeing up enough disk space so that more than 5% of the disk is free will solve this problem. Elasticsearch won't automatically take itself out of read-only mode once enough disk is free though, you'll have to do something like this to unlock the indices:

$ curl -XPUT -H "Content-Type: application/json" https://[YOUR_ELASTICSEARCH_ENDPOINT]:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

Solution 2: change the flood stage watermark setting

Change the "cluster.routing.allocation.disk.watermark.flood_stage" setting to something else. It can either be set to a lower percentage or to an absolute value. Here's an example of how to change the setting from the docs:

PUT _cluster/settings
{
  "transient": {
    "cluster.routing.allocation.disk.watermark.low": "100gb",
    "cluster.routing.allocation.disk.watermark.high": "50gb",
    "cluster.routing.allocation.disk.watermark.flood_stage": "10gb",
    "cluster.info.update.interval": "1m"
  }
}

Again, after doing this you'll have to use the curl command above to unlock the indices, but after that they should not go into read-only mode again.

MySQLDump one INSERT statement for each data row

In newer versions change was made to the flags: from the documentation:

--extended-insert, -e

Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.

--opt

This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.

Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.

--skip-extended-insert

Turn off extended-insert

How to remove the arrow from a select element in Firefox

I know this question is a bit old, but since it turns up on google, and this is a "new" solution:

appearance: normal Seems to work fine in Firefox for me (version 5 now). but not in Opera and IE8/9

As a workaround for Opera and IE9, I used the :before pseudoselector to create a new white box and put that on top of the arrow.

Unfortunately, In IE8 this doesn't work. The box is rendered correctly, but the arrow just sticks out anyway... :-/

Using select:before works fine in Opera, but not in IE. If I look at the developer tools, I see it is reading the rules correctly, and then just ignores them (they're crossed out). So I use a <span class="selectwrap"> around the actual <select>.

select {
  -webkit-appearance: normal;
  -moz-appearance: normal;
  appearance: normal;
}
.selectwrap { position: relative; }
.selectwrap:before {
  content: "";
  height: 0;
  width: 0;
  border: .9em solid red;
  background-color: red;
  position: absolute;
  right: -.1em;
  z-index: 42;
}

You may need to tweak this a bit, but this works for me!

Disclaimer: I'm using this to get a good looking hardcopy of a webpage with forms so I don't need to create a second page. I'm not a 1337 haxx0r who wants red scrollbars, <marquee> tags, and whatnot :-) Please do not apply excessive styling to forms unless you have a very good reason.

What is the difference between declarative and imperative paradigm in programming?

A great C# example of declarative vs. imperative programming is LINQ.

With imperative programming, you tell the compiler what you want to happen, step by step.

For example, let's start with this collection, and choose the odd numbers:

List<int> collection = new List<int> { 1, 2, 3, 4, 5 };

With imperative programming, we'd step through this, and decide what we want:

List<int> results = new List<int>();
foreach(var num in collection)
{
    if (num % 2 != 0)
          results.Add(num);
}

Here, we're saying:

  1. Create a result collection
  2. Step through each number in the collection
  3. Check the number, if it's odd, add it to the results

With declarative programming, on the other hand, you write code that describes what you want, but not necessarily how to get it (declare your desired results, but not the step-by-step):

var results = collection.Where( num => num % 2 != 0);

Here, we're saying "Give us everything where it's odd", not "Step through the collection. Check this item, if it's odd, add it to a result collection."

In many cases, code will be a mixture of both designs, too, so it's not always black-and-white.

how to set the background image fit to browser using html

add this css in your stylesheet

body
    {
        background:url(Desert.jpg) no-repeat center center fixed;
        background-size: cover;
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        margin: 0;
        padding: 0;
    }

FIDDLE

How to get the number of characters in a std::string?

Simplest way to get length of string without bothering about std namespace is as follows

string with/without spaces

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str;
    getline(cin,str);
    cout<<"Length of given string is"<<str.length();
    return 0;
}

string without spaces

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str;
    cin>>str;
    cout<<"Length of given string is"<<str.length();
    return 0;
}

scp via java

I use this SFTP API which has SCP called Zehon, it's great, so easy to use with a lot of sample code. Here is the site http://www.zehon.com

How to add an image to a JPanel?

I'm doing something very similar in a private project I'm working on. Thus far I've generated images up to 1024x1024 without any problems (except memory) and can display them very quickly and without any performance problems.

Overriding the paint method of JPanel subclass is overkill and requires more work than you need to do.

The way I do it is:

Class MapIcon implements Icon {...}

OR

Class MapIcon extends ImageIcon {...}

The code you use to generate the image will be in this class. I use a BufferedImage to draw onto then when the paintIcon() is called, use g.drawImvge(bufferedImage); This reduces the amount of flashing done while you generate your images, and you can thread it.

Next I extend JLabel:

Class MapLabel extends Scrollable, MouseMotionListener {...}

This is because I want to put my image on a scroll pane, I.e. display part of the image and have the user scroll around as needed.

So then I use a JScrollPane to hold the MapLabel, which contains only the MapIcon.

MapIcon map = new MapIcon (); 
MapLabel mapLabel = new MapLabel (map);
JScrollPane scrollPane = new JScrollPane();

scrollPane.getViewport ().add (mapLabel);

But for your scenario (just show the whole image every time). You need to add the MapLabel to the top JPanel, and make sure to size them all to the full size of the image (by overriding the GetPreferredSize()).

How can I position my div at the bottom of its container?

Maybe this helps someone: You can always place the div outside the other div and then push it upwards using negative margin:

<div id="container" style="background-color: #ccc; padding-bottom: 30px;">
  Hello!
</div>
<div id="copyright" style="margin-top: -20px;">
  Copyright Foo web designs
</div>

How do you stylize a font in Swift?

Xamarin

Label.Font = UIFont.FromName("Copperplate", 10.0f);

Swift

text.font = UIFont.init(name: "Poppins-Regular", size: 14)

To get the list of font family Github/IOS-UIFont-Names

TypeError: 'builtin_function_or_method' object is not subscriptable

You are trying to access pop as if was a list or a tupple, but pop is not. It's a method.

Set cellpadding and cellspacing in CSS?

In an HTML table, the cellpadding and cellspacing can be set like this:

For cell-padding:

Just call simple td/th cell padding.

Example:

_x000D_
_x000D_
/******Call-Padding**********/_x000D_
_x000D_
table {_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td {_x000D_
  border: 1px solid red;_x000D_
  padding: 10px;_x000D_
}
_x000D_
<table>_x000D_
        <tr>_x000D_
            <th>Head1 </th>_x000D_
            <th>Head2 </th>_x000D_
            <th>Head3 </th>_x000D_
            <th>Head4 </th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>11</td>_x000D_
            <td>12</td>_x000D_
            <td>13</td>_x000D_
            <td>14</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>21</td>_x000D_
            <td>22</td>_x000D_
            <td>23</td>_x000D_
            <td>24</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>31</td>_x000D_
            <td>32</td>_x000D_
            <td>33</td>_x000D_
            <td>34</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>41</td>_x000D_
            <td>42</td>_x000D_
            <td>43</td>_x000D_
            <td>44</td>_x000D_
        </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

table {
    border-collapse: collapse;
}

td {
  border: 1px solid red;
  padding: 10px;
}

For cell-spacing

Just call simple table border-spacing

Example:

_x000D_
_x000D_
/********* Cell-Spacing   ********/_x000D_
table {_x000D_
    border-spacing: 10px;_x000D_
    border-collapse: separate;_x000D_
}_x000D_
_x000D_
td {_x000D_
  border: 1px solid red;_x000D_
}
_x000D_
<table>_x000D_
        <tr>_x000D_
            <th>Head1</th>_x000D_
            <th>Head2</th>_x000D_
            <th>Head3</th>_x000D_
            <th>Head4</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>11</td>_x000D_
            <td>12</td>_x000D_
            <td>13</td>_x000D_
            <td>14</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>21</td>_x000D_
            <td>22</td>_x000D_
            <td>23</td>_x000D_
            <td>24</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>31</td>_x000D_
            <td>32</td>_x000D_
            <td>33</td>_x000D_
            <td>34</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>41</td>_x000D_
            <td>42</td>_x000D_
            <td>43</td>_x000D_
            <td>44</td>_x000D_
        </tr>_x000D_
    </table>
_x000D_
_x000D_
_x000D_

/********* Cell-Spacing   ********/
table {
    border-spacing: 10px;
    border-collapse: separate;
}

td {
  border: 1px solid red;
}

More table style by CSS source link here you get more table style by CSS.

Best way to serialize/unserialize objects in JavaScript?

I had the exact same problem, and written a small tool to do the mixing of data and model. See https://github.com/khayll/jsmix

This is how you would do it:

//model object (or whatever you'd like the implementation to be)
var Person = function() {}
Person.prototype.isOld = function() {
    return this.age > RETIREMENT_AGE;
}

//then you could say:
var result = JSMix(jsonData).withObject(Person.prototype, "persons").build();

//and use
console.log(result.persons[3].isOld());

It can handle complex objects, like nested collections recursively as well.

As for serializing JS functions, I wouldn't do such thing because of security reasons.

Remove a HTML tag but keep the innerHtml

You can also use .replaceWith(), like this:

$("b").replaceWith(function() { return $(this).contents(); });

Or if you know it's just a string:

$("b").replaceWith(function() { return this.innerHTML; });

This can make a big difference if you're unwrapping a lot of elements since either approach above is significantly faster than the cost of .unwrap().

count distinct values in spreadsheet

=iferror(counta(unique(A1:A100))) counts number of unique cells from A1 to A100

How to get last 7 days data from current datetime to last 7 days in sql server

select id,    
NewsHeadline as news_headline,    
NewsText as news_text,    
state,    
CreatedDate as created_on    
from News    
WHERE CreatedDate>=DATEADD(DAY,-7,GETDATE())

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

    [HttpPost]
    public JsonResult ContactAdd(ContactViewModel contactViewModel)
    {
        if (ModelState.IsValid)
        {
            var job = new Job { Contact = new Contact() };

            Mapper.Map(contactViewModel, job);
            Mapper.Map(contactViewModel, job.Contact);

            _db.Jobs.Add(job);

            _db.SaveChanges();

            //you do not even need this line of code,200 is the default for ASP.NET MVC as long as no exceptions were thrown
            //Response.StatusCode = (int)HttpStatusCode.OK;

            return Json(new { jobId = job.JobId });
        }
        else
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(new { jobId = -1 });
        }
    }

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

This could also happen when your app doesn't actually compile, yet it's still launched in Tomcat. When I saw this happen, it wasn't compiling because the project had a "project specific" JDK specified, and the code was checked out on a machine that didn't have that specific JDK. Eclipse defaulted to a JRE instead, not a JDK, and then the app wasn't compiled.

To fix it in our specific case, we just turned off "Project Specific Settings" here:

"Project | Properties | Java Compiler"

Here's more detailed info on how to do this: https://stackoverflow.com/a/2540730/26510

How to display and hide a div with CSS?

You need

.abc,.ab {
    display: none;
}

#f:hover ~ .ab {
    display: block;
}

#s:hover ~ .abc {
    display: block;
}

#s:hover ~ .a,
#f:hover ~ .a{
    display: none;
}

Updated demo at http://jsfiddle.net/gaby/n5fzB/2/


The problem in your original CSS was that the , in css selectors starts a completely new selector. it is not combined.. so #f:hover ~ .abc,.a means #f:hover ~ .abc and .a. You set that to display:none so it was always set to be hidden for all .a elements.

How can I add a vertical scrollbar to my div automatically?

To show vertical scroll bar in your div you need to add

height: 100px;   
overflow-y : scroll;

or

height: 100px; 
overflow-y : auto;

In VBA get rid of the case sensitivity when comparing words?

You can convert both the values to lower case and compare.

Here is an example:

If LCase(Range("J6").Value) = LCase("Tawi") Then
   Range("J6").Value = "Tawi-Tawi"
End If

Create an Excel file using vbscripts

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = true
Set objWorkbook = objExcel.Workbooks.Add()
Set objWorksheet = objWorkbook.Worksheets(1)

intRow = 2
dim ch
objWorksheet.Cells(1,1) = "Name"
objWorksheet.Cells(1,2) = "Subject1"
objWorksheet.Cells(1,3) = "Subject2"
objWorksheet.Cells(1,4) = "Total"
for intRow = 2 to  10000 
name= InputBox("Enter your name")
sb1 = cint(InputBox("Enter your Marks in Subject 1"))
sb2 = cint(InputBox("Enter your Marks in Subject 2"))
total= sb1+sb2+sb3+sb4
objExcel.Cells(intRow, 1).Value = name
objExcel.Cells(intRow, 2).Value = sb1
objExcel.Cells(intRow, 3).Value = sb2
objExcel.Cells(intRow, 4).Value = total
ch = InputBox("Do you want continue..? if no then type no or y to continue")
    If ch = "no" Then Exit For 
Next

objExcel.Cells.EntireColumn.AutoFit

MsgBox "Done"
enter code here

How can I get npm start at a different directory?

This one-liner should work too:

(cd /path/to/your/app && npm start)

Note that the current directory will be changed to /path/to/your/app after executing this command. To preserve the working directory:

(cd /path/to/your/app && npm start && cd -)

I used this solution because a program configuration file I was editing back then didn't support specifying command line arguments.

How can I search Git branches for a file or directory?

git ls-tree might help. To search across all existing branches:

for branch in `git for-each-ref --format="%(refname)" refs/heads`; do
  echo $branch :; git ls-tree -r --name-only $branch | grep '<foo>'
done

The advantage of this is that you can also search with regular expressions for the file name.

Double precision - decimal places

It is actually 53 binary places, which translates to 15 stable decimal places, meaning that if you round a start out with a number with 15 decimal places, convert it to a double, and then round the double back to 15 decimal places you'll get the same number. To uniquely represent a double you need 17 decimal places (meaning that for every number with 17 decimal places, there's a unique closest double) which is why 17 places are showing up, but not all 17-decimal numbers map to different double values (like in the examples in the other answers).

How to check how many letters are in a string in java?

A)

String str = "a string";
int length = str.length( ); // length == 8

http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29

edit

If you want to count the number of a specific type of characters in a String, then a simple method is to iterate through the String checking each index against your test case.

int charCount = 0;
char temp;

for( int i = 0; i < str.length( ); i++ )
{
    temp = str.charAt( i );

    if( temp.TestCase )
        charCount++;
}

where TestCase can be isLetter( ), isDigit( ), etc.

Or if you just want to count everything but spaces, then do a check in the if like temp != ' '

B)

String str = "a string";
char atPos0 = str.charAt( 0 ); // atPos0 == 'a'

http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29

How to give a delay in loop execution using Qt

C++11 has some portable timer stuff. Check out sleep_for.

How to put labels over geom_bar for each bar in R with ggplot2

To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
 geom_bar(position = "dodge", stat = 'identity') +
 geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)

Error Dropping Database (Can't rmdir '.test\', errno: 17)

Just to add to the responses so far: In Windows 10, the data files are kept here...

C:\ProgramData\MySQL\MySQL Server [m.n]\data

There will be directories for each schema in your database. You will want to go inside the schema you are trying to drop, manually delete any superfluous files then try the drop command again.

Any workbench changes against a database will get stored in this location. For example, I had this error following a reverse engineering exercise on one of my databases and saving the changes which get stored in a .mwb file in this location.

How to kill a nodejs process in Linux?

You can use the killall command as follows:

killall node

Terminal Commands: For loop with echo

The default shell on OS X is bash. You could write this:

for i in {1..100}; do echo http://www.example.com/${i}.jpg; done

Here is a link to the reference manual of bash concerning loop constructs.

How can I convert tabs to spaces in every file of a directory?

One can use vim for that:

find -type f \( -name '*.css' -o -name '*.html' -o -name '*.js' -o -name '*.php' \) -execdir vim -c retab -c wq {} \;

As Carpetsmoker stated, it will retab according to your vim settings. And modelines in the files, if any. Also, it will replace tabs not only at the beginning of the lines. Which is not what you generally want. E.g., you might have literals, containing tabs.

Unix tail equivalent command in Windows Powershell

Very basic, but does what you need without any addon modules or PS version requirements:

while ($true) {Clear-Host; gc E:\test.txt | select -last 3; sleep 2 }

How to sort an array of objects by multiple fields?

I was looking for something similar and ended up with this:

First we have one or more sorting functions, always returning either 0, 1 or -1:

const sortByTitle = (a, b): number => 
  a.title === b.title ? 0 : a.title > b.title ? 1 : -1;

You can create more functions for each other property you want to sort on.

Then I have a function that combines these sorting functions into one:

const createSorter = (...sorters) => (a, b) =>
  sorters.reduce(
    (d, fn) => (d === 0 ? fn(a, b) : d),
    0
  );

This can be used to combine the above sorting functions in a readable way:

const sorter = createSorter(sortByTitle, sortByYear)

items.sort(sorter)

When a sorting function returns 0 the next sorting function will be called for further sorting.

In Javascript, how to conditionally add a member to an object?

What about using Enhanced Object Properties and only set the property if it is truthy, e.g.:

[isConditionTrue() && 'propertyName']: 'propertyValue'

So if the condition is not met it doesn't create the preferred property and thus you can discard it. See: http://es6-features.org/#ComputedPropertyNames

UPDATE: It is even better to follow the approach of Axel Rauschmayer in his blog article about conditionally adding entries inside object literals and arrays (http://2ality.com/2017/04/conditional-literal-entries.html):

const arr = [
  ...(isConditionTrue() ? [{
    key: 'value'
  }] : [])
];

const obj = {
  ...(isConditionTrue() ? {key: 'value'} : {})
};

Quite helped me a lot.

Get url parameters from a string in .NET

I used it and it run perfectly

<%=Request.QueryString["id"] %>

Add Variables to Tuple

" once the info is added to the DB, should I delete the tuple? i mean i dont need the tuple anymore."

No.

Generally, there's no reason to delete anything. There are some special cases for deleting, but they're very, very rare.

Simply define a narrow scope (i.e., a function definition or a method function in a class) and the objects will be garbage collected at the end of the scope.

Don't worry about deleting anything.

[Note. I worked with a guy who -- in addition to trying to delete objects -- was always writing "reset" methods to clear them out. Like he was going to save them and reuse them. Also a silly conceit. Just ignore the objects you're no longer using. If you define your functions in small-enough blocks of code, you have nothing more to think about.]

How do I commit case-sensitive only filename changes in Git?

We can use git mv command. Example below , if we renamed file abcDEF.js to abcdef.js then we can run the following command from terminal

git mv -f .\abcDEF.js  .\abcdef.js

How to open this .DB file?

I don't think there is a way to tell which program to use from just the .db extension. It could even be an encrypted database which can't be opened. You can MS Access, or a sqlite manager.

Edit: Try to rename the file to .txt and open it with a text editor. The first couple of words in the file could tell you the DB Type.

If it is a SQLite database, it will start with "SQLite format 3"

How to get the browser viewport dimensions?

This code is from http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

NB : to read the width, use console.log('viewport width'+viewport().width);

How to calculate a time difference in C++

just in case you are on Unix, you can use time to get the execution time:

$ g++ myprog.cpp -o myprog
$ time ./myprog

Retrieve a Fragment from a ViewPager

For my case, none of the above solutions worked.

However since I am using the Child Fragment Manager in a Fragment, the following was used:

Fragment f = getChildFragmentManager().getFragments().get(viewPager.getCurrentItem());

This will only work if your fragments in the Manager correspond to the viewpager item.

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

no module named urllib.parse (How should I install it?)

pip install -U websocket 

I just use this to fix my problem

Remote origin already exists on 'git push' to a new repository

You can simply edit your configuration file in a text editor.

In the ~/.gitconfig you need to put in something like the following:

[user]
        name  = Uzumaki Naruto
        email = [email protected]

[github]
        user = myname
        token = ff44ff8da195fee471eed6543b53f1ff

In the oldrep/.git/config file (in the configuration file of your repository):

[remote "github"]
        url = [email protected]:myname/oldrep.git
        push  = +refs/heads/*:refs/heads/*
        push  = +refs/tags/*:refs/tags/*

If there is a remote section in your repository's configuration file, and the URL matches, you need only to add push configuration. If you use a public URL for fetching, you can put in the URL for pushing as 'pushurl' (warning: this requires the just-released Git version 1.6.4).

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

In python, the str() method is similar to the toString() method in other languages. It is called passing the object to convert to a string as a parameter. Internally it calls the __str__() method of the parameter object to get its string representation.

In this case, however, you are comparing a UserProperty author from the database, which is of type users.User with the nickname string. You will want to compare the nickname property of the author instead with todo.author.nickname in your template.

Invalid length parameter passed to the LEFT or SUBSTRING function

That would only happen if PostCode is missing a space. You could add conditionality such that all of PostCode is retrieved should a space not be found as follows

select SUBSTRING(PostCode, 1 ,
case when  CHARINDEX(' ', PostCode ) = 0 then LEN(PostCode) 
else CHARINDEX(' ', PostCode) -1 end)

SQL Server - NOT IN

It's because of the way NOT IN works.

To avoid these headaches (and for a faster query in many cases), I always prefer NOT EXISTS:

SELECT  *  
FROM Table1 t1 
WHERE NOT EXISTS (
    SELECT * 
    FROM Table2 t2 
    WHERE t1.MAKE = t2.MAKE
    AND   t1.MODEL = t2.MODEL
    AND   t1.[Serial Number] = t2.[serial number]);

Format datetime in asp.net mvc 4

Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

    if (!string.IsNullOrEmpty(displayFormat) && value != null)
    {
        DateTime date;
        displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
        // use the format specified in the DisplayFormat attribute to parse the date
         if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
        {
            return date;
        }
        else
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName,
                string.Format("{0} is an invalid date format", value.AttemptedValue)
            );
        }
    }

    return base.BindModel(controllerContext, bindingContext);
}

Hope this could help someone else...

creating batch script to unzip a file without additional zip tools

Another approach to this issue could be to create a self extracting executable (.exe) using something like winzip and use this as the install vector rather than the zip file. Similarly, you could use NSIS to create an executable installer and use that instead of the zip.

"SMTP Error: Could not authenticate" in PHPMailer

SMTP Error: could not authenticate I had the same problem. The following troubleshooting steps helped me.

  • I turned off two-factor authentication in my gmail account.
  • I allowed less secure apps to access my gmail account. To get it working, I had to go to myaccount.google.com -> Sign-in & security -> Apps with account access, and turn Allow less secure apps to ON (near the bottom of the page).
  • At this step, when I tried to register a user, I would get the same error. Google would sent me a warning message that someone has my password and the login was blocked.
  • Gmail will then provide you with options. You either click whether the activity was yours or not yours. Click the option that the activity was yours.
  • Try registration again. It should now work.

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

Is there a way to perform "if" in python's lambda

why don't you just define a function?

def f(x):
    if x == 2:
        print(x)
    else:
        raise ValueError

there really is no justification to use lambda in this case.

dropdownlist set selected value in MVC3 Razor

You should use view models and forget about ViewBag Think of it as if it didn't exist. You will see how easier things will become. So define a view model:

public class MyViewModel
{
    public int SelectedCategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; } 
}

and then populate this view model from the controller:

public ActionResult NewsEdit(int ID, dms_New dsn)
{
    var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
    var categories = (from b in dc.dms_NewsCategories select b).ToList();

    var model = new MyViewModel
    {
        SelectedCategoryId = dsn.NewsCategoriesID,
        Categories = categories.Select(x => new SelectListItem
        {
            Value = x.NewsCategoriesID.ToString(),
            Text = x.NewsCategoriesName
        })
    };
    return View(model);
}

and finally in your view use the strongly typed DropDownListFor helper:

@model MyViewModel

@Html.DropDownListFor(
    x => x.SelectedCategoryId,
    Model.Categories
)

Checking Maven Version

you can use just

     <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version></version>
    </dependency>

What is a 'Closure'?

A simple example in Groovy for your reference:

def outer() {
    def x = 1
    return { -> println(x)} // inner
}
def innerObj = outer()
innerObj() // prints 1

Current Subversion revision command

I think I have to do svn info and then retrieve the number with a string manipulation from "Revision: xxxxxx" It would be just nice, if there were a command that returns just the number :)

How to disable action bar permanently

If you want to get full screen without actionBar and Title.

Add it in style.xml

<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
      <item name="windowActionBar">false</item>
      <item name="windowNoTitle">true</item>
      <item name="android:windowFullscreen">true</item>
</style>

and use the style at manifest.xml.

android:theme="@style/AppTheme.NoActionBar" 

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

May be useful for someone:--

What I have noticed is, if we check the shouldShowRequestPermissionRationale() flag in to onRequestPermissionsResult() callback method, it shows only two states.

State 1:-Return true:-- Any time user clicks Deny permissions (including the very first time).

State 2:-Returns false :- if user selects “never asks again".

Link of detailed working example

How to view the current heap size that an application is using?

Personal favourite for when jvisualvm is overkill or you need cli-only: jvmtop

JvmTop 0.8.0 alpha   amd64  8 cpus, Linux 2.6.32-27, load avg 0.12
https://github.com/patric-r/jvmtop

PID MAIN-CLASS      HPCUR HPMAX NHCUR NHMAX    CPU     GC    VM USERNAME   #T DL
3370 rapperSimpleApp  165m  455m  109m  176m  0.12%  0.00% S6U37 web        21
11272 ver.resin.Resin [ERROR: Could not attach to VM]
27338 WatchdogManager   11m   28m   23m  130m  0.00%  0.00% S6U37 web        31
19187 m.jvmtop.JvmTop   20m 3544m   13m  130m  0.93%  0.47% S6U37 web        20
16733 artup.Bootstrap  159m  455m  166m  304m  0.12%  0.00% S6U37 web        46

Host binding and Host listening

This is the simple example to use both of them:

import {
  Directive, HostListener, HostBinding
}
from '@angular/core';

@Directive({
  selector: '[Highlight]'
})
export class HighlightDirective {
  @HostListener('mouseenter') mouseover() {
    this.backgroundColor = 'green';
  };

  @HostListener('mouseleave') mouseleave() {
    this.backgroundColor = 'white';
  }

  @HostBinding('style.backgroundColor') get setColor() {
     return this.backgroundColor;
  };

  private backgroundColor = 'white';
  constructor() {}

}

Introduction:

  1. HostListener can bind an event to the element.

  2. HostBinding can bind a style to the element.

  3. this is directive, so we can use it for

    Some Text
  4. So according to the debug, we can find that this div has been binded style = "background-color:white"

    Some Text
  5. we also can find that EventListener of this div has two event: mouseenter and mouseleave. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.

Is it possible to decrypt SHA1

SHA1 is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.

However, breaking a SHA1 hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.

So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.

As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod eliminate information from your input. Suppose you calculate mod 5 and you get 0. What was the input? Was it 0, 5 or 500? You see, you can't really 'go back' in this case.

tomcat - CATALINA_BASE and CATALINA_HOME variables

I can't say I know the best practice, but here's my perspective.

Are you using these variables for anything?

Personally, I haven't needed to change neither, on Linux nor Windows, in environments varying from development to production. Unless you are doing something particular that relies on them, chances are you could leave them alone.

catalina.sh sets the variables that Tomcat needs to work out of the box. It also says that CATALINA_BASE is optional:

#   CATALINA_HOME   May point at your Catalina "build" directory.
#
#   CATALINA_BASE   (Optional) Base directory for resolving dynamic portions
#                   of a Catalina installation.  If not present, resolves to
#                   the same directory that CATALINA_HOME points to.

I'm pretty sure you'll find out whether or not your setup works when you start your server.

phpinfo() is not working on my CentOS server

For people who have no experience in building websites (like me) I tried a lot, only to find out that I hadn't used the .php extension, but the .html extension.

How can I scan barcodes on iOS?

If support for the iPad 2 or iPod Touch is important for your application, I'd choose a barcode scanner SDK that can decode barcodes in blurry images, such as our Scandit barcode scanner SDK for iOS and Android. Decoding blurry barcode images is also helpful on phones with autofocus cameras because the user does not have to wait for the autofocus to kick in.

Scandit comes with a free community price plan and also has a product API that makes it easy to convert barcode numbers into product names.

(Disclaimer: I'm a co-founder of Scandit)

Array of arrays (Python/NumPy)

a=np.array([[1,2,3],[4,5,6]])

a.tolist()

tolist method mentioned above will return the nested Python list

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Then, as this blog post suggests,

"How to Cure Net::HTTP’s Risky Default HTTPS Behavior"

you might want to install the always_verify_ssl_certificates gem that allow you to set a default value for ca_file.

How to use multiprocessing pool.map with multiple arguments?

There are many answers here, but none seem to provide Python 2/3 compatible code that will work on any version. If you want your code to just work, this will work for either Python version:

# For python 2/3 compatibility, define pool context manager
# to support the 'with' statement in Python 2
if sys.version_info[0] == 2:
    from contextlib import contextmanager
    @contextmanager
    def multiprocessing_context(*args, **kwargs):
        pool = multiprocessing.Pool(*args, **kwargs)
        yield pool
        pool.terminate()
else:
    multiprocessing_context = multiprocessing.Pool

After that, you can use multiprocessing the regular Python 3 way, however you like. For example:

def _function_to_run_for_each(x):
       return x.lower()
with multiprocessing_context(processes=3) as pool:
    results = pool.map(_function_to_run_for_each, ['Bob', 'Sue', 'Tim'])    print(results)

will work in Python 2 or Python 3.

Laravel 5.2 not reading env file

I missed this in the upgrade instructions:

Add an env configuration option to your app.php configuration file that looks like the following: 'env' => env('APP_ENV', 'production')

Adding this line got the local .env file to be read in correctly.

Activity restart on rotation Android

What you describe is the default behavior. You have to detect and handle these events yourself by adding:

android:configChanges

to your manifest and then the changes that you want to handle. So for orientation, you would use:

android:configChanges="orientation"

and for the keyboard being opened or closed you would use:

android:configChanges="keyboardHidden"

If you want to handle both you can just separate them with the pipe command like:

android:configChanges="keyboardHidden|orientation"

This will trigger the onConfigurationChanged method in whatever Activity you call. If you override the method you can pass in the new values.

Hope this helps.

Maven: add a dependency to a jar by relative path

One small addition to the solution posted by Pascal

When I followed this route, I got an error in maven while installing ojdbc jar.

[INFO] --- maven-install-plugin:2.5.1:install-file (default-cli) @ validator ---
[INFO] pom.xml not found in ojdbc14.jar

After adding -DpomFile, the problem was resolved.

$ mvn install:install-file -Dfile=./lib/ojdbc14.jar -DgroupId=ojdbc \
   -DartifactId=ojdbc -Dversion=14 -Dpackaging=jar -DlocalRepositoryPath=./repo \
   -DpomFile=~/.m2/repository/ojdbc/ojdbc/14/ojdbc-14.pom

How to center a button within a div?

Responsive way to center your button in a div:

<div 
    style="display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 2rem;">
    <button type="button" style="height: 10%; width: 20%;">hello</button>
</div>

Difference between timestamps with/without time zone in PostgreSQL

Timestamptz vs Timestamp

The timestamptz field in Postgres is basically just the timestamp field where Postgres actually just stores the “normalised” UTC time, even if the timestamp given in the input string has a timezone.

If your input string is: 2018-08-28T12:30:00+05:30 , when this timestamp is stored in the database, it will be stored as 2018-08-28T07:00:00.

The advantage of this over the simple timestamp field is that your input to the database will be timezone independent, and will not be inaccurate when apps from different timezones insert timestamps, or when you move your database server location to a different timezone.

To quote from the docs:

For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system’s TimeZone parameter, and is converted to UTC using the offset for the timezone zone. To give a simple analogy, a timestamptz value represents an instant in time, the same instant for anyone viewing it. But a timestamp value just represents a particular orientation of a clock, which will represent different instances of time based on your timezone.

For pretty much any use case, timestamptz is almost always a better choice. This choice is made easier with the fact that both timestamptz and timestamp take up the same 8 bytes of data.

source: https://hasura.io/blog/postgres-date-time-data-types-on-graphql-fd926e86ee87/

@Media min-width & max-width

for some iPhone you have to put your viewport like this

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, shrink-to-fit=no, user-scalable=0" />

How do I schedule a task to run at periodic intervals?

public void schedule(TimerTask task,long delay)

Schedules the specified task for execution after the specified delay.

you want:

public void schedule(TimerTask task, long delay, long period)

Schedules the specified task for repeated fixed-delay execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals separated by the specified period.

Renew Provisioning Profile

They change how this works so often. This is what I had to do this time (May 2016):

  • Add a new provisioning profile in the Developer Member Center
  • Open XCode preferences, Account > Choose Apple ID > Choose Team Name > View Details
  • Click the Download button in the Action column for the newly-created provisioning profile

Python 3 turn range to a list

Use Range in Python 3.

Here is a example function that return in between numbers from two numbers

def get_between_numbers(a, b):
    """
    This function will return in between numbers from two numbers.
    :param a:
    :param b:
    :return:
    """
    x = []
    if b < a:
        x.extend(range(b, a))
        x.append(a)
    else:
        x.extend(range(a, b))
        x.append(b)

    return x

Result

print(get_between_numbers(5, 9))
print(get_between_numbers(9, 5))

[5, 6, 7, 8, 9]  
[5, 6, 7, 8, 9]

Correct way of using log4net (logger naming)

Instead of naming my invoking class, I started using the following:

private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.

Get Value From Select Option in Angular 4

_x000D_
_x000D_
export class MyComponent implements OnInit {_x000D_
_x000D_
  items: any[] = [_x000D_
    { id: 1, name: 'one' },_x000D_
    { id: 2, name: 'two' },_x000D_
    { id: 3, name: 'three' },_x000D_
    { id: 4, name: 'four' },_x000D_
    { id: 5, name: 'five' },_x000D_
    { id: 6, name: 'six' }_x000D_
  ];_x000D_
  selected: number = 1;_x000D_
_x000D_
  constructor() {_x000D_
  }_x000D_
  _x000D_
  ngOnInit() {_x000D_
  }_x000D_
  _x000D_
  selectOption(id: number) {_x000D_
    //getted from event_x000D_
    console.log(id);_x000D_
    //getted from binding_x000D_
    console.log(this.selected)_x000D_
  }_x000D_
_x000D_
}
_x000D_
<div>_x000D_
  <select (change)="selectOption($event.target.value)"_x000D_
  [(ngModel)]="selected">_x000D_
  <option [value]="item.id" *ngFor="let item of items">{{item.name}}</option>_x000D_
   </select>_x000D_
</div> 
_x000D_
_x000D_
_x000D_

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Simply adding it to the root folder works after a fashion, but I've found that if I need to change the favicon, it can take days to update... even a cache refresh doesn't do the trick.

URL encode sees “&” (ampersand) as “&amp;” HTML entity

There is HTML and URI encodings. &amp; is & encoded in HTML while %26 is & in URI encoding.

So before URI encoding your string you might want to HTML decode and then URI encode it :)

var div = document.createElement('div');
div.innerHTML = '&amp;AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);

result %26AndOtherHTMLEncodedStuff

Hope this saves you some time

iOS 7 status bar back to iOS 6 default style in iPhone app?

SOLUTION :

Set it in your viewcontroller or in rootviewcontroller by overriding the method :

-(BOOL) prefersStatusBarHidden
    {
        return YES;
    }

unexpected T_VARIABLE, expecting T_FUNCTION

check that you entered a variable as argument with the '$' symbol

Is it possible to create static classes in PHP (like in C#)?

final Class B{

    static $staticVar;
    static function getA(){
        self::$staticVar = New A;
    }
}

the stucture of b is calld a singeton handler you can also do it in a

Class a{
    static $instance;
    static function getA(...){
        if(!isset(self::$staticVar)){
            self::$staticVar = New A(...);
        }
        return self::$staticVar;
    }
}

this is the singleton use $a = a::getA(...);

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

Replace given value in vector

If you want to replace lot of values in single go, you can use 'library(car)'.

Example

library(car)

x <- rep(1:5,3)

xr <- recode(x, '3=1; 4=2')

x
## [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
xr
## [1] 1 2 1 2 5 1 2 1 2 5 1 2 1 2 5

C pass int array pointer as parameter into a function

Maybe you were trying to do this?

#include <stdio.h>

int func(int * B){

    /* B + OFFSET = 5 () You are pointing to the same region as B[OFFSET] */
    *(B + 2) = 5;
}

int main(void) {

    int B[10];

    func(B);

    /* Let's say you edited only 2 and you want to show it. */
    printf("b[0] = %d\n\n", B[2]);

    return 0;
}

OnItemCLickListener not working in listview

Faced same problem, tried for hours. If you have tried all of the above than try changing layout_width of Listview and list item to match_parent from wrap_content.

Android: Is it possible to display video thumbnails?

I am answering this question late but hope it will help the other candidate facing same problem.

I have used two methods to load thumbnail for videos list the first was

    Bitmap bmThumbnail;
    bmThumbnail = ThumbnailUtils.createVideoThumbnail(FILE_PATH
                    + videoList.get(position),
            MediaStore.Video.Thumbnails.MINI_KIND);

    if (bmThumbnail != null) {
        Log.d("VideoAdapter","video thumbnail found");
        holder.imgVideo.setImageBitmap(bmThumbnail);
    } else {
        Log.d("VideoAdapter","video thumbnail not found");
    }

its look good but there was a problem with this solution because when i scroll video list it will freeze some time due to its large processing.

so after this i found another solution which works perfectly by using Glide Library.

 Glide
            .with( mContext )
            .load( Uri.fromFile( new File( FILE_PATH+videoList.get(position) ) ) )
            .into( holder.imgVideo );

I recommended the later solution for showing thumbnail with video list . thanks

Getting Current date, time , day in laravel

Php has a date function which works very well. With laravel and blade you can use this without ugly <?php echo tags. For example, I use the following in a .blade.php file...

Copyright © {{ date('Y') }}

... and Laravel/blade translates that to the current year. If you want date time and day, you'll use something like this:

{{ date('Y-m-d H:i:s') }}

How do I import/include MATLAB functions?

If the folder just contains functions then adding the folders to the path at the start of the script will suffice.

addpath('../folder_x/');
addpath('../folder_y/');

If they are Packages, folders starting with a '+' then they also need to be imported.

import package_x.*
import package_y.*

You need to add the package folders parent to the search path.

How to copy java.util.list Collection

You may create a new list with an input of a previous list like so:

List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);

This will allow you to modify the order or what elemtents are contained independent of the first list.

Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.

example:

MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"

Edit

To avoid this you need a deep copy of each element in the list like so:

List<Torero> one = new ArrayList<Torero>();
//add elements

List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
    Torero copy = deepCopy(t);
    two.add(copy);
}

with copy like the following:

public Torero deepCopy(Torero input){
    Torero copy = new Torero();
    copy.setValue(input.getValue());//.. copy primitives, deep copy objects again

    return copy;
}

JavaScript replace/regex

Your regex pattern should have the g modifier:

var pattern = /[somepattern]+/g;

notice the g at the end. it tells the replacer to do a global replace.

Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:

var pattern = /[0-9a-zA-Z]+/g;

a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.

EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):

var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");

But you would need to change your replace function to this:

this.markup = this.markup.replace(pattern, value);

How to pass the id of an element that triggers an `onclick` event to the event handling function

Instead of passing the ID, you can just pass the element itself:

<link onclick="doWithThisElement(this)" />

Or, if you insist on passing the ID:

<link id="foo" onclick="doWithThisElement(this.id)" />

Here's the JSFiddle Demo: http://jsfiddle.net/dRkuv/

Check if string ends with one of the strings from a list

I just came across this, while looking for something else.

I would recommend to go with the methods in the os package. This is because you can make it more general, compensating for any weird case.

You can do something like:

import os

the_file = 'aaaa/bbbb/ccc.ddd'

extensions_list = ['ddd', 'eee', 'fff']

if os.path.splitext(the_file)[-1] in extensions_list:
    # Do your thing.

Powershell: Get FQDN Hostname

How about: "$env:computername.$env:userdnsdomain"

This actually only works if the user is logged into a domain (i.e. no local accounts), logged into the same domain as the server, and doesn't work with disjointed name space AD configurations.

Use this as referenced in another answer:

$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain ; Write-Host $myFQDN

How to add a search box with icon to the navbar in Bootstrap 3?

I'm running BS3 on a dev site and the following produces the effect/layout you're requesting. Of course you'll need the glyphicons set up in BS3.

<div class="navbar navbar-inverse navbar-static-top" role="navigation">

    <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" rel="home" href="/" title="Aahan Krish's Blog - Homepage">ITSMEEE</a>
    </div>

    <div class="collapse navbar-collapse navbar-ex1-collapse">

        <ul class="nav navbar-nav">
            <li><a href="/topic/notes/">/notes</a></li>
            <li><a href="/topic/dev/">/dev</a></li>
            <li><a href="/topic/good-reads/">/good-reads</a></li>
            <li><a href="/topic/art/">/art</a></li>
            <li><a href="/topic/bookmarks/">/bookmarks</a></li>
            <li><a href="/all-topics/">/all</a></li>
        </ul>

        <div class="col-sm-3 col-md-3 pull-right">
        <form class="navbar-form" role="search">
        <div class="input-group">
            <input type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term">
            <div class="input-group-btn">
                <button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
            </div>
        </div>
        </form>
        </div>

    </div>
</div>

UPDATE: See JSFiddle

Meaning of "referencing" and "dereferencing" in C

Referencing

& is the reference operator. It will refer the memory address to the pointer variable.

Example:

int *p;
int a=5;
p=&a; // Here Pointer variable p refers to the address of integer variable a.

Dereferencing

Dereference operator * is used by the pointer variable to directly access the value of the variable instead of its memory address.

Example:

int *p;
int a=5;
p=&a;
int value=*p; // Value variable will get the value of variable a that pointer variable p pointing to.

Create a folder and sub folder in Excel VBA

One sub and two functions. The sub builds your path and use the functions to check if the path exists and create if not. If the full path exists already, it will just pass on by. This will work on PC, but you will have to check what needs to be modified to work on Mac as well.

'requires reference to Microsoft Scripting Runtime
Sub MakeFolder()

Dim strComp As String, strPart As String, strPath As String

strComp = Range("A1") ' assumes company name in A1
strPart = CleanName(Range("C1")) ' assumes part in C1
strPath = "C:\Images\"

If Not FolderExists(strPath & strComp) Then 
'company doesn't exist, so create full path
    FolderCreate strPath & strComp & "\" & strPart
Else
'company does exist, but does part folder
    If Not FolderExists(strPath & strComp & "\" & strPart) Then
        FolderCreate strPath & strComp & "\" & strPart
    End If
End If

End Sub

Function FolderCreate(ByVal path As String) As Boolean

FolderCreate = True
Dim fso As New FileSystemObject

If Functions.FolderExists(path) Then
    Exit Function
Else
    On Error GoTo DeadInTheWater
    fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
    Exit Function
End If

DeadInTheWater:
    MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
    FolderCreate = False
    Exit Function

End Function

Function FolderExists(ByVal path As String) As Boolean

FolderExists = False
Dim fso As New FileSystemObject

If fso.FolderExists(path) Then FolderExists = True

End Function

Function CleanName(strName as String) as String
'will clean part # name so it can be made into valid folder name
'may need to add more lines to get rid of other characters

    CleanName = Replace(strName, "/","")
    CleanName = Replace(CleanName, "*","")
    etc...

End Function

Mean filter for smoothing images in Matlab

I see good answers have already been given, but I thought it might be nice to just give a way to perform mean filtering in MATLAB using no special functions or toolboxes. This is also very good for understanding exactly how the process works as you are required to explicitly set the convolution kernel. The mean filter kernel is fortunately very easy:

I = imread(...)
kernel = ones(3, 3) / 9; % 3x3 mean kernel
J = conv2(I, kernel, 'same'); % Convolve keeping size of I

Note that for colour images you would have to apply this to each of the channels in the image.

Adding git branch on the Bash command prompt

root:~/project#  -> root:~/project(dev)# 

add the following code to the end of your ~/.bashrc

force_color_prompt=yes
color_prompt=yes
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
fi
unset color_prompt force_color_prompt

Notepad++ - How can I replace blank lines

This should get your sorted:

  • Highlight from the end of the first line, to the very beginning of the third line.
  • Use the Ctrl + H to bring up the 'Find and Replace' window.
  • The highlighed region will already be plased in the 'Find' textbox.
  • Replace with: \r\n
  • 'Replace All' will then remove all the additional line spaces not required.

Here's how it should look: enter image description here

Open directory using C

Some feedback on the segment of code, though for the most part, it should work...

void main(int c,char **args)
  • int main - the standard defines main as returning an int.
  • c and args are typically named argc and argv, respectfully, but you are allowed to name them anything

...

{
DIR *dir;
struct dirent *dent;
char buffer[50];
strcpy(buffer,args[1]);
  • You have a buffer overflow here: If args[1] is longer than 50 bytes, buffer will not be able to hold it, and you will write to memory that you shouldn't. There's no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy...

...

dir=opendir(buffer);   //this part

If this returning NULL, it can be for a few reasons:

  • The directory didn't exist. (Did you type it right? Did it have a space in it, and you typed ./your_program my directory, which will fail, because it tries to opendir("my"))
  • You lack permissions to the directory
  • There's insufficient memory. (This is unlikely.)

Changing MongoDB data store directory

If installed via apt-get in Ubuntu 12.04, don't forget to chown -R mongodb:nogroup /path/to/new/directory. Also, change the configuration at /etc/mongodb.conf.

As a reminder, the mongodb-10gen package is now started via upstart, so the config script is in /etc/init/mongodb.conf

I just went through this, hope googlers find it useful :)

Word wrap for a label in Windows Forms

I had to find a quick solution, so I just used a TextBox with those properties:

var myLabel = new TextBox
                    {
                        Text = "xxx xxx xxx",
                        WordWrap = true,
                        AutoSize = false,
                        Enabled = false,
                        Size = new Size(60, 30),
                        BorderStyle = BorderStyle.None,
                        Multiline =  true,
                        BackColor =  container.BackColor
                    };

What is the @Html.DisplayFor syntax for?

DisplayFor is also useful for templating. You could write a template for your Model, and do something like this:

@Html.DisplayFor(m => m)

Similar to @Html.EditorFor(m => m). It's useful for the DRY principal so that you don't have to write the same display logic over and over for the same Model.

Take a look at this blog on MVC2 templates. It's still very applicable to MVC3:

http://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/


It's also useful if your Model has a Data annotation. For instance, if the property on the model is decorated with the EmailAddress data annotation, DisplayFor will render it as a mailto: link.

Best way to read a large file into a byte array in C#?

Simply replace the whole thing with:

return File.ReadAllBytes(fileName);

However, if you are concerned about the memory consumption, you should not read the whole file into memory all at once at all. You should do that in chunks.

Convert JSON array to an HTML table in jQuery

A still shorter way

$.makeTable = function (mydata) {
            if (mydata.length <= 0) return "";
           return $('<table border=1>').append("<tr>" + $.map(mydata[0], function (val, key) {
                return "<th>" + key + "</th>";
            }).join("\n") + "</tr>").append($.map(mydata, function (index, value) {
                return "<tr>" + $.map(index, function (val, key) {
                    return "<td>" + val + "</td>";
                }).join("\n") + "</tr>";
            }).join("\n"));
        };

getting the X/Y coordinates of a mouse click on an image with jQuery

Here is a better script:

$('#mainimage').click(function(e)
{   
    var offset_t = $(this).offset().top - $(window).scrollTop();
    var offset_l = $(this).offset().left - $(window).scrollLeft();

    var left = Math.round( (e.clientX - offset_l) );
    var top = Math.round( (e.clientY - offset_t) );

    alert("Left: " + left + " Top: " + top);

});

Timeout a command in bash without unnecessary delay

I prefer "timelimit", which has a package at least in debian.

http://devel.ringlet.net/sysutils/timelimit/

It is a bit nicer than the coreutils "timeout" because it prints something when killing the process, and it also sends SIGKILL after some time by default.

Two-dimensional array in Swift

Define mutable array

// 2 dimensional array of arrays of Ints 
var arr = [[Int]]() 

OR:

// 2 dimensional array of arrays of Ints 
var arr: [[Int]] = [] 

OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):

// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))

// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)

Change element at position

arr[0][1] = 18

OR

let myVar = 18
arr[0][1] = myVar

Change sub array

arr[1] = [123, 456, 789] 

OR

arr[0] += 234

OR

arr[0] += [345, 678]

If you had 3x2 array of 0(zeros) before these changes, now you have:

[
  [0, 0, 234, 345, 678], // 5 elements!
  [123, 456, 789],
  [0, 0]
]

So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.

Examine size/bounds before access

let a = 0
let b = 1

if arr.count > a && arr[a].count > b {
    println(arr[a][b])
}

Remarks: Same markup rules for 3 and N dimensional arrays.

Check if enum exists in Java

I don't know why anyone told you that catching runtime exceptions was bad.

Use valueOf and catching IllegalArgumentException is fine for converting/checking a string to an enum.

How can I display a list view in an Android Alert Dialog?

This is too simple

final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};

AlertDialog.Builder builder = new AlertDialog.Builder(MyProfile.this);

builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int item) {
        if (items[item].equals("Take Photo")) {
            getCapturesProfilePicFromCamera();
        } else if (items[item].equals("Choose from Library")) {
            getProfilePicFromGallery();
        } else if (items[item].equals("Cancel")) {
            dialog.dismiss();
        }
    }
});
builder.show();

Cross origin requests are only supported for HTTP but it's not cross-domain

For all python users:

Simply go to your destination folder in the terminal.

cd projectFoder

then start HTTP server For Python3+:

python -m http.server 8000

Serving HTTP on :: port 8000 (http://[::]:8000/) ...

go to your link: http://0.0.0.0:8000/

Enjoy :)

R - " missing value where TRUE/FALSE needed "

check the command : NA!=NA : you'll get the result NA, hence the error message.

You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

comments = c("no","yes",NA)
for (l in 1:length(comments)) {
    if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"

how to change attribute "hidden" in jquery

Use prop() for updating the hidden property, and change() for handling the change event.

_x000D_
_x000D_
$('#check').change(function() {_x000D_
  $("#delete").prop("hidden", !this.checked);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>_x000D_
      <input id="check" type="checkbox" name="del_attachment_id[]" value="<?php echo $attachment['link'];?>">_x000D_
    </td>_x000D_
_x000D_
    <td id="delete" hidden="true">_x000D_
      the file will be deleted from the newsletter_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Change the class from factor to numeric of many columns in a data frame

You have to be careful while changing factors to numeric. Here is a line of code that would change a set of columns from factor to numeric. I am assuming here that the columns to be changed to numeric are 1, 3, 4 and 5 respectively. You could change it accordingly

cols = c(1, 3, 4, 5);    
df[,cols] = apply(df[,cols], 2, function(x) as.numeric(as.character(x)));

Using str_replace so that it only acts on the first match?

The easiest way would be to use regular expression.

The other way is to find the position of the string with strpos() and then an substr_replace()

But i would really go for the RegExp.

Keyboard shortcuts in WPF

VB.NET:

Public Shared SaveCommand_AltS As New RoutedCommand

Inside the loaded event:

SaveCommand_AltS.InputGestures.Add(New KeyGesture(Key.S, ModifierKeys.Control))

Me.CommandBindings.Add(New CommandBinding(SaveCommand_AltS, AddressOf Me.save))

No XAML is needed.

How do I create a foreign key in SQL Server?

I always use this syntax to create the foreign key constraint between 2 tables

Alter Table ForeignKeyTable
Add constraint `ForeignKeyTable_ForeignKeyColumn_FK`
`Foreign key (ForeignKeyColumn)` references `PrimaryKeyTable (PrimaryKeyColumn)`

i.e.

Alter Table tblEmployee
Add constraint tblEmployee_DepartmentID_FK
foreign key (DepartmentID) references tblDepartment (ID)

Set Background color programmatically

You can use

 root.setBackgroundColor(0xFFFFFFFF);

or

 root.setBackgroundColor(Color.parseColor("#ffffff"));

Git fails when pushing commit to github

in these cases you can try ssh if https is stuck.

Also you can try increasing the buffer size to an astronomical figure so that you dont have to worry about the buffer size any more git config http.postBuffer 100000000

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

How can I pass a class member function as a callback?

This is a simple question but the answer is surprisingly complex. The short answer is you can do what you're trying to do with std::bind1st or boost::bind. The longer answer is below.

The compiler is correct to suggest you use &CLoggersInfra::RedundencyManagerCallBack. First, if RedundencyManagerCallBack is a member function, the function itself doesn't belong to any particular instance of the class CLoggersInfra. It belongs to the class itself. If you've ever called a static class function before, you may have noticed you use the same SomeClass::SomeMemberFunction syntax. Since the function itself is 'static' in the sense that it belongs to the class rather than a particular instance, you use the same syntax. The '&' is necessary because technically speaking you don't pass functions directly -- functions are not real objects in C++. Instead you're technically passing the memory address for the function, that is, a pointer to where the function's instructions begin in memory. The consequence is the same though, you're effectively 'passing a function' as a parameter.

But that's only half the problem in this instance. As I said, RedundencyManagerCallBack the function doesn't 'belong' to any particular instance. But it sounds like you want to pass it as a callback with a particular instance in mind. To understand how to do this you need to understand what member functions really are: regular not-defined-in-any-class functions with an extra hidden parameter.

For example:

class A {
public:
    A() : data(0) {}
    void foo(int addToData) { this->data += addToData; }

    int data;
};

...

A an_a_object;
an_a_object.foo(5);
A::foo(&an_a_object, 5); // This is the same as the line above!
std::cout << an_a_object.data; // Prints 10!

How many parameters does A::foo take? Normally we would say 1. But under the hood, foo really takes 2. Looking at A::foo's definition, it needs a specific instance of A in order for the 'this' pointer to be meaningful (the compiler needs to know what 'this' is). The way you usually specify what you want 'this' to be is through the syntax MyObject.MyMemberFunction(). But this is just syntactic sugar for passing the address of MyObject as the first parameter to MyMemberFunction. Similarly, when we declare member functions inside class definitions we don't put 'this' in the parameter list, but this is just a gift from the language designers to save typing. Instead you have to specify that a member function is static to opt out of it automatically getting the extra 'this' parameter. If the C++ compiler translated the above example to C code (the original C++ compiler actually worked that way), it would probably write something like this:

struct A {
    int data;
};

void a_init(A* to_init)
{
    to_init->data = 0;
}

void a_foo(A* this, int addToData)
{ 
    this->data += addToData;
}

...

A an_a_object;
a_init(0); // Before constructor call was implicit
a_foo(&an_a_object, 5); // Used to be an_a_object.foo(5);

Returning to your example, there is now an obvious problem. 'Init' wants a pointer to a function that takes one parameter. But &CLoggersInfra::RedundencyManagerCallBack is a pointer to a function that takes two parameters, it's normal parameter and the secret 'this' parameter. That's why you're still getting a compiler error (as a side note: If you've ever used Python, this kind of confusion is why a 'self' parameter is required for all member functions).

The verbose way to handle this is to create a special object that holds a pointer to the instance you want and has a member function called something like 'run' or 'execute' (or overloads the '()' operator) that takes the parameters for the member function, and simply calls the member function with those parameters on the stored instance. But this would require you to change 'Init' to take your special object rather than a raw function pointer, and it sounds like Init is someone else's code. And making a special class for every time this problem comes up will lead to code bloat.

So now, finally, the good solution, boost::bind and boost::function, the documentation for each you can find here:

boost::bind docs, boost::function docs

boost::bind will let you take a function, and a parameter to that function, and make a new function where that parameter is 'locked' in place. So if I have a function that adds two integers, I can use boost::bind to make a new function where one of the parameters is locked to say 5. This new function will only take one integer parameter, and will always add 5 specifically to it. Using this technique, you can 'lock in' the hidden 'this' parameter to be a particular class instance, and generate a new function that only takes one parameter, just like you want (note that the hidden parameter is always the first parameter, and the normal parameters come in order after it). Look at the boost::bind docs for examples, they even specifically discuss using it for member functions. Technically there is a standard function called [std::bind1st][3] that you could use as well, but boost::bind is more general.

Of course, there's just one more catch. boost::bind will make a nice boost::function for you, but this is still technically not a raw function pointer like Init probably wants. Thankfully, boost provides a way to convert boost::function's to raw pointers, as documented on StackOverflow here. How it implements this is beyond the scope of this answer, though it's interesting too.

Don't worry if this seems ludicrously hard -- your question intersects several of C++'s darker corners, and boost::bind is incredibly useful once you learn it.

C++11 update: Instead of boost::bind you can now use a lambda function that captures 'this'. This is basically having the compiler generate the same thing for you.

Python conversion from binary string to hexadecimal

Converting Binary into hex without ignoring leading zeros:

You could use the format() built-in function like this:

"{0:0>4X}".format(int("0000010010001101", 2))

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

For those who still have problems (Cannot pass parameter 2 by reference), define a variable with null value, not just pass null to PDO:

bindValue(':param', $n = null, PDO::PARAM_INT);

Hope this helps.

Where is nodejs log file?

For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan

Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.

const appRoot = require('app-root-path');
const winston = require('winston');

// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
} else {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
      new winston.transports.Console(options.console),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
}

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write(message) {
    logger.info(message);
  },
};

module.exports = logger;

After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log, " to the respective app.log created by you.

After this go to your index.js and include the following code in it.

const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));

winston.info('You have successfully started working with winston and morgan');

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

Why does JPA have a @Transient annotation?

Because they have different meanings. The @Transient annotation tells the JPA provider to not persist any (non-transient) attribute. The other tells the serialization framework to not serialize an attribute. You might want to have a @Transient property and still serialize it.

Launch an event when checking a checkbox in Angular2

StackBlitz

Template: You can either use the native change event or NgModel directive's ngModelChange.

<input type="checkbox" (change)="onNativeChange($event)"/>

or

<input type="checkbox" ngModel (ngModelChange)="onNgModelChange($event)"/>

TS:

onNativeChange(e) { // here e is a native event
  if(e.target.checked){
    // do something here
  }
}

onNgModelChange(e) { // here e is a boolean, true if checked, otherwise false
  if(e){
    // do something here
  }
}

SQL Data Reader - handling Null column values

neat one-liner:

    while (dataReader.Read())
{
    employee.FirstName = (!dataReader.IsDBNull(dataReader.GetOrdinal("FirstName"))) ? dataReader["FirstName"].ToString() : "";
}

How do I make an Event in the Usercontrol and have it handled in the Main Form?

one of the easy way to do that is use landa function without any problem like

userControl_Material1.simpleButton4.Click += (s, ee) =>
            {
                Save_mat(mat_global);
            };