i use concantenate. works for me.
.xlsx
loads 4 times longer than .xlsb
and saves 2 times longer and has 1.5 times a bigger file. I tested this on a generated worksheet with 10'000 rows * 1'000 columns = 10'000'000 (10^7) cells of simple chained =…+1
formulas:
?--------------------------------?
¦ ¦ .xlsx ¦ .xlsb ¦
¦--------------+--------+--------¦
¦ loading time ¦ 165s ¦ 43s ¦
+--------------+--------+--------¦
¦ saving time ¦ 115s ¦ 61s ¦
+--------------+--------+--------¦
¦ file size ¦ 91 MB ¦ 65 MB ¦
?--------------------------------?
(Hardware: Core2Duo 2.3 GHz, 4 GB RAM, 5.400 rpm SATA II HD; Windows 7, under somewhat heavy load from other processes.)
Beside this, there should be no differences. More precisely,
both formats support exactly the same feature set
cites this blog post from 2006-08-29. So maybe the info that .xlsb
does not support Ribbon code is newer than the upper citation, but I figure that forum source of yours is just wrong. When cracking open the binary file, it seems to condensedly mimic the OOXML file structure 1-to-1: Blog article from 2006-08-07
You need to re-add that certificate to your machine or chose another certificate.
To choose another certificate or to recreate one, head over to the Project's properties page, click on Signing tab and either
Once either of these is done, you should be able to build it again.
Check the version of the excel, if you are using older version then Value2 is not available for you and thus it is showing an error, while it will work with 2007+ version. Or the other way, the object is not getting created and thus the Value2 property is not available for the object.
I find it easier using this formula
=IF(B2<>"",TEXT(ROW(A1),"IR-0000"),"")
Need to paste this formula at A2, that means when you are encoding data at B cell the A cell will automatically input the serial code and when there's no data the cell will stay blank....you can change the "IR" to any first letter code you want to be placed in your row.
Hope it helps
Dim NuevoLibro As Workbook
Dim NombreLibro As String
NombreLibro = "LibroPrueba"
'---Creamos nuevo libro y lo guardamos
Set NuevoLibro = Workbooks.Add
With NuevoLibro
.SaveAs Filename:=NuevaRuta & NombreLibro, FileFormat:=52
End With
'*****************************
'valores para FileFormat
'.xlsx = 51 '(52 for Mac)
'.xlsm = 52 '(53 for Mac)
'.xlsb = 50 '(51 for Mac)
'.xls = 56 '(57 for Mac)
'*****************************
The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.
http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm
Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.
I put the data starting on row 5:
Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.
That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.
I think your problem is that it's closing the document that calls the macro before sending the command to quit the application.
Your solution in that case is to not send a command to close the workbook. Instead, you could set the "Saved" state of the workbook to true, which would circumvent any messages about closing an unsaved book. Note: this does not save the workbook; it just makes it look like it's saved.
ThisWorkbook.Saved = True
and then, right after
Application.Quit
I've read lots of blogs on this subject going back to 2005!!
I'm sure that Paul Simon is right (see his submission to this thread) and it's a question of finding which program on your machine is locking the clipboard. I do not run the programs listed in various solutons suggested (eg on Microsoft website) nor am I in a networked or virtual environment so for me those aren't the locking programs (but might be for you). Similarly I don't have the RDP task going in my processes. For me the locking program is the Skype Add-in.
I am not a sophisticated user and am scared of altering my registry so didn't want to go there.
I have now been able to reproduce accurately the "cannot clear the clipboard" message by turning on and off the skype addins in internet explorer. This is easy for amateurs to do and might be one of the more common clipboard locking programs:
I first confirmed that I can turn on/off the problem in Excel by opening/closing internet explorer.
Then I disabled the skype addins:
Internet Explorer: Tools menu --> Internet Options ; Programs Tab ; Manage Add-ons button; Toolbars and Extensions selected in panel on left - scroll down to find skype add ons. Press Disable button.
NB have to restart Internet explorer before this works.
.... 4 days later.... it's still working
The codes above wouldn't work in Excel 2010 My code bellow allows you to go through number of sheets you would like then select tables and delete rows
Sub DeleteTableRows()
Dim table As ListObject
Dim SelectedCell As Range
Dim TableName As String
Dim ActiveTable As ListObject
'select ammount of sheets want to this to run
For i = 1 To 3
Sheets(i).Select
Range("A1").Select
Set SelectedCell = ActiveCell
Selection.AutoFilter
'Determine if ActiveCell is inside a Table
On Error GoTo NoTableSelected
TableName = SelectedCell.ListObject.Name
Set ActiveTable = ActiveSheet.ListObjects(TableName)
On Error GoTo 0
'Clear first Row
ActiveTable.DataBodyRange.Rows(1).ClearContents
'Delete all the other rows `IF `they exist
On Error Resume Next
ActiveTable.DataBodyRange.Offset(1, 0).Resize(ActiveTable.DataBodyRange.Rows.Count - 1, _
ActiveTable.DataBodyRange.Columns.Count).Rows.Delete
Selection.AutoFilter
On Error GoTo 0
Next i
Exit Sub
'Error Handling
NoTableSelected:
MsgBox "There is no Table currently selected!", vbCritical
End Sub
With Excel 2013, I have encountered the same problem, but it seems related to some (self-made) Add-Ins I'm using, which add a tab to the ribbon. After unhooking these AddIns in the Options > Add-Ins > Goto: Exce-Add-Ins > Add_Ins Box and restarting Excel (!), all charts in the workbook kept updating immediately. But as soon as I activate (hook) one of these Add-Ins, none of the charts would update anymore. This issue does not show up with other Add-Ins (like e.g. Solver), so I still have to find out if it is caused by the Add-In creating an additional Tab in the ribbon, or just any Add-In of .xlam - type.
Only by help of following workaround code I could persuade the charts to do their job:
Dim chtChart As ChartObject
For Each chtChart In ActiveSheet.ChartObjects
chtChart.Chart.ChartWizard
Next chtChart
Strange enough, the .Chart.Refresh - method didn't work either, but .Chart.ChartWizard did, though no parameters are given so it doesn't change anything!
(And yes, the calculation method of the workbook was / still is automatic)
update (2019-09-17):
Since another (3rd party) Add-In did NOT prevent any charts from updating, I plunged into some further research, disabled all code, deleted all XML-contents of the customUI - ribbon and removed all relations to external libraries (as far as the VBE let me do). Still I could reliably prevent all charts from updating just by activating this now completely useless Add-In.
As a last try, I re-built the Add-In from scratch by copying all code into a fresh .xlam - file, set all required library relations and finally added the XML-code for the ribbon with the customUI - editor.
And behold!: now all charts kept updating :-D
So - without proof - I just can guess that my old AddIn (originally of 2011, so probably done with Excel 2007 or 2010) was not completely compatible with Excel 2013. So it's always a good idea to do a new setup / re-create any AddIn with the present version of Excel ;-)
Good luck!
Highlight the column and then Ctrl + F.
Find and replace
Find ".com"
Replace ".com, "
And then one for .in
Find and replace
Find ".in"
Replace ".in, "
Even simpler:
=indirect(address(row(), column() - 1))
OFFSET returns a reference relative to the current reference, so if indirect returns the correct reference, you don't need it.
I find that the problem only seems to happen when freeze panes is turned on, which will normally be on in most apps as you will place your command buttons etc in a location where they do not scroll out of view.
The solution that has worked for be is to group the controls but also ensuring that the group extends beyond the freeze panes area. I do this by adding a control outside the freeze panes area, add it into the group but also hide the control so you don't see it.
This is what you need:
=NOT(ISERROR(MATCH(<cell in col A>,<column B>, 0))) ## pseudo code
For the first cell of A, this would be:
=NOT(ISERROR(MATCH(A2,$B$2:$B$5, 0)))
Enter formula (and drag down) as follows:
You will get:
You have to add Button to excel sheet(say sheet1
) from which you can go to another sheet(say sheet2
).
Button can be added from Developer tab in excel. If developer tab is not there follow below steps to enable.
GOTO file -> options -> Customize Ribbon -> enable checkbox of developer on right panel -> Done.
To Add button :-
Developer Tab -> Insert -> choose first item button -> choose location of button-> Done.
To give name for button :-
Right click on button -> edit text.
To add code for going to sheet2 :-
Right click on button -> Assign Macro -> New -> (microsoft visual basic will open to code for button) -> paste below code
Worksheets("Sheet2").Visible = True
Worksheets("Sheet2").Activate
Save the file using 'Excel Macro Enable Template(*.xltm)' By which the code is appended with excel sheet.
you can use those functions together with iferror
as a work around.
try =IFERROR(VALUE(A4),(CONCATENATE(A4)))
I create equations with random numbers in VBA and for x squared put in x^2.
I read each square (or textbox) text into a string.
I then read each character in the string in turn and note the location of the ^ ("hats")'s in each.
Say the hats were at positions 4, 8 and 12.
I then "chop out" the first hat - the position of the character to be superscripted is now 4, the position of the other hats is now 7 and 11. I chop out the second hat, the character to superscript is now at 7 and the hat has moved to 10. I chop out the last hat .. the superscript character is now position 10.
I now select each character in turn and change the font to superscript.
Thus I can fill a whole spreadsheet with algebra using ^ and then call a routine to tidy it up.
For big powers like x to the 23 I build x^2^3 and the above routine does it.
Thank you for your answers! They definitely led me on the right track. But none of them completely got me everything I wanted, so here's what I actually ended up doing.
The key piece of information I was missing was that I needed to put the data together in one big block, but I could still leave empty cells in it. Something like this:
Date Actual remaining Desired remaining
7/13/2009 7350 7350
7/15/2009 7100
7/21/2009 7150
7/23/2009 6600
7/27/2009 6550
8/8/2009 6525
8/16/2009 6200
11/3/2009 0
Now I have something Excel is a little better at charting. So long as I set the chart options to "Show empty cells as: Connect data points with line," it ends up looking pretty nice. Using the above test data:
Then I just needed my update macro to insert new rows above the last one to fill in new data whenever I want. My macro looks something like this:
' Find the last cell on the left going down. This will be the last cell
' in the "Date" column
Dim left As Range
Set left = Range("A1").End(xlDown)
' Move two columns to the right and select so we have the 3 final cells,
' including "Date", "Actual remaining", and "Desired remaining"
Dim bottom As Range
Set bottom = Range(left.Cells(1), left.Offset(0, 2))
' Insert a new blank row, and then move up to account for it
bottom.Insert (xlShiftDown)
Set bottom = bottom.Offset(-1)
' We are now sitting on some blank cells very close to the end of the data,
' and are ready to paste in new values for the date and new pages remaining
' (I do this by grabbing some other cells and doing a PasteSpecial into bottom)
Improvement suggestions on that macro are welcome. I just fiddled with it until it worked.
Now I have a pretty chart and I can nerd out all I want with my nerdy books for nerds.
I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.
Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes
Right(A1, Len(A1)-Find("(asterisk)",Substitute(A1, "(space)","(asterisk)",Len(A1)-Len(Substitute(A1,"(space)", "(no space)")))))
Try this. Hope it works.
Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =
None of the suggested solutions worked for me.
What actually works (with any encoding):
Copy/paste the data from the csv-file (open in a text editor), then perform "text to columns" --> data gets transformed incorrectly.
The next stap is to go to the nearest empty column or empty worksheet and copy/paste again (same thing what you already have in your clipboard) --> automagically works now.
This works for me:
This is a criteria over two fields/columns (9 and 10), this filters rows with values >0 on column 9 and rows with values 4, 7, and 8 on column 10. lastrow
is the number of rows on the data section.
ActiveSheet.Range("$A$1:$O$" & lastrow).AutoFilter Field:=9, Criteria1:=">0", Operator:=xlAnd
ActiveSheet.Range("$A$1:$O$" & lastrow).AutoFilter Field:=10, Criteria1:=Arr("4","7","8"), Operator:=xlFilterValues
If you have applied border and/or fill on a cell, you need to clear both to go back to the default borders.
You may apply 'None' as the border option and expect the default borders to show, but it will not when the cell fill is white. It's not immediately obvious that it has a white fill, as unfilled cells are also white.
In this case, apply a 'No Fill' on the cells, and you will get the default borders back.
That's it. No messy format painting, no 'Clear Formats', none of those destructive methods. Easy, quick and painless.
Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.
Copy/Paste Code below:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date
End Sub
Good luck...
To declare a variable as a Decimal
, first declare it as a Variant
and then convert to Decimal
with CDec
. The type would be Variant/Decimal
in the watch window:
Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.
In the example below, we see that the expression:
0.1 + 0.11 = 0.21
is either True
or False
, depending on whether the collectibles (0.1,0.11) are declared as Double
or as Decimal
:
Public Sub TestMe()
Dim preciseA As Variant: preciseA = CDec(0.1)
Dim preciseB As Variant: preciseB = CDec(0.11)
Dim notPreciseA As Double: notPreciseA = 0.1
Dim notPreciseB As Double: notPreciseB = 0.11
Debug.Print preciseA + preciseB
Debug.Print preciseA + preciseB = 0.21 'True
Debug.Print notPreciseA + notPreciseB
Debug.Print notPreciseA + notPreciseB = 0.21 'False
End Sub
This is not necessarily a VBA task - This specific task is easiest sollowed with Auto filter.
1.Insert Auto filter (In Excel 2010 click on home-> (Editing) Sort & Filter -> Filter)
2. Filter on the 'Websites' column
3. Mark the 'none' and delete them
4. Clear filter
Here's a simple way:
=NUMBERVALUE( CONCAT(5.66,"%") )
Just concatenate a %
symbol after the number.
By itself, this output would be text, so we also tuck the CONCAT function inside the NUMBERVALUE function.
p.s., in old excel, you might need to type the full word "CONCATENATE"
I use
chartRange = xlWorkSheet.Rows[1];
chartRange.Font.Bold = true;
to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.
You can call in VBA directly
ActiveCell.Font.Bold = True
With this code I create a timestamp in the active cell, with bold font and yellow background
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveCell.Value = Now()
ActiveCell.Font.Bold = True
ActiveCell.Interior.ColorIndex = 6
End Sub
Based on your comment to Issun:
Thanks for the explanation. In my case, The object is declared and created prior to the If condition. So, How do I use If condition to check for < No Variables> ? In other words, I do not want to execute My_Object.Compute if My_Object has < No Variables>
You need to check one of the properties of the object. Without telling us what the object is, we cannot help you.
I did test several common objects and found that an instantiated Collection
with no items added shows <No Variables>
in the watch window. If your object is indeed a collection, you can check for the <No Variables>
condition using the .Count
property:
Sub TestObj()
Dim Obj As Object
Set Obj = New Collection
If Obj Is Nothing Then
Debug.Print "Object not instantiated"
Else
If Obj.Count = 0 Then
Debug.Print "<No Variables> (ie, no items added to the collection)"
Else
Debug.Print "Object instantiated and at least one item added"
End If
End If
End Sub
It is also worth noting that if you declare any object As New
then the Is Nothing
check becomes useless. The reason is that when you declare an object As New
then it gets created automatically when it is first called, even if the first time you call it is to see if it exists!
Dim MyObject As New Collection
If MyObject Is Nothing Then ' <--- This check always returns False
This does not seem to be the cause of your specific problem. But, since others may find this question through a Google search, I wanted to include it because it is a common beginner mistake.
for converting dd/mm/yyyy
to mm/dd/yyyy
=DATE(RIGHT(a1,4),MID(a1,4,2),LEFT(a1,2))
In addition to the answer of @teylyn, I would like to add that you can put the string of multiple search terms inside a SINGLE cell (as opposed to using a different cell for each term and then using that range as argument to SEARCH
), using named ranges and the EVALUATE
function as I found from this link.
For example, I put the following terms as text in a cell, $G$1
:
"PRB", "utilization", "alignment", "spectrum"
Then, I defined a named range named search_terms
for that cell as described in the link above and shown in the figure below:
In the Refers to:
field I put the following:
=EVALUATE("{" & TDoc_List!$G$1 & "}")
The above EVALUATE
expression is simple used to emulate the literal string
{"PRB", "utilization", "alignment", "spectrum"}
to be used as input to the SEARCH
function: using a direct reference to the SINGLE cell $G$1
(augmented with the curly braces in that case) inside SEARCH
does not work, hence the use of named ranges and EVALUATE
.
The trick now consists in replacing the direct reference to $G$1
by the EVALUATE
-augmented named range search_terms
.
It really works, and shows once more how powerful Excel really is!
Hope this helps.
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
will solve this issue.
This will search for a value in the first column to the left and return the value in the same row from a specific column.
You can use VLOOKUP, but this requires a wrapper function to return True
or False
. Not to mention it is (relatively) slow. Use COUNTIF or MATCH instead.
Fill down this formula in column K next to the existing values in column I (from I1
to I2691
):
=COUNTIF(<entire column E range>,<single column I value>)>0
=COUNTIF($E$1:$E$99504,$I1)>0
You can also use MATCH:
=NOT(ISNA(MATCH(<single column I value>,<entire column E range>)))
=NOT(ISNA(MATCH($I1,$E$1:$E$99504,0)))
Pretty easy way for rather short lists:
You have your link ;)
Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.
http://www.bettersolutions.com/excel/EED883/YI416010881.htm
Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales
This should fix your problem.
If you are using hand inputted data, you can enter your data as mm:ss,0
or mm:ss.0
depending on your language/region selection instead of 00:mm:ss
.
You need to specify your cell format as [m]:ss
if you like to see all minutes seconds format instead of hours minutes seconds format.
If you have Excel 2007 you can write VBA to alter the connections (i.e. the external data queries) in a workbook and update the CommandText property. If you simply add ?
where you want a parameter, then next time you refresh the data it'll prompt for the values for the connections! magic. When you look at the properties of the Connection the Parameters button will now be active and useable as normal.
E.g. I'd write a macro, step through it in the debugger, and make it set the CommandText appropriately. Once you've done this you can remove the macro - it's just a means to update the query.
Sub UpdateQuery
Dim cn As WorkbookConnection
Dim odbcCn As ODBCConnection, oledbCn As OLEDBConnection
For Each cn In ThisWorkbook.Connections
If cn.Type = xlConnectionTypeODBC Then
Set odbcCn = cn.ODBCConnection
' If you do have multiple connections you would want to modify
' the line below each time you run through the loop.
odbcCn.CommandText = "select blah from someTable where blah like ?"
ElseIf cn.Type = xlConnectionTypeOLEDB Then
Set oledbCn = cn.OLEDBConnection
oledbCn.CommandText = "select blah from someTable where blah like ?"
End If
Next
End Sub
I had this problem and changing Extended Properties to HTML Import fixed it as per this post by Marcus Miris:
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & importedFilePathAndName _
& ";Extended Properties=""HTML Import;HDR=No;IMEX=1"";"
This works with me :
1- select the cells which shall be be affected by the drop down list .
2- home -> conditional formating -> new rule .
3- format only cells that contain .
4- in format only cells with ... select specific text , in formatting rule "= select Elementary from your drop down list"
if drop list in another sheet then when select Elementary we see "=Sheet3!$F$2" in the new rule , with your own sheet and cell number.
5- format -> fill -> select color -> ok.
6-ok .
do the same for each element in drop down list then you will see the magic !
Jonathan from the ExcelCentral forums suggests:
=WEEKNUM(A1,2)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),2)+1
This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:
=WEEKNUM(A1,1)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),1)+1
For weeks beginning on Tuesday, use:
=WEEKNUM(A1,12)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),12)+1
etc.
I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).
We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.
Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.
In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0
They are certainly not equivalent!
Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123
Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.
Use the Chart Wizard.
On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.
Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.
Select your new series.
There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.
Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.
Hope that helps.
EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.
I think you may be getting tripped up on the sheet protection. I streamlined your code a little and am explicitly setting references to the workbook and worksheet objects. In your example, you explicitly refer to the workbook and sheet when you're setting the TxtRng object, but not when you unprotect the sheet.
Try this:
Sub varchanger()
Dim wb As Workbook
Dim ws As Worksheet
Dim TxtRng As Range
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Sheet1")
'or ws.Unprotect Password:="yourpass"
ws.Unprotect
Set TxtRng = ws.Range("A1")
TxtRng.Value = "SubTotal"
'http://stackoverflow.com/questions/8253776/worksheet-protection-set-using-ws-protect-but-doesnt-unprotect-using-the-menu
' or ws.Protect Password:="yourpass"
ws.Protect
End Sub
If I run the sub with ws.Unprotect
commented out, I get a run-time error 1004. (Assuming I've protected the sheet and have the range locked.) Uncommenting the line allows the code to run fine.
NOTES:
Cells(1, 1)
notation can cause a huge amount of grief. Be careful using it. Range("A1")
is a lot easier for humans to parse and tends to prevent forehead-slapping mistakes.I struggled like mad, but this is actually the right answer. For what it is worth, what I missed was is this:
By the way the page that explains it on Ron's site is now at http://www.rondebruin.nl/win/s2/win002.htm
And here is his example on how you enable /disable buttons on the Ribbon http://www.rondebruin.nl/win/s2/win013.htm
For other xml examples of ribbons please also see http://msdn.microsoft.com/en-us/library/office/aa338202%28v=office.12%29.aspx
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
All values of column A that are not present in column B will have a red background. Hope that it helps as starting point.
Sub highlight_missings()
Dim i As Long, lastA As Long, lastB As Long
Dim compare As Variant
Range("A:A").ClearFormats
lastA = Range("A65536").End(xlUp).Row
lastB = Range("B65536").End(xlUp).Row
For i = 2 To lastA
compare = Application.Match(Range("a" & i), Range("B2:B" & lastB), 0)
If IsError(compare) Then
Range("A" & i).Interior.ColorIndex = 3
End If
Next i
End Sub
AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh
. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program
To improve on Ryan's answer:
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size {
CGFloat oldWidth = image.size.width;
CGFloat oldHeight = image.size.height;
//You may need to take some retina adjustments into consideration here
CGFloat scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;
return [UIImage imageWithCGImage:image.CGImage scale:scaleFactor orientation:UIImageOrientationUp];
}
You can use System.in
to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.
class MyProg {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Printing the file passed in:");
while(sc.hasNextLine()) System.out.println(sc.nextLine());
}
}
Hopefully it might help someone.
I tried the above pieces of code but I did not do any streaming.
sudo rabbitmqctl list_queues | awk '{print $1}' > queues.txt; for line in $(cat queues.txt); do sudo rabbitmqctl delete_queue "$line"; done
.
I generate a file that contains all the queue names and loops through it line by line to the delete them. For the loops, while read ...
did not do it for me. It was always stopping at the first queue name.
Also, if you want to delete a single queue, the above solutions will help(python, Java ...) and also do sudo rabbitmqctl delete_queue queue_name
. I am using rabbitmqctl
instead of rabbitmqadmin
.
AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)
I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).
Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.
Which version of JUnit is this? I've only ever seen delta, not epsilon - but that's a side issue!
From the JUnit javadoc:
delta - the maximum delta between expected and actual for which both numbers are still considered equal.
It's probably overkill, but I typically use a really small number, e.g.
private static final double DELTA = 1e-15;
@Test
public void testDelta(){
assertEquals(123.456, 123.456, DELTA);
}
If you're using hamcrest assertions, you can just use the standard equalTo()
with two doubles (it doesn't use a delta). However if you want a delta, you can just use closeTo()
(see javadoc), e.g.
private static final double DELTA = 1e-15;
@Test
public void testDelta(){
assertThat(123.456, equalTo(123.456));
assertThat(123.456, closeTo(123.456, DELTA));
}
FYI the upcoming JUnit 5 will also make delta optional when calling assertEquals()
with two doubles. The implementation (if you're interested) is:
private static boolean doublesAreEqual(double value1, double value2) {
return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2);
}
Short extension for Kotlin
Method returns absolute position of all items (not the position of only visible items).
fun RecyclerView.getChildPositionAt(x: Float, y: Float): Int {
return getChildAdapterPosition(findChildViewUnder(x, y))
}
And usage
val position = recyclerView.getChildPositionAt(event.x, event.y)
Instead of
host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port
you should try
port = 12397 # Reserve a port for your service
s.bind(('', port)) #Bind to the port
so that the listening socket isn't too restricted. Maybe otherwise the listening only occurs on one interface which, in turn, isn't related with the local network.
One example could be that it only listens to 127.0.0.1
, which makes connecting from a different host impossible.
Checkout the following article
on MSDN about examples of the N
format. This is also covered in the Standard Numeric Format Strings
article.
Relevant excerpts:
// Formatting of 1054.32179:
// N: 1,054.32
// N0: 1,054
// N1: 1,054.3
// N2: 1,054.32
// N3: 1,054.322
When precision specifier controls the number of fractional digits in the result string, the result string reflects a number that is rounded to a representable result nearest to the infinitely precise result. If there are two equally near representable results:
- On the .NET Framework and .NET Core up to .NET Core 2.0, the runtime selects the result with the greater least significant digit (that is, using MidpointRounding.AwayFromZero).
- On .NET Core 2.1 and later, the runtime selects the result with an even least significant digit (that is, using MidpointRounding.ToEven).
This should do the work:
.category_table tr:first-child td {
vertical-align: top;
}
No support for regular expressions in your environment? E.g. Shopify Script Editor (April, 2018):
[Error]: uninitialized constant RegExp
A workaround following a combination of methods already previously covered in here and here:
code = '!ADD-SUPER-BONUS!'
class StrContains
def self.===(item)
item.include? 'SUPER' or item.include? 'MEGA' or\
item.include? 'MINI' or item.include? 'UBER'
end
end
case code.upcase
when '12345PROMO', 'CODE-007', StrContains
puts "Code #{code} is a discount code!"
when '!ADD-BONUS!'
puts 'This is a bonus code!'
else
puts 'Sorry, we can\'t do anything with the code you added...'
end
I used or
s in the class method statement since ||
has higher precedence than
.include?
.
If you still prefer using ||
, even though or
is preferable in this case, you can do this instead: (item.include? 'A') || ...
.
You can test it in this repl.it.
"\n" => Newline or Linefeed (semantics)
Unix based systems use just a "\n" to end a line of text.
In Rails, the unit folder is meant to hold tests for your models, the functional folder is meant to hold tests for your controllers, and the integration folder is meant to hold tests that involve any number of controllers interacting. Fixtures are a way of organizing test data; they reside in the fixtures folder. The test_helper.rb file holds the default configuration for your tests. u can visit this.
If the OpenSSL headers are in the openssl
sub-directory of the current directory, use:
gcc -I. -o Opentest Opentest.c -lcrypto
The pre-processor looks to create a name such as "./openssl/ssl.h
" from the ".
" in the -I
option and the name specified in angle brackets. If you had specified the names in double quotes (#include "openssl/ssl.h"
), you might never have needed to ask the question; the compiler on Unix usually searches for headers enclosed in double quotes in the current directory automatically, but it does not do so for headers enclosed in angle brackets (#include <openssl/ssl.h>
). It is implementation defined behaviour.
You don't say where the OpenSSL libraries are - you might need to add an appropriate option and argument to specify that, such as '-L /opt/openssl/lib
'.
Let's consider f(n) > 0
and g(n) > 0
for all n
. It's ok to consider this, because the fastest real algorithm has at least one operation and completes its execution after the start. This will simplify the calculus, because we can use the value (f(n)
) instead of the absolute value (|f(n)|
).
f(n) = O(g(n))
General:
f(n)
0 = lim -------- < 8
n?8 g(n)
For g(n) = n
:
f(n)
0 = lim -------- < 8
n?8 n
Examples:
Expression Value of the limit
------------------------------------------------
n = O(n) 1
1/2*n = O(n) 1/2
2*n = O(n) 2
n+log(n) = O(n) 1
n = O(n*log(n)) 0
n = O(n²) 0
n = O(nn) 0
Counterexamples:
Expression Value of the limit
-------------------------------------------------
n ? O(log(n)) 8
1/2*n ? O(sqrt(n)) 8
2*n ? O(1) 8
n+log(n) ? O(log(n)) 8
f(n) = T(g(n))
General:
f(n)
0 < lim -------- < 8
n?8 g(n)
For g(n) = n
:
f(n)
0 < lim -------- < 8
n?8 n
Examples:
Expression Value of the limit
------------------------------------------------
n = T(n) 1
1/2*n = T(n) 1/2
2*n = T(n) 2
n+log(n) = T(n) 1
Counterexamples:
Expression Value of the limit
-------------------------------------------------
n ? T(log(n)) 8
1/2*n ? T(sqrt(n)) 8
2*n ? T(1) 8
n+log(n) ? T(log(n)) 8
n ? T(n*log(n)) 0
n ? T(n²) 0
n ? T(nn) 0
Datanewolf's code is ALMOST right. I had to reverse both the winding and the normals to make it work properly with the fixed pipeline. The below works correctly with cull on or off for me:
std::vector<GLfloat> vertices;
std::vector<GLfloat> normals;
std::vector<GLfloat> texcoords;
std::vector<GLushort> indices;
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
int r, s;
vertices.resize(rings * sectors * 3);
normals.resize(rings * sectors * 3);
texcoords.resize(rings * sectors * 2);
std::vector<GLfloat>::iterator v = vertices.begin();
std::vector<GLfloat>::iterator n = normals.begin();
std::vector<GLfloat>::iterator t = texcoords.begin();
for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
*t++ = s*S;
*t++ = r*R;
*v++ = x * radius;
*v++ = y * radius;
*v++ = z * radius;
*n++ = -x;
*n++ = -y;
*n++ = -z;
}
indices.resize(rings * sectors * 4);
std::vector<GLushort>::iterator i = indices.begin();
for(r = 0; r < rings-1; r++)
for(s = 0; s < sectors-1; s++) {
/*
*i++ = r * sectors + s;
*i++ = r * sectors + (s+1);
*i++ = (r+1) * sectors + (s+1);
*i++ = (r+1) * sectors + s;
*/
*i++ = (r+1) * sectors + s;
*i++ = (r+1) * sectors + (s+1);
*i++ = r * sectors + (s+1);
*i++ = r * sectors + s;
}
Edit: There was a question on how to draw this... in my code I encapsulate these values in a G3DModel class. This is my code to setup the frame, draw the model, and end it:
void GraphicsProvider3DPriv::BeginFrame()const{
int win_width;
int win_height;// framework of choice here
glfwGetWindowSize(window, &win_width, &win_height); // retrieve window
float const win_aspect = (float)win_width / (float)win_height;
// set lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_DEPTH_TEST);
GLfloat lightpos[] = {0, 0.0, 0, 0.};
glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
GLfloat lmodel_ambient[] = { 0.2, 0.2, 0.2, 1.0 };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
// set up world transform
glClearColor(0.f, 0.f, 0.f, 1.f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT|GL_ACCUM_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
}
void GraphicsProvider3DPriv::DrawModel(const G3DModel* model, const Transform3D transform)const{
G3DModelPriv* privModel = (G3DModelPriv *)model;
glPushMatrix();
glLoadMatrixf(transform.GetOGLData());
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &privModel->vertices[0]);
glNormalPointer(GL_FLOAT, 0, &privModel->normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &privModel->texcoords[0]);
glEnable(GL_TEXTURE_2D);
//glFrontFace(GL_CCW);
glEnable(GL_CULL_FACE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, privModel->texname);
glDrawElements(GL_QUADS, privModel->indices.size(), GL_UNSIGNED_SHORT, &privModel->indices[0]);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
void GraphicsProvider3DPriv::EndFrame()const{
/* Swap front and back buffers */
glDisable(GL_LIGHTING);
glDisable(GL_LIGHT0);
glDisable(GL_CULL_FACE);
glfwSwapBuffers(window);
/* Poll for and process events */
glfwPollEvents();
}
The resource drawable names are not stored as strings, so you'll have to resolve the string into the integer constant generated during the build. You can use the Resources
class to resolve the string into that integer.
Resources res = getResources();
int resourceId = res.getIdentifier(
generatedString, "drawable", getPackageName() );
imageView.setImageResource( resourceId );
This resolves your generated string into the integer that the ImageView
can use to load the right image.
Alternately, you can use the id to load the Drawable
manually and then set the image using that drawable instead of the resource ID.
Drawable drawable = res.getDrawable( resourceId );
imageView.setImageDrawable( drawable );
Not the solution, but for your interest: HTTP authentication only works, when PHP runs as Apache module. Most hosters provide PHP as CGI version only.
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
The second parameter of axios.post
is data
(not config
). config
is the third parameter. Please see this for details: https://github.com/mzabriskie/axios#axiosposturl-data-config
open avd manager click on the arrow next to the pencil icon and wipe data works for me...
You can test it by using this snipped code:
private static void Main(string[] args)
{
int threadCount = 0;
try
{
for (int i = 0; i < int.MaxValue; i ++)
{
new Thread(() => Thread.Sleep(Timeout.Infinite)).Start();
threadCount ++;
}
}
catch
{
Console.WriteLine(threadCount);
Console.ReadKey(true);
}
}
Beware of 32-bit and 64-bit mode of application.
$("input").on("keydown",function search(e) {
if(e.keyCode == 13) {
alert($(this).val());
}
});
jsFiddle example : http://jsfiddle.net/NH8K2/1/
For that
See
Then then create the dynamic CSS file as per the detected browser
/***** Selector Hacks ******/
/* IE6 and below */
* html #uno { color: red }
/* IE7 */
*:first-child+html #dos { color: red }
/* IE7, FF, Saf, Opera */
html>body #tres { color: red }
/* IE8, FF, Saf, Opera (Everything but IE 6,7) */
html>/**/body #cuatro { color: red }
/* Opera 9.27 and below, safari 2 */
html:first-child #cinco { color: red }
/* Safari 2-3 */
html[xmlns*=""] body:last-child #seis { color: red }
/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:nth-of-type(1) #siete { color: red }
/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:first-of-type #ocho { color: red }
/* saf3+, chrome1+ */
@media screen and (-webkit-min-device-pixel-ratio:0) {
#diez { color: red }
}
/* iPhone / mobile webkit */
@media screen and (max-device-width: 480px) {
#veintiseis { color: red }
}
/* Safari 2 - 3.1 */
html[xmlns*=""]:root #trece { color: red }
/* Safari 2 - 3.1, Opera 9.25 */
*|html[xmlns*=""] #catorce { color: red }
/* Everything but IE6-8 */
:root *> #quince { color: red }
/* IE7 */
*+html #dieciocho { color: red }
/* Firefox only. 1+ */
#veinticuatro, x:-moz-any-link { color: red }
/* Firefox 3.0+ */
#veinticinco, x:-moz-any-link, x:default { color: red }
/***** Attribute Hacks ******/
/* IE6 */
#once { _color: blue }
/* IE6, IE7 */
#doce { *color: blue; /* or #color: blue */ }
/* Everything but IE6 */
#diecisiete { color/**/: blue }
/* IE6, IE7, IE8 */
#diecinueve { color: blue\9; }
/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }
/* IE6, IE7 -- acts as an !important */
#veintesiete { color: blue !ie; } /* string after ! can be anything */
Source: http://paulirish.com/2009/browser-specific-css-hacks/
Extending @oopbase's answer with return;
statement.
Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,
/* Some Import Statements here. */
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
}
// ....
session.getAttribute("user_id");
// ....
/* Some More JSP+Java+HTML code here */
It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch
block or handled if(null != session.getAttribute("attr_name"))
everytime.
So by putting a return;
statement I stopped further execution and forced to redirect page to certain location.
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
return;
}
Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).
Use following line to select using value:
mSpinner.setSelection(yourList.indexOf("value"));
This is pretty basic, just put in the php file you want to use for processing in the element.
For example
<form action="process.php" method="post">
Then in process.php you would get the form values using $_POST['name of the variable]
In your case, the first value to insert must be NULL, because it's AUTO_INCREMENT.
You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);
, you just need to get rid of default sum(max_count)
. No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL
as the value for every cell in that column.
So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.
You also have the option to always COALESCE
the column to your desired default and leave it NULL
for now. This option fails when you want NULL
to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE
.
If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.
modified $.each
function
$.fn.eachReturn = function(arr, callback) {
var result = null;
$.each(arr, function(index, value){
var test = callback(index, value);
if (test) {
result = test;
return false;
}
});
return result ;
}
it will break loop on non-false/non-empty result and return it back, so in your case it would be
return $.eachReturn(someArray, function(i){
...
Be careful, reset --hard
will remove your local (uncommitted) modifications, too.
git reset --hard HEAD^
note: if you're on windows you'll need to quote the HEAD^ so
git reset --hard "HEAD^"
If you want to revert the commit WITHOUT throwing away work, use the --soft flag instead of --hard
Angular convention : write business logic in controller and DOM manipulation in link.
Apart from this you can call one controller function from link function of another directive.For example you have 3 custom directives
<animal>
<panther>
<leopard></leopard>
</panther>
</animal>
and you want to access animal from inside of "leopard" directive.
http://egghead.io/lessons/angularjs-directive-communication will be helpful to know about inter-directive communication
Android SDK
Installing the Android SDK is also necessary. The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android.
Cordova requires the ANDROID_HOME
environment variable to be set. This should point to the [ANDROID_SDK_DIR]\android-sdk
directory (for example c:\android\android-sdk).
Next, update your PATH to include the tools/ and platform-tools/ folder in that folder. So, using ANDROID_HOME
, you would add both %ANDROID_HOME%\tools
and %ANDROID_HOME%\platform-tools
.
Reference : http://ionicframework.com/docs/v1/guide/installation.html
Whilst I was looking for my answer for the same question, I found this:
<img src="img.png" style=max-
width:100%;overflow:hidden;border:none;padding:0;margin:0 auto;display:block;" marginheight="0" marginwidth="0">
You can use it inside a tag (iframe or img) the image will adjust based on it's device.
HTML
<Select id="SDistrict" class="form-control">
<option value="1" data-color="yellow" > Mango </option>
</select>
JS when initialized
$('#SDistrict').selectize({
create: false,
sortField: 'text',
onInitialize: function() {
var s = this;
this.revertSettings.$children.each(function() {
$.extend(s.options[this.value], $(this).data());
});
},
onChange: function(value) {
var option = this.options[value];
alert(option.text + ' color is ' + option.color);
}
});
You can access data attribute of option tag with option.[data-attribute]
JS Fiddle : https://jsfiddle.net/shashank_p/9cqoaeyt/3/
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
UPDATED
DEMO: http://jsbin.com/uneti3/3
your code is wrong, it should be something like this:
$(bla).click(function() {
var disable = $target.toggleClass('open').hasClass('open');
$target.prev().prop("disabled", disable);
});
you are using the toggleClass function in wrong way
You could also do:
SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = DATE '2011-01-26'
jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.
The poster didn't ask about looking up values if exact=FALSE
, but I'm adding this as an answer for my own reference and possibly others.
If you're looking up categorical values, use the other answers.
Excel's vlookup
also allows you to match match approximately for numeric values with the 4th argument(1) match=TRUE
. I think of match=TRUE
like looking up values on a thermometer. The default value is FALSE, which is perfect for categorical values.
If you want to match approximately (perform a lookup), R has a function called findInterval
, which (as the name implies) will find the interval / bin that contains your continuous numeric value.
However, let's say that you want to findInterval
for several values. You could write a loop or use an apply function. However, I've found it more efficient to take a DIY vectorized approach.
Let's say that you have a grid of values indexed by x and y:
grid <- list(x = c(-87.727, -87.723, -87.719, -87.715, -87.711),
y = c(41.836, 41.839, 41.843, 41.847, 41.851),
z = (matrix(data = c(-3.428, -3.722, -3.061, -2.554, -2.362,
-3.034, -3.925, -3.639, -3.357, -3.283,
-0.152, -1.688, -2.765, -3.084, -2.742,
1.973, 1.193, -0.354, -1.682, -1.803,
0.998, 2.863, 3.224, 1.541, -0.044),
nrow = 5, ncol = 5)))
and you have some values you want to look up by x and y:
df <- data.frame(x = c(-87.723, -87.712, -87.726, -87.719, -87.722, -87.722),
y = c(41.84, 41.842, 41.844, 41.849, 41.838, 41.842),
id = c("a", "b", "c", "d", "e", "f")
Here is the example visualized:
contour(grid)
points(df$x, df$y, pch=df$id, col="blue", cex=1.2)
You can find the x intervals and y intervals with this type of formula:
xrng <- range(grid$x)
xbins <- length(grid$x) -1
yrng <- range(grid$y)
ybins <- length(grid$y) -1
df$ix <- trunc( (df$x - min(xrng)) / diff(xrng) * (xbins)) + 1
df$iy <- trunc( (df$y - min(yrng)) / diff(yrng) * (ybins)) + 1
You could take it one step further and perform a (simplistic) interpolation on the z values in grid
like this:
df$z <- with(df, (grid$z[cbind(ix, iy)] +
grid$z[cbind(ix + 1, iy)] +
grid$z[cbind(ix, iy + 1)] +
grid$z[cbind(ix + 1, iy + 1)]) / 4)
Which gives you these values:
contour(grid, xlim = range(c(grid$x, df$x)), ylim = range(c(grid$y, df$y)))
points(df$x, df$y, pch=df$id, col="blue", cex=1.2)
text(df$x + .001, df$y, lab=round(df$z, 2), col="blue", cex=1)
df
# x y id ix iy z
# 1 -87.723 41.840 a 2 2 -3.00425
# 2 -87.712 41.842 b 4 2 -3.11650
# 3 -87.726 41.844 c 1 3 0.33150
# 4 -87.719 41.849 d 3 4 0.68225
# 6 -87.722 41.838 e 2 1 -3.58675
# 7 -87.722 41.842 f 2 2 -3.00425
Note that ix, and iy could have also been found with a loop using findInterval
, e.g. here's one example for the second row
findInterval(df$x[2], grid$x)
# 4
findInterval(df$y[2], grid$y)
# 2
Which matches ix
and iy
in df[2]
Footnote: (1) The fourth argument of vlookup was previously called "match", but after they introduced the ribbon it was renamed to "[range_lookup]".
Simple
ng g component plainsight/some-name
It will create "plainsight" folder and generate some-name component inside it.
I would like to recommend:
Microsoft Edge Run Wrapper
https://github.com/mihula/RunEdge
You run it this way:
RunEdge.exe [URL]
Examples:
RunEdge.exe http://google.com
RunEdge.exe www.stackoverflow.com
It is not exactly new way how to do it, but it is wrapped as exe file, which could be useful in some situations. For me it is way how to start Edge from IBM Notes Basic client.
Steps:
Example
x=pd.DataFrame([1,2,3,4])
def add(i1, i2):
return i1+i2
x.apply(add,i2=9)
The outcome of this example is that each number in the dataframe will be added to the number 9.
0
0 10
1 11
2 12
3 13
Explanation:
The "add" function has two parameters: i1, i2. The first parameter is going to be the value in data frame and the second is whatever we pass to the "apply" function. In this case, we are passing "9" to the apply function using the keyword argument "i2".
I know that the topic is way too old. But I am pretty sure that there are some developpers who still need this, so I made this simple script for you. I hope you enjoy it!
Hello back, It's 2020 and I've added some modification hope it will help a lot better now!
function strtotime(date, addTime){
let generatedTime=date.getTime();
if(addTime.seconds) generatedTime+=1000*addTime.seconds; //check for additional seconds
if(addTime.minutes) generatedTime+=1000*60*addTime.minutes;//check for additional minutes
if(addTime.hours) generatedTime+=1000*60*60*addTime.hours;//check for additional hours
return new Date(generatedTime);
}
Date.prototype.strtotime = function(addTime){
return strtotime(new Date(), addTime);
}
let futureDate = new Date().strtotime({
hours: 16, //Adding one hour
minutes: 45, //Adding fourty five minutes
seconds: 0 //Adding 0 seconds return to not adding any second so we can remove it.
});
_x000D_
<button onclick="console.log(futureDate)">Travel to the future</button>
_x000D_
For questions on simple string manipulation the dir
built-in function comes in handy. It gives you, among others, a list of methods of the argument, e.g., dir(s)
returns a list containing upper
.
Going back to Servlet days, web.xml can have only one <context-param>
, so only one context object gets created when server loads an application and the data in that context is shared among all resources (Ex: Servlets and JSPs). It is same as having Database driver name in the context, which will not change. In similar way, when we declare contextConfigLocation param in <contex-param>
Spring creates one Application Context object.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.myApp.ApplicationContext</param-value>
</context-param>
You can have multiple Servlets in an application. For example you might want to handle /secure/* requests in one way and /non-seucre/* in other way. For each of these Servlets you can have a context object, which is a WebApplicationContext.
<servlet>
<servlet-name>SecureSpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>com.myapp.secure.SecureContext</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SecureSpringDispatcher</servlet-name>
<url-pattern>/secure/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>NonSecureSpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>com.myapp.non-secure.NonSecureContext</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>NonSecureSpringDispatcher</servlet-name>
<url-pattern>/non-secure/*</url-patten>
</servlet-mapping>
For those who are using Firebase hosting none of the answers will work on this page. Because you can't use .htaccess
in Firebase hosting. You will have to configure the firebase.json file. Just add the line "cleanUrls": true
in your file and save it. That's it.
After adding the line firebase.json will look like this :
{
"hosting": {
"public": "public",
"cleanUrls": true,
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
For react native app, the error was java.lang.RuntimeException: Unable to get provider com.google.firebase.provider.FirebaseInitProvider: java.lang.ClassNotFoundException: Didn't find class "com.google.firebase.provider.FirebaseInitProvider"
It was only getting for devices with Android Version < ~4.4
Solved it by just replacing Application
in MainApplication.java
with MultiDexApplication
NOTE: import android.support.multidex.MultiDexApplication;
This error happen usually when tables in the query doesn't exist. Just check the table's spelling in the query, and it will work.
You can use * operator to unpack dict_values:
>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']
or list object
>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']
Finally after several hours of investigation I think I have another solution for everyone having issues with AVD Manager "Unable to locate adb".
I know we have the setting for the SDK in File -> Settings -> Appearance & Behavior -> System Settings -> Android SDK. This it seems is not enough! It appears that Android Studio (at least the new version 4) does not give projects a default SDK, despite the above setting.
So, you also (for each project) need to go to File -> Project Structure -> Project Settings -> Project, and select the Project SDK, which is set to [No SDK] by default.
If there's nothing in the drop-down box, then select New, select Android SDK, and navigate to your Android SDK location (normally C:\Users[username]\AppData\Local\Android\Sdk on Windows). You will then be able to select the Android API xx Platform. You now should not get this annoying adb error.
HTH
Install PAR::Packer
. Example for *nix:
sudo cpan -i PAR::Packer
For Strawberry Perl for Windows or for ActivePerl and MSVC installed:
cpan -i PAR::Packer
Pack it with pp
. It will create an executable named "example" or "example.exe" on Windows.
pp -o example example.pl
This would work only on the OS where it was built.
P.S. It is really hard to find a Unix clone without Perl. Did you mean Windows?
Test for ':' first, then take test string up to ':' or end, depending on if it was found
Dim strResult As String
' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
' : found, so take up to :
strResult = Left(strTest, intPos - 1)
Else
' : not found, so take whole string
strResult = strTest
End If
You can use the following command to update the DATA PUMP DIRECTORY path,
create or replace directory DATA_PUMP_DIR as '/u01/app/oracle/admin/MYDB/dpdump/';
For me data path correction was required as I have restored the my database from production to test environment.
Same command can be used to create a new DATA PUMP DIRECTORY
name
and path
.
The Linq extension method Any could work for you...
buildingStatus.Any(item => item.GetCharValue() == v.Status)
You can also use display: inline-block
. The advantage of this is that it will set the height and width like a block element but also set it inline so that you can have another a tag sitting right next to it, permitting the parent space.
You can find out more about display properties here
These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit
for Chrome, Safari; -moz
for Firefox, -o
for Opera, -ms
for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.
This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.
To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:
.elementClass {
-moz-border-radius: 2em;
-ms-border-radius: 2em;
-o-border-radius: 2em;
-webkit-border-radius: 2em;
border-radius: 2em;
}
Specifically, to address the CSS in your question, the lines you quote:
-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;
Specify the column-count
, column-gap
and column-fill
properties for Webkit browsers and Firefox.
References:
Note:
1) $.browser appears to be dropped in jQuery 1.9+ (as noted by Mandeep Jain). It is recommended to use .support instead.
2) $.browser.version can return "7" in IE >7 when the browser is in "compatibility" mode.
3) As of IE 10, conditional comments will no longer work.
4) jQuery 2.0+ will drop support for IE 6/7/8
5) document.documentMode appears to be defined only in Internet Explorer 8+ browsers. The value returned will tell you in what "compatibility" mode Internet Explorer is running. Still not a good solution though.
I tried numerous .support() options, but it appears that when an IE browser (9+) is in compatibility mode, it will simply behave like IE 7 ... :(
So far I only found this to work (kind-a):
(if documentMode is not defined and htmlSerialize and opacity are not supported, then you're very likely looking at IE <8 ...)
if(!document.documentMode && !$.support.htmlSerialize && !$.support.opacity)
{
// IE 6/7 code
}
#Return first n items of the iterable as a list
list(itertools.islice(iterable, n))
WPF contains the following MessageBox:
if (MessageBox.Show("Do you want to Save?", "Confirm",
MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
}
json.dumps()
is used to decode JSON dataimport json
# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
'int': int_data,
'str': str_data,
'float': float_data,
'list': list_data,
'nested list': nested_list
}
# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4)) # the json data will be indented
output:
String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
1,
1.5,
[
"normal string",
1,
1.5
]
]
Dictionary : {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
| Python | JSON |
|:--------------------------------------:|:------:|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
json.loads()
is used to convert JSON data into Python data.import json
# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'
# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)
print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])
print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])
output:
arrayJson to list_data :
[1, 1.5, ['normal string', 1, 1.5]]
Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]
objectJson to dictionary :
{'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}
Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
| JSON | Python |
|:-------------:|:------:|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | True |
| false | False |
In some scenarios, port
can only be designated by the environment and is saved in a user environment variable. Below is how node.js apps work with it.
The process
object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require()
.
The process.env
property returns an object containing the user environment.
An example of this object looks like:
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
For example,
terminal: set a new user environment variable, not permanently
export MY_TEST_PORT=9999
app.js: read the new environment variable from node app
console.log(process.env.MY_TEST_PORT)
terminal: run the node app and get the value
$ node app.js
9999
I've had the same problems including jpegs in LaTeX. The engine isn't really built to gather all the necessary size and scale information from JPGs. It is often better to take the JPEG and convert it into a PDF (on a mac) or EPS (on a PC). GraphicsConvertor on a mac will do that for you easily. Whereas a PDF includes DPI and size, a JPEG has only a size in terms of pixels.
( I know this is not the answer you wanted, but it's probably better to give them EPS/PDF that they can use than to worry about what happens when they try to scale your JPG).
I had the same problem, and it turned out I hadn't installed the library.
this link was super usefull.
Since the questions about best practice, I would add, that very often good idea to use hybrid approach for creating fragment when working with some REST web services
We can't pass complex objects, for example some User model, for case of displaying user fragment
But what we can do, is to check in onCreate
that user!=null and if not - then bring him from data layer, otherwise - use existing.
This way we gain both ability to recreate by userId in case of fragment recreation by Android and snappiness for user actions, as well as ability to create fragments by holding to object itself or only it's id
Something likes this:
public class UserFragment extends Fragment {
public final static String USER_ID="user_id";
private User user;
private long userId;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userId = getArguments().getLong(USER_ID);
if(user==null){
//
// Recreating here user from user id(i.e requesting from your data model,
// which could be services, direct request to rest, or data layer sitting
// on application model
//
user = bringUser();
}
}
public static UserFragment newInstance(User user, long user_id){
UserFragment userFragment = new UserFragment();
Bundle args = new Bundle();
args.putLong(USER_ID,user_id);
if(user!=null){
userFragment.user=user;
}
userFragment.setArguments(args);
return userFragment;
}
public static UserFragment newInstance(long user_id){
return newInstance(null,user_id);
}
public static UserFragment newInstance(User user){
return newInstance(user,user.id);
}
}
I'm a big fan of Autohotkey. I defined a 'paste plain text' macro that works in any application. It runs when I press Ctrl+Shift+V and pastes a plain version of whatever is on the clipboard. The nice thing about Autohotkey: you can code things to work the way you want them to work across all applications.
^+v::
; Convert any copied files, HTML, or other formatted text to plain text
Clipboard = %Clipboard%
; Paste by pressing Ctrl+V
SendInput, ^v
return
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));
Try chmod u+x foo.sh
instead of chmod +x foo.sh
if you have trouble with the guides above. This worked for me when the other solutions did not.
2018 edit: I think this answer has some interesting info, but for any practical applications you should use Joe's answer instead.
A simple way to create a unique ID in JavaScript is to use the Date object:
var uniqid = Date.now();
That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.
The problem with that value now is that you cannot use it as an element's ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.
var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
var uniqid = randLetter + Date.now();
This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.
use php implode()
or serialize()
The following is simple and worked for me:
bool hasMyColumn = (reader.GetSchemaTable().Select("ColumnName = 'MyColumnName'").Count() == 1);
To set Compatibility error
use this before using pivot function
ALTER DATABASE [dbname] SET COMPATIBILITY_LEVEL = 100
<html>
<title>
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.css">
<body>
<!-- <asp:LinkButton ID="MoreInfoButton" runat="server" Text="<%#MoreInfo%>" > -->
<!-- </asp:LinkButton> -->
<!-- </asp:LinkButton> -->
<br />
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
<div>
<a><span id="imgDownArrow_0" class="glyphicon glyphicon-chevron-right " runat="server"> MoreInformation</span></a>
<div id="parent" class="dataContentSectionMessages" style="display:none">
<!-- repeater1 starts -->
<!-- <sc:text field="Event Description" runat="server" item="<%#Container.DataItem %>" /> -->
<ul >
<li ><h6><strong>lorem</strong></h6></li>
<li ><h6><strong>An assigned contact who knows you and your lorem analysis system</strong></h6></li>
<li ><h6><strong>Internet accessible on-demand information and an easy to use internet shop</strong></h6></li>
<li ><h6><strong>Extensive and flexible repair capabilities at any location</strong></h6></li>
<li ><h6><strong>Full Service Contracts</strong></h6></li>
<li ><h6><strong>Maintenance Contracts</strong></h6></li>
</ul>
<!-- repeater1 ends -->
</div>
</div>
</asp:Repeater>
</body>
<!-- Predefined JavaScript -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>
<script>
$(function () {
$('a').click(function() {
$(this).parent().children('.dataContentSectionMessages').slideToggle();
});
});
</script>
</html>
//Here is an example
public class StaticClass
{
static int version;
public void printVersion() {
System.out.println(version);
}
}
public class MainClass
{
public static void main(String args[]) {
StaticClass staticVar1 = new StaticClass();
staticVar1.version = 10;
staticVar1.printVersion() // Output 10
StaticClass staticVar2 = new StaticClass();
staticVar2.printVersion() // Output 10
staticVar2.version = 20;
staticVar2.printVersion() // Output 20
staticVar1.printVersion() // Output 20
}
}
If you are using the version 1.21.1:
Now, just close the active tab pane and you are done.
I had the same problem. Just after enabling Internet Virtualization from BIOS. After that let the system boot and install HAXM once again. Now emulator will run faster than before and HAXM will work. Enjoy!!
another solution is to add toggle=false to the collapse target, this will stop it randomly opening and closing which happens if you just remove the "in"
eg
<div class="accordion-heading">
<a class="accordion-toggle"
data-toggle="collapse"
data-parent="#accordion2"
href="#collapseOne">Open!</a>
</div>
<div
id="collapseOne"
class="accordion-body collapse"
data-toggle="false"
>
<div class="span6">
<div class="well well-small">
<div class="accordion-toggle">
...some text...
</div>
</div>
</div>
<div class="span2"></div>
</div>
Reference ServiceBase
to your class and put the below code in the OnStart
event:
Constants.TimeIntervalValue = 1
(hour)..Ideally you should set this value in config file.
StartSendingMails = function name you want to run in the application.
protected override void OnStart(string[] args)
{
// It tells in what interval the service will run each time.
Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000;
base.OnStart(args);
TimerCallback timerDelegate = new TimerCallback(StartSendingMails);
serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval));
}
Below link is used to export datatable to excel in C# Code.
http://royalarun.blogspot.in/2012/01/export-datatable-to-excel-in-c-windows.html
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
namespace ExportExcel
{
public partial class ExportDatatabletoExcel : Form
{
public ExportDatatabletoExcel()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
//Add Datacolumn
DataColumn workCol = dt.Columns.Add("FirstName", typeof(String));
dt.Columns.Add("LastName", typeof(String));
dt.Columns.Add("Blog", typeof(String));
dt.Columns.Add("City", typeof(String));
dt.Columns.Add("Country", typeof(String));
//Add in the datarow
DataRow newRow = dt.NewRow();
newRow["firstname"] = "Arun";
newRow["lastname"] = "Prakash";
newRow["Blog"] = "http://royalarun.blogspot.com/";
newRow["city"] = "Coimbatore";
newRow["country"] = "India";
dt.Rows.Add(newRow);
//open file
StreamWriter wr = new StreamWriter(@"D:\\Book1.xls");
try
{
for (int i = 0; i < dt.Columns.Count; i++)
{
wr.Write(dt.Columns[i].ToString().ToUpper() + "\t");
}
wr.WriteLine();
//write rows to excel file
for (int i = 0; i < (dt.Rows.Count); i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (dt.Rows[i][j] != null)
{
wr.Write(Convert.ToString(dt.Rows[i][j]) + "\t");
}
else
{
wr.Write("\t");
}
}
//go to next line
wr.WriteLine();
}
//close file
wr.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
I agree with @zzzzBov's answer, but the "fail fast" advantage of Promise.all
is not the only difference. Some users in the comments have asked why using Promise.all
is worth it when it's only faster in the negative scenario (when some task fails). And I ask, why not? If I have two independent async parallel tasks and the first one takes a very long time to resolve but the second is rejected in a very short time, why leave the user to wait for the longer call to finish to receive an error message? In real-life applications we must consider the negative scenario. But OK - in this first difference you can decide which alternative to use: Promise.all
vs. multiple await
.
But when considering error handling, YOU MUST use Promise.all
. It is not possible to correctly handle errors of async parallel tasks triggered with multiple await
s. In the negative scenario you will always end with UnhandledPromiseRejectionWarning
and PromiseRejectionHandledWarning
, regardless of where you use try/ catch. That is why Promise.all
was designed. Of course someone could say that we can suppress those errors using process.on('unhandledRejection', err => {})
and process.on('rejectionHandled', err => {})
but this is not good practice. I've found many examples on the internet that do not consider error handling for two or more independent async parallel tasks at all, or consider it but in the wrong way - just using try/ catch and hoping it will catch errors. It's almost impossible to find good practice in this.
TL;DR: Never use multiple await
for two or more independent async parallel tasks, because you will not be able to handle errors correctly. Always use Promise.all()
for this use case.
Async/ await
is not a replacement for Promises, it's just a pretty way to use promises. Async code is written in "sync style" and we can avoid multiple then
s in promises.
Some people say that when using Promise.all()
we can't handle task errors separately, and that we can only handle the error from the first rejected promise (separate handling can be useful e.g. for logging). This is not a problem - see "Addition" heading at the bottom of this answer.
Consider this async task...
const task = function(taskNum, seconds, negativeScenario) {
return new Promise((resolve, reject) => {
setTimeout(_ => {
if (negativeScenario)
reject(new Error('Task ' + taskNum + ' failed!'));
else
resolve('Task ' + taskNum + ' succeed!');
}, seconds * 1000)
});
};
When you run tasks in the positive scenario there is no difference between Promise.all
and multiple await
s. Both examples end with Task 1 succeed! Task 2 succeed!
after 5 seconds.
// Promise.all alternative
const run = async function() {
// tasks run immediate in parallel and wait for both results
let [r1, r2] = await Promise.all([
task(1, 5, false),
task(2, 5, false)
]);
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!
// multiple await alternative
const run = async function() {
// tasks run immediate in parallel
let t1 = task(1, 5, false);
let t2 = task(2, 5, false);
// wait for both results
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: Task 1 succeed! Task 2 succeed!
However, when the first task takes 10 seconds and succeeds, and the second task takes 5 seconds but fails, there are differences in the errors issued.
// Promise.all alternative
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, false),
task(2, 5, true)
]);
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// multiple await alternative
const run = async function() {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
run();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
We should already notice here that we are doing something wrong when using multiple await
s in parallel. Let's try handling the errors:
// Promise.all alternative
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, false),
task(2, 5, true)
]);
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: Caught error Error: Task 2 failed!
As you can see, to successfully handle errors, we need to add just one catch to the run
function and add code with catch logic into the callback. We do not need to handle errors inside the run
function because async functions do this automatically - promise rejection of the task
function causes rejection of the run
function.
To avoid a callback we can use "sync style" (async/ await
+ try/ catch)
try { await run(); } catch(err) { }
but in this example it's not possible, because we can't use await
in the main thread - it can only be used in async functions (because nobody wants to block main thread). To test if handling works in "sync style" we can call the run
function from another async function or use an IIFE (Immediately Invoked Function Expression: MDN):
(async function() {
try {
await run();
} catch(err) {
console.log('Caught error', err);
}
})();
This is the only correct way to run two or more async parallel tasks and handle errors. You should avoid the examples below.
// multiple await alternative
const run = async function() {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
console.log(r1 + ' ' + r2);
};
We can try to handle errors in the code above in several ways...
try { run(); } catch(err) { console.log('Caught error', err); };
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled
... nothing got caught because it handles sync code but run
is async.
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
... huh? We see firstly that the error for task 2 was not handled and later that it was caught. Misleading and still full of errors in console, it's still unusable this way.
(async function() { try { await run(); } catch(err) { console.log('Caught error', err); }; })();
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: Caught error Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
... the same as above. User @Qwerty in his deleted answer asked about this strange behavior where an error seems to be caught but are also unhandled. We catch error the because run()
is rejected on the line with the await
keyword and can be caught using try/ catch when calling run()
. We also get an unhandled error because we are calling an async task function synchronously (without the await
keyword), and this task runs and fails outside the run()
function.
It is similar to when we are not able to handle errors by try/ catch when calling some sync function which calls setTimeout:
function test() {
setTimeout(function() {
console.log(causesError);
}, 0);
};
try {
test();
} catch(e) {
/* this will never catch error */
}`.
Another poor example:
const run = async function() {
try {
let t1 = task(1, 10, false);
let t2 = task(2, 5, true);
let r1 = await t1;
let r2 = await t2;
}
catch (err) {
return new Error(err);
}
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Caught error', err); });
// at 5th sec: UnhandledPromiseRejectionWarning: Error: Task 2 failed!
// at 10th sec: PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
... "only" two errors (3rd one is missing) but nothing is caught.
const run = async function() {
let [r1, r2] = await Promise.all([
task(1, 10, true).catch(err => { console.log('Task 1 failed!'); throw err; }),
task(2, 5, true).catch(err => { console.log('Task 2 failed!'); throw err; })
]);
console.log(r1 + ' ' + r2);
};
run().catch(err => { console.log('Run failed (does not matter which task)!'); });
// at 5th sec: Task 2 failed!
// at 5th sec: Run failed (does not matter which task)!
// at 10th sec: Task 1 failed!
... note that in this example I rejected both tasks to better demonstrate what happens (throw err
is used to fire final error).
Private constructor means a user cannot directly instantiate a class. Instead, you can create objects using something like the Named Constructor Idiom, where you have static
class functions that can create and return instances of a class.
The Named Constructor Idiom is for more intuitive usage of a class. The example provided at the C++ FAQ is for a class that can be used to represent multiple coordinate systems.
This is pulled directly from the link. It is a class representing points in different coordinate systems, but it can used to represent both Rectangular and Polar coordinate points, so to make it more intuitive for the user, different functions are used to represent what coordinate system the returned Point
represents.
#include <cmath> // To get std::sin() and std::cos()
class Point {
public:
static Point rectangular(float x, float y); // Rectangular coord's
static Point polar(float radius, float angle); // Polar coordinates
// These static methods are the so-called "named constructors"
...
private:
Point(float x, float y); // Rectangular coordinates
float x_, y_;
};
inline Point::Point(float x, float y)
: x_(x), y_(y) { }
inline Point Point::rectangular(float x, float y)
{ return Point(x, y); }
inline Point Point::polar(float radius, float angle)
{ return Point(radius*std::cos(angle), radius*std::sin(angle)); }
There have been a lot of other responses that also fit the spirit of why private constructors are ever used in C++ (Singleton pattern among them).
Another thing you can do with it is to prevent inheritance of your class, since derived classes won't be able to access your class' constructor. Of course, in this situation, you still need a function that creates instances of the class.
Cython is definitely the way to go, unless you anticipate writing Java wrappers, in which case SWIG may be preferable.
I recommend using the runcython
command line utility, it makes the process of using Cython extremely easy. If you need to pass structured data to C++, take a look at Google's protobuf library, it's very convenient.
Here is a minimal examples I made that uses both tools:
https://github.com/nicodjimenez/python2cpp
Hope it can be a useful starting point.
For me the error was:
Error: unexpected input in "?"
and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.
EDIT: OP requested an example. Here it goes.
? ~ cat a.R
cat('hello world\n')
? ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f ...cat('hello wo
00000010: 726c 645c 6e27 290a rld\n').
? ~ R -f a.R
R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> cat('hello world\n')
Error: unexpected input in "?"
Execution halted
In case someone comes here and want to activate the autocomplete function, go to
Preferences -> Java -> Editor -> Content Assist.
Then in the Auto Activation section fill in Auto activation triggers for Java:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._
Another way to handle the situation is exception handling.
Every time a non-existent value is called, your code will recover from the exception and just continue with the loop. In the catch-block you can handle the error the same way you write it down in your else-statement when the expression (... != null) returns false. Of course throwing and handling exceptions is a relatively costly operation which might not be ideal depending on the performance requirements.
SonarQube documentation recommends adding static
keyword to the class declaration.
That is, change public class FilePathHelper
to public static class FilePathHelper
.
Alternatively you can add a private or protected constructor.
public class FilePathHelper
{
// private or protected constructor
// because all public fields and methods are static
private FilePathHelper() {
}
}
You can add array keys to your return values and then use these keys to print the array values, as shown here:
function data() {
$out['a'] = "abc";
$out['b'] = "def";
$out['c'] = "ghi";
return $out;
}
$data = data();
echo $data['a'];
echo $data['b'];
echo $data['c'];
If you have array of arrays and want to concat the elements into a single array, try the following code (Requires ES2015):
let arrOfArr = [[1,2,3,4],[5,6,7,8]];
let newArr = [];
for (let arr of arrOfArr) {
newArr.push(...arr);
}
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];
Or if you're into functional programming
let arrOfArr = [[1,2,3,4],[5,6,7,8]];
let newArr = arrOfArr.reduce((result,current)=>{
result.push(...current);
return result;
});
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];
Or even better with ES5 syntax, without the spread operator
var arrOfArr = [[1,2,3,4],[5,6,7,8]];
var newArr = arrOfArr.reduce((result,current)=>{
return result.concat(current);
});
console.log(newArr);
//Output: [1,2,3,4,5,6,7,8];
This way is handy if you do not know the no. of arrays at the code time.
Try:
$data = file_get_contents ("file.json");
$json = json_decode($data, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br/>';
}
}
}
Keep it simple.
func NowAsUnixMilli() int64 {
return time.Now().UnixNano() / 1e6
}
AngularJS : AngularJS is for developing heavy web applications. AngularJS can use jQuery if it’s present in the web-app when the application is being bootstrapped. If it's not present in the script path, then AngularJS falls back to its own implementation of the subset of jQuery.
JQuery : jQuery is a small, fast, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler. jQuery simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.
Read more details here: angularjs-vs-jquery
Actually, CheckBoxPreference does have the ability to specify a different summary based on the checkbox value. See the android:summaryOff and android:summaryOn attributes (as well as the corresponding CheckBoxPreference methods).
Inside a module
Option Explicit
dim objExcelApp as Excel.Application
dim wb as Excel.Workbook
sub Initialize()
set objExcelApp = new Excel.Application
end sub
sub ProcessDataWorkbook()
dim ws as Worksheet
set wb = objExcelApp.Workbooks.Open("path to my workbook")
set ws = wb.Sheets(1)
ws.Cells(1,1).Value = "Hello"
ws.Cells(1,2).Value = "World"
'Close the workbook
wb.Close
set wb = Nothing
end sub
sub Release()
set objExcelApp = Nothing
end sub
You simply pass the FormControl an array of validators.
Here's an example showing how you can add validators to an existing FormControl:
this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);
Note, this will reset any existing validators you added when you created the FormControl.
Try this :
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys("[email protected]");
You can find every file what is created/modified in the last day, use this example:
find /directory -newermt $(date +%Y-%m-%d -d '1 day ago') -type f -print
for finding everything in the last week, use '1 week ago' or '7 day ago' anything you want
As noted in previous responses, using "$MyInvocation" is subject to scoping issues and doesn't necessarily provide consistent data (return value vs. direct access value). I've found that the "cleanest" (most consistent) method for getting script info like script path, name, parms, command line, etc. regardless of scope (in main or subsequent/nested function calls) is to use "Get-Variable" on "MyInvocation"...
# Get the MyInvocation variable at script level
# Can be done anywhere within a script
$ScriptInvocation = (Get-Variable MyInvocation -Scope Script).Value
# Get the full path to the script
$ScriptPath = $ScriptInvocation.MyCommand.Path
# Get the directory of the script
$ScriptDirectory = Split-Path $ScriptPath
# Get the script name
# Yes, could get via Split-Path, but this is "simpler" since this is the default return value
$ScriptName = $ScriptInvocation.MyCommand.Name
# Get the invocation path (relative to $PWD)
# @GregMac, this addresses your second point
$InvocationPath = ScriptInvocation.InvocationName
So, you can get the same info as $PSCommandPath, but a whole lot more in the deal. Not sure, but it looks like "Get-Variable" was not available until PS3 so not a lot of help for really old (not updated) systems.
There are also some interesting aspects when using "-Scope" as you can backtrack to get the names, etc. of the calling function(s). 0=current, 1=parent, etc.
Hope this is somewhat helpful.
Ref, https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-variable
java.lang
does not contain a class called StringUtils
. Several third-party libs do, such as Apache Commons Lang or the Spring framework. Make sure you have the relevant jar in your project classpath and import the correct class.
Using AES or implementing AES? To use AES, there is the System.Security.Cryptography.RijndaelManaged class.
Visual Studio 2003:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.0\Registration\PIDKEY
Visual Studio 2005:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY
Visual Studio 2008:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY
Visual Studio 2003:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\7.0\Registration\PIDKEY
Visual Studio 2005:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\8.0\Registration\PIDKEY
Visual Studio 2008:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\Registration\PIDKEY
If PIDKEY value is empty try to look at the subfolders e.g.
...\Registration\1000.0x0000\PIDKEY
or
...\Registration\2000.0x0000\PIDKEY
If you have a datetime.timedelta
value td
, td.days
already gives you the "days" you want. timedelta
values keep fraction-of-day as seconds (not directly hours or minutes) so you'll indeed have to perform "nauseatingly simple mathematics", e.g.:
def days_hours_minutes(td):
return td.days, td.seconds//3600, (td.seconds//60)%60
for centos, just zlib didn't solve the problem.I did
sudo yum install zlib-devel.i686
Refer the Q/A for logging the request and response for the rest template by enabling the multiple reads on the HttpInputStream
Why my custom ClientHttpRequestInterceptor with empty response
I was facing this issue while deploying my ear to my local weblogic instance. Clearing the local repository and building the ear again resolved the issue for me.
The <b> tag is alive and well. <b> is not deprecated, but its use has been clarified and limited. <b> has no semantic meaning, nor does it convey vocal emphasis such as might be spoken by a screen reader. <b> does, however, convey printed empasis, as does the <i> tag. Both have a specific place in typograpghy, but not in spoken communication, mes frères.
To quote from http://www.whatwg.org/
The b element represents a span of text to be stylistically offset from the normal prose without conveying any extra importance, such as key words in a document abstract, product names in a review, or other spans of text whose typical typographic presentation is boldened.
in my test.
close
will send fin packet and destroy fd immediately when socket is not shared with other processes
shutdown
SHUT_RD, process can still recv data from the socket, but recv
will return 0 if TCP buffer is empty.After peer send more data, recv
will return data again.
shutdown
SHUT_WR will send fin packet to indicate the Further sends are disallowed. the peer can recv data but it will recv 0 if its TCP buffer is empty
shutdown
SHUT_RDWR (equal to use both SHUT_RD and SHUT_WR) will send rst packet if peer send more data.
Swift 3 and Swift 4:
myView.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
You want to use transform
this will return a Series with the index aligned to the df so you can then add it as a new column:
In [74]:
df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
Data2 Data3 Date Sym Data4
0 11 5 2015-05-08 aapl 55
1 8 8 2015-05-07 aapl 108
2 10 6 2015-05-06 aapl 66
3 15 1 2015-05-05 aapl 121
4 110 50 2015-05-08 aaww 55
5 60 100 2015-05-07 aaww 108
6 100 60 2015-05-06 aaww 66
7 40 120 2015-05-05 aaww 121
You can use the file Object to get the length of the file to initialize your array:
int length = Long.valueOf(file.length()).intValue();
byte[] byteArray = new byte[length];
The script element that loads the API is missing the required authentication parameter. If you are using the standard Maps JavaScript API, you must use a key parameter with a valid API key. If you are a Premium Plan customer, you must use either a client parameter with your client ID or a key parameter with a valid API key.
See the guide to API keys and client IDs.
I would try to avoid changing the xticklabels
if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.
Defining the range of your grid is probably the best and with imshow
it can be done by adding the extent
keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks
with perhaps some formatter. Altering the labels directly should be the last resort.
fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio
If have a solution without jQuery. A link where you can see a working example: http://www.letmaier.com/_selectbox/select_general_code.html (styled with more css)
The style-section of my solution:
<style>
#container { margin: 10px; padding: 5px; background: #E7E7E7; width: 300px; background: #ededed); }
#ul1 { display: none; list-style-type: none; list-style-position: outside; margin: 0px; padding: 0px; }
#container a { color: #333333; text-decoration: none; }
#container ul li { padding: 3px; padding-left: 0px; border-bottom: 1px solid #aaa; font-size: 0.8em; cursor: pointer; }
#container ul li:hover { background: #f5f4f4; }
</style>
Now the HTML-code inside the body-tag:
<form>
<div id="container" onMouseOver="document.getElementById('ul1').style.display = 'block';" onMouseOut="document.getElementById('ul1').style.display = 'none';">
Select one entry: <input name="entrytext" type="text" disabled readonly>
<ul id="ul1">
<li onClick="document.forms[0].elements['entrytext'].value='Entry 1'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 1</a></li>
<li onClick="document.forms[0].elements['entrytext'].value='Entry 2'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 2</a></li>
<li onClick="document.forms[0].elements['entrytext'].value='Entry 3'; document.getElementById('ul1').style.display = 'none';"><a href="#">Entry 3</a></li>
</ul>
</div>
</form>
Extension methods I commonly use to solve this problem:
public static string RemoveAfter(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(0, index);
}
return value;
}
public static string RemoveBefore(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(index + 1);
}
return value;
}
If you're using Building Standalone Apps with Expo, the versionCode error might creep up owing to the fact that the standard app.json
config only has a reference to the version
property.
I was able to add a versionCode
property under android
as follows:
Sample App.json
{
"expo": {
"sdkVersion": "29.0.0",
"name": "App Name",
"version": "1.1.0",
"slug": "app-name",
"icon": "src/images/app-icon.png",
"privacy": "public",
"android": {
"package": "com.madhues.app",
"permissions": [],
"versionCode": 2 // Notice the versionCode added under android.
}
}
}
Detailed documentation: https://docs.expo.io/versions/v32.0.0/workflow/configuration/#versioncode
if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:
select
psat.schemaname,
psat.relname,
pa.attname,
psat.relid
from
pg_catalog.pg_stat_all_tables psat,
pg_catalog.pg_attribute pa
where
psat.relid = pa.attrelid
change schema name:
ALTER SCHEMA "XXXXX" RENAME TO xxxxx;
change table names:
ALTER TABLE xxxxx."AAAAA" RENAME TO aaaaa;
change column names:
ALTER TABLE xxxxx.aaaaa RENAME COLUMN "CCCCC" TO ccccc;
A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
This method holds instructions to paint this component. Actually, in Swing, you should change paintComponent() instead of paint(), as paint calls paintBorder(), paintComponent() and paintChildren(). You shouldn't call this method directly, you should call repaint() instead.
This method can't be overridden. It controls the update() -> paint() cycle. You should call this method to get a component to repaint itself. If you have done anything to change the look of the component, but not its size ( like changing color, animating, etc. ) then call this method.
That watermark in the bottom right only appears on mouseover
. There's no parameter to remove that, however if you stack a transparent div
on top of the video and make it a higher z-index
and the same size of the video, your mouseover
will not trigger the watermark because your mouse will be hitting the div
.
Of course the tradeoff for this is that you lose the ability to actually click on the video to pause it. But if you want to leave the ability to pause it, you could display the controls and have the top layer div
cover up until the bottom 30 pixels or so, letting you click the controls.
Just add overflow:hidden
to the table with border-radius
.
.tablewithradius {
overflow:hidden ;
border-radius: 15px;
}
No refresh is needed if the "val"-parameter is used for setting the value, see fiddle. Use brackets for the value to enable multiple selected values.
$('.selectpicker').selectpicker('val', [1]);
You can also use this approach in case you want to pass some http parameters and send a json request:
(note: I have added in some extra code just incase it helps any other future readers)
public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {
//add the http parameters you wish to pass
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
//Build the server URI together with the parameters you wish to pass
URIBuilder uriBuilder = new URIBuilder("http://google.ug");
uriBuilder.addParameters(postParameters);
HttpPost postRequest = new HttpPost(uriBuilder.build());
postRequest.setHeader("Content-Type", "application/json");
//this is your JSON string you are sending as a request
String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";
//pass the json string request in the entity
HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
postRequest.setEntity(entity);
//create a socketfactory in order to use an http connection manager
PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory)
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);
connManager.setMaxTotal(20);
connManager.setDefaultMaxPerRoute(20);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(HttpClientPool.connTimeout)
.setConnectTimeout(HttpClientPool.connTimeout)
.setConnectionRequestTimeout(HttpClientPool.readTimeout)
.build();
// Build the http client.
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.setDefaultRequestConfig(defaultRequestConfig)
.build();
CloseableHttpResponse response = httpclient.execute(postRequest);
//Read the response
String responseString = "";
int statusCode = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
HttpEntity responseHttpEntity = response.getEntity();
InputStream content = responseHttpEntity.getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = buffer.readLine()) != null) {
responseString += line;
}
//release all resources held by the responseHttpEntity
EntityUtils.consume(responseHttpEntity);
//close the stream
response.close();
// Close the connection manager.
connManager.close();
}
in the directory that you want to donwload:
git init
git remote add origin -f repoUrl // folder url
touch .git/info/sparse-checkout
git pull origin master
only 4 lines of code
What are disadvantages of the following solution? Seems to be faster and shorter.
var options = {
set0: ['Option 1','Option 2'],
set1: ['First Option','Second Option','Third Option']
};
var list = "<li>" + options.set0.join("</li><li>") + "</li>";
document.getElementById("list").innerHTML = list;
You're after the UPDATE FROM
syntax.
UPDATE
table T1
SET
column1 = T2.column1
FROM
table T2
INNER JOIN table T3 USING (column2)
WHERE
T1.column2 = T2.column2;
References
If you want to use slf4j simple
, you need these jar
files on your classpath:
If you want to use slf4j
and log4j
, you need these jar
files on your classpath:
No more, no less. Using slf4j simple
, you'll get basic logging to your console at INFO
level or higher. Using log4j
, you must configure it accordingly.
Since this must have an input element as a parent, you could just use
<input type="text" ng-model="foo" ng-change="myOnChangeFunction()">
Alternatively, you could use the ngModelController
and add a function to $formatters
, which executes functions on input change. See http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
.directive("myDirective", function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$formatters.push(function(value) {
// Do stuff here, and return the formatted value.
});
};
};
setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));
Simple PHP function to unzip. Please make sure you have zip extension installed on your server.
/**
* Unzip
* @param string $zip_file_path Eg - /tmp/my.zip
* @param string $extract_path Eg - /tmp/new_dir_name
* @return boolean
*/
function unzip(string $zip_file_path, string $extract_dir_path) {
$zip = new \ZipArchive;
$res = $zip->open($zip_file_path);
if ($res === TRUE) {
$zip->extractTo($extract_dir_path);
$zip->close();
return TRUE;
} else {
return FALSE;
}
}
Submodule repositories stay in a detached HEAD state pointing to a specific commit. Changing that commit simply involves checking out a different tag or commit then adding the change to the parent repository.
$ cd submodule
$ git checkout v2.0
Previous HEAD position was 5c1277e... bumped version to 2.0.5
HEAD is now at f0a0036... version 2.0
git-status
on the parent repository will now report a dirty tree:
# On branch dev [...]
#
# modified: submodule (new commits)
Add the submodule directory and commit to store the new pointer.
Have a look at the content by type web part - http://codeplex.com/eoffice - probably the most flexible viewing web part.
This has been used above but not mentioned exclusively.
setCropToPadding(boolean);
If true, the image will be cropped to fit within its padding.
This will make the ImageView
source to fit within the padding's added to its background.
Via XML it can be done as below-
android:cropToPadding="true"
*scanf()
family of functions return the number of values converted. So you should check to make sure sscanf()
returns 1 in your case. EOF
is returned for "input failure", which means that ssacnf()
will never return EOF
.
For sscanf()
, the function has to parse the format string, and then decode an integer. atoi()
doesn't have that overhead. Both suffer from the problem that out-of-range values result in undefined behavior.
You should use strtol()
or strtoul()
functions, which provide much better error-detection and checking. They also let you know if the whole string was consumed.
If you want an int
, you can always use strtol()
, and then check the returned value to see if it lies between INT_MIN
and INT_MAX
.
var filtered = projects;
foreach (var tag in filteredTags) {
filtered = filtered.Where(p => p.Tags.Contains(tag))
}
The nice thing with this approach is that you can refine search results incrementally.
to list the emulators you have
~/Library/Android/sdk/tools/emulator -list-avds
for example, I have this Nexus_5X_API_24
so the command to run that emulator is
cd ~/Library/Android/Sdk/tools && ./emulator -avd Nexus_5X_API_24
When searching for an example of a C++ class that calls one of its own instance methods in a new thread, this question comes up, but we were not able to use any of these answers that way. Here's an example that does that:
Class.h
class DataManager
{
public:
bool hasData;
void getData();
bool dataAvailable();
};
Class.cpp
#include "DataManager.h"
void DataManager::getData()
{
// perform background data munging
hasData = true;
// be sure to notify on the main thread
}
bool DataManager::dataAvailable()
{
if (hasData)
{
return true;
}
else
{
std::thread t(&DataManager::getData, this);
t.detach(); // as opposed to .join, which runs on the current thread
}
}
Note that this example doesn't get into mutex or locking.
If you want to generate 100 numbers that are random, but each number appearing only once, a good way would be to generate an array with the numbers in order, then shuffle it.
Something like this:
$arr = array();
for ($i=1;$i<=101;$i++) {
$arr[] = $i;
}
shuffle($arr);
print_r($arr);
Output will look something like this:
Array
(
[0] => 16
[1] => 93
[2] => 46
[3] => 55
[4] => 18
[5] => 63
[6] => 19
[7] => 91
[8] => 99
[9] => 14
[10] => 45
[11] => 68
[12] => 61
[13] => 86
[14] => 64
[15] => 17
[16] => 27
[17] => 35
[18] => 87
[19] => 10
[20] => 95
[21] => 43
[22] => 51
[23] => 92
[24] => 22
[25] => 58
[26] => 71
[27] => 13
[28] => 66
[29] => 53
[30] => 49
[31] => 78
[32] => 69
[33] => 1
[34] => 42
[35] => 47
[36] => 26
[37] => 76
[38] => 70
[39] => 100
[40] => 57
[41] => 2
[42] => 23
[43] => 15
[44] => 96
[45] => 48
[46] => 29
[47] => 81
[48] => 4
[49] => 33
[50] => 79
[51] => 84
[52] => 80
[53] => 101
[54] => 88
[55] => 90
[56] => 56
[57] => 62
[58] => 65
[59] => 38
[60] => 67
[61] => 74
[62] => 37
[63] => 60
[64] => 21
[65] => 89
[66] => 3
[67] => 32
[68] => 25
[69] => 52
[70] => 50
[71] => 20
[72] => 12
[73] => 7
[74] => 54
[75] => 36
[76] => 28
[77] => 97
[78] => 94
[79] => 41
[80] => 72
[81] => 40
[82] => 83
[83] => 30
[84] => 34
[85] => 39
[86] => 6
[87] => 98
[88] => 8
[89] => 24
[90] => 5
[91] => 11
[92] => 73
[93] => 44
[94] => 85
[95] => 82
[96] => 75
[97] => 31
[98] => 77
[99] => 9
[100] => 59
)
If your matrix is called m
, just use :
R> m[m$three == 11, ]
Try this.
namespace EraseJunkFiles
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo yourRootDir = new DirectoryInfo(@"C:\somedirectory\");
foreach (DirectoryInfo dir in yourRootDir.GetDirectories())
DeleteDirectory(dir.FullName, true);
}
public static void DeleteDirectory(string directoryName, bool checkDirectiryExist)
{
if (Directory.Exists(directoryName))
Directory.Delete(directoryName, true);
else if (checkDirectiryExist)
throw new SystemException("Directory you want to delete is not exist");
}
}
}
Here's a solution that may work better in the case you are referencing objWorksheet.UsedRange.
Excel.Worksheet mySheet = ...(load a workbook, etc);
Excel.Range myRange = mySheet.UsedRange;
var values = (myRange.Value as Object[,]);
int rowNumber = 3, columnNumber = 5;
string cellValue = Convert.ToString(values[rowNumber, columnNumber]);
It is general practice in various messaging protocols to keep heartbeating each other (keep sending ping packets) the packet does not need to be very large. The probing mechanism will allow you to detect the disconnected client even before TCP figures it out in general (TCP timeout is far higher) Send a probe and wait for say 5 seconds for a reply, if you do not see reply for say 2-3 subsequent probes, your player is disconnected.
Also, related question
You don't need JavaScript for this. Just wanted to make that clear, since as of the time this answer was posted, all of the answers to this question involve the use of JavaScript in some way or another.
You can do this rather easily with pure HTML and CSS by creating a form with hidden fields containing the data you want to submit, then styling the submit button of the form to look like a link.
For example:
.inline {_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
.link-button {_x000D_
background: none;_x000D_
border: none;_x000D_
color: blue;_x000D_
text-decoration: underline;_x000D_
cursor: pointer;_x000D_
font-size: 1em;_x000D_
font-family: serif;_x000D_
}_x000D_
.link-button:focus {_x000D_
outline: none;_x000D_
}_x000D_
.link-button:active {_x000D_
color:red;_x000D_
}
_x000D_
<a href="some_page">This is a regular link</a>_x000D_
_x000D_
<form method="post" action="some_page" class="inline">_x000D_
<input type="hidden" name="extra_submit_param" value="extra_submit_value">_x000D_
<button type="submit" name="submit_param" value="submit_value" class="link-button">_x000D_
This is a link that sends a POST request_x000D_
</button>_x000D_
</form>
_x000D_
The exact CSS you use may vary depending on how regular links on your site are styled.
Check below method is working awesome also Oreo 8.1 ..
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO ManualMT-generated method stub
switch (requestCode) {
case PICKFILE_RESULT_CODE:
if (resultCode == RESULT_OK) {
try {
FilePath = data.getData().getPath();
Uri selectedImageUri = data.getData();
if (selectedImageUri.toString().contains("storage/emulated")){
String[] split = selectedImageUri.toString().split("storage/");
FilePath = "storage/"+split[1];
} else {
FilePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
}
recyclerview.setVisibility(View.VISIBLE);
if (FilePath == null) {
FilePath = "";
}
File file = new File(FilePath);
reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
image_list.add(FilePath);
composeImageAdapter.notifyDataSetChanged();
} catch (Exception e){
Toast.makeText(ClusterCreateNote.this , e.toString(),Toast.LENGTH_SHORT).show();
}
}
break;
}
}
URI path Class:
public static class ImageFilePath {
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/
public static String getPath(final Context context, final Uri uri) {
String selection = null;
String[] selectionArgs = null;
// DocumentProvider
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.wifAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Log.e("typetype",type);
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{
split[1]
};
Log.e("gddhjf",getDataColumn(context, contentUri, selection, selectionArgs));
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
String[] projection = {
MediaStore.Images.Media.DATA
};
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(uri, projection, selection, selectionArgs, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return
"com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return
"com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
Pretty much. One small difference though: if the Task
fails, GetResult()
will just throw the exception caused directly, while Task.Result
will throw an AggregateException
. However, what's the point of using either of those when it's async
? The 100x better option is to use await
.
Also, you're not meant to use GetResult()
. It's meant to be for compiler use only, not for you. But if you don't want the annoying AggregateException
, use it.
New-style classes are ones that subclass "object" (directly or indirectly). They have a __new__
class method in addition to __init__
and have somewhat more rational low-level behavior.
Usually, you'll want to override __getattr__
(if you're overriding either), otherwise you'll have a hard time supporting "self.foo" syntax within your methods.
Extra info: http://www.devx.com/opensource/Article/31482/0/page/4
If you are unable to get rid of extra xmlns attributes for each element, when serializing to xml from generated classes (e.g.: when xsd.exe was used), so you have something like:
<manyElementWith xmlns="urn:names:specification:schema:xsd:one" />
then i would share with you what worked for me (a mix of previous answers and what i found here)
explicitly set all your different xmlns as follows:
Dim xmlns = New XmlSerializerNamespaces()
xmlns.Add("one", "urn:names:specification:schema:xsd:one")
xmlns.Add("two", "urn:names:specification:schema:xsd:two")
xmlns.Add("three", "urn:names:specification:schema:xsd:three")
then pass it to the serialize
serializer.Serialize(writer, object, xmlns);
you will have the three namespaces declared in the root element and no more needed to be generated in the other elements which will be prefixed accordingly
<root xmlns:one="urn:names:specification:schema:xsd:one" ... />
<one:Element />
<two:ElementFromAnotherNameSpace /> ...
My version based on the work by @mcgrailm... tweaked because the report needed to be reviewed within 3 business days, and if submitted on a weekend, the counting would start on the following Monday:
function business_days_add($start_date, $business_days, $holidays = array()) {
$current_date = strtotime($start_date);
$business_days = intval($business_days); // Decrement does not work on strings
while ($business_days > 0) {
if (date('N', $current_date) < 6 && !in_array(date('Y-m-d', $current_date), $holidays)) {
$business_days--;
}
if ($business_days > 0) {
$current_date = strtotime('+1 day', $current_date);
}
}
return $current_date;
}
And working out the difference of two dates in terms of business days:
function business_days_diff($start_date, $end_date, $holidays = array()) {
$business_days = 0;
$current_date = strtotime($start_date);
$end_date = strtotime($end_date);
while ($current_date <= $end_date) {
if (date('N', $current_date) < 6 && !in_array(date('Y-m-d', $current_date), $holidays)) {
$business_days++;
}
if ($current_date <= $end_date) {
$current_date = strtotime('+1 day', $current_date);
}
}
return $business_days;
}
As a note, everyone who is using 86400, or 24*60*60, please don't... your forgetting time changes from winter/summer time, where a day it not exactly 24 hours. While it's a little slower the strtotime('+1 day', $timestamp), it much more reliable.
I like the accepted answer: it is straightforward and will get the job done. I would also like to offer an alternative implementation:
def chunks(filename, buffer_size=4096):
"""Reads `filename` in chunks of `buffer_size` bytes and yields each chunk
until no more characters can be read; the last chunk will most likely have
less than `buffer_size` bytes.
:param str filename: Path to the file
:param int buffer_size: Buffer size, in bytes (default is 4096)
:return: Yields chunks of `buffer_size` size until exhausting the file
:rtype: str
"""
with open(filename, "rb") as fp:
chunk = fp.read(buffer_size)
while chunk:
yield chunk
chunk = fp.read(buffer_size)
def chars(filename, buffersize=4096):
"""Yields the contents of file `filename` character-by-character. Warning:
will only work for encodings where one character is encoded as one byte.
:param str filename: Path to the file
:param int buffer_size: Buffer size for the underlying chunks,
in bytes (default is 4096)
:return: Yields the contents of `filename` character-by-character.
:rtype: char
"""
for chunk in chunks(filename, buffersize):
for char in chunk:
yield char
def main(buffersize, filenames):
"""Reads several files character by character and redirects their contents
to `/dev/null`.
"""
for filename in filenames:
with open("/dev/null", "wb") as fp:
for char in chars(filename, buffersize):
fp.write(char)
if __name__ == "__main__":
# Try reading several files varying the buffer size
import sys
buffersize = int(sys.argv[1])
filenames = sys.argv[2:]
sys.exit(main(buffersize, filenames))
The code I suggest is essentially the same idea as your accepted answer: read a given number of bytes from the file. The difference is that it first reads a good chunk of data (4006 is a good default for X86, but you may want to try 1024, or 8192; any multiple of your page size), and then it yields the characters in that chunk one by one.
The code I present may be faster for larger files. Take, for example, the entire text of War and Peace, by Tolstoy. These are my timing results (Mac Book Pro using OS X 10.7.4; so.py is the name I gave to the code I pasted):
$ time python so.py 1 2600.txt.utf-8
python so.py 1 2600.txt.utf-8 3.79s user 0.01s system 99% cpu 3.808 total
$ time python so.py 4096 2600.txt.utf-8
python so.py 4096 2600.txt.utf-8 1.31s user 0.01s system 99% cpu 1.318 total
Now: do not take the buffer size at 4096
as a universal truth; look at the results I get for different sizes (buffer size (bytes) vs wall time (sec)):
2 2.726
4 1.948
8 1.693
16 1.534
32 1.525
64 1.398
128 1.432
256 1.377
512 1.347
1024 1.442
2048 1.316
4096 1.318
As you can see, you can start seeing gains earlier on (and my timings are likely very inaccurate); the buffer size is a trade-off between performance and memory. The default of 4096 is just a reasonable choice but, as always, measure first.
The best practice is to compare it using constructor
, something like this
if(some_variable.constructor === Array){
// do something
}
You can use other methods too like typeOf
, converting it to a string and then comparing but comparing it with dataType is always a better approach.
There is another alternative solution, that seems to be more attractive.
Now with all the above setup, you have a few options for the client:
Update: I did go this route, and it has been working nicely. Just wanted to add to this.
Reference links:
Note the official docs on connection configuration variables or "behavioral" variables - which aren't listed in host vars, appears to be List of Behavioral Inventory Parameters in the Inventory documentation.
P.S. The sudo
option is undocumented there (yes its sudo
not ansible_sudo
as you'd expect ...) and probably a couple more aren't, but thats best doc I've found on em.
This should work for you:
var date1 = new Date(year, month, day, hour, minute, seconds);
I had to create date form a string so I have done it like this:
var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2), d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));
Remember that the months in javascript are from 0 to 11, so you should reduce the month value by 1, like this:
var d = '2013-07-20 16:57:27';
var date1 = new Date(d.substr(0, 4), d.substr(5, 2) - 1, d.substr(8, 2), d.substr(11, 2), d.substr(14, 2), d.substr(17, 2));
Functions that might be helpful:
open("file").read()
which reads the contents of the whole file at once'string'.splitlines()
which separates lines from each other (and discards empty lines)By using len() and those functions you could accomplish what you're doing.
Always encode from unicode to bytes.
In this direction, you get to choose the encoding.
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print _
??
The other way is to decode from bytes to unicode.
In this direction, you have to know what the encoding is.
>>> bytes = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print bytes
??
>>> bytes.decode('utf-8')
u'\u4f60\u597d'
>>> print _
??
This point can't be stressed enough. If you want to avoid playing unicode "whack-a-mole", it's important to understand what's happening at the data level. Here it is explained another way:
decode
on it.encode
on it.Now, on seeing .encode
on a byte string, Python 2 first tries to implicitly convert it to text (a unicode
object). Similarly, on seeing .decode
on a unicode string, Python 2 implicitly tries to convert it to bytes (a str
object).
These implicit conversions are why you can get Unicode
Decode
Error
when you've called encode
. It's because encoding usually accepts a parameter of type unicode
; when receiving a str
parameter, there's an implicit decoding into an object of type unicode
before re-encoding it with another encoding. This conversion chooses a default 'ascii' decoder†, giving you the decoding error inside an encoder.
In fact, in Python 3 the methods str.decode
and bytes.encode
don't even exist. Their removal was a [controversial] attempt to avoid this common confusion.
† ...or whatever coding sys.getdefaultencoding()
mentions; usually this is 'ascii'
You will have to use some sort of network sniffer if you want to get at this sort of data and you're likely to run into the same problem (pulling out the relevant data from the overall network traffic) with those that you do now with Wireshark.
In your binding configuration, there are four timeout values you can tweak:
<bindings>
<basicHttpBinding>
<binding name="IncreasedTimeout"
sendTimeout="00:25:00">
</binding>
</basicHttpBinding>
The most important is the sendTimeout
, which says how long the client will wait for a response from your WCF service. You can specify hours:minutes:seconds
in your settings - in my sample, I set the timeout to 25 minutes.
The openTimeout
as the name implies is the amount of time you're willing to wait when you open the connection to your WCF service. Similarly, the closeTimeout
is the amount of time when you close the connection (dispose the client proxy) that you'll wait before an exception is thrown.
The receiveTimeout
is a bit like a mirror for the sendTimeout
- while the send timeout is the amount of time you'll wait for a response from the server, the receiveTimeout
is the amount of time you'll give you client to receive and process the response from the server.
In case you're send back and forth "normal" messages, both can be pretty short - especially the receiveTimeout
, since receiving a SOAP message, decrypting, checking and deserializing it should take almost no time. The story is different with streaming - in that case, you might need more time on the client to actually complete the "download" of the stream you get back from the server.
There's also openTimeout, receiveTimeout, and closeTimeout. The MSDN docs on binding gives you more information on what these are for.
To get a serious grip on all the intricasies of WCF, I would strongly recommend you purchase the "Learning WCF" book by Michele Leroux Bustamante:
and you also spend some time watching her 15-part "WCF Top to Bottom" screencast series - highly recommended!
For more advanced topics I recommend that you check out Juwal Lowy's Programming WCF Services book.
Call
setSupportActionBar(toolbar)
inside
onViewCreated(...)
of Fragment
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((MainActivity)getActivity()).setSupportActionBar(toolbar);
setHasOptionsMenu(true);
}
Version 3.6+: Use a formatted string literal, f-string for short
print(f"{i}. {key} appears {wordBank[key]} times.")
Clone target repository same way like you cloning any other project:
git clone [email protected]:myuser/foo.git
Then install it in develop mode:
cd foo
pip install -e .
You can change anything you wan't and every code using foo
package will use modified code.
There 2 benefits ot this solution:
.git
dir, so it's regular Git repository. You can push to your fork right away.As per node js doc
process.cwd()
cwd
is a method of global object process
, returns a string value which is the current working directory of the Node.js process.
As per node js doc
__dirname
The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.
Let me explain with example,
suppose we have a main.js
file resides inside C:/Project/main.js
and running node main.js
both these values return same file
or simply with following folder structure
Project
+-- main.js
+--lib
+-- script.js
main.js
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true
suppose we have another file script.js
files inside a sub directory of project ie C:/Project/lib/script.js
and running node main.js
which require script.js
main.js
require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true
script.js
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false
In ES6, import
s are live read-only views on exported-values. As a result, when you do import a from "somemodule";
, you cannot assign to a
no matter how you declare a
in the module.
However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):
//------ lib.js ------
export let counter = 3;
export function incCounter() {
counter++;
}
//------ main1.js ------
import { counter, incCounter } from './lib';
// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4
// The imported value can’t be changed
counter++; // TypeError
As you can see, the difference really lies in lib.js
, not main1.js
.
To summarize:
import
-ed variables, no matter how you declare the corresponding variables in the module.let
-vs-const
semantics applies to the declared variable in the module.
const
, it cannot be reassigned or rebound in anywhere.let
, it can only be reassigned in the module (but not the user). If it is changed, the import
-ed variable changes accordingly.In python3.7+ there's a brand new defaults= keyword argument.
defaults can be
None
or an iterable of default values. Since fields with a default value must come after any fields without a default, the defaults are applied to the rightmost parameters. For example, if the fieldnames are['x', 'y', 'z']
and the defaults are(1, 2)
, thenx
will be a required argument,y
will default to1
, andz
will default to2
.
Example usage:
$ ./python
Python 3.7.0b1+ (heads/3.7:4d65430, Feb 1 2018, 09:28:35)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import namedtuple
>>> nt = namedtuple('nt', ('a', 'b', 'c'), defaults=(1, 2))
>>> nt(0)
nt(a=0, b=1, c=2)
>>> nt(0, 3)
nt(a=0, b=3, c=2)
>>> nt(0, c=3)
nt(a=0, b=1, c=3)
for a in soup("p",{'id':'pagination'})[0]("a",{'href': True}):
if createunicode(a.text) in ['<','<']:
links.append(a.attrMap['href'])
else:
continue
It works for me.
Create,Alter,Drop of (Databases,Tables,Keys,Index,Views,Functions,Stored Procedures)
Insert ,Delete,Update,Truncate of (Tables)
float_number = 12.234325335563
round(float_number, 2)
This will return;
12.23
round function takes two arguments; Number to be rounded and the number of decimal places to be returned.Here i returned 2 decimal places.
For Windows I found this working:
Set http = CreateObject("Microsoft.XmlHttp")
http.open "GET", "http://www.mywebservice.com/webmethod.asmx?WSDL", FALSE
http.send ""
WScript.Echo http.responseText
Reference: CodeProject
{
isloading? progressIos:Container()
progressIos(int i) {
return Container(
color: i == 1
? AppColors.liteBlack
: i == 2 ? AppColors.darkBlack : i == 3 ? AppColors.pinkBtn : '',
child: Center(child: CupertinoActivityIndicator()));
}
}
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
Looking at the language itself may help; it often helps me (I'm not a native English speaker).
In duck typing
:
1) the word typing
does not mean typing on a keyboard (as was the persistent image in my mind), it means determining "what type of a thing is that thing?"
2) the word duck
expresses how is that determining done; it's kind of a 'loose' determining, as in: "if it walks like a duck ... then it's a duck". It's 'loose' because the thing may be a duck or may not, but whether it actually is a duck doesn't matter; what matters is that I can do with it what I can do with ducks and expect behaviors exhibited by ducks. I can feed it bread crumbs and the thing may go towards me or charge at me or back off ... but it will not devour me like a grizzly would.
1
is a literal. name = value
is an assignment. 1 = value
is an assignment to a literal, which makes no sense. Why would you want 1
to mean something other than 1
?
Though it is perfectly possible to use a recursive regex as MizardX has posted, for this kind of things it is much more useful a parser. Regexes were originally intended to be used with regular languages, being recursive or having balancing groups is just a patch.
The language that defines valid regexes is actually a context free grammar, and you should use an appropriate parser for handling it. Here is an example for a university project for parsing simple regexes (without most constructs). It uses JavaCC. And yes, comments are in Spanish, though method names are pretty self-explanatory.
SKIP :
{
" "
| "\r"
| "\t"
| "\n"
}
TOKEN :
{
< DIGITO: ["0" - "9"] >
| < MAYUSCULA: ["A" - "Z"] >
| < MINUSCULA: ["a" - "z"] >
| < LAMBDA: "LAMBDA" >
| < VACIO: "VACIO" >
}
IRegularExpression Expression() :
{
IRegularExpression r;
}
{
r=Alternation() { return r; }
}
// Matchea disyunciones: ER | ER
IRegularExpression Alternation() :
{
IRegularExpression r1 = null, r2 = null;
}
{
r1=Concatenation() ( "|" r2=Alternation() )?
{
if (r2 == null) {
return r1;
} else {
return createAlternation(r1,r2);
}
}
}
// Matchea concatenaciones: ER.ER
IRegularExpression Concatenation() :
{
IRegularExpression r1 = null, r2 = null;
}
{
r1=Repetition() ( "." r2=Repetition() { r1 = createConcatenation(r1,r2); } )*
{ return r1; }
}
// Matchea repeticiones: ER*
IRegularExpression Repetition() :
{
IRegularExpression r;
}
{
r=Atom() ( "*" { r = createRepetition(r); } )*
{ return r; }
}
// Matchea regex atomicas: (ER), Terminal, Vacio, Lambda
IRegularExpression Atom() :
{
String t;
IRegularExpression r;
}
{
( "(" r=Expression() ")" {return r;})
| t=Terminal() { return createTerminal(t); }
| <LAMBDA> { return createLambda(); }
| <VACIO> { return createEmpty(); }
}
// Matchea un terminal (digito o minuscula) y devuelve su valor
String Terminal() :
{
Token t;
}
{
( t=<DIGITO> | t=<MINUSCULA> ) { return t.image; }
}
If you're looking to re-enable the blink tag for your own browsing, you can install this simple Chrome extension I wrote: https://github.com/etlovett/Blink-Tag-Enabler-Chrome-Extension. It just hides and shows all <blink> tags on every page using setInterval.
This is my experience for this problem maybe it could help you :
I copied all folders and files inside the /data
folder to have a backup from my db
.
When I switched to another Computer's Xampp
and I started copying all folders and files copied before from previous phpmyadmin /data
folder.
So when I was done this problem happened for me .
To solve this issue :
1 - I made a backup from /data
folder of phpmyadmin
by copying only only folders have same name with tables I want to make backup .
2 - Uninstall Xampp.
3 - Reinstall Xampp .
4 - Copy all folders Kept in step 1 inside mysql/data
folder . this folders are only database tables and be careful don't touch another file and folder or replace anything when copying.
The full answer could delve into the internals of the DBMS. It depends on how the query engine (which executes the query plan generated by the SQL optimizer) operates.
However, one possible explanation (applicable to at least some versions of some DBMS - not necessarily to MS SQL Server) is that there is no index on the ID column, so any process trying to work a query with 'WHERE id = ?
' in it ends up doing a sequential scan of the table, and that sequential scan hits the lock which your process applied. You can also run into problems if the DBMS applies page-level locking by default; locking one row locks the entire page and all the rows on that page.
There are some ways you could debunk this as the source of trouble. Look at the query plan; study the indexes; try your SELECT with ID of 1000000 instead of 1 and see whether other processes are still blocked.
Right click on the project, go to Maven -> Update Project... , then check the Force Update of Snapshots/Releases , then click Ok. It's done!
Im using Asp.Net Core 2.2 with MVC and Razor cshtml My JQuery is referenced in a layout page I needed to add the following to my view.cshtml:
@section Scripts {
$script-here
}
I provide a more general and safer way to do this stuff,
".." <- function (x)
{
stopifnot(inherits(x, "character"))
stopifnot(length(x) == 1)
get(x, parent.frame(4))
}
set_colclass <- function(x, class){
stopifnot(all(class %in% c("integer", "numeric", "double","factor","character")))
for(i in intersect(names(class), names(x))){
f <- get(paste0("as.", class[i]))
x[, (..("i")):=..("f")(get(..("i")))]
}
invisible(x)
}
The function ..
makes sure we get a variable out of the scope of data.table; set_colclass will set the classes of your cols.
You can use it like this:
dt <- data.table(i=1:3,f=3:1)
set_colclass(dt, c(i="character"))
class(dt$i)
You also need to change the DataSource
of the connection string. KELVIN-PC
is the name of your local machine and the sql server is running on the default instance.
If you are sure the the server is running as the default instance, you can always use .
in the DataSource, eg.
connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"
otherwise, you need to specify the name of the instance of the server,
connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"
I have same error. Problem was that branch was deleted, released. But in PhpStorm I still could see it in remote branches. I could checkout as local branch. And then doing git pull was giving this error.
So need to check if this brnach really exists remotely.
There is a really nice, easy to use, lightweight (uses native browser events for detection) plugin for both basic JavaScript and for jQuery that was released this year. It performs perfectly:
Try to change the layout_width to android:layout_width="match_parent"
because gravity:"right"
aligns the text inside the layout_width, and if you choose wrap content it does not have where to go, but if you choose match parent it can go to the right.
You could use ES6 Map
const colors = new Map([
['RED', 'red'],
['BLUE', 'blue'],
['GREEN', 'green']
]);
console.log(colors.get('RED'));
Try this code...
li:before {
content: "? "; /* caractère UTF-8 */
}
Here is query to find email
's which are used for more then one login_id
:
SELECT email
FROM table
GROUP BY email
HAVING count(*) > 1
You'll need second (of nested) query to get list of login_id
by email
.
You could also do this is plain in html with a meta tag:
<html>
<head>
<meta http-equiv="refresh" content="0;url=new.aspx" />
</head>
<body>
</body>
</html>
there you go
date('d.m.Y',strtotime("-1 days"));
this will work also if month change
You could use preg_split
instead of explode
and split on [ ]+
(one or more spaces). But I think in this case you could go with preg_match_all
and capturing:
preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];
The pattern matches a space, php
, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php
as part of a user name but really only as a command.
An alternative to capturing is the "keep" feature of PCRE. If you use \K
in the pattern, everything before it is discarded in the match:
preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];
I would use preg_match()
. I do something similar for many of my system management scripts. Here is an example:
$test = "user 12052 0.2 0.1 137184 13056 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user 12054 0.2 0.1 137184 13064 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user 12055 0.6 0.1 137844 14220 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user 12057 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user 12058 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user 12059 0.3 0.1 135112 13000 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root 12068 0.0 0.0 106088 1164 pts/1 S+ 10:00 0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root 12070 0.0 0.0 103240 828 pts/1 R+ 10:00 0:00 grep utilities";
$lines = explode("\n", $test);
foreach($lines as $line){
if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
print_r($matches);
}
}
The above prints:
Array
(
[0] => .php cust1 cron
[1] => cust1
)
Array
(
[0] => .php cust3 cron
[1] => cust3
)
Array
(
[0] => .php cust4 cron
[1] => cust4
)
Array
(
[0] => .php cust89 cron
[1] => cust89
)
Array
(
[0] => .php cust435 cron
[1] => cust435
)
Array
(
[0] => .php cust16 cron
[1] => cust16
)
You can set $test
to equal the output from exec. the values you are looking for would be in the if
statement under the foreach
. $matches[1]
will have the custx value.
example:
c++ -Wall filefork.cpp -lrt -O2
For gcc
version 4.6.1, -lrt
must be after filefork.cpp otherwise you get a link error.
Some older gcc
version doesn't care about the position.
You can use any attribute as selector with [attribute_name=value]
.
$('td[name=tcol1]').hide();
Most people responding don't even seem to know what an array pointer is...
The problem is that you do pointer arithmetics with an array pointer: ptr + 1 will mean "jump 5 bytes ahead since ptr points at a 5 byte array".
Do like this instead:
#include <stdio.h>
int main()
{
char (*ptr)[5];
char arr[5] = {'a','b','c','d','e'};
int i;
ptr = &arr;
for(i=0; i<5; i++)
{
printf("\nvalue: %c", (*ptr)[i]);
}
}
Take the contents of what the array pointer points at and you get an array. So they work just like any pointer in C.
If you want to export all JAR-files of a Java web-project, open the latest generated WAR-file with a ZIP-tool (e.g. 7-Zip), navigate to the /WEB-INF/lib/ folder. Here you will find all JAR-files you need for this project (as listed in "Referenced Libraries").
This is working code:
<html>
<body bgcolor=cyan>
<img src ="backgr1.JPG" id="my" width="310" height="392" style="position: absolute; top:92px; left:375px; visibility:hidden"/>
<script type="text/javascript">
function tend() {
document.getElementById('my').style.visibility='visible';
}
function tn() {
document.getElementById('my').style.visibility='hidden';
}
</script>
<input type="button" onclick="tend()" value="back">
<input type="button" onclick="tn()" value="close">
</body>
</html>
you just need to use:
Map<>.toString().replace("]","\n");
and replaces the ending square bracket of each key=value set with a new line.
It's very annoying. I'm not sure why Google places it there - no one needs these trash from emulator at all; we know what we are doing. I'm using pidcat
and I modified it a bit
BUG_LINE = re.compile(r'.*nativeGetEnabledTags.*')
BUG_LINE2 = re.compile(r'.*glUtilsParamSize.*')
BUG_LINE3 = re.compile(r'.*glSizeof.*')
and
bug_line = BUG_LINE.match(line)
if bug_line is not None:
continue
bug_line2 = BUG_LINE2.match(line)
if bug_line2 is not None:
continue
bug_line3 = BUG_LINE3.match(line)
if bug_line3 is not None:
continue
It's an ugly fix and if you're using the real device you may need those OpenGL errors, but you got the idea.
The easiest way to do that is by binding the array itself as a parameter:
$queryBuilder->andWhere('r.winner IN (:ids)')
->setParameter('ids', $ids);
Probably a duplicate of this post: A customized input text box in html/html5
input {_x000D_
border: 0;_x000D_
outline: 0;_x000D_
background: transparent;_x000D_
border-bottom: 1px solid black;_x000D_
}
_x000D_
<input></input>
_x000D_
If you miss, Microsoft.CSharp.dll this error can occur. Check you project references.
You can try fxCanvas: https://code.google.com/p/fxcanvas/
It implements almost all Canvas API within flash shim.