Programs & Examples On #Ms access

Microsoft Access, also known as Microsoft Office Access, is a database management system from Microsoft that commonly combines the relational Microsoft Jet/ACE Database Engine with a graphical user interface and software-development tools. A number of other database engines, such as SQL Server, can also be used as a back-end.

How to create a new column in a select query

It depends what you wanted to do with that column e.g. here's an example of appending a new column to a recordset which can be updated on the client side:

Sub MSDataShape_AddNewCol()

  Dim rs As ADODB.Recordset
  Set rs = CreateObject("ADODB.Recordset")
  With rs
    .ActiveConnection = _
    "Provider=MSDataShape;" & _
    "Data Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=C:\Tempo\New_Jet_DB.mdb"
    .Source = _
    "SHAPE {" & _
    " SELECT ExistingField" & _
    " FROM ExistingTable" & _
    " ORDER BY ExistingField" & _
    "} APPEND NEW adNumeric(5, 4) AS NewField"

    .LockType = adLockBatchOptimistic

    .Open

    Dim i As Long
    For i = 0 To .RecordCount - 1
      .Fields("NewField").Value = Round(.Fields("ExistingField").Value, 4)
      .MoveNext
    Next

    rs.Save "C:\rs.xml", adPersistXML

  End With
End Sub

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

How to copy to clipboard using Access/VBA?

User Leigh Webber on the social.msdn.microsoft.com site posted VBA code implementing an easy-to-use clipboard interface that uses the Windows API:

http://social.msdn.microsoft.com/Forums/en/worddev/thread/ee9e0d28-0f1e-467f-8d1d-1a86b2db2878

You can get Leigh Webber's source code here

If this link doesn't go through, search for "A clipboard object for VBA" in the Office Dev Center > Microsoft Office for Developers Forums > Word for Developers section.

I created the two classes, ran his test cases, and it worked perfectly inside Outlook 2007 SP3 32-bit VBA under Windows 7 64-bit. It will most likely work for Access. Tip: To rename classes, select the class in the VBA 'Project' window, then click 'View' on the menu bar and click 'Properties Window' (or just hit F4).

With his classes, this is what it takes to copy to/from the clipboard:

Dim myClipboard As New vbaClipboard  ' Create clipboard

' Copy text to clipboard as ClipboardFormat TEXT (CF_TEXT)    
myClipboard.SetClipboardText "Text to put in clipboard", "CF_TEXT"    

' Retrieve clipboard text in CF_TEXT format (CF_TEXT = 1)
mytxt = myClipboard.GetClipboardText(1)

He also provides other functions for manipulating the clipboard.

It also overcomes 32KB MSForms_DataObject.SetText limitation - the main reason why SetText often fails. However, bear in mind that, unfortunatelly, I haven't found a reference on Microsoft recognizing this limitation.

-Jim

How to do INSERT into a table records extracted from another table

I believe your problem in this instance is the "values" keyword. You use the "values" keyword when you are inserting only one row of data. For inserting the results of a select, you don't need it.

Also, you really don't need the parentheses around the select statement.

From msdn:

Multiple-record append query:

INSERT INTO target [(field1[, field2[, …]])] [IN externaldatabase]
SELECT [source.]field1[, field2[, …]
FROM tableexpression

Single-record append query:

INSERT INTO target [(field1[, field2[, …]])]     
VALUES (value1[, value2[, …])

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

Retrieve column values of the selected row of a multicolumn Access listbox

For multicolumn listbox extract data from any column of selected row by

 listboxControl.List(listboxControl.ListIndex,col_num)

where col_num is required column ( 0 for first column)

Requery a subform from another form?

I had a similar kind of issue, but with some differences...

In my case, my main form has a Control (vendor) which value I used to update a Query in my DB, using the following code:

Sub Set_Qry_PedidosRealizadosImportados_frm(Vd As Long)
Dim temp_qry As DAO.QueryDef

'Procedimento para ajustar o codigo do cliente na Qry_Pedidos realizados e importados
'Procedure to adjust the code of the client on Qry_Pedidos realizados e importados
Set temp_qry = CurrentDb.QueryDefs("Qry_Pedidos realizados e importados")
temp_qry.SQL = "SELECT DISTINCT " & _
            "[Qry_Pedidos distintos].[Codigo], " & _
            "[Qry_Pedidos distintos].[Razao social], " & _
            "COUNT([Qry_Pedidos distintos].[Pedido Avante]) As [Pedidos realizados], " & _
            "SUM(IIf(NZ([Qry_Pedidos distintos].[Pedido Flexx], 0) > 1, 1, 0)) As [Pedidos Importados] " & _
            "FROM [Qry_Pedidos distintos] " & _
            "WHERE [Qry_Pedidos distintos].Vd = " & Vd & _
            " Group BY " & _
            "[Qry_Pedidos distintos].[Razao social], " & _
            "[Qry_Pedidos distintos].[Codigo];"
End Sub

Since the beginning my subform record source was the query named "Qry_Pedidos realizados e importados".

But the only way I could update the subform data inside the main form context was to refresh the data source of the subform to it self, like posted bellow:

Private Sub cmb_vendedor_v1_Exit(Cancel As Integer)
'Codigo para atualizar o comando SQL da query
'Code to update the SQL statement of the query 
    Call Set_Qry_Pedidosrealizadosimportados_frm(Me.cmb_vendedor_v1.Value)

'Codigo para forçar o Access a aceitar o novo comando SQL
'Code to force de Access to accept the new sql statement
    Me!Frm_Pedidos_realizados_importados.Form.RecordSource = "Qry_Pedidos realizados e importados"
End Sub

No refresh, recalc, requery, etc, was necessary after all...

Maximum number of rows in an MS Access database engine table?

It's been some years since I last worked with Access but larger database files always used to have more problems and be more prone to corruption than smaller files.

Unless the database file is only being accessed by one person or stored on a robust network you may find this is a problem before the 2GB database size limit is reached.

Good Free Alternative To MS Access

VistaDB is the only alternative if you going to run your website at shared hosting (almost all of them won't let you run your websites under Full Trust mode) and also if you need simple x-copy deployment enabled website.

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

you have:

WHERE ID = " & siteID & ";", dbOpenSnapshot)

you need:

WHERE ID = "'" & siteID & "';", dbOpenSnapshot)

Note the extra quotations ('). . . this kills me everytime

Edit: added missing double quote

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

How to execute a query in ms-access in VBA code?

Take a look at this tutorial for how to use SQL inside VBA:

http://www.ehow.com/how_7148832_access-vba-query-results.html

For a query that won't return results, use (reference here):

DoCmd.RunSQL

For one that will, use (reference here):

Dim dBase As Database
dBase.OpenRecordset

How to use a SQL SELECT statement with Access VBA

If you wish to use the bound column value, you can simply refer to the combo:

sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo

You can also refer to the column property:

sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"

Dim rs As DAO.Recordset     
Set rs = CurrentDB.OpenRecordset(sSQL)

strText = rs!AText
strText = rs.Fields(1)

In a textbox:

= DlookUp("AText","MyTable","ID=" & MyCombo)

*edited

MS Access VBA: Sending an email through Outlook

Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.

Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")

Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing


End Sub

How to I say Is Not Null in VBA

Use Not IsNull(Fields!W_O_Count.Value)

How to replace blank (null ) values with 0 for all records?

Better solution is to use NZ (null to zero) function during generating table => NZ([ColumnName]) It comes 0 where is "null" in ColumnName.

Error: "Could Not Find Installable ISAM"

Have you checked this http://support.microsoft.com/kb/209805? In particular, whether you have Msrd3x40.dll.

You may also like to check that you have the latest version of Jet: http://support.microsoft.com/kb/239114

where to place CASE WHEN column IS NULL in this query

Thanks for all your help! @Svetoslav Tsolov had it very close, but I was still getting an error, until I figured out the closing parenthesis was in the wrong place. Here's the final query that works:

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
(CASE WHEN dbo.EU_Admin3.EUID IS NULL THEN dbo.EU_Admin2.EUID ELSE dbo.EU_Admin3.EUID END) AS EUID
FROM dbo.AdminID 

LEFT OUTER JOIN dbo.EU_Admin2
ON dbo.AdminID.DistrictID = dbo.EU_Admin2.DistrictID

LEFT OUTER JOIN dbo.EU_Admin3
ON dbo.AdminID.ADMIN3_ID = dbo.EU_Admin3.ADMIN3_ID

How to query a MS-Access Table from MS-Excel (2010) using VBA

Sub Button1_Click()
Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Documents and Settings\XXXXXX\My Documents\my_access_table.accdb"
    strSql = "SELECT Count(*) FROM mytable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.Fields(0) & " rows in MyTable"

    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

End Sub

Access 2013 - Cannot open a database created with a previous version of your application

I've just used Excel 2016 to open Access 2003 tables.

  1. Open a new worksheet
  2. Go to Data tab
  3. Click on "From Access" menu item
  4. Select the database's .mdb file
  5. In the "Data Link Properties" box that opens, switch to the "Provider" tab
  6. Select the "Microsoft Jet 4.0 OLE DB Provider"
  7. Click on Next
  8. Reselect the database's .mdb file (it forgets it when you change Provider)
  9. Click OK
  10. From the Select Table dialogue that appears, choose the table you want to import.

Select query with date condition

select Qty, vajan, Rate,Amt,nhamali,ncommission,ntolai from SalesDtl,SalesMSt where SalesDtl.PurEntryNo=1 and SalesMST.SaleDate=  (22/03/2014) and SalesMST.SaleNo= SalesDtl.SaleNo;

That should work.

How do you comment an MS-access Query?

NOTE: Confirmed with Access 2003, don't know about earlier versions.

For a query in an MDB you can right-click in the query designer (anywhere in the empty space where the tables are), select Properties from the context menu, and enter text in the Description property.

You're limited to 256 characters, but it's better than nothing.

You can get at the description programatically with something like this:

Dim db As Database
Dim qry As QueryDef

Set db = Application.CurrentDb
Set qry = db.QueryDefs("myQuery")

Debug.Print qry.Properties("Description")

Access Form - Syntax error (missing operator) in query expression

I was able to quickly fix it by going into Design View of the Form and putting [] around any field names that had spaces. I am now able to use the built in filters without the annoying popup about syntax problems.

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

MS Access: how to compact current database in VBA

DBEngine.CompactDatabase source, dest

Does VBA contain a comment block syntax?

prefix the comment with a single-quote. there is no need for an "end" tag.

'this is a comment

Extend to multiple lines using the line-continuation character, _:

'this is a multi-line _
   comment

This is an option in the toolbar to select a line(s) of code and comment/uncomment:

enter image description here

Autonumber value of last inserted row - MS Access / VBA

If DAO use

RS.Move 0, RS.LastModified
lngID = RS!AutoNumberFieldName

If ADO use

cn.Execute "INSERT INTO TheTable.....", , adCmdText + adExecuteNoRecords
Set rs = cn.Execute("SELECT @@Identity", , adCmdText)
Debug.Print rs.Fields(0).Value

cn being a valid ADO connection, @@Identity will return the last Identity (Autonumber) inserted on this connection.

Note that @@Identity might be troublesome because the last generated value may not be the one you are interested in. For the Access database engine, consider a VIEW that joins two tables, both of which have the IDENTITY property, and you INSERT INTO the VIEW. For SQL Server, consider if there are triggers that in turn insert records into another table that also has the IDENTITY property.

BTW DMax would not work as if someone else inserts a record just after you've inserted one but before your Dmax function finishes excecuting, then you would get their record.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

The action or event has been blocked by Disabled Mode

Another issue is that your database may be in a "non-trusted" location. Go to the trust center settings and add your database location to the trusted locations list.

How to connect to a MS Access file (mdb) using C#?

Another simplest way to connect is through an OdbcConnection using App.config file like this

  <appSettings>  
    <add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True"/>
  </appSettings>

MyDB.mdb is my database file and it is present in current primary application folder with main exe file.

if your mdf file has password then use like this

  <appSettings>
    <add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True;Jet OLEDB:Database Password=Admin$@123"/>
  </appSettings>

How do I make a stored procedure in MS Access?

Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).

If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.

For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.

For example:

screenshot

Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table alt text

Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.

How to add default signature in Outlook

I like Mozzi's answer but found that it did not retain the default fonts that are user specific. The text all appeared in a system font as normal text. The code below retains the user's favourite fonts, while making it only a little longer. It is based on Mozzi's approach, uses a regular expression to replace the default body text and places the user's chosen Body text where it belongs by using GetInspector.WordEditor. I found that the call to GetInspector did not populate the HTMLbody as dimitry streblechenko says above in this thread, at least, not in Office 2010, so the object is still displayed in my code. In passing, please note that it is important that the MailItem is created as an Object, not as a straightforward MailItem - see here for more. (Oh, and sorry to those of different tastes, but I prefer longer descriptive variable names so that I can find routines!)

Public Function GetSignedMailItemAsObject(ByVal ToAddress As String, _
                      ByVal Subject As String, _
                      ByVal Body As String, _
                      SignatureName As String) As Object
'================================================================================================================='Creates a new MailItem in HTML format as an Object.
'Body, if provided, replaces all text in the default message.
'A Signature is appended at the end of the message.
'If SignatureName is invalid any existing default signature is left in place.
'=================================================================================================================
' REQUIRED REFERENCES
' VBScript regular expressions (5.5)
' Microsoft Scripting Runtime
'=================================================================================================================
Dim OlM As Object               'Do not define this as Outlook.MailItem.  If you do, some things will work and some won't (i.e. SendUsingAccount)
Dim Signature As String
Dim Doc As Word.Document
Dim Regex As New VBScript_RegExp_55.RegExp       '(can also use use Object if VBScript is not Referenced)

Set OlM = Application.CreateItem(olMailItem)
With OlM
    .To = ToAddress
    .Subject = Subject
    'SignatureName is the exactname that you gave your signature in the Message>Insert>Signature Dialog
    Signature = GetSignature(SignatureName)
    If Signature <> vbNullString Then
'        Should really strip the terminal </body tag out of signature by removing all characters from the start of the tag
'        but Outlook seems to handle this OK if you don't bother.
        .Display                                'Needed.  Without it, there is no existing HTMLbody available to work with.
        Set Doc = OlM.GetInspector.WordEditor   'Get any existing body with the WordEditor and delete all of it
        Doc.Range(Doc.Content.Start, Doc.Content.End) = vbNullString 'Delete all existing content - we don't want any default signature
        'Preserve all local email formatting by placing any new body text, followed by the Signature, into the empty HTMLbody.
        With Regex
            .IgnoreCase = True                  'Case insensitive
            .Global = False                     'Regex finds only the first match
            .MultiLine = True                   'In case there are stray EndOfLines (there shouldn't be in HTML but Word exports of HTML can be dire)
            .Pattern = "(<body.*)(?=<\/body)"   'Look for the whole HTMLbody but do NOT include the terminal </body tag in the value returned
            OlM.HTMLbody = .Replace(OlM.HTMLbody, "$1" & Signature)
        End With ' Regex
        Doc.Range(Doc.Content.Start, Doc.Content.Start) = Body 'Place the required Body before the signature (it will get the default style)
        .Close olSave                           'Close the Displayed MailItem (actually Object) and Save it.  If it is left open some later updates may fail.
    End If ' Signature <> vbNullString
End With ' OlM
Set GetSignedMailItemAsObject = OlM
End Function

Private Function GetSignature(sigName As String) As String
Dim oTextStream As Scripting.TextStream
Dim oSig As Object
Dim appDataDir, Signature, sigPath, fileName As String
Dim FileSys As Scripting.FileSystemObject        'Requires Microsoft Scripting Runtime to be available
    appDataDir = Environ("APPDATA") & "\Microsoft\Signatures"
    sigPath = appDataDir & "\" & sigName & ".htm"
    Set FileSys = CreateObject("Scripting.FileSystemObject")
    Set oTextStream = FileSys.OpenTextFile(sigPath)
    Signature = oTextStream.ReadAll
    ' fix relative references to images, etc. in Signature
    ' by making them absolute paths, OL will find the image
    fileName = Replace(sigName, ".htm", "") & "_files/"
    Signature = Replace(Signature, fileName, appDataDir & "\" & fileName)
    GetSignature = Signature
End Function

How to use "like" and "not like" in SQL MSAccess for the same field?

If you're doing it in VBA (and not in a query) then: where field like "AA" and field not like "BB" then would not work.

You'd have to use: where field like "AA" and field like "BB" = false then

Code to loop through all records in MS Access

In "References", import DAO 3.6 object reference.

private sub showTableData

dim db as dao.database
dim rs as dao.recordset

set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously

'populate the table
rs.movelast
rs.movefirst

do while not rs.EOF
   debug.print(rs!myField) 'myField is a field name in table myTable
   rs.movenext             'press Ctrl+G to see debuG window beneath
loop

msgbox("End of Table")

end sub

You can interate data objects like queries and filtered tables in different ways:

Trhough query:

private sub showQueryData

dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string

sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"

set db = currentDb
set rs = db.openRecordset(sqlStr)

rs.movefirst

do while not rs.EOF
  debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
  rs.movenext
loop

msgbox("End of customers from Brazil")

end sub

You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.

I hope I've helped.

How to connect PHP with Microsoft Access database

Are you sure the odbc connector is well created ? if not check the step "Create an ODBC Connection" again

EDIT: Connection without DSN from php.net

// Microsoft Access

$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

in your case it might be if your filename is northwind and your file extension mdb:

$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=northwind", "", "");

How to check if a table exists in MS Access for vb macros

This is not a new question. I addresed it in comments in one SO post, and posted my alternative implementations in another post. The comments in the first post actually elucidate the performance differences between the different implementations.

Basically, which works fastest depends on what database object you use with it.

How to get logged-in user's name in Access vba?

Try this:

Function UserNameWindows() As String
     UserName = Environ("USERNAME")
End Function

How to SUM two fields within an SQL query

If you want to add two columns together, all you have to do is add them. Then you will get the sum of those two columns for each row returned by the query.

What your code is doing is adding the two columns together and then getting a sum of the sums. That will work, but it might not be what you are attempting to accomplish.

How to get start and end of previous month in VB

Public Shared Function GetFOMPrev(ByVal tdate As Date) As Date
    Return tdate.AddDays(-(tdate.Day - 1))
End Function

Public Shared Function GetEOMPrev(ByVal tdate As Date) As Date
    Return tdate.AddDays(-tdate.Day)
End Function

Usage:

'Get End of Month of Previous Month - Pass today's date
EOM = GetEOMPrev(Date.Today)

'Get First of Month of Previous Month - Pass date just calculated
FOM = GetFOMPrev(EOM)

Using Excel as front end to Access database (with VBA)

It Depends how much functionality you are expecting by Excel<->Acess solution. In many cases where you don't have budget to get a complete application solution, these little utilities does work. If the Scope of project is limited then I would go for this solution, because excel does give you flexibility to design spreadsheets as in accordance to your needs and then you may use those predesigned sheets for users to use. Designing a spreadsheet like form in Access is more time consuming and difficult and does requires some ActiveX. It object might not only handling data but presenting in spreadsheet like formates then this solution should works with limited scope.

SQL Query - Using Order By in UNION

I think this does a good job of explaining.

The following is a UNION query that uses an ORDER BY clause:

select supplier_id, supplier_name
from suppliers
where supplier_id > 2000
UNION
select company_id, company_name
from companies
where company_id > 1000
ORDER BY 2;

Since the column names are different between the two "select" statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set.

In this example, we've sorted the results by supplier_name / company_name in ascending order, as denoted by the "ORDER BY 2".

The supplier_name / company_name fields are in position #2 in the result set.

Taken from here: http://www.techonthenet.com/sql/union.php

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.

I did it a different way, without using VBA, by using a table containing the query parameters.

E.g:

SELECT a_table.a_field 
FROM QueryParameters, a_table 
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min 
AND QueryParameters.a_field_max

Where QueryParameters is a table with two fields, a_field_min and a_field_max

It can even be used with GROUP BY, if you include the query parameter fields in the GROUP BY clause, and the FIRST operator on the parameter fields in the HAVING clause.

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Below are three functions you can use to alter and use the MS Access 2010 Import Specification. The third sub changes the name of an existing import specification. The second sub allows you to change any xml text in the import spec. This is useful if you need to change column names, data types, add columns, change the import file location, etc.. In essence anything you want modify for an existing spec. The first Sub is a routine that allows you to call an existing import spec, modify it for a specific file you are attempting to import, importing that file, and then deleting the modified spec, keeping the import spec "template" unaltered and intact. Enjoy.

Public Sub MyExcelTransfer(myTempTable As String, myPath As String)
On Error GoTo ERR_Handler:
    Dim mySpec As ImportExportSpecification
    Dim myNewSpec As ImportExportSpecification
    Dim x As Integer

    For x = 0 To CurrentProject.ImportExportSpecifications.Count - 1
    If CurrentProject.ImportExportSpecifications.Item(x).Name = "TemporaryImport" Then
        CurrentProject.ImportExportSpecifications.Item("TemporaryImport").Delete
        x = CurrentProject.ImportExportSpecifications.Count
    End If
    Next x
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(myTempTable)
    CurrentProject.ImportExportSpecifications.Add "TemporaryImport", mySpec.XML
    Set myNewSpec = CurrentProject.ImportExportSpecifications.Item("TemporaryImport")

    myNewSpec.XML = Replace(myNewSpec.XML, "\\MyComputer\ChangeThis", myPath)
    myNewSpec.Execute
    myNewSpec.Delete
    Set mySpec = Nothing
    Set myNewSpec = Nothing
    exit_ErrHandler:
    For x = 0 To CurrentProject.ImportExportSpecifications.Count - 1
    If CurrentProject.ImportExportSpecifications.Item(x).Name = "TemporaryImport" Then
        CurrentProject.ImportExportSpecifications.Item("TemporaryImport").Delete
        x = CurrentProject.ImportExportSpecifications.Count
    End If
    Next x
Exit Sub    
ERR_Handler:
    MsgBox Err.Description
    Resume exit_ErrHandler
End Sub

Public Sub fixImportSpecs(myTable As String, strFind As String, strRepl As String)
    Dim mySpec As ImportExportSpecification    
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(myTable)    
    mySpec.XML = Replace(mySpec.XML, strFind, strRepl)
    Set mySpec = Nothing
End Sub


Public Sub MyExcelChangeName(OldName As String, NewName As String)
    Dim mySpec As ImportExportSpecification
    Dim myNewSpec As ImportExportSpecification
    Set mySpec = CurrentProject.ImportExportSpecifications.Item(OldName)    
    CurrentProject.ImportExportSpecifications.Add NewName, mySpec.XML
    mySpec.Delete
    Set mySpec = Nothing
    Set myNewSpec = Nothing
End Sub

Find the directory part (minus the filename) of a full path in access 97

If you're just needing the path of the MDB currently open in the Access UI, I'd suggest writing a function that parses CurrentDB.Name and then stores the result in a Static variable inside the function. Something like this:

Public Function CurrentPath() As String
  Dim strCurrentDBName As String
  Static strPath As String
  Dim i As Integer

  If Len(strPath) = 0 Then
     strCurrentDBName = CurrentDb.Name
     For i = Len(strCurrentDBName) To 1 Step -1
       If Mid(strCurrentDBName, i, 1) = "\" Then
          strPath = Left(strCurrentDBName, i)
          Exit For
       End If
    Next
  End If
  CurrentPath = strPath
End Function

This has the advantage that it only loops through the name one time.

Of course, it only works with the file that's open in the user interface.

Another way to write this would be to use the functions provided at the link inside the function above, thus:

Public Function CurrentPath() As String
  Static strPath As String

  If Len(strPath) = 0 Then
     strPath = FolderFromPath(CurrentDB.Name)
  End If
  CurrentPath = strPath
End Function

This makes retrieving the current path very efficient while utilizing code that can be used for finding the path for any filename/path.

Call a VBA Function into a Sub Procedure

Procedures in a Module start being useful and generic when you pass in arguments.

For example:

Public Function DoSomethingElse(strMessage As String)  
    MsgBox strMessage
End Function

Can now display any message that is passed in with the string variable called strMessage.

Access: Move to next record until EOF

If (Not IsNull(Me.id.Value)) Then
DoCmd.GoToRecord , , acNext
End If

Hi, you need to put this in form activate, and have an id field named id...

this way it passes until it reaches the one without id (AKA new one)...

Determining whether an object is a member of a collection in VBA

You can shorten the suggested code for this as well as generalize for unexpected errors. Here you go:

Public Function InCollection(col As Collection, key As String) As Boolean

  On Error GoTo incol
  col.Item key

incol:
  InCollection = (Err.Number = 0)

End Function

Export tables to an excel spreadsheet in same directory

Lawrence has given you a good answer. But if you want more control over what gets exported to where in Excel see Modules: Sample Excel Automation - cell by cell which is slow and Modules: Transferring Records to Excel with Automation You can do things such as export the recordset starting in row 2 and insert custom text in row 1. As well as any custom formatting required.

Now() function with time trim

You could also use Format$(Now(), "Short Date") or whatever date format you want. Be aware, this function will return the Date as a string, so using Date() is a better approach.

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

how do you view macro code in access?

Open the Access Database, you will see Table, Query, Report, Module & Macro.
This contains the macros which can be used to invoke common MS-Access actions in a sequence.

For custom VBA macro, press ALT+F11.

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Convert String to Date in MS Access Query

If you need to display all the records after 2014-09-01, add this to your query:

SELECT * FROM Events
WHERE Format(Events.DATE_TIME,'yyyy-MM-dd hh:mm:ss')  >= Format("2014-09-01 00:00:00","yyyy-MM-dd hh:mm:ss")

Corrupted Access .accdb file: "Unrecognized Database Format"

Well, I have tried something I hope it helps ..

They changed the schema a little bit ..

Use the following :

1- Change the AccessDataSource to SQLDataSource in the toolbox.

2- In the drop down menu choose your access database (xxxx.accdb or xxxx.mdb)

3- Next -> Next -> Test Query -> Finish.

Worked for me.

Is there an equivalent to the SUBSTRING function in MS Access SQL?

You can use the VBA string functions (as @onedaywhen points out in the comments, they are not really the VBA functions, but their equivalents from the MS Jet libraries. As far as function signatures go, they are called and work the same, even though the actual presence of MS Access is not required for them to be available.):

SELECT DISTINCT Left(LastName, 1)
FROM Authors;

SELECT DISTINCT Mid(LastName, 1, 1)
FROM Authors;

How to insert values into the database table using VBA in MS access

  1. Remove this line of code: For i = 1 To DatDiff. A For loop must have the word NEXT
  2. Also, remove this line of code: StrSQL = StrSQL & "SELECT 'Test'" because its making Access look at your final SQL statement like this; INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );SELECT 'Test' Notice the semicolon in the middle of the SQL statement (should always be at the end. its by the way not required. you can also omit it). also, there is no space between the semicolon and the key word SELECT

in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?

Try a software called Access to MySQL.

Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.

  • Wizard interface.
  • Transfer data directly from one server to another.
  • Create a dump file.
  • Select tables to transfer.
  • Select fields to transfer.
  • Transfer password protected databases.
  • Supports both shared security and user-level security.
  • Optional transfer of indexes.
  • Optional transfer of records.
  • Optional transfer of default values in field definitions.
  • Identifies and transfers auto number field types.
  • Command line interface.
  • Easy install, uninstall and upgrade.

See the aforementioned link for a step-by-step tutorial with screenshots.

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

Microsoft.ACE.OLEDB.12.0 provider is not registered

Basically, if you're on a 64-bit machine, IIS 7 is not (by default) serving 32-bit apps, which the database engine operates on. So here is exactly what you do:

1) ensure that the 2007 database engine is installed, this can be downloaded at: http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en

2) open IIS7 manager, and open the Application Pools area. On the right sidebar, you will see an option that says "Set application pool defaults". Click it, and a window will pop up with the options.

3) the second field down, which says 'Enable 32-bit applications' is probably set to FALSE by default. Simply click where it says 'false' to change it to 'true'.

4) Restart your app pool (you can do this by hitting RECYCLE instead of STOP then START, which will also work).

5) done, and your error message will go away.

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

SQL to Query text in access with an apostrophe in it

...better is declare the name as varible ,and ask before if thereis a apostrophe in the string:

e.g.:

DIM YourName string

YourName = "Daniel O'Neal"

  If InStr(YourName, "'") Then
      SELECT * FROM tblStudents WHERE [name]  Like """ Your Name """ ;
   else
      SELECT * FROM tblStudents WHERE [name] Like '" Your Name "' ;       
  endif

Access VBA | How to replace parts of a string with another string

You could use a function similar to this also, it would allow you to add in different cases where you would like to change values:

Public Function strReplace(varValue As Variant) as Variant

    Select Case varValue

        Case "Avenue"
            strReplace = "Ave"

        Case "North"
            strReplace = "N"

        Case Else
            strReplace = varValue

    End Select

End Function

Then your SQL would read something like:

SELECT strReplace(Address) As Add FROM Tablename

Access 2010 VBA query a table and iterate through results

Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:

EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!

Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Set colReturn = New Collection

Dim SQL As String
SQL = _
    "SELECT tblState.State, tblState.StateName " & _
    "FROM tblState"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
    Do Until .EOF
        colReturn.Add Nz(!State, "")
        .MoveNext
    Loop
    End If
    .Close
End With
cn.Close

Set rs = Nothing
Set cn = Nothing

Set StatesCollection = colReturn

End Function

Row numbers in query result using Microsoft Access

I needed the best x results of points per team.

Ranking does not solves this problem when there are results with equal points. So I need a recordnumber

I made a VBA function in Access to create a recordnumber that resets on ID change.

You have to query this query with where recordnumber <= x to get the points per team.

NB Access changes the record-number

  1. when you query the query filtered on record number
  2. when you filter out some results
  3. when you change the sort order

That is not what I thought that would happen.

Solved this by using a temporary table and saving the recordnumbers and keys or an extra field in the table.

SELECT ID, Points, RecordNumberOffId([ID}) AS Recordnumber
FROM Team ORDER BY ID ASC, Points DESC;

It uses 3 module level variables to remember between calls

Dim PreviousID As Long
Dim PreviousRecordNumber As Long
Dim TimeLastID As Date

Public Function RecordNumberOffID(ID As Long) As Long 
'ID is sortgroup identity
'Reset if last call longer dan nn seconds in the past
If Time() - TimeLastID > 0.0003 Then '0,000277778 = 1 second
    PreviousID = 0
    PreviousRecordNumber = 0
End If
If ID <> PreviousID Then
    PreviousRecordNumber = 0
    PreviousID = ID
End If
PreviousRecordNumber = PreviousRecordNumber + 1
RecordNumberOffID = PreviousRecordNumber
TimeLastID = Time()
End Function

What is the equivalent of Select Case in Access SQL?

You can use IIF for a similar result.

Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html

SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer 
FROM MyTable;

How to refresh an access form

I recommend that you use REQUERY the specific combo box whose data you have changed AND that you do it after the Cmd.Close statement. that way, if you were inputing data, that data is also requeried.

DoCmd.Close
Forms![Form_Name]![Combo_Box_Name].Requery

you might also want to point to the recently changed value

Dim id As Integer
id = Me.[Index_Field]
DoCmd.Close
Forms![Form_Name]![Combo_Box_Name].Requery
Forms![Form_Name]![Combo_Box_Name] = id

this example supposes that you opened a form to input data into a secondary table.

let us say you save School_Index and School_Name in a School table and refer to it in a Student table (which contains only the School_Index field). while you are editing a student, you need to associate him with a school that is not in your School table, etc etc

How can I get table names from an MS Access Database?

Schema information which is designed to be very close to that of the SQL-92 INFORMATION_SCHEMA may be obtained for the Jet/ACE engine (which is what I assume you mean by 'access') via the OLE DB providers.

See:

OpenSchema Method (ADO)

Supported Schema Rowsets

How to execute VBA Access module?

Well it depends on how you want to call this code.

Are you calling it from a button click on a form, if so then on the properties for the button on form, go to the Event tab, then On Click item, select [Event Procedure]. This will open the VBA code window for that button. You would then call your Module.Routine and then this would trigger when you click the button.

Similar to this:

Private Sub Command1426_Click()
    mdl_ExportMorning.ExportMorning
End Sub

This button click event calls the Module mdl_ExportMorning and the Public Sub ExportMorning.

How do I correctly use "Not Equal" in MS Access?

I have struggled to get a query to return fields from Table 1 that do not exist in Table 2 and tried most of the answers above until I found a very simple way to obtain the results that I wanted.

I set the join properties between table 1 and table 2 to the third setting (3) (All fields from Table 1 and only those records from Table 2 where the joined fields are equal) and placed a Is Null in the criteria field of the query in Table 2 in the field that I was testing for. It works perfectly.

Thanks to all above though.

Operation must use an updatable query. (Error 3073) Microsoft Access

This occurs when there is not a UNIQUE MS-ACCESS key for the table(s) being updated. (Regardless of the SQL schema).

When creating MS-Access Links to SQL tables, you are asked to specify the index (key) at link time. If this is done incorrectly, or not at all, the query against the linked table is not updatable

When linking SQL tables into Access MAKE SURE that when Access prompts you for the index (key) you use exactly what SQL uses to avoid problem(s), although specifying any unique key is all Access needs to update the table.

If you were not the person who originally linked the table, delete the linked table from MS-ACCESS (the link only gets deleted) and re-link it specifying the key properly and all will work correctly.

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

How to restart counting from 1 after erasing table in MS Access?

In Access 2007 - 2010, go to Database Tools and click Compact and Repair Database, and it will automatically reset the ID.

how to refresh my datagridview after I add new data

this.tablenameTableAdapter.Fill(this.databasenameDataSet.tablename)

Show "Open File" Dialog

I have a similar solution to the above and it works for opening, saving, file selecting. I paste it into its own module and use in all the Access DB's I create. As the code states it requires Microsoft Office 14.0 Object Library. Just another option I suppose:

Public Function Select_File(InitPath, ActionType, FileType)
    ' Requires reference to Microsoft Office 14.0 Object Library.

    Dim fDialog As Office.FileDialog
    Dim varFile As Variant


    If ActionType = "FilePicker" Then
        Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
        ' Set up the File Dialog.
    End If
    If ActionType = "SaveAs" Then
        Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
    End If
    If ActionType = "Open" Then
        Set fDialog = Application.FileDialog(msoFileDialogOpen)
    End If
    With fDialog
        .AllowMultiSelect = False
        ' Disallow user to make multiple selections in dialog box
        .Title = "Please specify the file to save/open..."
        ' Set the title of the dialog box.
        If ActionType <> "SaveAs" Then
            .Filters.Clear
            ' Clear out the current filters, and add our own.
            .Filters.Add FileType, "*." & FileType
        End If
        .InitialFileName = InitPath
        ' Show the dialog box. If the .Show method returns True, the
        ' user picked a file. If the .Show method returns
        ' False, the user clicked Cancel.
        If .Show = True Then
        'Loop through each file selected and add it to our list box.
            For Each varFile In .SelectedItems
                'return the subroutine value as the file path & name selected
                Select_File = varFile
            Next
        End If
    End With
End Function

How do I count unique items in field in Access query?

A quick trick to use for me is using the find duplicates query SQL and changing 1 to 0 in Having expression. Like this:

SELECT COUNT([UniqueField]) AS DistinctCNT FROM
(
  SELECT First([FieldName]) AS [UniqueField]
  FROM TableName
  GROUP BY [FieldName]
  HAVING (((Count([FieldName]))>0))
);

Hope this helps, not the best way I am sure, and Access should have had this built in.

"Operation must use an updateable query" error in MS Access

I was accessing the database using UNC path and occasionally this exception was thrown. When I replaced the computer name with IP address, the problem was suddenly resolved.

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

Get length of array?

Try CountA:

Dim myArray(1 to 10) as String
Dim arrayCount as String
arrayCount = Application.CountA(myArray)
Debug.Print arrayCount

Setting up an MS-Access DB for multi-user access

I find the answers to this question to be problematic, confusing and incomplete, so I'll make an effort to do better.

Q1: How can we make sure that the write-user can make changes to the table data while other users use the data? Do the read-users put locks on tables? Does the write-user have to put locks on the table? Does Access do this for us or do we have to explicitly code this?

Nobody has really answered this in any complete fashion. The information on setting locks in the Access options has nothing to do with read vs. write locking. No Locks vs. All Records vs. Edited Record is how you set the default record locking for WRITES.

  • No locks means you are using OPTIMISTIC locking, which means you allow multiple users to edit the record and then inform them after the fact if the record has changed since they launched their own edits. Optimistic locking is what you should start with as it requires no coding to implement it, and for small users populations it hardly ever causes a problem.

  • All Records means that the whole table is locked any time an edit is launched.

  • Edited Record means that fewer records are locked, but whether or not it's a single record or more than one record depends on whether your database is set up to use record-level locking (first added in Jet 4) or page-level locking. Frankly, I've never thought it worth the trouble to set up record-level locking, as optimistic locking takes care of most of the problems.

One might think that you want to use record-level pessimistic locking, but the fact is that in the vast majority of apps, two users are almost never editing the same record. Now, obviously, certain kinds of apps might be exceptions to that, but if I ran into such an app, I'd likely try to engineer it away by redesigning the schema so that it would be very uncommon for two users to edit the same record (usually by going to some form of transactional editing instead, where changes are made by adding records, rather than editing the existing data).

Now, for your actual question, there are a number of ways to accomplish restricting some users to read-only and granting others write privileges. Jet user-level security was intended for this purpose and works fine insofar as it's "security" for any meaningful definition of the term. In general, as long as you're using a Jet/ACE data store, the best security you're going to get is that provided by Jet ULS. It's crackable, yes, but your users would be committing a firable offense by breaking it, so it might be sufficient.

I would tend to not implement Jet ULS at all and instead just architect the data editing forms such that they checked the user's Windows logon and made the forms read-only or writable depending on which users are supposed to get which access. Whether or not you want to record group membership in a data table, or maintain Windows security groups for this purpose is up to you. You could also use a Jet workgroup file to deal with it, and provide a different system.mdw file for the write users. The read-only users would log on transparently as admin, and those logged on as admin would be granted only read-only access. The write users would log on as some other username (transparently, in the shortcut you provide them for launching the app, supplying no password), and that would be used to set up the forms as read or write.

If you use Jet ULS, it can become really hairy to get it right. It involves locking down all the tables as read-only (or maybe not even that) and then using RWOP queries to provide access to the data. I haven't done but one such app in my 14 years of professional Access development.

To summarize my answers to the parts of your question:

How can we make sure that the write-user can make changes to the table data while other users use the data?

I would recommend doing this in the application, setting forms to read/only or editable at runtime depending on the user logon. The easiest approach is to set your forms to be read-only and change to editable for the write users when they open the form.

Do the read-users put locks on tables?

Not in any meaningful sense. Jet/ACE does have read locks, but they are there only for the purpose of maintaining state for individual views, and for refreshing data for the user. They do not lock out write operations of any kind, though the overhead of tracking them theoretically slows things down. It's not enough to worry about.

Does the write-user have to put locks on the table?

Access in combination with Jet/ACE does this for you automatically, particularly if you choose optimistic locking as your default. The key point here is that Access apps are databound, so as soon as a form is loaded, the record has a read lock, and as soon as the record is edited, whether or not it is write-locked for other users is determined by whether you are using optimistic or pessimistic locking. Again, this is the kind of thing Access takes care of for you with its default behaviors in bound forms. You don't worry about any of it until the point at which you encounter problems.

Does Access do this for us or do we have to explicitly code this?

Basically, other than setting editability at runtime (according to who has write access), there is no coding necessary if you're using optimistic locking. With pessimistic locking, you don't have to code, but you will almost always need to, as you can't just leave the user stuck with the default behaviors and error messages.

Q2: Are there any common problems with "MS Access transactions" that we should be aware of?

Jet/ACE has support for commit/rollback transactions, but it's not clear to me if that's what you mean in this question. In general, I don't use transactions except for maintaining atomicity, e.g., when creating an invoice, or doing any update that involves multiple tables. It works about the way you'd expect it to but is not really necessary for the vast majority of operations in an Access application.

Perhaps one of the issues here (particularly in light of the first question) is that you may not quite grasp that Access is designed for creating apps with data bound to the forms. "Transactions" is a topic of great importance for unbound and stateless apps (e.g., browser-based), but for data bound apps, the editing and saving all happens transparently.

For certain kinds of operations this can be problematic, and occasionally it's appropriate to edit data in Access with unbound forms. But that's very seldom the case, in my experience. It's not that I don't use unbound forms -- I use lots of them for dialogs and the like -- it's just that my apps don't edit data tables with unbound forms. With almost no exceptions, all my apps edit data with bound forms.

Now, unbound forms are actually fairly easy to implement in Access (particularly if you name your editing controls the same as the underlying fields), but going with unbound data editing forms is really missing the point of using Access, which is that the binding is all done for you. And the main drawback of going unbound is that you lose all the record-level form events, such as OnInsert, BeforeUpdate and so forth.

Q3. Can we work on forms, queries etc. while they are being used? How can we "program" without being in the way of the users?

This is one of the questions that's been well-addressed. All multi-user or replicated Access apps should be split, and most single-user apps should be, too. It's good design and also makes the apps more stable, as only the data tables end up being opened by more than one user at a time.

Q4. Which settings in MS Access have an influence on how things are handled?

"Things?" What things?

Q5. Our background is mostly in Oracle, where is Access different in handling multiple users? Is there such thing as "isolation levels" in Access?

I don't know anything specifically about Oracle (none of my clients could afford it even if they wanted to), but asking for a comparison of Access and Oracle betrays a fundamental misunderstanding somewhere along the line.

Access is an application development tool.

Oracle is an industrial strength database server.

Apples and oranges.

Now, of course, Access ships with a default database engine, originally called Jet and now revised and renamed ACE, but there are many levels at which Access the development platform can be entirely decoupled from Jet/ACE, the default database engine.

In this case, you've chosen to use a Jet/ACE back end, which will likely be just fine for small user populations, i.e., under 25. Jet/ACE can also be fine up to 50 or 100, particularly when only a few of the simultaneous users have write permission. While the 255-user limit in Jet/ACE includes both read-only and write users, it's the number of write users that really controls how many simultaneous users you can support, and in your case, you've got an app with mostly read-only users, so it oughtn't be terribly difficult to engineer a good app that has no problems with the back end.

Basically, I think your Oracle background is likely leading you to misunderstand how to develop in Access, where the expected approach is to bind your forms to recordsources that are updated without any need to write code. Now, for efficiency's sake it's a good idea to bind your forms to subsets of records, rather than to whole tables, but even with an entire table in the recordsource behind a data editing form, Access is going to be fairly efficient in editing Jet/ACE tables (the old myth about pulling the whole table across the wire is still out there) as long your data tables are efficiently indexed.

Record locking is something you mostly shouldn't have any cause to worry about, and one of the reasons for that is because of bound editing, where the form knows what's going on in the back end at all times (well, at intervals about a second apart, the default refresh interval). That is, it's not like a web page where you retrieve a copy of the data and then post your edits back to the server in a transaction completely unconnected to the original data retrieval operation. In a bound environment like Access, the locking file on the back-end data file is always going to be keeping track of the fact that someone has the record open for editing. This prevents a user's edits from stomping on someone else's edits, because Access knows the state and informs the user. This all happens without any coding on the part of the developer and is one of the great advantages of the bound editing model (aside from not having to write code to post the edits).

For all those who are experienced database programmers familiar with other platforms who are coming to Access for the first time, I strongly suggest using Access like an end user. Try out all the point and click features. Run the form and report wizards and check out the results that they produce. I can't vouch for all of them as demonstrating good practices, but they definitely demonstrate the default assumptions behind the way Access is intended to be used.

If you find yourself writing a lot of code, then you're likely missing the point of Access.

"You tried to execute a query that does not include the specified aggregate function"

GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.

Access Database opens as read only

Check that there are no missing references - to do this, go to the database window and click on "Modules", then "Design", then select the menu "Tools" and then "References". Or try doing a compile and see if it compiles fully (go to the Debug menu then select Compile) - it might tell you of a missing reference e.g. Microsoft Office 11.0 Object Library. Select References from the Tools menu again and see if any references are ticked and say "MISSING:". In some cases you can select a different version from the list, if 11.0 is missing, look for version 12.0 then recompile. That usually does the trick for me.

How to open a folder in Windows Explorer from VBA?

I just used this and it works fine:

System.Diagnostics.Process.Start("C:/Users/Admin/files");

delete all from table

You can also use truncate.

truncate table table_name;

How to find longest string in the table column data

This was the first result on "longest string in postgres" google search so I'll put my answer here for those looking for a postgres solution.

SELECT max(char_length(column)) AS Max_Length_String FROM table

postgres docs: http://www.postgresql.org/docs/9.2/static/functions-string.html

How do I test if a recordSet is empty? isNull?

RecordCount is what you want to use.

If Not temp_rst1.RecordCount > 0 ...

How do I execute multiple SQL Statements in Access' Query Editor?

Better just create a XLSX file with field names on top row. Create it manually or using Mockaroo. Export it to Excel(or CSV) and then import it to Access using New Data Source -> From File

IMHO it's the best and most performant way to do it in Access.

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

in JDK 8, jdbc odbc bridge is no longer used and thus removed fro the JDK. to use Microsoft Access database in JAVA, you need 5 extra JAR libraries.

1- hsqldb.jar

2- jackcess 2.0.4.jar

3- commons-lang-2.6.jar

4- commons-logging-1.1.1.jar

5- ucanaccess-2.0.8.jar

add these libraries to your java project and start with following lines.

Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<Path to your database i.e. MS Access DB>");
Statement s = conn.createStatement();

path could be like E:/Project/JAVA/DBApp

and then your query to be executed. Like

ResultSet rs = s.executeQuery("SELECT * FROM Course");
while(rs.next())
    System.out.println(rs.getString("Title") + " " + rs.getString("Code") + " " + rs.getString("Credits"));

certain imports to be used. try catch block must be used and some necessary things no to be forgotten.

Remember, no need of bridging drivers like jdbc odbc or any stuff.

MS Access - execute a saved query by name in VBA

To use CurrentDb.Execute, your query must be an action query, AND in quotes.

CurrentDb.Execute "queryname"

MS-access reports - The search key was not found in any record - on save

I know this is a very old post but as I was searching for additional solutions to this same error while running my command (I'd previously encountered the spaces in the Excel wb headers and remedied it with VBA each time the file is updated so I knew it wasn't that). I considered the fact that the xlsm file and DB were on separate network drives but didn't want to explore moving one unless it was my last resort.

I attempted to run the save import manually and there it was right in front of my face. The folder containing the xlsm file had been renamed....I changed the name back to match my saved import and....smh, it was that all along.

@AspectJ pointcut for all methods of a class with specific annotation

Using annotations, as described in the question.

Annotation: @Monitor

Annotation on class, app/PagesController.java:

package app;
@Controller
@Monitor
public class PagesController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Annotation on method, app/PagesController.java:

package app;
@Controller
public class PagesController {
    @Monitor
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Custom annotation, app/Monitor.java:

package app;
@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {
}

Aspect for annotation, app/MonitorAspect.java:

package app;
@Component
@Aspect
public class MonitorAspect {
    @Before(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void before(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }

    @After(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void after(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }
}

Enable AspectJ, servlet-context.xml:

<aop:aspectj-autoproxy />

Include AspectJ libraries, pom.xml:

<artifactId>spring-aop</artifactId>
<artifactId>aspectjrt</artifactId>
<artifactId>aspectjweaver</artifactId>
<artifactId>cglib</artifactId>

How to remove all listeners in an element?

Here's a function that is also based on cloneNode, but with an option to clone only the parent node and move all the children (to preserve their event listeners):

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners on one element:

recreateNode(document.getElementById("btn"));

Remove event listeners on an element and all of its children:

recreateNode(document.getElementById("list"), true);

If you need to keep the object itself and therefore can't use cloneNode, then you have to wrap the addEventListener function and track the listener list by yourself, like in this answer.

How to check if the docker engine and a docker container are running?

container status: true/false

# docker inspect --format '{{json .State.Running}}' container-name
true
#

Node.js: get path from the request

simply call req.url. that should do the work. you'll get something like /something?bla=foo

possible EventEmitter memory leak detected

I was facing the same issue, but i have successfully handled with async await.
Please check if it helps.

let dataLength = 25;
Before:
  for (let i = 0; i < dataLength; i++) {
      sftp.get(remotePath, fs.createWriteStream(xyzProject/${data[i].name}));
  }

After:
  for (let i = 0; i < dataLength; i++) {
      await sftp.get(remotePath, fs.createWriteStream(xyzProject/${data[i].name}));
  }

What is REST? Slightly confused

It stands for Representational State Transfer and it can mean a lot of things, but usually when you are talking about APIs and applications, you are talking about REST as a way to do web services or get programs to talk over the web.

REST is basically a way of communicating between systems and does much of what SOAP RPC was designed to do, but while SOAP generally makes a connection, authenticates and then does stuff over that connection, REST works pretty much the same way that that the web works. You have a URL and when you request that URL you get something back. This is where things start getting confusing because people describe the web as a the largest REST application and while this is technically correct it doesn't really help explain what it is.

In a nutshell, REST allows you to get two applications talking over the Internet using tools that are similar to what a web browser uses. This is much simpler than SOAP and a lot of what REST does is says, "Hey, things don't have to be so complex."

Worth reading:

Do conditional INSERT with SQL?

You can do that with a single statement and a subquery in nearly all relational databases.

INSERT INTO targetTable(field1) 
SELECT field1
FROM myTable
WHERE NOT(field1 IN (SELECT field1 FROM targetTable))

Certain relational databases have improved syntax for the above, since what you describe is a fairly common task. SQL Server has a MERGE syntax with all kinds of options, and MySQL has optional INSERT OR IGNORE syntax.

Edit: SmallSQL's documentation is fairly sparse as to which parts of the SQL standard it implements. It may not implement subqueries, and as such you may be unable to follow the advice above, or anywhere else, if you need to stick with SmallSQL.

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

you can use this method just pass your date to it

-(NSString *)getDateFromString:(NSString *)string
{

    NSString * dateString = [NSString stringWithFormat: @"%@",string];

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"your current date format"];
    NSDate* myDate = [dateFormatter dateFromString:dateString];

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"your desired format"];
    NSString *stringFromDate = [formatter stringFromDate:myDate];

    NSLog(@"%@", stringFromDate);
    return stringFromDate;
}

How to get scrollbar position with Javascript?

If you are using jQuery there is a perfect function for you: .scrollTop()

doc here -> http://api.jquery.com/scrollTop/

note: you can use this function to retrieve OR set the position.

see also: http://api.jquery.com/?s=scroll

JVM option -Xss - What does it do exactly?

It indeed sets the stack size on a JVM.

You should touch it in either of these two situations:

  • StackOverflowError (the stack size is greater than the limit), increase the value
  • OutOfMemoryError: unable to create new native thread (too many threads, each thread has a large stack), decrease it.

The latter usually comes when your Xss is set too large - then you need to balance it (testing!)

Can I use GDB to debug a running process?

You can attach to a running process with gdb -p PID.

Java, reading a file from current directory?

None of the above answer works for me. Here is what works for me.

Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:

URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));

JAVA_HOME is set to an invalid directory:

JAVA_HOME should be C:\Program Files\Java\jdk1.8.0_172 don't include semi-colon(;) or bin in path. Any jdk version above 7 will work. Also, you need to re-start the cmd

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

trigger('submit') does not work.beacuse onSubmit method does not get fired. the following code works for me, call onSubmit method when using this code :

$("form").find(':submit').click();

Google Script to see if text contains a value

Update 2020:

You can now use Modern ECMAScript syntax thanks to V8 Runtime.

You can use includes():

var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}

Regular expression to allow spaces between words

Try with this one:

result = re.search(r"\w+( )\w+", text)

How to enable core dump in my Linux C++ program

You need to set ulimit -c. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited and check if everything is correct ulimit -a. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>.

Should I test private methods or only public ones?

One main point is

If we test to ensure the correctness of the logic, and a private method is carrying a logic, we should test it. Isn't it? So why are we going to skip that?

Writing tests based on the visibility of methods is completely irrelevant idea.

Conversely

On the other hand, calling a private method outside the original class is a main problem. And also there are limitations to mock a private method in some mocking tools. (Ex: Mockito)

Though there are some tools like Power Mock which supports that, it is a dangerous operation. The reason is it needs to hack the JVM to achieve that.

One work around that can be done is (If you want to write test cases for private methods)

Declare those private methods as protected. But it may not be convenient for several situations.

Determine which element the mouse pointer is on top of in JavaScript

DEMO

There's a really cool function called document.elementFromPoint which does what it sounds like.

What we need is to find the x and y coords of the mouse and then call it using those values:

var x = event.clientX, y = event.clientY,
    elementMouseIsOver = document.elementFromPoint(x, y);

document.elementFromPoint

jQuery event object

Android Activity without ActionBar

Considering everyone is posting older ways of hiding the ActionBar here is the proper way of implementing it within styles for AppCompat support library. Which I highly suggest moving toward if you haven't already.

Simply removing the ActionBar

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>

If you are using the appcompat support libraries, this is the easiest and recommended way of hiding the ActionBar to make full screen or start implementing to toolbar within your layouts.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Your Toolbar Color-->
    <item name="colorPrimary">@color/primary</item>

    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">@color/primary_dark</item>

    <!-- colorAccent is used as the default value for colorControlActivated,
     which is used to tint widgets -->
    <item name="colorAccent">@color/accent</item>

    <!-- You can also set colorControlNormal, colorControlActivated
     colorControlHighlight, and colorSwitchThumbNormal. -->
</style>

Then to change your toolbar color

<android.support.v7.widget.Toolbar
    android:id=”@+id/my_awesome_toolbar”
    android:layout_height=”wrap_content”
    android:layout_width=”match_parent”
    android:minHeight=”?attr/actionBarSize”
    android:background=”?attr/primary” />

Last note: Your Activity class should extend AppCompatActivity

public class MainActivity extends AppCompatActivity {

<!--Activity Items -->

}

How to COUNT rows within EntityFramework without loading contents?

Well, even the SELECT COUNT(*) FROM Table will be fairly inefficient, especially on large tables, since SQL Server really can't do anything but do a full table scan (clustered index scan).

Sometimes, it's good enough to know an approximate number of rows from the database, and in such a case, a statement like this might suffice:

SELECT 
    SUM(used_page_count) * 8 AS SizeKB,
    SUM(row_count) AS [RowCount], 
    OBJECT_NAME(OBJECT_ID) AS TableName
FROM 
    sys.dm_db_partition_stats
WHERE 
    OBJECT_ID = OBJECT_ID('YourTableNameHere')
    AND (index_id = 0 OR index_id = 1)
GROUP BY 
    OBJECT_ID

This will inspect the dynamic management view and extract the number of rows and the table size from it, given a specific table. It does so by summing up the entries for the heap (index_id = 0) or the clustered index (index_id = 1).

It's quick, it's easy to use, but it's not guaranteed to be 100% accurate or up to date. But in many cases, this is "good enough" (and put much less burden on the server).

Maybe that would work for you, too? Of course, to use it in EF, you'd have to wrap this up in a stored proc or use a straight "Execute SQL query" call.

Marc

Find the most popular element in int[] array

You can count the occurrences of the different numbers, then look for the highest one. This is an example that uses a Map, but could relatively easily be adapted to native arrays.

Second largest element: Let us take example : [1,5,4,2,3] in this case, Second largest element will be 4.

  1. Sort the Array in descending order, once the sort done output will be A = [5,4,3,2,1]

  2. Get the Second Largest Element from the sorted array Using Index 1. A[1] -> Which will give the Second largest element 4.

private static int getMostOccuringElement(int[] A) { Map occuringMap = new HashMap();

    //count occurences
    for (int i = 0; i < A.length; i++) { 
        if (occuringMap.get(A[i]) != null) {
            int val = occuringMap.get(A[i]) + 1;
            occuringMap.put(A[i], val);
        } else {
            occuringMap.put(A[i], 1);
        }
    }

    //find maximum occurence
    int max = Integer.MIN_VALUE; 
    int element = -1;
    for (Map.Entry<Integer, Integer> entry : occuringMap.entrySet()) {
        if (entry.getValue() > max) {
            max = entry.getValue();
            element = entry.getKey();
        }
    }
    return element;
}

How do I loop through or enumerate a JavaScript object?

Using a for-of on Object.keys()

Like:

_x000D_
_x000D_
let object = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
};

for (let key of Object.keys(object)) {
  console.log(key + " : " + object[key])
}
_x000D_
_x000D_
_x000D_

Jquery get input array field

this usualy works on Checkboxes and Radio buttons... but, each name should be the same.

<input type="text" value="2" name="pages_title[]">
<input type="text" value="1" name="pages_title[]">

var x = $('input[name="pages_title[]"]').val();

that is "supposed" to get you all the fields in comma separated values. never tried it with text boxes, so cant guarantee it.

as @John commented: to iterate over them. $('input[name="pages_title[]"]').each(function() { var aValue = $(this).val(); });

EDIT: Not allways you need just to answer the OP questions, sometimes you need to teach them better methods. (sorry if that sounds Arrogant)

COMMENT: defining inputs as

<input type="text" value="1" name="pages_title[1]">
<input type="text" value="2" name="pages_title[2]">

is breaking the array, each input has a unique name, therefor, it is not an array anymore.

CSS selector - element with a given child

Is it possible to select an element if it contains a specific child element?

Unfortunately not yet.

The CSS2 and CSS3 selector specifications do not allow for any sort of parent selection.


A Note About Specification Changes

This is a disclaimer about the accuracy of this post from this point onward. Parent selectors in CSS have been discussed for many years. As no consensus has been found, changes keep happening. I will attempt to keep this answer up-to-date, however be aware that there may be inaccuracies due to changes in the specifications.


An older "Selectors Level 4 Working Draft" described a feature which was the ability to specify the "subject" of a selector. This feature has been dropped and will not be available for CSS implementations.

The subject was going to be the element in the selector chain that would have styles applied to it.

Example HTML
<p><span>lorem</span> ipsum dolor sit amet</p>
<p>consecteture edipsing elit</p>

This selector would style the span element

p span {
    color: red;
}

This selector would style the p element

!p span {
    color: red;
}

A more recent "Selectors Level 4 Editor’s Draft" includes "The Relational Pseudo-class: :has()"

:has() would allow an author to select an element based on its contents. My understanding is it was chosen to provide compatibility with jQuery's custom :has() pseudo-selector*.

In any event, continuing the example from above, to select the p element that contains a span one could use:

p:has(span) {
    color: red;
}

* This makes me wonder if jQuery had implemented selector subjects whether subjects would have remained in the specification.

View stored procedure/function definition in MySQL

You can use this:

SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = 'yourdb' AND ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_NAME = "procedurename";

Why can I ping a server but not connect via SSH?

ping (ICMP protocol) and ssh are two different protocols.

  1. It could be that ssh service is not running or not installed

  2. firewall restriction (local to server like iptables or even sshd config lock down ) or (external firewall that protects incomming traffic to network hosting 111.111.111.111)

First check is to see if ssh port is up

nc -v -w 1 111.111.111.111 -z 22

if it succeeds then ssh should communicate if not then it will never work until restriction is lifted or ssh is started

How to enable PHP's openssl extension to install Composer?

you need to enable the openssl extension in

C:\wamp\bin\php\php5.4.12\php.ini 

that is the php configuration file that has it type has "configuration settings" with a driver-notepad like icon.

  1. open it either with notepad or any editor,
  2. search for openssl "your ctrl + F " would do.
  3. there is a semi-colon before the openssl extension

    ;extension=php_openssl.dll
    

    remove the semi-colon and you'll have

    extension=php_openssl.dll
    
  4. save the file and restart your WAMP server after that you're good to go. re-install the application again that should work.

How to Ping External IP from Java Android

In my case ping works from device but not from the emulator. I found this documentation: http://developer.android.com/guide/developing/devices/emulator.html#emulatornetworking

On the topic of "Local Networking Limitations" it says:

"Depending on the environment, the emulator may not be able to support other protocols (such as ICMP, used for "ping") might not be supported. Currently, the emulator does not support IGMP or multicast."

Further information: http://groups.google.com/group/android-developers/browse_thread/thread/8657506be6819297

this is a known limitation of the QEMU user-mode network stack. Quoting from the original doc: Note that ping is not supported reliably to the internet as it would require root privileges. It means you can only ping the local router (10.0.2.2).

Deleting Elements in an Array if Element is a Certain value VBA

Sub DelEle(Ary, SameTypeTemp, Index As Integer) '<<<<<<<<< pass only not fixed sized array (i don't know how to declare same type temp array in proceder)
    Dim I As Integer, II As Integer
    II = -1
    If Index < LBound(Ary) And Index > UBound(Ary) Then MsgBox "Error.........."
    For I = 0 To UBound(Ary)
        If I <> Index Then
            II = II + 1
            ReDim Preserve SameTypeTemp(II)
            SameTypeTemp(II) = Ary(I)
        End If
    Next I
    ReDim Ary(UBound(SameTypeTemp))
    Ary = SameTypeTemp
    Erase SameTypeTemp
End Sub

Sub Test()
    Dim a() As Integer, b() As Integer
    ReDim a(3)
    Debug.Print "InputData:"
    For I = 0 To UBound(a)
        a(I) = I
        Debug.Print "    " & a(I)
    Next
    DelEle a, b, 1
    Debug.Print "Result:"
    For I = 0 To UBound(a)
        Debug.Print "    " & a(I)
    Next
End Sub

ASP.net using a form to insert data into an sql server table

Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

How do you use "git --bare init" repository?

Answering your questions one by one:

Bare repository is the one that has no working tree. It means its whole contents is what you have in .git directory.

You can only commit to bare repository by pushing to it from your local clone. It has no working tree, so it has no files modified, no changes.

To have central repository the only way it is to have a bare repository.

Android studio takes too much memory

I have used all of Sam's recommendations above, but I found that the VM command line options are no longer supported as described. (I received an error when used)

As an alternative, I was able to reduce gradle dramatically by adding the following line to the "gradle.properties" file

org.gradle.jvmargs=-Xms512m -Xmx1024m

As of A.S. ver 1.3, the file is located in the same folder level as "gradle.build".

The above configuration is a "memory stack" of 512 meg, and "memory heap" of 1024 meg.

I tested this on a small project, using settings where both memory sizes were set to 256 meg. It limited the JVM sizes as expected. In all my tests, I restarted A.S. to force the JVM to restart.

Hopefully, this will save others dealing with this issue from getting those "Get yourself a better computer" responses. :-)

Dilber

Mysql - How to quit/exit from stored procedure

MainLabel:BEGIN

IF (<condition>) IS NOT NULL THEN
    LEAVE MainLabel;
END IF; 

....code

i.e.
IF (@skipMe) IS NOT NULL THEN /* @skipMe returns Null if never set or set to NULL */
     LEAVE MainLabel;
END IF;

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

1) When the user logs out (Forms signout in Action) I want to redirect to a login page.

public ActionResult Logout() {
    //log out the user
    return RedirectToAction("Login");
}

2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)

Why would you want to redirect from a controller init?

the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:

public ActionResult Index() {
    return RedirectToAction("whateverAction", "whateverController");
}

Xcode 6 Storyboard the wrong size?

On your storyboard page, go to File Inspector and uncheck 'Use Size Classes'. This should shrink your view controller to regular IPhone size you were familiar with. Note that using 'size classes' will let you design your project across many devices. Once you uncheck this the Xcode will give you a warning dialogue as follows. This should be self-explainatory.

"Disabling size classes will limit this document to storing data for a single device family. The data for the size class best representing the targeted device will be retained, and all other data will be removed. In addition, segues will be converted to their non-adaptive equivalents."

Connecting to remote URL which requires authentication using Java

You can also use the following, which does not require using external packages:

URL url = new URL(“location address”);
URLConnection uc = url.openConnection();

String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

Encrypt Password in Configuration Files?

Check out jasypt, which is a library offering basic encryption capabilities with minimum effort.

Changing SVG image color with javascript

Given some SVG:

<div id="main">
  <svg id="octocat" xmlns="http://www.w3.org/2000/svg" width="400px" height="400px" viewBox="-60 0 420 330" style="fill:#fff;stroke: #000; stroke-opacity: 0.1">
    <path id="puddle" d="m296.94 295.43c0 20.533-47.56 37.176-106.22 37.176-58.67 0-106.23-16.643-106.23-37.176s47.558-37.18 106.23-37.18c58.66 0 106.22 16.65 106.22 37.18z"/>
    <path class="shadow-legs" d="m161.85 331.22v-26.5c0-3.422-.619-6.284-1.653-8.701 6.853 5.322 7.316 18.695 7.316 18.695v17.004c6.166.481 12.534.773 19.053.861l-.172-16.92c-.944-23.13-20.769-25.961-20.769-25.961-7.245-1.645-7.137 1.991-6.409 4.34-7.108-12.122-26.158-10.556-26.158-10.556-6.611 2.357-.475 6.607-.475 6.607 10.387 3.775 11.33 15.105 11.33 15.105v23.622c5.72.98 11.71 1.79 17.94 2.4z"/>
    <path class="shadow-legs" d="m245.4 283.48s-19.053-1.566-26.16 10.559c.728-2.35.839-5.989-6.408-4.343 0 0-19.824 2.832-20.768 25.961l-.174 16.946c6.509-.025 12.876-.254 19.054-.671v-17.219s.465-13.373 7.316-18.695c-1.034 2.417-1.653 5.278-1.653 8.701v26.775c6.214-.544 12.211-1.279 17.937-2.188v-24.113s.944-11.33 11.33-15.105c0-.01 6.13-4.26-.48-6.62z"/>
    <path id="cat" d="m378.18 141.32l.28-1.389c-31.162-6.231-63.141-6.294-82.487-5.49 3.178-11.451 4.134-24.627 4.134-39.32 0-21.073-7.917-37.931-20.77-50.759 2.246-7.25 5.246-23.351-2.996-43.963 0 0-14.541-4.617-47.431 17.396-12.884-3.22-26.596-4.81-40.328-4.81-15.109 0-30.376 1.924-44.615 5.83-33.94-23.154-48.923-18.411-48.923-18.411-9.78 24.457-3.733 42.566-1.896 47.063-11.495 12.406-18.513 28.243-18.513 47.659 0 14.658 1.669 27.808 5.745 39.237-19.511-.71-50.323-.437-80.373 5.572l.276 1.389c30.231-6.046 61.237-6.256 80.629-5.522.898 2.366 1.899 4.661 3.021 6.879-19.177.618-51.922 3.062-83.303 11.915l.387 1.36c31.629-8.918 64.658-11.301 83.649-11.882 11.458 21.358 34.048 35.152 74.236 39.484-5.704 3.833-11.523 10.349-13.881 21.374-7.773 3.718-32.379 12.793-47.142-12.599 0 0-8.264-15.109-24.082-16.292 0 0-15.344-.235-1.059 9.562 0 0 10.267 4.838 17.351 23.019 0 0 9.241 31.01 53.835 21.061v32.032s-.943 11.33-11.33 15.105c0 0-6.137 4.249.475 6.606 0 0 28.792 2.361 28.792-21.238v-34.929s-1.142-13.852 5.663-18.667v57.371s-.47 13.688-7.551 18.881c0 0-4.723 8.494 5.663 6.137 0 0 19.824-2.832 20.769-25.961l.449-58.06h4.765l.453 58.06c.943 23.129 20.768 25.961 20.768 25.961 10.383 2.357 5.663-6.137 5.663-6.137-7.08-5.193-7.551-18.881-7.551-18.881v-56.876c6.801 5.296 5.663 18.171 5.663 18.171v34.929c0 23.6 28.793 21.238 28.793 21.238 6.606-2.357.474-6.606.474-6.606-10.386-3.775-11.33-15.105-11.33-15.105v-45.786c0-17.854-7.518-27.309-14.87-32.3 42.859-4.25 63.426-18.089 72.903-39.591 18.773.516 52.557 2.803 84.873 11.919l.384-1.36c-32.131-9.063-65.692-11.408-84.655-11.96.898-2.172 1.682-4.431 2.378-6.755 19.25-.80 51.38-.79 82.66 5.46z"/>
    <path id="face" d="m258.19 94.132c9.231 8.363 14.631 18.462 14.631 29.343 0 50.804-37.872 52.181-84.585 52.181-46.721 0-84.589-7.035-84.589-52.181 0-10.809 5.324-20.845 14.441-29.174 15.208-13.881 40.946-6.531 70.147-6.531 29.07-.004 54.72-7.429 69.95 6.357z"/>
    <path id="eyes" d="m160.1 126.06 c0 13.994-7.88 25.336-17.6 25.336-9.72 0-17.6-11.342-17.6-25.336 0-13.992 7.88-25.33 17.6-25.33 9.72.01 17.6 11.34 17.6 25.33z m94.43 0 c0 13.994-7.88 25.336-17.6 25.336-9.72 0-17.6-11.342-17.6-25.336 0-13.992 7.88-25.33 17.6-25.33 9.72.01 17.6 11.34 17.6 25.33z"/>
    <path id="pupils" d="m154.46 126.38 c0 9.328-5.26 16.887-11.734 16.887s-11.733-7.559-11.733-16.887c0-9.331 5.255-16.894 11.733-16.894 6.47 0 11.73 7.56 11.73 16.89z m94.42 0 c0 9.328-5.26 16.887-11.734 16.887s-11.733-7.559-11.733-16.887c0-9.331 5.255-16.894 11.733-16.894 6.47 0 11.73 7.56 11.73 16.89z"/>
    <circle id="nose" cx="188.5" cy="148.56" r="4.401"/>
    <path id="mouth" d="m178.23 159.69c-.26-.738.128-1.545.861-1.805.737-.26 1.546.128 1.805.861 1.134 3.198 4.167 5.346 7.551 5.346s6.417-2.147 7.551-5.346c.26-.738 1.067-1.121 1.805-.861s1.121 1.067.862 1.805c-1.529 4.324-5.639 7.229-10.218 7.229s-8.68-2.89-10.21-7.22z"/>
    <path id="octo" d="m80.641 179.82 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m8.5 4.72 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m5.193 6.14 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m4.72 7.08 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m5.188 6.61 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m7.09 5.66 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m9.91 3.78 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m9.87 0 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m10.01 -1.64 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z"/>
    <path id="drop" d="m69.369 186.12l-3.066 10.683s-.8 3.861 2.84 4.546c3.8-.074 3.486-3.627 3.223-4.781z"/>
  </svg>
</div>

Using jQuery, for instance, you could do:

var _currentFill = "#f00"; // red
$svg = $("#octocat");
$("#face", $svg).attr('style', "fill:"+_currentFill); })

I provided a coloring book demo as an answer to another stackoverflow question: http://bl.ocks.org/4545199. Tested on Safari, Chrome, and Firefox.

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Android Studio Gradle Configuration with name 'default' not found

My solution is to simply remove a line from the settings.gradle file, which represents a module that doesn't exist:

include ':somesdk'

and also remove the corresponding line from the main project's build.gradle:

compile project(':somesdk')

Modulo operator in Python

you should use fmod(a,b)

While abs(x%y) < abs(y) is true mathematically, for floats it may not be true numerically due to roundoff.

For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that -1e-100 % 1e100 have the same sign as 1e100, the computed result is -1e-100 + 1e100, which is numerically exactly equal to 1e100.

Function fmod() in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100 in this case. Which approach is more appropriate depends on the application.

where x = a%b is used for integer modulo

Getting Access Denied when calling the PutObject operation with bucket-level permission

I had a similar issue uploading to an S3 bucket protected with KWS encryption. I have a minimal policy that allows the addition of objects under a specific s3 key.

I needed to add the following KMS permissions to my policy to allow the role to put objects in the bucket. (Might be slightly more than are strictly required)

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "kms:ListKeys",
                "kms:GenerateRandom",
                "kms:ListAliases",
                "s3:PutAccountPublicAccessBlock",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAllMyBuckets",
                "s3:HeadBucket"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "kms:ImportKeyMaterial",
                "kms:ListKeyPolicies",
                "kms:ListRetirableGrants",
                "kms:GetKeyPolicy",
                "kms:GenerateDataKeyWithoutPlaintext",
                "kms:ListResourceTags",
                "kms:ReEncryptFrom",
                "kms:ListGrants",
                "kms:GetParametersForImport",
                "kms:TagResource",
                "kms:Encrypt",
                "kms:GetKeyRotationStatus",
                "kms:GenerateDataKey",
                "kms:ReEncryptTo",
                "kms:DescribeKey"
            ],
            "Resource": "arn:aws:kms:<MY-REGION>:<MY-ACCOUNT>:key/<MY-KEY-GUID>"
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": [
            <The S3 actions>
            ],
            "Resource": [
                "arn:aws:s3:::<MY-BUCKET-NAME>",
                "arn:aws:s3:::<MY-BUCKET-NAME>/<MY-BUCKET-KEY>/*"
            ]
        }
    ]
}

Advantages of std::for_each over for loop

There are a lot of good reasons in other answers but all seem to forget that for_each allows you to use reverse or pretty much any custom iterator when for loop always starts with begin() iterator.

Example with reverse iterator:

std::list<int> l {1,2,3};
std::for_each(l.rbegin(), l.rend(), [](auto o){std::cout<<o;});

Example with some custom tree iterator:

SomeCustomTree<int> a{1,2,3,4,5,6,7};
auto node = a.find(4);
std::for_each(node.breadthFirstBegin(), node.breadthFirstEnd(), [](auto o){std::cout<<o;});

Getting time span between two times in C#?

Another way ( longer ) In VB.net [ Say 2300 Start and 0700 Finish next day ]

If tsStart > tsFinish Then

                            ' Take Hours difference and adjust accordingly
                            tsDifference = New TimeSpan((24 - tsStart.Hours) + tsFinish.Hours, 0, 0)

                            ' Add Minutes to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, Math.Abs(tsStart.Minutes - tsFinish.Minutes), 0))


                            ' Add Seonds to Difference
                            tsDifference = tsDifference.Add(New TimeSpan(0, 0, Math.Abs(tsStart.Seconds - tsFinish.Seconds)))

How to use google maps without api key

this simple code work 100% all you need is changing 'lat','long' for address to show

<iframe src="http://maps.google.com/maps?q=25.3076008,51.4803216&z=16&output=embed" height="450" width="600"></iframe>

How can I connect to a Tor hidden service using cURL in PHP?

I use Privoxy and cURL to scrape Tor pages:

<?php
    $ch = curl_init('http://jhiwjjlqpyawmpjx.onion'); // Tormail URL
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
    curl_setopt($ch, CURLOPT_PROXY, "localhost:8118"); // Default privoxy port
    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    curl_exec($ch);
    curl_close($ch);
?>

After installing Privoxy you need to add this line to the configuration file (/etc/privoxy/config). Note the space and '.' a the end of line.

forward-socks4a / localhost:9050 .

Then restart Privoxy.

/etc/init.d/privoxy restart

Gradle build without tests

Reference

To exclude any task from gradle use -x command-line option. See the below example

task compile << {
    println 'task compile'
}

task compileTest(dependsOn: compile) << {
    println 'compile test'
}

task runningTest(dependsOn: compileTest) << {
    println 'running test'
}
task dist(dependsOn:[runningTest, compileTest, compile]) << {
    println 'running distribution job'
}

Output of: gradle -q dist -x runningTest

task compile
compile test
running distribution job

Hope this would give you the basic

Reading int values from SqlDataReader

you can use

reader.GetInt32(3);

to read an 32 bit int from the data reader.

If you know the type of your data I think its better to read using the Get* methods which are strongly typed rather than just reading an object and casting.

Have you considered using

reader.GetInt32(reader.GetOrdinal(columnName)) 

rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.

Return a `struct` from a function in C

yes, it is possible we can pass structure and return structure as well. You were right but you actually did not pass the data type which should be like this struct MyObj b = a.

Actually I also came to know when I was trying to find out a better solution to return more than one values for function without using pointer or global variable.

Now below is the example for the same, which calculate the deviation of a student marks about average.

#include<stdio.h>
struct marks{
    int maths;
    int physics;
    int chem;
};

struct marks deviation(struct marks student1 , struct marks student2 );

int main(){

    struct marks student;
    student.maths= 87;
    student.chem = 67;
    student.physics=96;

    struct marks avg;
    avg.maths= 55;
    avg.chem = 45;
    avg.physics=34;
    //struct marks dev;
    struct marks dev= deviation(student, avg );
    printf("%d %d %d" ,dev.maths,dev.chem,dev.physics);

    return 0;
 }

struct marks deviation(struct marks student , struct marks student2 ){
    struct marks dev;

    dev.maths = student.maths-student2.maths;
    dev.chem = student.chem-student2.chem;
    dev.physics = student.physics-student2.physics; 

    return dev;
}

Test or check if sheet exists

My solution looks much like Tims but also works in case of non-worksheet sheets - charts

Public Function SheetExists(strSheetName As String, Optional wbWorkbook As Workbook) As Boolean
    If wbWorkbook Is Nothing Then Set wbWorkbook = ActiveWorkbook 'or ThisWorkbook - whichever appropriate
    Dim obj As Object
    On Error GoTo HandleError
    Set obj = wbWorkbook.Sheets(strSheetName)
    SheetExists = True
    Exit Function
HandleError:
    SheetExists = False
End Function

.

Dead simple example of using Multiprocessing Queue, Pool and Locking

This might be not 100% related to the question, but on my search for an example of using multiprocessing with a queue this shows up first on google.

This is a basic example class that you can instantiate and put items in a queue and can wait until queue is finished. That's all I needed.

from multiprocessing import JoinableQueue
from multiprocessing.context import Process


class Renderer:
    queue = None

    def __init__(self, nb_workers=2):
        self.queue = JoinableQueue()
        self.processes = [Process(target=self.upload) for i in range(nb_workers)]
        for p in self.processes:
            p.start()

    def render(self, item):
        self.queue.put(item)

    def upload(self):
        while True:
            item = self.queue.get()
            if item is None:
                break

            # process your item here

            self.queue.task_done()

    def terminate(self):
        """ wait until queue is empty and terminate processes """
        self.queue.join()
        for p in self.processes:
            p.terminate()

r = Renderer()
r.render(item1)
r.render(item2)
r.terminate()

JavaScript Editor Plugin for Eclipse

Complete the following steps in Eclipse to get plugins for JavaScript files:

  1. Open Eclipse -> Go to "Help" -> "Install New Software"
  2. Select the repository for your version of Eclipse. I have Juno so I selected http://download.eclipse.org/releases/juno
  3. Expand "Programming Languages" -> Check the box next to "JavaScript Development Tools"
  4. Click "Next" -> "Next" -> Accept the Terms of the License Agreement -> "Finish"
  5. Wait for the software to install, then restart Eclipse (by clicking "Yes" button at pop up window)
  6. Once Eclipse has restarted, open "Window" -> "Preferences" -> Expand "General" and "Editors" -> Click "File Associations" -> Add ".js" to the "File types:" list, if it is not already there
  7. In the same "File Associations" dialog, click "Add" in the "Associated editors:" section
  8. Select "Internal editors" radio at the top
  9. Select "JavaScript Viewer". Click "OK" -> "OK"

To add JavaScript Perspective: (Optional)
10. Go to "Window" -> "Open Perspective" -> "Other..."
11. Select "JavaScript". Click "OK"

To open .html or .js file with highlighted JavaScript syntax:
12. (Optional) Select JavaScript Perspective
13. Browse and Select .html or .js file in Script Explorer in [JavaScript Perspective] (Or Package Explorer [Java Perspective] Or PyDev Package Explorer [PyDev Perspective] Don't matter.)
14. Right-click on .html or .js file -> "Open With" -> "Other..."
15. Select "Internal editors"
16. Select "Java Script Editor". Click "OK" (see JavaScript syntax is now highlighted )

There is no tracking information for the current branch

The same thing happened to me before when I created a new git branch while not pushing it to origin.

Try to execute those two lines first:

git checkout -b name_of_new_branch # create the new branch
git push origin name_of_new_branch # push the branch to github

Then:

git pull origin name_of_new_branch

It should be fine now!

Best lightweight web server (only static content) for Windows

Have a look at Cassini. This is basically what Visual Studio uses for its built-in debug web server. I've used it with Umbraco and it seems quite good.

Example to use shared_ptr?

The best way to add different objects into same container is to use make_shared, vector, and range based loop and you will have a nice, clean and "readable" code!

typedef std::shared_ptr<gate> Ptr   
vector<Ptr> myConatiner; 
auto andGate = std::make_shared<ANDgate>();
myConatiner.push_back(andGate );
auto orGate= std::make_shared<ORgate>();
myConatiner.push_back(orGate);

for (auto& element : myConatiner)
    element->run();

Get column index from column name in python pandas

Here is a solution through list comprehension. cols is the list of columns to get index for:

[df.columns.get_loc(c) for c in cols if c in df]

How to count down in for loop?

In python, when you have an iterable, usually you iterate without an index:

letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
    print(l)

If you need to traverse the iterable in reverse order, you would do:

for l in letters[::-1]:
    print(l)

When for any reason you need the index, you can use enumerate:

for i, l in enumerate(letters, start=1): #start is 0 by default
    print(i,l)

You can enumerate in reverse order too...

for i, l in enumerate(letters[::-1])
    print(i,l)

ON ANOTHER NOTE...

Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map:

If we need to capitilize each letter:

map(str.upper, letters)

Or get the Unicode code of each letter:

map(ord, letters)

Swift add icon/image in UITextField

enter image description here
Another way to set placeholder icon & set padding to TextField.

let userIcon = UIImage(named: "ImageName") 
setPaddingWithImage(image: userIcon, textField: txtUsername)

func setPaddingWithImage(image: UIImage, textField: UITextField){
    let imageView = UIImageView(image: image)
    imageView.contentMode = .scaleAspectFit
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 50))
    imageView.frame = CGRect(x: 13.0, y: 13.0, width: 24.0, height: 24.0)
    //For Setting extra padding other than Icon.
    let seperatorView = UIView(frame: CGRect(x: 50, y: 0, width: 10, height: 50))
    seperatorview.backgroundColor = UIColor(red: 80/255, green: 89/255, blue: 94/255, alpha: 1)
    view.addSubview(seperatorView)
    textField.leftViewMode = .always
    view.addSubview(imageView)
    view.backgroundColor = .darkGray
    textField.leftViewMode = UITextFieldViewMode.always
    textField.leftView = view
}

programmatically add column & rows to WPF Datagrid

To programatically add a row:

DataGrid.Items.Add(new DataItem());

To programatically add a column:

DataGridTextColumn textColumn = new DataGridTextColumn(); 
textColumn.Header = "First Name"; 
textColumn.Binding = new Binding("FirstName"); 
dataGrid.Columns.Add(textColumn); 

Check out this post on the WPF DataGrid discussion board for more information.

Read String line by line

There is also Scanner. You can use it just like the BufferedReader:

Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  // process the line
}
scanner.close();

I think that this is a bit cleaner approach that both of the suggested ones.

How to call Oracle MD5 hash function?

To calculate MD5 hash of CLOB content field with my desired encoding without implicitly recoding content to AL32UTF8, I've used this code:

create or replace function clob2blob(AClob CLOB) return BLOB is
  Result BLOB;
  o1 integer;
  o2 integer;
  c integer;
  w integer;
begin
  o1 := 1;
  o2 := 1;
  c := 0;
  w := 0;
  DBMS_LOB.CreateTemporary(Result, true);
  DBMS_LOB.ConvertToBlob(Result, AClob, length(AClob), o1, o2, 0, c, w);
  return(Result);
end clob2blob;
/

update my_table t set t.hash = (rawtohex(DBMS_CRYPTO.Hash(clob2blob(t.content),2)));

In jQuery, what's the best way of formatting a number to 2 decimal places?

We modify a Meouw function to be used with keyup, because when you are using an input it can be more helpful.

Check this:

Hey there!, @heridev and I created a small function in jQuery.

You can try next:

HTML

<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">?

jQuery

// apply the two-digits behaviour to elements with 'two-digits' as their class
$( function() {
    $('.two-digits').keyup(function(){
        if($(this).val().indexOf('.')!=-1){         
            if($(this).val().split(".")[1].length > 2){                
                if( isNaN( parseFloat( this.value ) ) ) return;
                this.value = parseFloat(this.value).toFixed(2);
            }  
         }            
         return this; //for chaining
    });
});

? DEMO ONLINE:

http://jsfiddle.net/c4Wqn/

(@heridev, @vicmaster)

Programmatically set the initial view controller using Storyboards

Found simple solution - no need to remove "initial view controller check" from storyboard and editing project Info tab and use makeKeyAndVisible, just place

self.window.rootViewController = rootVC;

in

- (BOOL) application:didFinishLaunchingWithOptions:

Global variables in c#.net

I second jdk's answer: any public static member of any class of your application can be considered as a "global variable".

However, do note that this is an ASP.NET application, and as such, it's a multi-threaded context for your global variables. Therefore, you should use some locking mechanism when you update and/or read the data to/from these variables. Otherwise, you might get your data in a corrupted state.

jQuery UI Dialog individual CSS styling

I created custom styles by just overriding jQuery classes in inline style. So on top of the page, you have the jQuery CSS linked and right after that override the classes you need to modify:

<head>
    <link href="/Content/theme/base/jquery.ui.all.css" rel="stylesheet"/>

    <style type="text/css">
        .ui-dialog .ui-dialog-content
        {
            position: relative;
            border: 0;
            padding: .5em 1em;
            background: none;
            overflow: auto;
            zoom: 1;
            background-color: #ffd;
            border: solid 1px #ea7;
        }

        .ui-dialog .ui-dialog-titlebar
        {
            display:none;
        }

        .ui-widget-content
        {
            border:none;
        }
    </style>
</head>

How to export html table to excel using javascript

Check https://github.com/linways/table-to-excel. Its a wrapper for exceljs/exceljs to export html tables to xlsx.

_x000D_
_x000D_
TableToExcel.convert(document.getElementById("simpleTable1"));
_x000D_
<script src="https://cdn.jsdelivr.net/gh/linways/[email protected]/dist/tableToExcel.js"></script>_x000D_
<table id="simpleTable1" data-cols-width="70,15,10">_x000D_
<tbody>_x000D_
    <tr>_x000D_
        <td class="header" colspan="5" data-f-sz="25" data-f-color="FFFFAA00" data-a-h="center" data-a-v="middle" data-f-underline="true">_x000D_
            Sample Excel_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="5" data-f-italic="true" data-a-h="center" data-f-name="Arial" data-a-v="top">_x000D_
            Italic and horizontal center in Arial_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <th data-a-text-rotation="90">Col 1 (number)</th>_x000D_
        <th data-a-text-rotation="vertical">Col 2</th>_x000D_
        <th data-a-wrap="true">Wrapped Text</th>_x000D_
        <th data-a-text-rotation="-45">Col 4 (date)</th>_x000D_
        <th data-a-text-rotation="-90">Col 5</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td rowspan="1" data-t="n">1</td>_x000D_
        <td rowspan="1" data-b-b-s="thick" data-b-l-s="thick" data-b-r-s="thick">_x000D_
            ABC1_x000D_
        </td>_x000D_
        <td rowspan="1" data-f-strike="true">Striked Text</td>_x000D_
        <td data-t="d">05-20-2018</td>_x000D_
        <td data-t="n" data-num-fmt="$ 0.00">2210.00</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
        <td rowspan="2" data-t="n">2</td>_x000D_
        <td rowspan="2" data-fill-color="FFFF0000" data-f-color="FFFFFFFF">_x000D_
            ABC 2_x000D_
        </td>_x000D_
        <td rowspan="2" data-a-indent="3">Merged cell</td>_x000D_
        <td data-t="d">05-21-2018</td>_x000D_
        <td data-t="n" data-b-a-s="dashed" data-num-fmt="$ 0.00">230.00</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-t="d">05-22-2018</td>_x000D_
_x000D_
        <td data-t="n" data-num-fmt="$ 0.00">2493.00</td>_x000D_
    </tr>_x000D_
_x000D_
    <tr>_x000D_
        <td colspan="4" align="right" data-f-bold="true" data-a-h="right" data-hyperlink="https://google.com">_x000D_
            <b><a href="https://google.com">Hyperlink</a></b>_x000D_
        </td>_x000D_
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
            <b>4933.00</b>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="4" align="right" data-f-bold="true" data-a-rtl="true">_x000D_
            ?????_x000D_
        </td>_x000D_
        <td colspan="1" align="right" data-t="n" data-f-bold="true" data-num-fmt="$ 0.00">_x000D_
            <b>2009.00</b>_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-b-a-s="dashed" data-b-a-c="FFFF0000">All borders</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-t="b">true</td>_x000D_
        <td data-t="b">false</td>_x000D_
        <td data-t="b">1</td>_x000D_
        <td data-t="b">0</td>_x000D_
        <td data-error="#VALUE!">Value Error</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td data-b-t-s="thick" data-b-l-s="thick" data-b-b-s="thick" data-b-r-s="thick" data-b-t-c="FF00FF00" data-b-l-c="FF00FF00" data-b-b-c="FF00FF00" data-b-r-c="FF00FF00">_x000D_
            All borders separately_x000D_
        </td>_x000D_
    </tr>_x000D_
    <tr data-exclude="true">_x000D_
        <td>Excluded row</td>_x000D_
        <td>Something</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Included Cell</td>_x000D_
        <td data-exclude="true">Excluded Cell</td>_x000D_
        <td>Included Cell</td>_x000D_
    </tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This creates valid xlsx on the client side. Also supports some basic styling. Check https://codepen.io/rohithb/pen/YdjVbb for a working example.

Make one div visible and another invisible

You can use the display property of style. Intialy set the result section style as

style = "display:none"

Then the div will not be visible and there won't be any white space.

Once the search results are being populated change the display property using the java script like

document.getElementById("someObj").style.display = "block"

Using java script you can make the div invisible

document.getElementById("someObj").style.display = "none"

Get Wordpress Category from Single Post

<div class="post_category">
        <?php $category = get_the_category();
             $allcategory = get_the_category(); 
        foreach ($allcategory as $category) {
        ?>
           <a class="btn"><?php echo $category->cat_name;; ?></a>
        <?php 
        }
        ?>
 </div>

How can I change my Cygwin home folder after installation?

Starting with Cygwin 1.7.34, the recommended way to do this is to add a custom db_home setting to /etc/nsswitch.conf. A common wish when doing this is to make your Cygwin home directory equal to your Windows user profile directory. This setting will do that:

db_home: windows

Or, equivalently:

db_home: /%H

You need to use the latter form if you want some variation on this scheme, such as to segregate your Cygwin home files into a subdirectory of your Windows user profile directory:

db_home: /%H/cygwin

There are several other alternative schemes for the windows option plus several other % tokens you can use instead of %H or in addition to it. See the nsswitch.conf syntax description in the Cygwin User Guide for details.

If you installed Cygwin prior to 1.7.34 or have run its mkpasswd utility so that you have an /etc/passwd file, you can change your Cygwin home directory by editing your user's entry in that file. Your home directory is the second-to-last element on your user's line in /etc/passwd

Whichever way you do it, this causes the HOME environment variable to be set during shell startup.²

See this FAQ item for more on the topic.


Footnotes:

  1. Consider moving /etc/passwd and /etc/group out of the way in order to use the new SAM/AD-based mechanism instead.

  2. While it is possible to simply set %HOME% via the Control Panel, it is officially discouraged. Not only does it unceremoniously override the above mechanisms, it doesn't always work, such as when running shell scripts via cron.

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

Returning a value from callback function in Node.js

Example code for node.js - async function to sync function:

var deasync = require('deasync');

function syncFunc()
{
    var ret = null;
    asyncFunc(function(err, result){
        ret = {err : err, result : result}
    });

    while((ret == null))
    {
         deasync.runLoopOnce();
    }

    return (ret.err || ret.result);
}

In python, how do I cast a class object to a dict

I am trying to write a class that is "both" a list or a dict. I want the programmer to be able to both "cast" this object to a list (dropping the keys) or dict (with the keys).

Looking at the way Python currently does the dict() cast: It calls Mapping.update() with the object that is passed. This is the code from the Python repo:

def update(self, other=(), /, **kwds):
    ''' D.update([E, ]**F) -> None.  Update D from mapping/iterable E and F.
        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
        In either case, this is followed by: for k, v in F.items(): D[k] = v
    '''
    if isinstance(other, Mapping):
        for key in other:
            self[key] = other[key]
    elif hasattr(other, "keys"):
        for key in other.keys():
            self[key] = other[key]
    else:
        for key, value in other:
            self[key] = value
    for key, value in kwds.items():
        self[key] = value

The last subcase of the if statement, where it is iterating over other is the one most people have in mind. However, as you can see, it is also possible to have a keys() property. That, combined with a __getitem__() should make it easy to have a subclass be properly casted to a dictionary:

class Wharrgarbl(object):
    def __init__(self, a, b, c, sum, version='old'):
        self.a = a
        self.b = b
        self.c = c
        self.sum = 6
        self.version = version

    def __int__(self):
        return self.sum + 9000

    def __keys__(self):
        return ["a", "b", "c"]

    def __getitem__(self, key):
        # have obj["a"] -> obj.a
        return self.__getattribute__(key)

Then this will work:

>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> dict(w)
{'a': 'one', 'c': 'three', 'b': 'two'}

C++/CLI Converting from System::String^ to std::string

This worked for me:

#include <stdlib.h>
#include <string.h>
#include <msclr\marshal_cppstd.h>
//..
using namespace msclr::interop;
//..
System::String^ clrString = (TextoDeBoton);
std::string stdString = marshal_as<std::string>(clrString); //String^ to std
//System::String^ myString = marshal_as<System::String^>(MyBasicStirng); //std to String^
prueba.CopyInfo(stdString); //MyMethod
//..
//Where: String^ = TextoDeBoton;
//and stdString is a "normal" string;

Difference between "process.stdout.write" and "console.log" in node.js?

Another important difference in this context would with process.stdout.clearLine() and process.stdout.cursorTo(0).

This would be useful if you want to show percentage of download or processing in the only one line. If you use clearLine(), cursorTo() with console.log() it doesn't work because it also append \n to the text. Just try out this example:

var waitInterval = 500;
var totalTime = 5000;
var currentInterval = 0;

function showPercentage(percentage){
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
    console.log(`Processing ${percentage}%...` ); //replace this line with process.stdout.write(`Processing ${percentage}%...`);
}

var interval = setInterval(function(){
 currentInterval += waitInterval;
 showPercentage((currentInterval/totalTime) * 100);
}, waitInterval);

setTimeout(function(){
 clearInterval(interval); 
}, totalTime);

String to date in Oracle with milliseconds

I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Play audio with Python

This is the easiest & best iv'e found. It supports Linux/pulseaudio, Mac/coreaudio, and Windows/WASAPI.

import soundfile as sf
import soundcard as sc

default_speaker = sc.default_speaker()
samples, samplerate = sf.read('bell.wav')

default_speaker.play(samples, samplerate=samplerate)

See https://github.com/bastibe/PySoundFile and https://github.com/bastibe/SoundCard for tons of other super-useful features.

ImportError: No module named PIL

use pil instead of PIL

from pil import Image

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

The accepted answer doesn't quite work when you have foreign key relationships. In that case you have to drop the constraints and recreate them. Below is a stored proc for doing that based on the answer here

CREATE PROCEDURE [dbo].[deleteAllDataFromAllTables] AS
SET NOCOUNT ON

    DECLARE @dropAndCreateConstraintsTable TABLE ( DropStmt varchar(max) , CreateStmt varchar(max) )

    insert @dropAndCreateConstraintsTable select
      DropStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema + 
          '].[' + ForeignKeys.ForeignTableName + 
          '] DROP CONSTRAINT [' + ForeignKeys.ForeignKeyName + ']; '
    ,  CreateStmt = 'ALTER TABLE [' + ForeignKeys.ForeignTableSchema + 
          '].[' + ForeignKeys.ForeignTableName + 
          '] WITH CHECK ADD CONSTRAINT [' +  ForeignKeys.ForeignKeyName + 
          '] FOREIGN KEY([' + ForeignKeys.ForeignTableColumn + 
          ']) REFERENCES [' + schema_name(sys.objects.schema_id) + '].[' +
      sys.objects.[name] + ']([' +
      sys.columns.[name] + ']); '
     from sys.objects
      inner join sys.columns
        on (sys.columns.[object_id] = sys.objects.[object_id])
      inner join (
        select sys.foreign_keys.[name] as ForeignKeyName
         ,schema_name(sys.objects.schema_id) as ForeignTableSchema
         ,sys.objects.[name] as ForeignTableName
         ,sys.columns.[name]  as ForeignTableColumn
         ,sys.foreign_keys.referenced_object_id as referenced_object_id
         ,sys.foreign_key_columns.referenced_column_id as referenced_column_id
         from sys.foreign_keys
          inner join sys.foreign_key_columns
            on (sys.foreign_key_columns.constraint_object_id
              = sys.foreign_keys.[object_id])
          inner join sys.objects
            on (sys.objects.[object_id]
              = sys.foreign_keys.parent_object_id)
            inner join sys.columns
              on (sys.columns.[object_id]
                = sys.objects.[object_id])
               and (sys.columns.column_id
                = sys.foreign_key_columns.parent_column_id)
        ) ForeignKeys
        on (ForeignKeys.referenced_object_id = sys.objects.[object_id])
         and (ForeignKeys.referenced_column_id = sys.columns.column_id)
     where (sys.objects.[type] = 'U')
      and (sys.objects.[name] not in ('sysdiagrams'))


    DECLARE @DropStatement nvarchar(max)
    DECLARE @RecreateStatement nvarchar(max)

    DECLARE C1 CURSOR READ_ONLY
    FOR
    SELECT DropStmt from @dropAndCreateConstraintsTable
    OPEN C1

    FETCH NEXT FROM C1 INTO @DropStatement

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Executing ' + @DropStatement
        execute sp_executesql @DropStatement
        FETCH NEXT FROM C1 INTO @DropStatement
    END
    CLOSE C1
    DEALLOCATE C1

    DECLARE @DeleteTableStatement nvarchar(max)
    DECLARE C2 CURSOR READ_ONLY
    FOR
    SELECT 'Delete From [dbo].[' + TABLE_NAME + ']' from INFORMATION_SCHEMA.TABLES 
        WHERE TABLE_SCHEMA = 'dbo' -- Change your schema appropriately.
    OPEN C2

    FETCH NEXT FROM C2 INTO @DeleteTableStatement

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Executing ' + @DeleteTableStatement
        execute sp_executesql @DeleteTableStatement
        FETCH NEXT FROM C2 INTO  @DeleteTableStatement
    END
    CLOSE C2
    DEALLOCATE C2

    DECLARE C3 CURSOR READ_ONLY
    FOR
    SELECT CreateStmt from @dropAndCreateConstraintsTable
    OPEN C3

    FETCH NEXT FROM C3 INTO @RecreateStatement

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT 'Executing ' + @RecreateStatement
        execute sp_executesql @RecreateStatement
        FETCH NEXT FROM C3 INTO  @RecreateStatement
    END
    CLOSE C3
    DEALLOCATE C3

GO

Does height and width not apply to span?

Span takes width and height only when we make it block element.

span {display:block;}

Python: split a list based on a condition?

I basically like Anders' approach as it is very general. Here's a version that puts the categorizer first (to match filter syntax) and uses a defaultdict (assumed imported).

def categorize(func, seq):
    """Return mapping from categories to lists
    of categorized items.
    """
    d = defaultdict(list)
    for item in seq:
        d[func(item)].append(item)
    return d

How to go from Blob to ArrayBuffer

await blob.arrayBuffer() is good.

The problem is when iOS / Safari support is needed.. for that one would need this:

Blob.prototype.arrayBuffer ??=function(){ return new Response(this).arrayBuffer() }

jQuery: Get the cursor position of text in input without browser specific code?

A warning about the Jquery Caret plugin.

It will conflict with the Masked Input plugin (or vice versa). Fortunately the Masked Input plugin includes a caret() function of its own, which you can use very similarly to the Caret plugin for your basic needs - $(element).caret().begin or .end

Increment counter with loop

You can use varStatus in your c:forEach loop

In your first example you can get the counter to work properly as follows...

<c:forEach var="tableEntity" items='${requestScope.tables}'>
   <c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="count">            
        my count is ${count.count}
    </c:forEach>
</c:forEach>

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I just received a response from Kinook, who gave me a link:

Basically, I need to call the following prior to bulding. I guess Visual Studio 2013 does not automatically register the environment first, but 2012 did, or I did and forgot.

call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x86

Hopefully, this post helps someone else.

How can I get the current directory name in Javascript?

This one-liner works:

var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

As pointed out by @Jayan in another post, the solution was to do the following

import jenkins.model.*
jenkins = Jenkins.instance

Then I was able to do the rest of my scripting the way it was.

SQLAlchemy IN clause

Just wanted to share my solution using sqlalchemy and pandas in python 3. Perhaps, one would find it useful.

import sqlalchemy as sa
import pandas as pd
engine = sa.create_engine("postgresql://postgres:my_password@my_host:my_port/my_db")
values = [val1,val2,val3]   
query = sa.text(""" 
                SELECT *
                FROM my_table
                WHERE col1 IN :values; 
""")
query = query.bindparams(values=tuple(values))
df = pd.read_sql(query, engine)

Center Plot title in ggplot2

The ggeasy package has a function called easy_center_title() to do just that. I find it much more appealing than theme(plot.title = element_text(hjust = 0.5)) and it's so much easier to remember.

ggplot(data = dat, aes(time, total_bill, fill = time)) + 
  geom_bar(colour = "black", fill = "#DD8888", width = .8, stat = "identity") + 
  guides(fill = FALSE) +
  xlab("Time of day") +
  ylab("Total bill") +
  ggtitle("Average bill for 2 people") +
  ggeasy::easy_center_title()

enter image description here

Note that as of writing this answer you will need to install the development version of ggeasy from GitHub to use easy_center_title(). You can do so by running remotes::install_github("jonocarroll/ggeasy").

Spring Boot - Loading Initial Data

You can use something like this:

@SpringBootApplication  
public class Application {

@Autowired
private UserRepository userRepository;

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Bean
InitializingBean sendDatabase() {
    return () -> {
        userRepository.save(new User("John"));
        userRepository.save(new User("Rambo"));
      };
   }
}

What is the difference between "::" "." and "->" in c++

In C++ you can access fields or methods, using different operators, depending on it's type:

  • ClassName::FieldName : class public static field and methods
  • ClassInstance.FieldName : accessing a public field (or method) through class reference
  • ClassPointer->FieldName : accessing a public field (or method) dereferencing a class pointer

Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.

class AClass{
public:
static int static_field;
int instance_field;

static void static_method();
void method();
};

then you access this way:

AClass instance;
AClass *pointer = new AClass();

instance.instance_field; //access instance_field through a reference to AClass
instance.method();

pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();

AClass::static_field;  
AClass::static_method();

jQuery How to Get Element's Margin and Padding?

Border

I believe you can get the border width using .css('border-left-width'). You can also fetch top, right, and bottom and compare them to find the max value. The key here is that you have to specify a specific side.

Padding

See jQuery calculate padding-top as integer in px

Margin

Use the same logic as border or padding.

Alternatively, you could use outerWidth. The pseudo-code should be
margin = (outerWidth(true) - outerWidth(false)) / 2. Note that this only works for finding the margin horizontally. To find the margin vertically, you would need to use outerHeight.

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

How using try catch for exception handling is best practice

An exception is a blocking error.

First of all, the best practice should be don't throw exceptions for any kind of error, unless it's a blocking error.

If the error is blocking, then throw the exception. Once the exception is already thrown, there's no need to hide it because it's exceptional; let the user know about it (you should reformat the whole exception to something useful to the user in the UI).

Your job as software developer is to endeavour to prevent an exceptional case where some parameter or runtime situation may end in an exception. That is, exceptions mustn't be muted, but these must be avoided.

For example, if you know that some integer input could come with an invalid format, use int.TryParse instead of int.Parse. There is a lot of cases where you can do this instead of just saying "if it fails, simply throw an exception".

Throwing exceptions is expensive.

If, after all, an exception is thrown, instead of writing the exception to the log once it has been thrown, one of best practices is catching it in a first-chance exception handler. For example:

  • ASP.NET: Global.asax Application_Error
  • Others: AppDomain.FirstChanceException event.

My stance is that local try/catches are better suited for handling special cases where you may translate an exception into another, or when you want to "mute" it for a very, very, very, very, very special case (a library bug throwing an unrelated exception that you need to mute in order to workaround the whole bug).

For the rest of the cases:

  • Try to avoid exceptions.
  • If this isn't possible: first-chance exception handlers.
  • Or use a PostSharp aspect (AOP).

Answering to @thewhiteambit on some comment...

@thewhiteambit said:

Exceptions are not Fatal-Errors, they are Exceptions! Sometimes they are not even Errors, but to consider them Fatal-Errors is completely false understanding of what Exceptions are.

First of all, how an exception can't be even an error?

  • No database connection => exception.
  • Invalid string format to parse to some type => exception
  • Trying to parse JSON and while input isn't actually JSON => exception
  • Argument null while object was expected => exception
  • Some library has a bug => throws an unexpected exception
  • There's a socket connection and it gets disconnected. Then you try to send a message => exception
  • ...

We might list 1k cases of when an exception is thrown, and after all, any of the possible cases will be an error.

An exception is an error, because at the end of the day it is an object which collects diagnostic information -- it has a message and it happens when something goes wrong.

No one would throw an exception when there's no exceptional case. Exceptions should be blocking errors because once they're thrown, if you don't try to fall into the use try/catch and exceptions to implement control flow they mean your application/service will stop the operation that entered into an exceptional case.

Also, I suggest everyone to check the fail-fast paradigm published by Martin Fowler (and written by Jim Shore). This is how I always understood how to handle exceptions, even before I got to this document some time ago.

[...] consider them Fatal-Errors is completely false understanding of what exceptions are.

Usually exceptions cut some operation flow and they're handled to convert them to human-understandable errors. Thus, it seems like an exception actually is a better paradigm to handle error cases and work on them to avoid an application/service complete crash and notify the user/consumer that something went wrong.

More answers about @thewhiteambit concerns

For example in case of a missing Database-Connection the program could exceptionally continue with writing to a local file and send the changes to the Database once it is available again. Your invalid String-To-Number casting could be tried to parse again with language-local interpretation on Exception, like as you try default English language to Parse("1,5") fails and you try it with German interpretation again which is completely fine because we use comma instead of point as separator. You see these Exceptions must not even be blocking, they only need some Exception-handling.

  1. If your app might work offline without persisting data to database, you shouldn't use exceptions, as implementing control flow using try/catch is considered as an anti-pattern. Offline work is a possible use case, so you implement control flow to check if database is accessible or not, you don't wait until it's unreachable.

  2. The parsing thing is also an expected case (not EXCEPTIONAL CASE). If you expect this, you don't use exceptions to do control flow!. You get some metadata from the user to know what his/her culture is and you use formatters for this! .NET supports this and other environments too, and an exception because number formatting must be avoided if you expect a culture-specific usage of your application/service.

An unhandled Exception usually becomes an Error, but Exceptions itself are not codeproject.com/Articles/15921/Not-All-Exceptions-Are-Errors

This article is just an opinion or a point of view of the author.

Since Wikipedia can be also just the opinion of articule author(s), I wouldn't say it's the dogma, but check what Coding by exception article says somewhere in some paragraph:

[...] Using these exceptions to handle specific errors that arise to continue the program is called coding by exception. This anti-pattern can quickly degrade software in performance and maintainability.

It also says somewhere:

Incorrect exception usage

Often coding by exception can lead to further issues in the software with incorrect exception usage. In addition to using exception handling for a unique problem, incorrect exception usage takes this further by executing code even after the exception is raised. This poor programming method resembles the goto method in many software languages but only occurs after a problem in the software is detected.

Honestly, I believe that software can't be developed don't taking use cases seriously. If you know that...

  • Your database can go offline...
  • Some file can be locked...
  • Some formatting might be not supported...
  • Some domain validation might fail...
  • Your app should work in offline mode...
  • whatever use case...

...you won't use exceptions for that. You would support these use cases using regular control flow.

And if some unexpected use case isn't covered, your code will fail fast, because it'll throw an exception. Right, because an exception is an exceptional case.

In the other hand, and finally, sometimes you cover exceptional cases throwing expected exceptions, but you don't throw them to implement control flow. You do it because you want to notify upper layers that you don't support some use case or your code fails to work with some given arguments or environment data/properties.

DBNull if statement

Yes, just a syntax problem. Try this instead:

if (reader["usr.ursrdaystime"] != DBNull.Value)

.Equals() is checking to see if two Object instances are the same.

jQuery find file extension (from string)

Another way (which avoids extended switch-case statements) is to define arrays of file extensions for similar processing and use a function to check the extension result against an array (with comments):

// Define valid file extension arrays (according to your needs)
var _docExts = ["pdf", "doc", "docx", "odt"];
var _imgExts = ["jpg", "jpeg", "png", "gif", "ico"];
// Checks whether an extension is included in the array
function isExtension(ext, extnArray) {
    var result = false;
    var i;
    if (ext) {
        ext = ext.toLowerCase();
        for (i = 0; i < extnArray.length; i++) {
            if (extnArray[i].toLowerCase() === ext) {
                result = true;
                break;
            }
        }
    }
    return result;
}
// Test file name and extension
var testFileName = "example-filename.jpeg";
// Get the extension from the filename
var extn = testFileName.split('.').pop();
// boolean check if extensions are in parameter array
var isDoc = isExtension(extn, _docExts);
var isImg = isExtension(extn, _imgExts);
console.log("==> isDoc: " + isDoc + " => isImg: " + isImg);
// Process according to result: if(isDoc) { // .. etc }

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

You can use google map Obtaining User Location here!

After obtaining your location(longitude and latitude), you can use google place api

This code can help you get your location easily but not the best way.

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);  

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

Declare an output cursor variable to the inner sp :

@c CURSOR VARYING OUTPUT

Then declare a cursor c to the select you want to return. Then open the cursor. Then set the reference:

DECLARE c CURSOR LOCAL FAST_FORWARD READ_ONLY FOR 
SELECT ...
OPEN c
SET @c = c 

DO NOT close or reallocate.

Now call the inner sp from the outer one supplying a cursor parameter like:

exec sp_abc a,b,c,, @cOUT OUTPUT

Once the inner sp executes, your @cOUT is ready to fetch. Loop and then close and deallocate.

AngularJS open modal on button click

You should take a look at Batarang for AngularJS debugging

As for your issue:

Your scope variable is not directly attached to the modal correctly. Below is the adjusted code. You need to specify when the modal shows using ng-show

<!-- Confirmation Dialog -->
<div class="modal" modal="showModal" ng-show="showModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Delete confirmation</h4>
      </div>
      <div class="modal-body">
        <p>Are you sure?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="cancel()">No</button>
        <button type="button" class="btn btn-primary" ng-click="ok()">Yes</button>
      </div>
    </div>
  </div>
</div>
<!-- End of Confirmation Dialog -->

Django - iterate number in for loop of a template

{% for days in days_list %}
    <h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

or if you want to start from 0

{% for days in days_list %}
        <h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
    {% endfor %}

Read response headers from API response - Angular 5 + TypeScript

As Hrishikesh Kale has explained we need to pass the Access-Control-Expose-Headers.

Here how we can do it in the WebAPI/MVC environment:

protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
                HttpContext.Current.Response.End();
            }
        }

Another way is we can add code as below in the webApiconfig.cs file.

config.EnableCors(new EnableCorsAttribute("", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });

**We can add custom headers in the web.config file as below. *

<httpProtocol>
   <customHeaders>
      <add name="Access-Control-Expose-Headers" value="TestHeaderToExpose" />
   </customHeaders>
</httpProtocol>

we can create an attribute and decore the method with the attribute.

Happy Coding !!

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I used an approach described by Eric Daugherty: I created a special servlet that always answers with 403 code and put its mapping before the general one.

Mapping fragment:

  <servlet>
    <servlet-name>generalServlet</servlet-name>
    <servlet-class>project.servlet.GeneralServlet</servlet-class>
  </servlet>
 <servlet>
    <servlet-name>specialServlet</servlet-name>
    <servlet-class>project.servlet.SpecialServlet</servlet-class>
 </servlet>
 <servlet-mapping>
    <servlet-name>specialServlet</servlet-name>
    <url-pattern>/resources/restricted/*</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
    <servlet-name>generalServlet</servlet-name>
    <url-pattern>/resources/*</url-pattern>
 </servlet-mapping>

And the servlet class:

public class SpecialServlet extends HttpServlet {
    public SpecialServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}

How to test for $null array in PowerShell

If your solution requires returning 0 instead of true/false, I've found this to be useful:

PS C:\> [array]$foo = $null
PS C:\> ($foo | Measure-Object).Count
0

This operation is different from the count property of the array, because Measure-Object is counting objects. Since there are none, it will return 0.

Change Placeholder Text using jQuery

change placeholder text using jquery

try this

$('#selector').attr("placeholder", "Type placeholder");

How to pass arguments within docker-compose?

This feature was added in Compose 1.6.

Reference: https://docs.docker.com/compose/compose-file/#args

services:
  web:
    build:
      context: .
      args:
        FOO: foo

Changing password with Oracle SQL Developer

You can now do this in SQL Developer 4.1.0.17, no PL/SQL required, assuming you have another account that has administrative privileges:

  1. Create a connection to the database in SQL Developer 4.1.0.17 with an alternative administrative user
  2. Expand the "Other Users" section once connected, and right-click the user whose password has expired. Choose "Edit User".
  3. Uncheck the "Password Expired..." checkbox, type in a new password for the user, and hit "Save".
  4. Job done! You can test by connecting with the user whose password had expired, to confirm it is now valid again.

How can I Insert data into SQL Server using VBNet

Function ExtSql(ByVal sql As String) As Boolean
    Dim cnn As SqlConnection
    Dim cmd As SqlCommand
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        cmd = New SqlCommand
        cmd.Connection = cnn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = sql
        cmd.ExecuteNonQuery()
        cnn.Close()
        cmd.Dispose()
    Catch ex As Exception
        cnn.Close()
        Return False
    End Try
    Return True
End Function

How do I assign a port mapping to an existing Docker container?

For Windows & Mac Users, there is another pretty easy and friendly way to change the mapping port:

  1. download kitematic

  2. go to the settings page of the container, on the ports tab, you can directly modify the published port there.

  3. start the container again

Convert all data frame character columns to factors

As @Raf Z commented on this question, dplyr now has mutate_if. Super useful, simple and readable.

> str(df)
'data.frame':   5 obs. of  5 variables:
 $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
 $ B: int  1 2 3 4 5
 $ C: logi  TRUE TRUE FALSE FALSE TRUE
 $ D: chr  "a" "b" "c" "d" ...
 $ E: chr  "A a" "B b" "C c" "D d" ...

> df <- df %>% mutate_if(is.character,as.factor)

> str(df)
'data.frame':   5 obs. of  5 variables:
 $ A: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
 $ B: int  1 2 3 4 5
 $ C: logi  TRUE TRUE FALSE FALSE TRUE
 $ D: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
 $ E: Factor w/ 5 levels "A a","B b","C c",..: 1 2 3 4 5

Font size of TextView in Android application changes on changing font size from native settings

change the DP to sp it is good pratice for android android:textSize="18sp"

Vertical Align text in a Label

To do this you should alter the vertical-align property of the input.

<dd><label class="<?=$email_confirm_class;?>" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; border:none;" name="email_confirm" id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>" tabindex="4" /> *</dd>

Here is a more complete version. It has been tested in IE 8 and it works. see the difference by removing the vertical-align: middle from the input:

<html><head></head><body><dl><dt>test</dt><dd><label class="test" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; font-size: 22px" name="email_confirm" id="email_confirm" size="28" value="test" tabindex="4" /> *</dd></dl></body></html>

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

How do you build a Singleton in Dart?

Hello what about something like this? Very simple implementation, Injector itself is singleton and also added classes into it. Of course can be extended very easily. If you are looking for something more sophisticated check this package: https://pub.dartlang.org/packages/flutter_simple_dependency_injection

void main() {  
  Injector injector = Injector();
  injector.add(() => Person('Filip'));
  injector.add(() => City('New York'));

  Person person =  injector.get<Person>(); 
  City city =  injector.get<City>();

  print(person.name);
  print(city.name);
}

class Person {
  String name;

  Person(this.name);
}

class City {
  String name;

  City(this.name);
}


typedef T CreateInstanceFn<T>();

class Injector {
  static final Injector _singleton =  Injector._internal();
  final _factories = Map<String, dynamic>();

  factory Injector() {
    return _singleton;
  }

  Injector._internal();

  String _generateKey<T>(T type) {
    return '${type.toString()}_instance';
  }

  void add<T>(CreateInstanceFn<T> createInstance) {
    final typeKey = _generateKey(T);
    _factories[typeKey] = createInstance();
  }

  T get<T>() {
    final typeKey = _generateKey(T);
    T instance = _factories[typeKey];
    if (instance == null) {
      print('Cannot find instance for type $typeKey');
    }

    return instance;
  }
}

Including one C source file in another?

is it ok? yes, it will compile

is it recommended? no - .c files compile to .obj files, which are linked together after compilation (by the linker) into the executable (or library), so there is no need to include one .c file in another. What you probably want to do instead is to make a .h file that lists the functions/variables available in the other .c file, and include the .h file

How to redirect Valgrind's output to a file?

valgrind --log-file="filename"

bundle install fails with SSL certificate verification error

Download rubygems-update-2.6.7.gem .

Now, using your Command Prompt:

C:\>gem install --local C:\rubygems-update-2.6.7.gem
C:\>update_rubygems --no-ri --no-rdoc

After this, gem --version should report the new update version.

You can now safely uninstall rubygems-update gem:

C:\>gem uninstall rubygems-update -x
Removing update_rubygems
Successfully uninstalled rubygems-update-2.6.7

How to switch to the new browser window, which opens after click on the button?

So the problem with a lot of these solutions is you're assuming the window appears instantly (nothing happens instantly, and things happen significantly less instantly in IE). Also you're assuming that there will only be one window prior to clicking the element, which is not always the case. Also IE will not return the window handles in a predictable order. So I would do the following.

 public String clickAndSwitchWindow(WebElement elementToClick, Duration 
    timeToWaitForWindowToAppear) {
    Set<String> priorHandles = _driver.getWindowHandles();

    elementToClick.click();
    try {
        new WebDriverWait(_driver,
                timeToWaitForWindowToAppear.getSeconds()).until(
                d -> {
                    Set<String> newHandles = d.getWindowHandles();
                    if (newHandles.size() > priorHandles.size()) {
                        for (String newHandle : newHandles) {
                            if (!priorHandles.contains(newHandle)) {
                                d.switchTo().window(newHandle);
                                return true;
                            }
                        }
                        return false;
                    } else {
                        return false;
                    }

                });
    } catch (Exception e) {
        Logging.log_AndFail("Encountered error while switching to new window after clicking element " + elementToClick.toString()
                + " seeing error: \n" + e.getMessage());
    }

    return _driver.getWindowHandle();
}

Converting XML to JSON using Python?

I found for simple XML snips, use regular expression would save troubles. For example:

# <user><name>Happy Man</name>...</user>
import re
names = re.findall(r'<name>(\w+)<\/name>', xml_string)
# do some thing to names

To do it by XML parsing, as @Dan said, there is not one-for-all solution because the data is different. My suggestion is to use lxml. Although not finished to json, lxml.objectify give quiet good results:

>>> from lxml import objectify
>>> root = objectify.fromstring("""
... <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
...   <a attr1="foo" attr2="bar">1</a>
...   <a>1.2</a>
...   <b>1</b>
...   <b>true</b>
...   <c>what?</c>
...   <d xsi:nil="true"/>
... </root>
... """)

>>> print(str(root))
root = None [ObjectifiedElement]
    a = 1 [IntElement]
      * attr1 = 'foo'
      * attr2 = 'bar'
    a = 1.2 [FloatElement]
    b = 1 [IntElement]
    b = True [BoolElement]
    c = 'what?' [StringElement]
    d = None [NoneElement]
      * xsi:nil = 'true'

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

Use the Bit datatype. It has values 1 and 0 when dealing with it in native T-SQL

Removing the title text of an iOS UIBarButtonItem

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefaultPrompt];
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(10.0, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],
                                                               NSFontAttributeName:[UIFont systemFontOfSize:1]}
                                                    forState:UIControlStateNormal];

How to gracefully handle the SIGKILL signal in Java

You can use Runtime.getRuntime().addShutdownHook(...), but you cannot be guaranteed that it will be called in any case.

Object of custom type as dictionary key

You need to add 2 methods, note __hash__ and __eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

Invalid length for a Base-64 char array

The length of a base64 encoded string is always a multiple of 4. If it is not a multiple of 4, then = characters are appended until it is. A query string of the form ?name=value has problems when the value contains = charaters (some of them will be dropped, I don't recall the exact behavior). You may be able to get away with appending the right number of = characters before doing the base64 decode.

Edit 1

You may find that the value of UserNameToVerify has had "+"'s changed to " "'s so you may need to do something like so:

a = a.Replace(" ", "+");

This should get the length right;

int mod4 = a.Length % 4;
if (mod4 > 0 )
{
    a += new string('=', 4 - mod4);
}

Of course calling UrlEncode (as in LukeH's answer) should make this all moot.

Working copy locked error in tortoise svn while committing

There are multiple meanings of "lock" in SVN and some of these answers that talk about "break lock" or a teammate holding a lock are not using the relevant meaning for the original question. This question is dealing with "working copy locks" (i.e. they are entirely local to the working copy on your computer and have nothing to do with you or teammates holding a lock/check-out on a file). The accepted answer by MicroEyes is referring to the correct usage and is your best option when this happens.

If a cleanup doesn't work you may need to check out a fresh working copy of the project. If you have any modified, un-commited files you will need to copy them over to the fresh working copy so you don't lose your changes.

See this page in the Tortoise SVN docs for a description of the three usages of "lock": http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-dug-locking.html

Excerpt (emphasis added):

The Three Meanings of “Lock”

In this section, and almost everywhere in this book, the words “lock” and “locking” describe a mechanism for mutual exclusion between users to avoid clashing commits. Unfortunately, there are two other sorts of “lock” with which Subversion, and therefore this book, sometimes needs to be concerned.

The second is working copy locks, used internally by Subversion to prevent clashes between multiple Subversion clients operating on the same working copy. Usually you get these locks whenever a command like update/commit/... is interrupted due to an error. These locks can be removed by running the cleanup command on the working copy, as described in the section called “Cleanup”.

...

MySQL - Operand should contain 1 column(s)

In my case, the problem was that I sorrounded my columns selection with parenthesis by mistake:

SELECT (p.column1, p.colum2, p.column3) FROM table1 p where p.column1 = 1;

And has to be:

SELECT p.column1, p.colum2, p.column3 FROM table1 p where p.column1 = 1;

Sounds silly, but it was causing this error and it took some time to figure it out.

How can I check if a date is the same day as datetime.today()?

  • If you need to compare only day of month value than you can use the following code:

    if yourdate.day == datetime.today().day:
        # do something
    
  • If you need to check that the difference between two dates is acceptable then you can use timedelta:

    if (datetime.today() - yourdate).days == 0:
        #do something
    
  • And if you want to compare date part only than you can simply use:

    from datetime import datetime, date
    if yourdatetime.date() < datetime.today().date()
        # do something
    

Note that timedelta has the following format:

datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

So you are able to check diff in days, seconds, msec, minutes and so on depending on what you really need:

from datetime import datetime
if (datetime.today() - yourdate).days == 0:
    #do something

In your case when you need to check that two dates are exactly the same you can use timedelta(0):

from datetime import datetime, timedelta
if (datetime.today() - yourdate) == timedelta(0):
    #do something

How can I do a case insensitive string comparison?

I'd like to write an extension method for EqualsIgnoreCase

public static class StringExtensions
{
    public static bool? EqualsIgnoreCase(this string strA, string strB)
    {
        return strA?.Equals(strB, StringComparison.CurrentCultureIgnoreCase);
    }
}

CFNetwork SSLHandshake failed iOS 9

For more info Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11

Curiously, you’ll notice that the connection attempts to change the http protocol to https to protect against mistakes in your code where you may have accidentally misconfigured the URL. In some cases, this might actually work, but it’s also confusing.

This Shipping an App With App Transport Security covers some good debugging tips

ATS Failure

Most ATS failures will present as CFErrors with a code in the -9800 series. These are defined in the Security/SecureTransport.h header

2015-08-23 06:34:42.700 SelfSignedServerATSTest[3792:683731] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)

CFNETWORK_DIAGNOSTICS

Set the environment variable CFNETWORK_DIAGNOSTICS to 1 in order to get more information on the console about the failure

nscurl

The tool will run through several different combinations of ATS exceptions, trying a secure connection to the given host under each ATS configuration and reporting the result.

nscurl --ats-diagnostics https://example.com

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

If its working when you are using a browser and then passing on your username and password for the first time - then this means that once authentication is done Request header of your browser is set with required authentication values, which is then passed on each time a request is made to hosting server.

So start with inspecting Request Header (this could be done using Web Developers tools), Once you established whats required in header then you could pass this within your HttpWebRequest Header.

Example with Digest Authentication:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace NUI
{
    public class DigestAuthFixer
    {
        private static string _host;
        private static string _user;
        private static string _password;
        private static string _realm;
        private static string _nonce;
        private static string _qop;
        private static string _cnonce;
        private static DateTime _cnonceDate;
        private static int _nc;

public DigestAuthFixer(string host, string user, string password)
{
    // TODO: Complete member initialization
    _host = host;
    _user = user;
    _password = password;
}

private string CalculateMd5Hash(
    string input)
{
    var inputBytes = Encoding.ASCII.GetBytes(input);
    var hash = MD5.Create().ComputeHash(inputBytes);
    var sb = new StringBuilder();
    foreach (var b in hash)
        sb.Append(b.ToString("x2"));
    return sb.ToString();
}

private string GrabHeaderVar(
    string varName,
    string header)
{
    var regHeader = new Regex(string.Format(@"{0}=""([^""]*)""", varName));
    var matchHeader = regHeader.Match(header);
    if (matchHeader.Success)
        return matchHeader.Groups[1].Value;
    throw new ApplicationException(string.Format("Header {0} not found", varName));
}

private string GetDigestHeader(
    string dir)
{
    _nc = _nc + 1;

    var ha1 = CalculateMd5Hash(string.Format("{0}:{1}:{2}", _user, _realm, _password));
    var ha2 = CalculateMd5Hash(string.Format("{0}:{1}", "GET", dir));
    var digestResponse =
        CalculateMd5Hash(string.Format("{0}:{1}:{2:00000000}:{3}:{4}:{5}", ha1, _nonce, _nc, _cnonce, _qop, ha2));

    return string.Format("Digest username=\"{0}\", realm=\"{1}\", nonce=\"{2}\", uri=\"{3}\", " +
        "algorithm=MD5, response=\"{4}\", qop={5}, nc={6:00000000}, cnonce=\"{7}\"",
        _user, _realm, _nonce, dir, digestResponse, _qop, _nc, _cnonce);
}

public string GrabResponse(
    string dir)
{
    var url = _host + dir;
    var uri = new Uri(url);

    var request = (HttpWebRequest)WebRequest.Create(uri);

    // If we've got a recent Auth header, re-use it!
    if (!string.IsNullOrEmpty(_cnonce) &&
        DateTime.Now.Subtract(_cnonceDate).TotalHours < 1.0)
    {
        request.Headers.Add("Authorization", GetDigestHeader(dir));
    }

    HttpWebResponse response;
    try
    {
        response = (HttpWebResponse)request.GetResponse();
    }
    catch (WebException ex)
    {
        // Try to fix a 401 exception by adding a Authorization header
        if (ex.Response == null || ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.Unauthorized)
            throw;

        var wwwAuthenticateHeader = ex.Response.Headers["WWW-Authenticate"];
        _realm = GrabHeaderVar("realm", wwwAuthenticateHeader);
        _nonce = GrabHeaderVar("nonce", wwwAuthenticateHeader);
        _qop = GrabHeaderVar("qop", wwwAuthenticateHeader);

        _nc = 0;
        _cnonce = new Random().Next(123400, 9999999).ToString();
        _cnonceDate = DateTime.Now;

        var request2 = (HttpWebRequest)WebRequest.Create(uri);
        request2.Headers.Add("Authorization", GetDigestHeader(dir));
        response = (HttpWebResponse)request2.GetResponse();
    }
    var reader = new StreamReader(response.GetResponseStream());
    return reader.ReadToEnd();
}

}

Then you could call it:

DigestAuthFixer digest = new DigestAuthFixer(domain, username, password);
string strReturn = digest.GrabResponse(dir);

if Url is: http://xyz.rss.com/folder/rss then domain: http://xyz.rss.com (domain part) dir: /folder/rss (rest of the url)

you could also return it as stream and use XmlDocument Load() method.

Java for loop syntax: "for (T obj : objects)"

Yes, It is called the for-each loop. Objects in the collectionName will be assigned one after one from the beginning of that collection, to the created object reference, 'objectName'. So in each iteration of the loop, the 'objectName' will be assigned an object from the 'collectionName' collection. The loop will terminate once when all the items(objects) of the 'collectionName' Collection have finished been assigning or simply the objects to get are over.

for (ObjectType objectName : collectionName.getObjects()){ //loop body> //You can use the 'objectName' here as needed and different objects will be //reepresented by it in each iteration. }

Read CSV file column by column

I am sorry, but none of these answers provide an optimal solution. If you use a library such as OpenCSV you will have to write a lot of code to handle special cases to extract information from specific columns.

For example, if you have rows with less columns than what you're after, you'll have to write a lot of code to handle it. Using the OpenCSV example:

  CSVReader reader = new CSVReader(new FileReader(strFile));
  String [] nextLine;
  while ((nextLine = reader.readNext()) != null) {
       //let's say you are interested in getting columns 20, 30, and 40
       String[] outputRow = new String[3];
       if(parsedRow.length < 40){
            outputRow[2] = null;
       } else {
            outputRow[2] = parsedRow[40]
       }
       if(parsedRow.length < 30){
            outputRow[1] = null;
       } else {
            outputRow[1] = parsedRow[30]
       }
       if(parsedRow.length < 20){
            outputRow[0] = null;
       } else {
            outputRow[0] = parsedRow[20]
       }

  }

This is a lot of code for a simple requirement. It gets worse if you are trying to get values of columns by name. You should use a more modern parser such as the one provided by uniVocity-parsers.

To reliably and easily get the columns you want, simply write:

CsvParserSettings settings = new CsvParserSettings();
parserSettings.selectIndexes(20, 30, 40);
CsvParser parser = new CsvParser(settings);
List<String[]> allRows = parser.parseAll(new FileReader(yourFile));

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

Get the current displaying UIViewController on the screen in AppDelegate.m

Simple extension for UIApplication in Swift (cares even about moreNavigationController within UITabBarController on iPhone):

extension UIApplication {
    class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }

        if let tab = base as? UITabBarController {
            let moreNavigationController = tab.moreNavigationController

            if let top = moreNavigationController.topViewController where top.view.window != nil {
                return topViewController(top)
            } else if let selected = tab.selectedViewController {
                return topViewController(selected)
            }
        }

        if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }

        return base
    }
}

Simple usage:

    if let rootViewController = UIApplication.topViewController() {
        //do sth with root view controller
    }

Works perfect:-)

UPDATE for clean code:

extension UIViewController {
    var top: UIViewController? {
        if let controller = self as? UINavigationController {
            return controller.topViewController?.top
        }
        if let controller = self as? UISplitViewController {
            return controller.viewControllers.last?.top
        }
        if let controller = self as? UITabBarController {
            return controller.selectedViewController?.top
        }
        if let controller = presentedViewController {
            return controller.top
        }
        return self
    }
}

Manually Triggering Form Validation using jQuery

When there is a very complex (especially asynchronous) validation process, there is a simple workaround:

<form id="form1">
<input type="button" onclick="javascript:submitIfVeryComplexValidationIsOk()" />
<input type="submit" id="form1_submit_hidden" style="display:none" />
</form>
...
<script>
function submitIfVeryComplexValidationIsOk() {
    var form1 = document.forms['form1']
    if (!form1.checkValidity()) {
        $("#form1_submit_hidden").click()
        return
    }

    if (checkForVeryComplexValidation() === 'Ok') {
         form1.submit()
    } else {
         alert('form is invalid')
    }
}
</script>

How to set session timeout dynamically in Java web applications?

As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.

getRequest().getSession().setMaxInactiveInterval(123);

Should you always favor xrange() over range()?

I would just like to say that it REALLY isn't that difficult to get an xrange object with slice and indexing functionality. I have written some code that works pretty dang well and is just as fast as xrange for when it counts (iterations).

from __future__ import division

def read_xrange(xrange_object):
    # returns the xrange object's start, stop, and step
    start = xrange_object[0]
    if len(xrange_object) > 1:
       step = xrange_object[1] - xrange_object[0]
    else:
        step = 1
    stop = xrange_object[-1] + step
    return start, stop, step

class Xrange(object):
    ''' creates an xrange-like object that supports slicing and indexing.
    ex: a = Xrange(20)
    a.index(10)
    will work

    Also a[:5]
    will return another Xrange object with the specified attributes

    Also allows for the conversion from an existing xrange object
    '''
    def __init__(self, *inputs):
        # allow inputs of xrange objects
        if len(inputs) == 1:
            test, = inputs
            if type(test) == xrange:
                self.xrange = test
                self.start, self.stop, self.step = read_xrange(test)
                return

        # or create one from start, stop, step
        self.start, self.step = 0, None
        if len(inputs) == 1:
            self.stop, = inputs
        elif len(inputs) == 2:
            self.start, self.stop = inputs
        elif len(inputs) == 3:
            self.start, self.stop, self.step = inputs
        else:
            raise ValueError(inputs)

        self.xrange = xrange(self.start, self.stop, self.step)

    def __iter__(self):
        return iter(self.xrange)

    def __getitem__(self, item):
        if type(item) is int:
            if item < 0:
                item += len(self)

            return self.xrange[item]

        if type(item) is slice:
            # get the indexes, and then convert to the number
            start, stop, step = item.start, item.stop, item.step
            start = start if start != None else 0 # convert start = None to start = 0
            if start < 0:
                start += start
            start = self[start]
            if start < 0: raise IndexError(item)
            step = (self.step if self.step != None else 1) * (step if step != None else 1)
            stop = stop if stop is not None else self.xrange[-1]
            if stop < 0:
                stop += stop

            stop = self[stop]
            stop = stop

            if stop > self.stop:
                raise IndexError
            if start < self.start:
                raise IndexError
            return Xrange(start, stop, step)

    def index(self, value):
        error = ValueError('object.index({0}): {0} not in object'.format(value))
        index = (value - self.start)/self.step
        if index % 1 != 0:
            raise error
        index = int(index)


        try:
            self.xrange[index]
        except (IndexError, TypeError):
            raise error
        return index

    def __len__(self):
        return len(self.xrange)

Honestly, I think the whole issue is kind of silly and xrange should do all of this anyway...

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

javascript regex : only english letters allowed

The answer that accepts empty string:

/^[a-zA-Z]*$/.test('something')

the * means 0 or more occurrences of the preceding item.

How can I convert an image into a Base64 string?

If you're doing this on Android, here's a helper copied from the React Native codebase:

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;

// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
  try {
    InputStream is = new FileInputStream(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
    byte[] buffer = new byte[8192];
    int bytesRead;
    try {
      while ((bytesRead = is.read(buffer)) > -1) {
        b64os.write(buffer, 0, bytesRead);
      }
      return baos.toString();
    } catch (IOException e) {
      Log.e(TAG, "Cannot read file " + path, e);
      // Or throw if you prefer
      return "";
    } finally {
      closeQuietly(is);
      closeQuietly(b64os); // This also closes baos
    }
  } catch (FileNotFoundException e) {
    Log.e(TAG, "File not found " + path, e);
    // Or throw if you prefer
    return "";
  }
}

private static void closeQuietly(Closeable closeable) {
  try {
    closeable.close();
  } catch (IOException e) {
  }
}

SQL Server - after insert trigger - update another column in the same table

It might be safer to exit the trigger when there is nothing to do. Checking the nested level or altering the database by switching off RECURSIVE can be prone to issues.

Ms sql provides a simple way, in a trigger, to see if specific columns have been updated. Use the UPDATE() method to see if certain columns have been updated such as UPDATE(part_description_upper).

IF UPDATE(part_description_upper)
  return

ASP.NET Identity reset password

In case of password reset, it is recommended to reset it through sending password reset token to registered user email and ask user to provide new password. If have created a easily usable .NET library over Identity framework with default configuration settins. You can find details at blog link and source code at github.

How to install Android SDK on Ubuntu?

If you are on Ubuntu 17.04 (Zesty), and you literally just need the SDK (no Android Studio), you can install it like on Debian:

  • sudo apt install android-sdk android-sdk-platform-23
  • export ANDROID_HOME=/usr/lib/android-sdk
  • In build.gradle, change compileSdkVersion to 23 and buildToolsVersion to 24.0.0
  • run gradle build

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

How to overlay density plots in R?

ggplot2 is another graphics package that handles things like the range issue Gavin mentions in a pretty slick way. It also handles auto generating appropriate legends and just generally has a more polished feel in my opinion out of the box with less manual manipulation.

library(ggplot2)

#Sample data
dat <- data.frame(dens = c(rnorm(100), rnorm(100, 10, 5))
                   , lines = rep(c("a", "b"), each = 100))
#Plot.
ggplot(dat, aes(x = dens, fill = lines)) + geom_density(alpha = 0.5)

enter image description here

How do I encrypt and decrypt a string in python?

Take a look at PyCrypto. It supports Python 3.2 and does exactly what you want.

From their pip website:

>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
>>> obj2 = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
>>> obj2.decrypt(ciphertext)
'The answer is no'

If you want to encrypt a message of an arbitrary size use AES.MODE_CFB instead of AES.MODE_CBC.

I need to convert an int variable to double

Either use casting as others have already said, or multiply one of the int variables by 1.0:

double firstSolution = ((1.0* b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));

FirstOrDefault returns NullReferenceException if no match is found

FirstOrDefault returns the default value of a type if no item matches the predicate. For reference types that is null. Thats the reason for the exception.

So you just have to check for null first:

string displayName = null;
var keyValue = Dictionary
    .FirstOrDefault(x => x.Value.ID == long.Parse(options.ID));
if(keyValue  != null)
{
    displayName = keyValue.Value.DisplayName;
} 

But what is the key of the dictionary if you are searching in the values? A Dictionary<tKey,TValue> is used to find a value by the key. Maybe you should refactor it.

Another option is to provide a default value with DefaultIfEmpty:

string displayName = Dictionary
    .Where(kv => kv.Value.ID == long.Parse(options.ID))
    .Select(kv => kv.Value.DisplayName)   // not a problem even if no item matches
    .DefaultIfEmpty("--Option unknown--") // or no argument -> null
    .First();                             // cannot cause an exception

How to get column by number in Pandas?

One is a column (aka Series), while the other is a DataFrame:

In [1]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])

In [2]: df
Out[2]:
   a  b
0  1  2
1  3  4

The column 'b' (aka Series):

In [3]: df['b']
Out[3]:
0    2
1    4
Name: b, dtype: int64

The subdataframe with columns (position) in [1]:

In [4]: df[[1]]
Out[4]:
   b
0  2
1  4

Note: it's preferable (and less ambiguous) to specify whether you're talking about the column name e.g. ['b'] or the integer location, since sometimes you can have columns named as integers:

In [5]: df.iloc[:, [1]]
Out[5]:
   b
0  2
1  4

In [6]: df.loc[:, ['b']]
Out[6]:
   b
0  2
1  4

In [7]: df.loc[:, 'b']
Out[7]:
0    2
1    4
Name: b, dtype: int64

MongoError: connect ECONNREFUSED 127.0.0.1:27017

just start the mongo server from terminal

Ubuntu -

     sudo systemctl start mongod

Log exception with traceback

You can log all uncaught exceptions on the main thread by assigning a handler to sys.excepthook, perhaps using the exc_info parameter of Python's logging functions:

import sys
import logging

logging.basicConfig(filename='/tmp/foobar.log')

def exception_hook(exc_type, exc_value, exc_traceback):
    logging.error(
        "Uncaught exception",
        exc_info=(exc_type, exc_value, exc_traceback)
    )

sys.excepthook = exception_hook

raise Exception('Boom')

If your program uses threads, however, then note that threads created using threading.Thread will not trigger sys.excepthook when an uncaught exception occurs inside them, as noted in Issue 1230540 on Python's issue tracker. Some hacks have been suggested there to work around this limitation, like monkey-patching Thread.__init__ to overwrite self.run with an alternative run method that wraps the original in a try block and calls sys.excepthook from inside the except block. Alternatively, you could just manually wrap the entry point for each of your threads in try/except yourself.

VBA procedure to import csv file into access

The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.

You can link the table either manually or with VBA like this

DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true

UPDATE

Dim db As DAO.Database

' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next:   db.TableDefs.Delete "tblImport":   On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
    FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh

' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
   & "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close:   Set db = Nothing

Server Client send/receive simple text

CLIENT

namespace SocketKlient

{
    class Program

    {
        static Socket Klient;
        static IPEndPoint endPoint;
        static void Main(string[] args)
        {
            Klient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            string command;
            Console.WriteLine("Write IP address");
            command = Console.ReadLine();
            IPAddress Address;
            while(!IPAddress.TryParse(command, out Address)) 
            {
                Console.WriteLine("wrong IP format");
                command = Console.ReadLine();
            }
            Console.WriteLine("Write port");
            command = Console.ReadLine();

            int port;
            while (!int.TryParse(command, out port) && port > 0)
            {
                Console.WriteLine("Wrong port number");
                command = Console.ReadLine();
            }
            endPoint = new IPEndPoint(Address, port); 
            ConnectC(Address, port);
            while(Klient.Connected)
            {
                Console.ReadLine();
                Odesli();
            }
        }

        public static void ConnectC(IPAddress ip, int port)
        {
            IPEndPoint endPoint = new IPEndPoint(ip, port);
            Console.WriteLine("Connecting...");
            try
            {
                Klient.Connect(endPoint);
                Console.WriteLine("Connected!");
            }
            catch
            {
                Console.WriteLine("Connection fail!");
                return; 
            }
            Task t = new Task(WaitForMessages); 
            t.Start(); 
        }

        public static void SendM()
        {
            string message = "Actualy date is " + DateTime.Now; 
            byte[] buffer = Encoding.UTF8.GetBytes(message);
            Console.WriteLine("Sending: " + message);
            Klient.Send(buffer);
        }

        public static void WaitForMessages()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[64]; 
                    Console.WriteLine("Waiting for answer");
                    Klient.Receive(buffer, 0, buffer.Length, 0); 

                    string message = Encoding.UTF8.GetString(buffer); 
                    Console.WriteLine("Answer: " + message); 
                }
            }
            catch
            {
                Console.WriteLine("Disconnected");
            }
        }
    }
}

How to have stored properties in Swift, the same way I had on Objective-C?

I tried to store properties by using objc_getAssociatedObject, objc_setAssociatedObject, without any luck. My goal was create extension for UITextField, to validate text input characters length. Following code works fine for me. Hope this will help someone.

private var _min: Int?
private var _max: Int?

extension UITextField {    
    @IBInspectable var minLength: Int {
        get {
            return _min ?? 0
        }
        set {
            _min = newValue
        }
    }

    @IBInspectable var maxLength: Int {
        get {
            return _max ?? 1000
        }
        set {
            _max = newValue
        }
    }

    func validation() -> (valid: Bool, error: String) {
        var valid: Bool = true
        var error: String = ""
        guard let text = self.text else { return (true, "") }

        if text.characters.count < minLength {
            valid = false
            error = "Textfield should contain at least \(minLength) characters"
        }

        if text.characters.count > maxLength {
            valid = false
            error = "Textfield should not contain more then \(maxLength) characters"
        }

        if (text.characters.count < minLength) && (text.characters.count > maxLength) {
            valid = false
            error = "Textfield should contain at least \(minLength) characters\n"
            error = "Textfield should not contain more then \(maxLength) characters"
        }

        return (valid, error)
    }
}

Execute command on all files in a directory

The following bash code will pass $file to command where $file will represent every file in /dir

for file in /dir/*
do
  cmd [option] "$file" >> results.out
done

Example

el@defiant ~/foo $ touch foo.txt bar.txt baz.txt
el@defiant ~/foo $ for i in *.txt; do echo "hello $i"; done
hello bar.txt
hello baz.txt
hello foo.txt

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

Dherik : I'm not sure about what you say, when you don't use fetch the result will be of type : List<Object[ ]> which means a list of Object tables and not a list of Employee.

Object[0] refers an Employee entity 
Object[1] refers a Departement entity 

When you use fetch, there is just one select and the result is the list of Employee List<Employee> containing the list of departements. It overrides the lazy declaration of the entity.

How to display a confirmation dialog when clicking an <a> link?

USING PHP, HTML AND JAVASCRIPT for prompting

Just if someone looking for using php, html and javascript in a single file, the answer below is working for me.. i attached with the used of bootstrap icon "trash" for the link.

<a class="btn btn-danger" href="<?php echo "delete.php?&var=$var"; ?>" onclick="return confirm('Are you sure want to delete this?');"><span class="glyphicon glyphicon-trash"></span></a>

the reason i used php code in the middle is because i cant use it from the beginning..

the code below doesnt work for me:-

echo "<a class='btn btn-danger' href='delete.php?&var=$var' onclick='return confirm('Are you sure want to delete this?');'><span class='glyphicon glyphicon-trash'></span></a>";

and i modified it as in the 1st code then i run as just what i need.. I hope that can i can help someone inneed of my case.

React-Native Button style not work

React Native buttons are very limited in the option they provide.You can use TouchableHighlight or TouchableOpacity by styling these element and wrapping your buttons with it like this

             <TouchableHighlight 
                style ={{
                    height: 40,
                    width:160,
                    borderRadius:10,
                    backgroundColor : "yellow",
                    marginLeft :50,
                    marginRight:50,
                    marginTop :20
                }}>
            <Button onPress={this._onPressButton}            
            title="SAVE"
            accessibilityLabel="Learn more about this button"
          /> 
          </TouchableHighlight> 

You can also use react library for customised button .One nice library is react-native-button (https://www.npmjs.com/package/react-native-button)

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

You can use Database Engine Tuning Advisor.

This tool is for improving the query performances by examining the way queries are processed and recommended enhancements by specific indexes.

How to use the Database Engine Tuning Advisor?

1- Copy the select statement that you need to speed up into the new query.

2- Parse (Ctrl+F5).

3- Press The Icon of the (Database Engine Tuning Advisor).

matplotlib savefig in jpeg format

Matplotlib can handle directly and transparently jpg if you have installed PIL. You don't need to call it, it will do it by itself. If Python cannot find PIL, it will raise an error.

Print Html template in Angular 2 (ng-print in Angular 2)

If you need to print some custom HTML, you can use this method:

ts:

    let control_Print;

    control_Print = document.getElementById('__printingFrame');

    let doc = control_Print.contentWindow.document;
    doc.open();
    doc.write("<div style='color:red;'>I WANT TO PRINT THIS, NOT THE CURRENT HTML</div>");
    doc.close();

    control_Print = control_Print.contentWindow;
    control_Print.focus();
    control_Print.print();

html:

<iframe title="Lets print" id="__printingFrame" style="width: 0; height: 0; border: 0"></iframe>

Secure FTP using Windows batch script

The built in FTP command doesn't have a facility for security. Use cUrl instead. It's scriptable, far more robust and has FTP security.

How to make a SIMPLE C++ Makefile

Since this is for Unix, the executables don't have any extensions.

One thing to note is that root-config is a utility which provides the right compilation and linking flags; and the right libraries for building applications against root. That's just a detail related to the original audience for this document.

Make Me Baby

or You Never Forget The First Time You Got Made

An introductory discussion of make, and how to write a simple makefile

What is Make? And Why Should I Care?

The tool called Make is a build dependency manager. That is, it takes care of knowing what commands need to be executed in what order to take your software project from a collection of source files, object files, libraries, headers, etc., etc.---some of which may have changed recently---and turning them into a correct up-to-date version of the program.

Actually, you can use Make for other things too, but I'm not going to talk about that.

A Trivial Makefile

Suppose that you have a directory containing: tool tool.cc tool.o support.cc support.hh, and support.o which depend on root and are supposed to be compiled into a program called tool, and suppose that you've been hacking on the source files (which means the existing tool is now out of date) and want to compile the program.

To do this yourself you could

  1. Check if either support.cc or support.hh is newer than support.o, and if so run a command like

    g++ -g -c -pthread -I/sw/include/root support.cc
    
  2. Check if either support.hh or tool.cc are newer than tool.o, and if so run a command like

    g++ -g  -c -pthread -I/sw/include/root tool.cc
    
  3. Check if tool.o is newer than tool, and if so run a command like

    g++ -g tool.o support.o -L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
    -lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz -Wl,-framework,CoreServices \
    -Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root -lm -ldl
    

Phew! What a hassle! There is a lot to remember and several chances to make mistakes. (BTW-- the particulars of the command lines exhibited here depend on our software environment. These ones work on my computer.)

Of course, you could just run all three commands every time. That would work, but it doesn't scale well to a substantial piece of software (like DOGS which takes more than 15 minutes to compile from the ground up on my MacBook).

Instead you could write a file called makefile like this:

tool: tool.o support.o
    g++ -g -o tool tool.o support.o -L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
        -lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz -Wl,-framework,CoreServices \
        -Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root -lm -ldl

tool.o: tool.cc support.hh
    g++ -g  -c -pthread -I/sw/include/root tool.cc

support.o: support.hh support.cc
    g++ -g -c -pthread -I/sw/include/root support.cc

and just type make at the command line. Which will perform the three steps shown above automatically.

The unindented lines here have the form "target: dependencies" and tell Make that the associated commands (indented lines) should be run if any of the dependencies are newer than the target. That is, the dependency lines describe the logic of what needs to be rebuilt to accommodate changes in various files. If support.cc changes that means that support.o must be rebuilt, but tool.o can be left alone. When support.o changes tool must be rebuilt.

The commands associated with each dependency line are set off with a tab (see below) should modify the target (or at least touch it to update the modification time).

Variables, Built In Rules, and Other Goodies

At this point, our makefile is simply remembering the work that needs doing, but we still had to figure out and type each and every needed command in its entirety. It does not have to be that way: Make is a powerful language with variables, text manipulation functions, and a whole slew of built-in rules which can make this much easier for us.

Make Variables

The syntax for accessing a make variable is $(VAR).

The syntax for assigning to a Make variable is: VAR = A text value of some kind (or VAR := A different text value but ignore this for the moment).

You can use variables in rules like this improved version of our makefile:

CPPFLAGS=-g -pthread -I/sw/include/root
LDFLAGS=-g
LDLIBS=-L/sw/lib/root -lCore -lCint -lRIO -lNet -lHist -lGraf -lGraf3d -lGpad -lTree -lRint \
       -lPostscript -lMatrix -lPhysics -lMathCore -lThread -lz -L/sw/lib -lfreetype -lz \
       -Wl,-framework,CoreServices -Wl,-framework,ApplicationServices -pthread -Wl,-rpath,/sw/lib/root \
       -lm -ldl

tool: tool.o support.o
    g++ $(LDFLAGS) -o tool tool.o support.o $(LDLIBS)

tool.o: tool.cc support.hh
    g++ $(CPPFLAGS) -c tool.cc

support.o: support.hh support.cc
    g++ $(CPPFLAGS) -c support.cc

which is a little more readable, but still requires a lot of typing

Make Functions

GNU make supports a variety of functions for accessing information from the filesystem or other commands on the system. In this case we are interested in $(shell ...) which expands to the output of the argument(s), and $(subst opat,npat,text) which replaces all instances of opat with npat in text.

Taking advantage of this gives us:

CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)

SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))

tool: $(OBJS)
    g++ $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)

tool.o: tool.cc support.hh
    g++ $(CPPFLAGS) -c tool.cc

support.o: support.hh support.cc
    g++ $(CPPFLAGS) -c support.cc

which is easier to type and much more readable.

Notice that

  1. We are still stating explicitly the dependencies for each object file and the final executable
  2. We've had to explicitly type the compilation rule for both source files

Implicit and Pattern Rules

We would generally expect that all C++ source files should be treated the same way, and Make provides three ways to state this:

  1. suffix rules (considered obsolete in GNU make, but kept for backwards compatibility)
  2. implicit rules
  3. pattern rules

Implicit rules are built in, and a few will be discussed below. Pattern rules are specified in a form like

%.o: %.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -c $<

which means that object files are generated from C source files by running the command shown, where the "automatic" variable $< expands to the name of the first dependency.

Built-in Rules

Make has a whole host of built-in rules that mean that very often, a project can be compile by a very simple makefile, indeed.

The GNU make built in rule for C source files is the one exhibited above. Similarly we create object files from C++ source files with a rule like $(CXX) -c $(CPPFLAGS) $(CFLAGS).

Single object files are linked using $(LD) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS), but this won't work in our case, because we want to link multiple object files.

Variables Used By Built-in Rules

The built-in rules use a set of standard variables that allow you to specify local environment information (like where to find the ROOT include files) without re-writing all the rules. The ones most likely to be interesting to us are:

  • CC -- the C compiler to use
  • CXX -- the C++ compiler to use
  • LD -- the linker to use
  • CFLAGS -- compilation flag for C source files
  • CXXFLAGS -- compilation flags for C++ source files
  • CPPFLAGS -- flags for the c-preprocessor (typically include file paths and symbols defined on the command line), used by C and C++
  • LDFLAGS -- linker flags
  • LDLIBS -- libraries to link

A Basic Makefile

By taking advantage of the built-in rules we can simplify our makefile to:

CC=gcc
CXX=g++
RM=rm -f
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)

SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))

all: tool

tool: $(OBJS)
    $(CXX) $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)

tool.o: tool.cc support.hh

support.o: support.hh support.cc

clean:
    $(RM) $(OBJS)

distclean: clean
    $(RM) tool

We have also added several standard targets that perform special actions (like cleaning up the source directory).

Note that when make is invoked without an argument, it uses the first target found in the file (in this case all), but you can also name the target to get which is what makes make clean remove the object files in this case.

We still have all the dependencies hard-coded.

Some Mysterious Improvements

CC=gcc
CXX=g++
RM=rm -f
CPPFLAGS=-g $(shell root-config --cflags)
LDFLAGS=-g $(shell root-config --ldflags)
LDLIBS=$(shell root-config --libs)

SRCS=tool.cc support.cc
OBJS=$(subst .cc,.o,$(SRCS))

all: tool

tool: $(OBJS)
    $(CXX) $(LDFLAGS) -o tool $(OBJS) $(LDLIBS)

depend: .depend

.depend: $(SRCS)
    $(RM) ./.depend
    $(CXX) $(CPPFLAGS) -MM $^>>./.depend;

clean:
    $(RM) $(OBJS)

distclean: clean
    $(RM) *~ .depend

include .depend

Notice that

  1. There are no longer any dependency lines for the source files!?!
  2. There is some strange magic related to .depend and depend
  3. If you do make then ls -A you see a file named .depend which contains things that look like make dependency lines

Other Reading

Know Bugs and Historical Notes

The input language for Make is whitespace sensitive. In particular, the action lines following dependencies must start with a tab. But a series of spaces can look the same (and indeed there are editors that will silently convert tabs to spaces or vice versa), which results in a Make file that looks right and still doesn't work. This was identified as a bug early on, but (the story goes) it was not fixed, because there were already 10 users.

(This was copied from a wiki post I wrote for physics graduate students.)

How do I truncate a .NET string?

For the sake of (over)complexity I'll add my overloaded version which replaces the last 3 characters with an ellipsis in respect with the maxLength parameter.

public static string Truncate(this string value, int maxLength, bool replaceTruncatedCharWithEllipsis = false)
{
    if (replaceTruncatedCharWithEllipsis && maxLength <= 3)
        throw new ArgumentOutOfRangeException("maxLength",
            "maxLength should be greater than three when replacing with an ellipsis.");

    if (String.IsNullOrWhiteSpace(value)) 
        return String.Empty;

    if (replaceTruncatedCharWithEllipsis &&
        value.Length > maxLength)
    {
        return value.Substring(0, maxLength - 3) + "...";
    }

    return value.Substring(0, Math.Min(value.Length, maxLength)); 
}

Build fat static library (device + simulator) using Xcode and SDK 4+

XCode 12 update:

If you run xcodebuild without -arch param, XCode 12 will build simulator library with architecture "arm64 x86_64" as default.

Then run xcrun -sdk iphoneos lipo -create -output will conflict, because arm64 architecture exist in simulator and also device library.

I fork script from Adam git and fix it.

Grab a segment of an array in Java without creating a new array on heap

The Lists allow you to use and work with subList of something transparently. Primitive arrays would require you to keep track of some kind of offset - limit. ByteBuffers have similar options as I heard.

Edit: If you are in charge of the useful method, you could just define it with bounds (as done in many array related methods in java itself:

doUseful(byte[] arr, int start, int len) {
    // implementation here
}
doUseful(byte[] arr) {
    doUseful(arr, 0, arr.length);
}

It's not clear, however, if you work on the array elements themselves, e.g. you compute something and write back the result?

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

Any approach should give you roughly same number. It is always a good idea to allocate the heap using -X..m -X..x for all generations. You can then guarantee and also do ps to see what parameters were passed and hence being used.

For actual memory usages, you can roughly compare VIRT (allocated and shared) and RES (actual used) compare against the jstat values as well:

For Java 8, see jstat for these values actually mean. Assuming you run a simple class with no mmap or file processing.

$ jstat -gccapacity 32277
 NGCMN    NGCMX     NGC     S0C   S1C       EC      OGCMN      OGCMX       OGC         OC       MCMN     MCMX      MC     CCSMN    CCSMX     CCSC    YGC    FGC
215040.0 3433472.0  73728.0  512.0  512.0  67072.0   430080.0  6867968.0   392704.0   392704.0      0.0 1083392.0  39680.0      0.0 1048576.0   4864.0   7225     2
$ jstat -gcutil 32277
  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT
  6.25   0.00   7.96  18.21  98.01  95.29   7228   30.859     2    0.173   31.032

Max:

     NGCMX + S0C + S1C + EC    + OGCMX   + MCMX    + CCSMX
   3433472 + 512 + 512 + 67072 + 6867968 + 1083392 + 1048576 = 12 GB

(roughly close and below to VIRT memory)

Max(Min, Used):

215040 + 512 + 512 + 67072 + 430080  + 39680    +  4864  = ~ 1GB

(roughly close to RES memory)

"Don't quote me on this" but VIRT mem is roughly close to or more than Max memory allocated but as long as memory being used is free/available in physical memory, JVM does not throw memory exception. In fact, max memory is not even checked against physical memory on JVM startup even with swap off on OS. A better explanation of what Virtual memory really used by a Java process is discussed here.

Executing multiple SQL queries in one statement with PHP

You can just add the word JOIN or add a ; after each line(as @pictchubbate said). Better this way because of readability and also you should not meddle DELETE with INSERT; it is easy to go south.

The last question is a matter of debate, but as far as I know yes you should close after a set of queries. This applies mostly to old plain mysql/php and not PDO, mysqli. Things get more complicated(and heated in debates) in these cases.

Finally, I would suggest either using PDO or some other method.

How to draw a custom UIView that is just a circle - iPhone app

Here is another way by using UIBezierPath (maybe it's too late ^^) Create a circle and mask UIView with it, as follows:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
view.backgroundColor = [UIColor blueColor];

CAShapeLayer *shape = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:view.center radius:(view.bounds.size.width / 2) startAngle:0 endAngle:(2 * M_PI) clockwise:YES];
shape.path = path.CGPath;
view.layer.mask = shape;

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

The question is a bit old but I just solved a very similar problem. We have several intranet sites here including the one I'm responsible for, and the others require compatibility mode or they break. For that reason, site rules default IE to compatibility mode on intranet sites. I am upgrading my own stuff and no longer need it; in fact, some of the features I'm trying to use don't look right in compat mode. I'm using the meta IE-Edge tag like you are.

IE assumes websites without the fully-qualified address are intranet, and acts accordingly. With that in mind I just altered the bindings in IIS to only listen to the fully-qualified address, then set up a dummy website that listened for the unqualified address. The second one redirects all traffic to the fully-qualified address, making IE believe it's an external site. The site renders correctly with or without the Compatibility Mode on Intranet Sites box checked.

How can I check if a checkbox is checked?

remember is undefined … and the checked property is a boolean not a number.

function validate(){
    var remember = document.getElementById('remember');
    if (remember.checked){
        alert("checked") ;
    }else{
        alert("You didn't check it! Let me check it for you.")
    }
}

Adding/removing items from a JavaScript object with jQuery

If you are using jQuery you can use the extend function to add new items.

var olddata = {"fruit":{"apples":10,"pears":21}};

var newdata = {};
newdata['vegetables'] = {"carrots": 2, "potatoes" : 5};

$.extend(true, olddata, newdata);

This will generate:

{"fruit":{"apples":10,"pears":21}, "vegetables":{"carrots":2,"potatoes":5}};

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

You can simply go to Build Path -> Add Libraries and for the library type to add select "Server Runtime." Click Next and select a server runtime to add to the classpath and the problem goes away if jstl.jar and standard.jar are in your server's classpath.

In Python, how do I index a list with another list?

L= {'a':'a','d':'d', 'h':'h'}
index= ['a','d','h'] 
for keys in index:
    print(L[keys])

I would use a Dict add desired keys to index

Get a Div Value in JQuery

$('#myDiv').text()

Although you'd be better off doing something like:

_x000D_
_x000D_
var txt = $('#myDiv p').text();_x000D_
alert(txt);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"><p>Some Text</p></div>
_x000D_
_x000D_
_x000D_

Make sure you're linking to your jQuery file too :)

How do I implement basic "Long Polling"?

Here is a simple long-polling example in PHP by Erik Dubbelboer using the Content-type: multipart/x-mixed-replace header:

<?

header('Content-type: multipart/x-mixed-replace; boundary=endofsection');

// Keep in mind that the empty line is important to separate the headers
// from the content.
echo 'Content-type: text/plain

After 5 seconds this will go away and a cat will appear...
--endofsection
';
flush(); // Don't forget to flush the content to the browser.


sleep(5);


echo 'Content-type: image/jpg

';

$stream = fopen('cat.jpg', 'rb');
fpassthru($stream);
fclose($stream);

echo '
--endofsection
';

And here is a demo:

http://dubbelboer.com/multipart.php

FFT in a single C-file

This file works properly as it is: just copy and paste in your computer. Surfing on the web I have found this easy implementation on wikipedia page here. The page is in italian, so I re-wrote the code with some translations. Here there are almost the same informations but in english. ENJOY!

#include <iostream>
#include <complex>
#define MAX 200

using namespace std;

#define M_PI 3.1415926535897932384

int log2(int N)    /*function to calculate the log2(.) of int numbers*/
{
  int k = N, i = 0;
  while(k) {
    k >>= 1;
    i++;
  }
  return i - 1;
}

int check(int n)    //checking if the number of element is a power of 2
{
  return n > 0 && (n & (n - 1)) == 0;
}

int reverse(int N, int n)    //calculating revers number
{
  int j, p = 0;
  for(j = 1; j <= log2(N); j++) {
    if(n & (1 << (log2(N) - j)))
      p |= 1 << (j - 1);
  }
  return p;
}

void ordina(complex<double>* f1, int N) //using the reverse order in the array
{
  complex<double> f2[MAX];
  for(int i = 0; i < N; i++)
    f2[i] = f1[reverse(N, i)];
  for(int j = 0; j < N; j++)
    f1[j] = f2[j];
}

void transform(complex<double>* f, int N) //
{
  ordina(f, N);    //first: reverse order
  complex<double> *W;
  W = (complex<double> *)malloc(N / 2 * sizeof(complex<double>));
  W[1] = polar(1., -2. * M_PI / N);
  W[0] = 1;
  for(int i = 2; i < N / 2; i++)
    W[i] = pow(W[1], i);
  int n = 1;
  int a = N / 2;
  for(int j = 0; j < log2(N); j++) {
    for(int i = 0; i < N; i++) {
      if(!(i & n)) {
        complex<double> temp = f[i];
        complex<double> Temp = W[(i * a) % (n * a)] * f[i + n];
        f[i] = temp + Temp;
        f[i + n] = temp - Temp;
      }
    }
    n *= 2;
    a = a / 2;
  }
  free(W);
}

void FFT(complex<double>* f, int N, double d)
{
  transform(f, N);
  for(int i = 0; i < N; i++)
    f[i] *= d; //multiplying by step
}

int main()
{
  int n;
  do {
    cout << "specify array dimension (MUST be power of 2)" << endl;
    cin >> n;
  } while(!check(n));
  double d;
  cout << "specify sampling step" << endl; //just write 1 in order to have the same results of matlab fft(.)
  cin >> d;
  complex<double> vec[MAX];
  cout << "specify the array" << endl;
  for(int i = 0; i < n; i++) {
    cout << "specify element number: " << i << endl;
    cin >> vec[i];
  }
  FFT(vec, n, d);
  cout << "...printing the FFT of the array specified" << endl;
  for(int j = 0; j < n; j++)
    cout << vec[j] << endl;
  return 0;
}

How to copy a string of std::string type in C++?

Caesar's solution is the best in my opinion, but if you still insist to use the strcpy function, then after you have your strings ready:

string a = "text";
string b = "image";

You can try either:

strcpy(a.data(), b.data());

or

strcpy(a.c_str(), b.c_str());

Just call either the data() or c_str() member functions of the std::string class, to get the char* pointer of the string object.

The strcpy() function doesn't have overload to accept two std::string objects as parameters. It has only one overload to accept two char* pointers as parameters.

Both data and c_str return what does strcpy() want exactly.

How to convert a hex string to hex number

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)

Enforcing the type of the indexed members of a Typescript object?

You can pass a name to the unknown key and then write your types:

type StuffBody = {
  [key: string]: string;
};

Now you can use it in your type checking:

let stuff: StuffBody = {};

But for FlowType there is no need to have name:

type StuffBody = {
  [string]: string,
};

Read file data without saving it in Flask

If you want to use standard Flask stuff - there's no way to avoid saving a temporary file if the uploaded file size is > 500kb. If it's smaller than 500kb - it will use "BytesIO", which stores the file content in memory, and if it's more than 500kb - it stores the contents in TemporaryFile() (as stated in the werkzeug documentation). In both cases your script will block until the entirety of uploaded file is received.

The easiest way to work around this that I have found is:

1) Create your own file-like IO class where you do all the processing of the incoming data

2) In your script, override Request class with your own:

class MyRequest( Request ):
  def _get_file_stream( self, total_content_length, content_type, filename=None, content_length=None ):
    return MyAwesomeIO( filename, 'w' )

3) Replace Flask's request_class with your own:

app.request_class = MyRequest

4) Go have some beer :)

How to allow download of .json file with ASP.NET

  1. Navigate to C:\Users\username\Documents\IISExpress\config
  2. Open applicationhost.config with Visual Studio or your favorite text-editor.
  3. Search for the word mimeMap, you should find lots of 'em.
  4. Add the following line to the top of the list: .

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

You have configured the auth.php and used members table for authentication but there is no user_email field in the members table so, Laravel says

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_email' in 'where clause' (SQL: select * from members where user_email = ? limit 1) (Bindings: array ( 0 => '[email protected]', ))

Because, it tries to match the user_email in the members table and it's not there. According to your auth configuration, laravel is using members table for authentication not users table.

java, get set methods

To understand get and set, it's all related to how variables are passed between different classes.

The get method is used to obtain or retrieve a particular variable value from a class.

A set value is used to store the variables.

The whole point of the get and set is to retrieve and store the data values accordingly.

What I did in this old project was I had a User class with my get and set methods that I used in my Server class.

The User class's get set methods:

public int getuserID()
    {
        //getting the userID variable instance
        return userID;
    }
    public String getfirstName()
    {
        //getting the firstName variable instance
        return firstName;
    }
    public String getlastName()
    {
        //getting the lastName variable instance
        return lastName;
    }
    public int getage()
    {
        //getting the age variable instance
        return age;
    }

    public void setuserID(int userID)
    {
        //setting the userID variable value
        this.userID = userID;
    }
    public void setfirstName(String firstName)
    {
        //setting the firstName variable text
        this.firstName = firstName;
    }
    public void setlastName(String lastName)
    {
        //setting the lastName variable text
        this.lastName = lastName;
    }
    public void setage(int age)
    {
        //setting the age variable value
        this.age = age;
    }
}

Then this was implemented in the run() method in my Server class as follows:

//creates user object
                User use = new User(userID, firstName, lastName, age);
                //Mutator methods to set user objects
                use.setuserID(userID);
                use.setlastName(lastName);
                use.setfirstName(firstName);               
                use.setage(age); 

Change a Rails application to production

How to setup and run a Rails 4 app in Production mode (step-by-step) using Apache and Phusion Passenger:

Normally you would be able to enter your Rails project, rails s, and get a development version of your app at http://something.com:3000. Production mode is a little trickier to configure.

I've been messing around with this for a while, so I figured I'd write this up for the newbies (such as myself). There are a few little tweaks which are spread throughout the internet and figured this might be easier.

  1. Refer to this guide for core setup of the server (CentOS 6, but it should apply to nearly all Linux flavors): https://www.digitalocean.com/community/tutorials/how-to-setup-a-rails-4-app-with-apache-and-passenger-on-centos-6

  2. Make absolute certain that after Passenger is set up you've edited the /etc/httpd/conf/httpd.conf file to reflect your directory structure. You want to point DocumentRoot to your Rails project /public folder Anywhere in the httpd.conf file that has this sort of dir: /var/www/html/your_application/public needs to be updated or everything will get very frustrating. I cannot stress this enough.

  3. Reboot the server (or Apache at the very least - service httpd restart )

  4. Enter your Rails project folder /var/www/html/your_application and start the migration with rake db:migrate. Make certain that a database table exists, even if you plan on adding tables later (this is also part of step 1).

  5. RAILS_ENV=production rake secret - this will create a secret_key that you can add to config/secrets.yml . You can copy/paste this into config/secrets.yml for the sake of getting things running, although I'd recommend you don't do this. Personally, I do this step to make sure everything else is working, then change it back and source it later.

  6. RAILS_ENV=production rake db:migrate

  7. RAILS_ENV=production rake assets:precompile if you are serving static assets. This will push js, css, image files into the /public folder.

  8. RAILS_ENV=production rails s

At this point your app should be available at http://something.com/whatever instead of :3000. If not, passenger-memory-stats and see if there an entry like 908 469.7 MB 90.9 MB Passenger RackApp: /var/www/html/projectname

I've probably missed something heinous, but this has worked for me in the past.

Array versus List<T>: When to use which?

It is rare, in reality, that you would want to use an array. Definitely use a List<T> any time you want to add/remove data, since resizing arrays is expensive. If you know the data is fixed length, and you want to micro-optimise for some very specific reason (after benchmarking), then an array may be useful.

List<T> offers a lot more functionality than an array (although LINQ evens it up a bit), and is almost always the right choice. Except for params arguments, of course. ;-p

As a counter - List<T> is one-dimensional; where-as you have have rectangular (etc) arrays like int[,] or string[,,] - but there are other ways of modelling such data (if you need) in an object model.

See also:

That said, I make a lot of use of arrays in my protobuf-net project; entirely for performance:

  • it does a lot of bit-shifting, so a byte[] is pretty much essential for encoding;
  • I use a local rolling byte[] buffer which I fill before sending down to the underlying stream (and v.v.); quicker than BufferedStream etc;
  • it internally uses an array-based model of objects (Foo[] rather than List<Foo>), since the size is fixed once built, and needs to be very fast.

But this is definitely an exception; for general line-of-business processing, a List<T> wins every time.

Open Facebook Page in Facebook App (if installed) on Android

Okay I modifed @AndroidMechanics Code, because on devices were facebook is disabled the app crashes!

here is the modifed getFacebookUrl:

public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

            boolean activated =  packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
            if(activated){
                if ((versionCode >= 3002850)) { 
                    return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
                } else { 
                    return "fb://page/" + FACEBOOK_PAGE_ID;
                }
            }else{
                return FACEBOOK_URL;
            }
         } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL; 
        }
    }

The only added thing is to look if the app is disabled or not if it is disabled the app will call the webbrowser!

What does the ^ (XOR) operator do?

Another application for XOR is in circuits. It is used to sum bits.

When you look at a truth table:

 x | y | x^y
---|---|-----
 0 | 0 |  0     // 0 plus 0 = 0 
 0 | 1 |  1     // 0 plus 1 = 1
 1 | 0 |  1     // 1 plus 0 = 1
 1 | 1 |  0     // 1 plus 1 = 0 ; binary math with 1 bit

You can notice that the result of XOR is x added with y, without keeping track of the carry bit, the carry bit is obtained from the AND between x and y.

x^y // is actually ~xy + ~yx
    // Which is the (negated x ANDed with y) OR ( negated y ANDed with x ).

Getting String Value from Json Object Android

Include org.json.jsonobject in your project.

You can then do this:

JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");

Assuming, responseString holds the response you receive.

If you need to know how to convert the received response to a String, here's how to do it:

ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();

How do I find all of the symlinks in a directory tree?

One command, no pipes

find . -type l -ls

Explanation: find from the current directory . onwards all references of -type link and list -ls those in detail. Plain and simple...

Expanding upon this answer, here are a couple more symbolic link related find commands:

Find symbolic links to a specific target

find . -lname link_target

Note that link_target is a pattern that may contain wildcard characters.

Find broken symbolic links

find -L . -type l -ls

The -L option instructs find to follow symbolic links, unless when broken.

Find & replace broken symbolic links

find -L . -type l -delete -exec ln -s new_target {} \;

More find examples

More find examples can be found here: https://hamwaves.com/find/

Simplest way to do a recursive self-join?

Using CTEs you can do it this way

DECLARE @Table TABLE(
        PersonID INT,
        Initials VARCHAR(20),
        ParentID INT
)

INSERT INTO @Table SELECT     1,'CJ',NULL
INSERT INTO @Table SELECT     2,'EB',1
INSERT INTO @Table SELECT     3,'MB',1
INSERT INTO @Table SELECT     4,'SW',2
INSERT INTO @Table SELECT     5,'YT',NULL
INSERT INTO @Table SELECT     6,'IS',5

DECLARE @PersonID INT

SELECT @PersonID = 1

;WITH Selects AS (
        SELECT *
        FROM    @Table
        WHERE   PersonID = @PersonID
        UNION ALL
        SELECT  t.*
        FROM    @Table t INNER JOIN
                Selects s ON t.ParentID = s.PersonID
)
SELECT  *
FROm    Selects

Remove header and footer from window.print()

@media print {
    .footer,
    #non-printable {
        display: none !important;
    }
    #printable {
        display: block;
    }
}

How to round the corners of a button

You may want to check out my library called DCKit. It's written on the latest version of Swift.

You'd be able to make a rounded corner button/text field from the Interface builder directly:

DCKit: rounded button

It also has many other cool features, such as text fields with validation, controls with borders, dashed borders, circle and hairline views etc.

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

Apache won't start in wamp

This solved the issue for me:

Right click on the WAMP system try icon -> Tools -> Reinstall all services

c# foreach (property in object)... Is there a simple way of doing this?

Use Reflection to do this

SomeClass A = SomeClass(...)
PropertyInfo[] properties = A.GetType().GetProperties();

Interpreting "condition has length > 1" warning from `if` function

The way I cam across this question was when I tried doing something similar where I was defining a function and it was being called with the array like others pointed out

You could do something like this however for this scenarios its less elegant compared to Sven's method.

sapply(a, function(x) afunc(x))

afunc<-function(a){
  if (a>0){
    a/sum(a)
  }
  else 1
}

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

Microsoft now recommends using an IHttpClientFactory with the following benefits:

  • Provides a central location for naming and configuring logical HttpClient instances. For example, a client named github could be registered and configured to access GitHub. A default client can be registered for general access.
  • Codifies the concept of outgoing middleware via delegating handlers in HttpClient. Provides extensions for Polly-based middleware to take advantage of delegating handlers in HttpClient.
  • Manages the pooling and lifetime of underlying HttpClientMessageHandler instances. Automatic management avoids common DNS (Domain Name System) problems that occur when manually managing HttpClient lifetimes.
  • Adds a configurable logging experience (via ILogger) for all requests sent through clients created by the factory.

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1

Setup:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient();
        // Remaining code deleted for brevity.

POST example:

public class BasicUsageModel : PageModel
{
    private readonly IHttpClientFactory _clientFactory;

    public BasicUsageModel(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
    
    public async Task CreateItemAsync(TodoItem todoItem)
    {
        var todoItemJson = new StringContent(
            JsonSerializer.Serialize(todoItem, _jsonSerializerOptions),
            Encoding.UTF8,
            "application/json");
            
        var httpClient = _clientFactory.CreateClient();
        
        using var httpResponse =
            await httpClient.PostAsync("/api/TodoItems", todoItemJson);
    
        httpResponse.EnsureSuccessStatusCode();
    }

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#make-post-put-and-delete-requests