If Table variable has large data, then instead of table variable(@table) create temp table (#table).table variable doesn't allow to create index after insert.
CREATE TABLE #Table(C1 int,
C2 NVarchar(100) , C3 varchar(100)
UNIQUE CLUSTERED (c1)
);
Create table with unique clustered index
Insert data into Temp "#Table" table
Create non clustered indexes.
CREATE NONCLUSTERED INDEX IX1 ON #Table (C2,C3);
There are a few differences between Temporary Tables (#tmp) and Table Variables (@tmp), although using tempdb isn't one of them, as spelt out in the MSDN link below.
As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables. (This is an overly broad guideline with of course lots of exceptions - see below and following articles.)
Some points to consider when choosing between them:
Temporary Tables are real tables so you can do things like CREATE INDEXes, etc. If you have large amounts of data for which accessing by index will be faster then temporary tables are a good option.
Table variables can have indexes by using PRIMARY KEY or UNIQUE constraints. (If you want a non-unique index just include the primary key column as the last column in the unique constraint. If you don't have a unique column, you can use an identity column.) SQL 2014 has non-unique indexes too.
Table variables don't participate in transactions and SELECT
s are implicitly with NOLOCK
. The transaction behaviour can be very helpful, for instance if you want to ROLLBACK midway through a procedure then table variables populated during that transaction will still be populated!
Temp tables might result in stored procedures being recompiled, perhaps often. Table variables will not.
You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing datatypes over time, since you don't need to define your temp table structure upfront.
You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (eg make a function to split a string into a table of values on some arbitrary delimiter).
Using Table Variables within user-defined functions enables those functions to be used more widely (see CREATE FUNCTION documentation for details). If you're writing a function you should use table variables over temp tables unless there's a compelling need otherwise.
Both table variables and temp tables are stored in tempdb. But table variables (since 2005) default to the collation of the current database versus temp tables which take the default collation of tempdb (ref). This means you should be aware of collation issues if using temp tables and your db collation is different to tempdb's, causing problems if you want to compare data in the temp table with data in your database.
Global Temp Tables (##tmp) are another type of temp table available to all sessions and users.
Some further reading:
Martin Smith's great answer on dba.stackexchange.com
MSDN FAQ on difference between the two: https://support.microsoft.com/en-gb/kb/305977
MDSN blog article: https://docs.microsoft.com/archive/blogs/sqlserverstorageengine/tempdb-table-variable-vs-local-temporary-table
Article: https://searchsqlserver.techtarget.com/tip/Temporary-tables-in-SQL-Server-vs-table-variables
Unexpected behaviors and performance implications of temp tables and temp variables: Paul White on SQLblog.com
Well, I figured out the way and thought to share with the people out there who might run into the same problem.
Let me start with the problem I had been facing,
I had been trying to execute a Dynamic Sql Statement that used two temporary tables I declared at the top of my stored procedure, but because that dynamic sql statment created a new scope, I couldn't use the temporary tables.
Solution:
I simply changed them to Global Temporary Variables and they worked.
Find my stored procedure underneath.
CREATE PROCEDURE RAFCustom_Room_GetRelatedProducts
-- Add the parameters for the stored procedure here
@PRODUCT_SKU nvarchar(15) = Null
AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;
IF OBJECT_ID('tempdb..##RelPro', 'U') IS NOT NULL
BEGIN
DROP TABLE ##RelPro
END
Create Table ##RelPro
(
RowID int identity(1,1),
ID int,
Item_Name nvarchar(max),
SKU nvarchar(max),
Vendor nvarchar(max),
Product_Img_180 nvarchar(max),
rpGroup int,
Assoc_Item_1 nvarchar(max),
Assoc_Item_2 nvarchar(max),
Assoc_Item_3 nvarchar(max),
Assoc_Item_4 nvarchar(max),
Assoc_Item_5 nvarchar(max),
Assoc_Item_6 nvarchar(max),
Assoc_Item_7 nvarchar(max),
Assoc_Item_8 nvarchar(max),
Assoc_Item_9 nvarchar(max),
Assoc_Item_10 nvarchar(max)
);
Begin
Insert ##RelPro(ID, Item_Name, SKU, Vendor, Product_Img_180, rpGroup)
Select distinct zp.ProductID, zp.Name, zp.SKU,
(Select m.Name From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID),
'http://s0001.server.com/is/sw11/DG/' +
(Select m.Custom1 From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID) +
'_' + zp.SKU + '_3?$SC_3243$', ep.RoomID
From Product zp(nolock) Inner Join RF_ExtendedProduct ep(nolock) On ep.ProductID = zp.ProductID
Where zp.ActiveInd = 1 And SUBSTRING(zp.SKU, 1, 2) <> 'GC' AND zp.Name <> 'PLATINUM' AND zp.SKU = (Case When @PRODUCT_SKU Is Not Null Then @PRODUCT_SKU Else zp.SKU End)
End
declare @curr_row int = 0,
@tot_rows int= 0,
@sku nvarchar(15) = null;
IF OBJECT_ID('tempdb..##TSku', 'U') IS NOT NULL
BEGIN
DROP TABLE ##TSku
END
Create Table ##TSku (tid int identity(1,1), relsku nvarchar(15));
Select @curr_row = (Select MIN(RowId) From ##RelPro);
Select @tot_rows = (Select MAX(RowId) From ##RelPro);
while @curr_row <= @tot_rows
Begin
select @sku = SKU from ##RelPro where RowID = @curr_row;
truncate table ##TSku;
Insert ##TSku(relsku)
Select distinct top(10) tzp.SKU From Product tzp(nolock) INNER JOIN
[INTRANET].raf_FocusAssociatedItem assoc(nolock) ON assoc.associatedItemID = tzp.SKU
Where (assoc.isActive=1) And (tzp.ActiveInd = 1) AND (assoc.productID = @sku)
declare @curr_row1 int = (Select Min(tid) From ##TSku),
@tot_rows1 int = (Select Max(tid) From ##TSku);
If(@tot_rows1 <> 0)
Begin
While @curr_row1 <= @tot_rows1
Begin
declare @col_name nvarchar(15) = null,
@sqlstat nvarchar(500) = null;
set @col_name = 'Assoc_Item_' + Convert(nvarchar(2), @curr_row1);
set @sqlstat = 'update ##RelPro set ' + @col_name + ' = (Select relsku From ##TSku Where tid = ' + Convert(nvarchar(2), @curr_row1) + ') Where RowID = ' + Convert(nvarchar(2), @curr_row);
Exec(@sqlstat);
set @curr_row1 = @curr_row1 + 1;
End
End
set @curr_row = @curr_row + 1;
End
Select * From ##RelPro;
END GO
@tableName
Table variables are alive for duration of the script running only i.e. they are only session level objects.
To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName
object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.
There is another type of table object which can be created for temporary use. They are #tableName
objects declared like similar create statement for physical tables:
Create table #test (Id int, Name varchar(50))
This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.
IF OBJECT_ID('tempdb..#test') IS NOT NULL
DROP TABLE #test
Hope this makes sense !
Indeed, you don't need to drop a @local_variable
.
But if you use #local_table
, it can be done, e.g. it's convenient to be able to re-execute a query several times.
SELECT *
INTO #recent_records
FROM dbo.my_table t
WHERE t.CreatedOn > '2021-01-01'
;
SELECT *
FROM #recent_records
;
/*
can DROP here, otherwise will fail with the following error
on re-execution in the same window (I use SSMS DB client):
Msg 2714, Level ..., State ..., Line ...
There is already an object named '#recent_records' in the database.
*/
DROP TABLE #recent_records
;
You can also put your SELECT statement in a TRANSACTION to be able to re-execute without an explicit DROP:
BEGIN TRANSACTION
SELECT *
INTO #recent_records
FROM dbo.my_table t
WHERE t.CreatedOn > '2021-01-01'
;
SELECT *
FROM #recent_records
;
ROLLBACK
You can loop through the table variable or you can cursor through it. This is what we usually call a RBAR - pronounced Reebar and means Row-By-Agonizing-Row.
I would suggest finding a SET-BASED answer to your question (we can help with that) and move away from rbars as much as possible.
Either use an Allias in the table like T and use T.ID, or use just the column name.
declare @TEMP table (ID int, Name varchar(max))
insert into @temp SELECT ID, Name FROM Table
SELECT * FROM @TEMP
WHERE ID = 1
The purpose of SELECT INTO
is (per the docs, my emphasis)
To create a new table from values in another table
But you already have a target table! So what you want is
The
INSERT
statement adds one or more new rows to a tableYou can specify the data values in the following ways:
...
By using a
SELECT
subquery to specify the data values for one or more rows, such as:INSERT INTO MyTable (PriKey, Description) SELECT ForeignKey, Description FROM SomeView
And in this syntax, it's allowed for MyTable
to be a table variable.
writing data in tables declared declare @tb
and after joining with other tables, I realized that the response time compared to temporary tables tempdb .. # tb
is much higher.
When I join them with @tb the time is much longer to return the result, unlike #tm, the return is almost instantaneous.
I did tests with a 10,000 rows join and join with 5 other tables
That's not yet implemented according this Microsoft Connect link: Microsoft Connect
Here you go:
$('td[id^="' + value +'"]')
so if the value is for instance 'foo'
, then the selector will be 'td[id^="foo"]'
.
Note that the quotes are mandatory: [id^="...."]
.
Source: http://api.jquery.com/attribute-starts-with-selector/
You have to use shell=True in subprocess and no shlex.split:
def subprocess_cmd(command):
process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
print proc_stdout
subprocess_cmd('echo a; echo b')
returns:
a
b
I believe that you're looking for numpy.split
or possibly numpy.array_split
if the number of sections doesn't need to divide the size of the array properly.
If you want to do it one line and you do not want to change list1 or list2 you can do it using stream
List<String> list1 = Arrays.asList("London", "Paris");
List<String> list2 = Arrays.asList("Moscow", "Tver");
List<String> list = Stream.concat(list1.stream(),list2.stream()).collect(Collectors.toList());
A straightforward way to do this with no extra tools is to export the registry to a text file before the install, then export it to another file after. Then, compare the two files.
Having said that, the Sysinternals tools are great for this.
Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.
View.VISIBLE The view is visible.
View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"
View.GONE The view is gone, you can't see it and it doesn't take up the "spot".
So to answer your question, you're looking for:
if (myImageView.getVisibility() == View.VISIBLE) {
// Its visible
} else {
// Either gone or invisible
}
on sql 2008 this is valid
DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable
on sql server 2005, you need to do this
DECLARE @myVariable nvarchar(Max)
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable
You can definitely use the section tag as a container. It is there to group content in a more semantically significant way than with a div or as the html5 spec says:
The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading. http://www.w3.org/TR/html5/sections.html#the-section-element
docker build -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .
this worked for me!
if some_queryset.objects.all().exists(): print("this table is not empty")
Here's an efficient Shuffler that returns a byte array of shuffled values. It never shuffles more than is needed. It can be restarted from where it previously left off. My actual implementation (not shown) is a MEF component that allows a user specified replacement shuffler.
public byte[] Shuffle(byte[] array, int start, int count)
{
int n = array.Length - start;
byte[] shuffled = new byte[count];
for(int i = 0; i < count; i++, start++)
{
int k = UniformRandomGenerator.Next(n--) + start;
shuffled[i] = array[k];
array[k] = array[start];
array[start] = shuffled[i];
}
return shuffled;
}
`
You can update with a join if you only affect one table like this:
UPDATE table1
SET table1.name = table2.name
FROM table1, table2
WHERE table1.id = table2.id
AND table2.foobar ='stuff'
But you are trying to affect multiple tables with an update statement that joins on multiple tables. That is not possible.
However, updating two tables in one statement is actually possible but will need to create a View using a UNION that contains both the tables you want to update. You can then update the View which will then update the underlying tables.
But this is a really hacky parlor trick, use the transaction and multiple updates, it's much more intuitive.
If the code is coming from a file, you can get its full name
sys._getframe().f_code.co_filename
You can also retrieve the function name as f_code.co_name
The correct format for passing variables in a GET request is
?variable1=value1&variable2=value2&variable3=value3...
^ ---notice &--- ^
But essentially, you have the right idea.
If by the type of a variable you mean the runtime class of the object that the variable points to, then you can get this through the class reference that all objects have.
val name = "sam";
name: java.lang.String = sam
name.getClass
res0: java.lang.Class[_] = class java.lang.String
If you however mean the type that the variable was declared as, then you cannot get that. Eg, if you say
val name: Object = "sam"
then you will still get a String
back from the above code.
If someone is sniffing your plain-text HTTP traffic (or cache/cookies) for passwords just turning the password into a hash won't help - The hash password can be "replayed" just as well as plain-text. The client would need to hash the password with something somewhat random (like the date and time) See the section on "AUTH CRAM-MD5" here: http://www.fehcom.de/qmail/smtpauth.html
select * into #temptable from tablename where 1<>1
The short answer would be: use friend when it actually improves encapsulation. Improving readability and usability (operators << and >> are the canonical example) is also a good reason.
As for examples of improving encapsulation, classes specifically designed to work with the internals of other classes (test classes come to mind) are good candidates.
Since Java 8:
List<String> myList = map.keySet().stream().collect(Collectors.toList());
I prefer not messing with HTML and use as much as native infrastructure as possible. You can use Output widget with Hbox or VBox:
import ipywidgets as widgets
from IPython import display
import pandas as pd
import numpy as np
# sample data
df1 = pd.DataFrame(np.random.randn(8, 3))
df2 = pd.DataFrame(np.random.randn(8, 3))
# create output widgets
widget1 = widgets.Output()
widget2 = widgets.Output()
# render in output widgets
with widget1:
display.display(df1)
with widget2:
display.display(df2)
# create HBox
hbox = widgets.HBox([widget1, widget2])
# render hbox
hbox
This outputs:
[Scrollview setContentOffset:CGPointMake(x, y) animated:YES];
See the docs for to_dict
. You can use it like this:
df.set_index('id').to_dict()
And if you have only one column, to avoid the column name is also a level in the dict (actually, in this case you use the Series.to_dict()
):
df.set_index('id')['value'].to_dict()
Such a silly solution in my case:
// Example a
#include <iostream>
#include "stdafx.h"
The above was odered as per example a, when I changed it to resemble example b below...
// Example b
#include "stdafx.h"
#include <iostream>
My code compiled like a charm. Try it, guaranteed to work.
Yahoo! This is really possible. I found it.
For Bottom Border:
div {box-shadow: 0px -3px 0px red inset; }
For Top Border:
div {box-shadow: 0px 3px 0px red inset; }
Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (source).
This can also be achieved with itertools.chain.from_iterable which will flatten the consecutive iterables:
import itertools
for item in itertools.chain.from_iterable(iterables):
# do something with item
Most modern browser support console.dir(obj)
, which will return all the properties of an object that it inherited through its constructor. See Mozilla's documentation for more info and current browser support.
console.dir(Math)
=> MathConstructor
E: 2.718281828459045
LN2: 0.6931471805599453
...
tan: function tan() { [native code] }
__proto__: Object
If you write: if(x === true)
, It will be true for only x = true
If you write: if(x)
, it will be true for any x that is not: '' (empty string), false, null, undefined, 0, NaN.
Install it using NuGet:
Install-Package Newtonsoft.Json
Posting this as an answer.
The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.
The expensive regex method and the css attribute selector with starts with ^ operator
Option Explicit
Public Sub test()
Debug.Print StartWithSubString("ab", "abc,d")
End Sub
Regex:
Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
'required reference Microsoft VBScript Regular Expressions
Dim re As VBScript_RegExp_55.RegExp
Set re = New VBScript_RegExp_55.RegExp
re.Pattern = "^" & substring
StartWithSubString = re.test(testString)
End Function
Css attribute selector with starts with operator
Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
'required reference Microsoft HTML Object Library
Dim html As MSHTML.HTMLDocument
Set html = New MSHTML.HTMLDocument
html.body.innerHTML = "<div test=""" & testString & """></div>"
StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0
End Function
Here is how to get the value of a hidden column in a GridView
that is set to Visible=False
: add the data field in this case SpecialInstructions
to the DataKeyNames property of the bound GridView , and access it this way.
txtSpcInst.Text = GridView2.DataKeys(GridView2.SelectedIndex).Values("SpecialInstructions")
That's it, it works every time very simple.
It says:
When you save and exit the editor, it will rewind you back to that last commit in that list and drop you on the command line with the following message:
$ git rebase -i HEAD~3
Stopped at 7482e0d... updated the gemspec to hopefully work better
You can amend the commit now, with
It does not mean:
type again
git rebase -i HEAD~3
Try to not typing git rebase -i HEAD~3
when exiting the editor, and it should work fine.
(otherwise, in your particular situation, a git rebase -i --abort
might be needed to reset everything and allow you to try again)
As Dave Vogt mentions in the comments, git rebase --continue
is for going to the next task in the rebasing process, after you've amended the first commit.
Also, Gregg Lind mentions in his answer the reword
command of git rebase
:
By replacing the command "pick" with the command "edit", you can tell
git rebase
to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing.If you just want to edit the commit message for a commit, replace the command "
pick
" with the command "reword
", since Git1.6.6 (January 2010).It does the same thing ‘
edit
’ does during an interactive rebase, except it only lets you edit the commit message without returning control to the shell. This is extremely useful.
Currently if you want to clean up your commit messages you have to:
$ git rebase -i next
Then set all the commits to ‘edit’. Then on each one:
# Change the message in your editor.
$ git commit --amend
$ git rebase --continue
Using ‘
reword
’ instead of ‘edit
’ lets you skip thegit-commit
andgit-rebase
calls.
You can use the following:
type
keyword, aliasing a function literal)Here is an example of how to use them:
type myCallbackType = (arg1: string, arg2: boolean) => number;
interface myCallbackInterface { (arg1: string, arg2: boolean): number };
class CallbackTest
{
// ...
public myCallback2: myCallbackType;
public myCallback3: myCallbackInterface;
public myCallback1: (arg1: string, arg2: boolean) => number;
// ...
}
One other option is to use a plyr function:
df <- ldply(listOfDataFrames, data.frame)
This is a little slower than the original:
> system.time({ df <- do.call("rbind", listOfDataFrames) })
user system elapsed
0.25 0.00 0.25
> system.time({ df2 <- ldply(listOfDataFrames, data.frame) })
user system elapsed
0.30 0.00 0.29
> identical(df, df2)
[1] TRUE
My guess is that using do.call("rbind", ...)
is going to be the fastest approach that you will find unless you can do something like (a) use a matrices instead of a data.frames and (b) preallocate the final matrix and assign to it rather than growing it.
Edit 1:
Based on Hadley's comment, here's the latest version of rbind.fill
from CRAN:
> system.time({ df3 <- rbind.fill(listOfDataFrames) })
user system elapsed
0.24 0.00 0.23
> identical(df, df3)
[1] TRUE
This is easier than rbind, and marginally faster (these timings hold up over multiple runs). And as far as I understand it, the version of plyr
on github is even faster than this.
What also seems to work fine is creating a file application-dev.properties
that contains:
security.basic.enabled=false
management.security.enabled=false
If you then start your Spring Boot app with the dev
profile, you don't need to log on.
The pythonic way of doing this is using subprocess.Popen
subprocess.Popen
takes a list where the first element is the command to be run followed by any command line arguments.
As an example:
import subprocess
args = ['echo', 'Hello!']
subprocess.Popen(args) // same as running `echo Hello!` on cmd line
args2 = ['echo', '-v', '"Hello Again"']
subprocess.Popen(args2) // same as running 'echo -v "Hello Again!"` on cmd line
If this is a windows app, you can just use the application executable path: new System.IO.FileInfo(Application.ExecutablePath).LastWriteTime.ToString("yyyy.MM.dd")
In some cases, nvl(sum(column_name),0) is also required. You may want to consider your scenarios.
For example, I am trying to fetch the sum of a particular column, from a particular table based on certain conditions. Based on the conditions,
If you use sum(nvl(column_name,0)) here, it would give you null. What you might want is nvl(sum(column_name),0).
This may be required especially when you are passing this result to, say, java, have the datatype as number there because then this will not require special null handling.
how to determine if a commit with particular hash have been pushed to the origin already?
# list remote branches that contain $commit
git branch -r --contains $commit
I don't think that is possible in an email, nor should it be. There would be major security ramifications.
Swift 5 Use button.setTitle()
@IBOutlet weak var button: UIButton!
setTitle
on the button followed by the text and the state.button.setTitle("Button text here", forState: .normal)
Use fabs() instead of abs(), it's the same but for floats instead of integers.
I had the same problem, just forgot to activate my virtual environment. For anyone out there who also had a mental blank.
Combining a couple of the previous answers, you could try start /b cmd /c foo.exe
.
For a trivial example, if you wanted to print out the versions of java/groovy/grails/gradle, you could do this in a batch file:
@start /b cmd /c java -version
@start /b cmd /c gradle -version
@start /b cmd /c groovy -version
@start /b cmd /c grails -version
If you have something like Process Explorer (Sysinternals), you will see a few child cmd.exe processes each with a java process (as per the above commands). The output will print to the screen in whatever order they finish.
start /b : Start application without creating a new window. The
application has ^C handling ignored. Unless the application
enables ^C processing, ^Break is the only way to interrupt
the application
cmd /c : Carries out the command specified by string and then terminates
Here is an option if you are using pandas
:
import pandas as pd
d = dict.fromkeys(['a', 'b', 'c', 'd'])
d['b'] = 'not null'
d['c'] = '' # empty string
print(d)
# convert `dict` to `Series` and replace any blank strings with `None`;
# use the `.dropna()` method and
# then convert back to a `dict`
d_ = pd.Series(d).replace('', None).dropna().to_dict()
print(d_)
This worked for me. Stolen from here: How do you get the name of the first page of an excel workbook?
object opt = System.Reflection.Missing.Value;
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook workbook = app.Workbooks.Open(WorkBookToOpen,
opt, opt, opt, opt, opt, opt, opt,
opt, opt, opt, opt, opt, opt, opt);
Excel.Worksheet worksheet = workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
string firstSheetName = worksheet.Name;
I have a very simple solution to just print json from csv on console using csvtojson module.
// require csvtojson
var csv = require("csvtojson");
const csvFilePath='customer-data.csv' //file path of csv
csv()
.fromFile(csvFilePath)``
.then((jsonObj)=>{
console.log(jsonObj);
})
you can go to project properties --> configuration properties --> General -->Project default and there change the "Character set" from "Unicode" to "Not set".
Use this it should help.
var currentUrl = "google.com"
var partOfUrl = currentUrl.substring(0, currentUrl.length-2)
webView.setWebViewClient(object: WebViewClient() {
override fun onLoadResource(WebView view, String url) {
//call loadUrl() method here
// also check if url contains partOfUrl, if not load it differently.
if(url.contains(partOfUrl, true)) {
//it should work if you reach inside this if scope.
} else if(!(currentUrl.startWith("w", true))) {
webView.loadurl("www.$currentUrl")
} else if(!(currentUrl.startWith("h", true))) {
webView.loadurl("https://$currentUrl")
} else {
//...
}
}
override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
// you can call again loadUrl from here too if there is any error.
}
// You should also override other override method for error such as
// onReceiveError to see how all these methods are called one after another and how
// they behave while debugging with break point.
}
For a search routine you should look to use Find
, AutoFilter
or variant array approaches. Range loops are nomally too slow, worse again if they use Select
The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2
which you can then further process
Option Explicit
Const strText As String = "%"
Sub ColSearch_DelRows()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim cel1 As Range
Dim cel2 As Range
Dim strFirstAddress As String
Dim lAppCalc As Long
'Get working range from user
On Error Resume Next
Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
With Application
lAppCalc = .Calculation
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)
'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
If Not cel1 Is Nothing Then
Set rng2 = cel1
strFirstAddress = cel1.Address
Do
Set cel1 = rng1.FindNext(cel1)
Set rng2 = Union(rng2, cel1)
Loop While strFirstAddress <> cel1.Address
End If
If Not rng2 Is Nothing Then
For Each cel2 In rng2
Debug.Print cel2.Address & " contained " & strText
Next
Else
MsgBox "No " & strText
End If
With Application
.ScreenUpdating = True
.Calculation = lAppCalc
End With
End Sub
Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.
It may be a little late but for this you can do:
HTML
<!-- html -->
<div class="images-wrapper">
<img src="images/1" alt="image 1" />
<img src="images/2" alt="image 2" />
<img src="images/3" alt="image 3" />
<img src="images/4" alt="image 4" />
</div>
SASS
// In _extra.scss
$maxImagesNumber: 5;
.images-wrapper {
img {
position: absolute;
padding: 5px;
border: solid black 1px;
}
@for $i from $maxImagesNumber through 1 {
:nth-child(#{ $i }) {
z-index: #{ $maxImagesNumber - ($i - 1) };
left: #{ ($i - 1) * 30 }px;
}
}
}
Try this code.
<body class="container">
<div class="col-lg-1 col-lg-offset-10">
<img data-src="holder.js/100x100" alt="" />
</div>
</body>
Here I have used col-lg-1, and the offset should be 10 for properly centered the div on large devices. If you need it to center on medium-to-large devices then just change the lg to md and so on.
Some additions to a given set of answers:
First of all if you going to use Redis hash efficiently you must know a keys count max number and values max size - otherwise if they break out hash-max-ziplist-value or hash-max-ziplist-entries Redis will convert it to practically usual key/value pairs under a hood. ( see hash-max-ziplist-value, hash-max-ziplist-entries ) And breaking under a hood from a hash options IS REALLY BAD, because each usual key/value pair inside Redis use +90 bytes per pair.
It means that if you start with option two and accidentally break out of max-hash-ziplist-value you will get +90 bytes per EACH ATTRIBUTE you have inside user model! ( actually not the +90 but +70 see console output below )
# you need me-redis and awesome-print gems to run exact code
redis = Redis.include(MeRedis).configure( hash_max_ziplist_value: 64, hash_max_ziplist_entries: 512 ).new
=> #<Redis client v4.0.1 for redis://127.0.0.1:6379/0>
> redis.flushdb
=> "OK"
> ap redis.info(:memory)
{
"used_memory" => "529512",
**"used_memory_human" => "517.10K"**,
....
}
=> nil
# me_set( 't:i' ... ) same as hset( 't:i/512', i % 512 ... )
# txt is some english fictionary book around 56K length,
# so we just take some random 63-symbols string from it
> redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), 63] ) } }; :done
=> :done
> ap redis.info(:memory)
{
"used_memory" => "1251944",
**"used_memory_human" => "1.19M"**, # ~ 72b per key/value
.....
}
> redis.flushdb
=> "OK"
# setting **only one value** +1 byte per hash of 512 values equal to set them all +1 byte
> redis.pipelined{ 10000.times{ |i| redis.me_set( "t:#{i}", txt[rand(50000), i % 512 == 0 ? 65 : 63] ) } }; :done
> ap redis.info(:memory)
{
"used_memory" => "1876064",
"used_memory_human" => "1.79M", # ~ 134 bytes per pair
....
}
redis.pipelined{ 10000.times{ |i| redis.set( "t:#{i}", txt[rand(50000), 65] ) } };
ap redis.info(:memory)
{
"used_memory" => "2262312",
"used_memory_human" => "2.16M", #~155 byte per pair i.e. +90 bytes
....
}
For TheHippo answer, comments on Option one are misleading:
hgetall/hmset/hmget to the rescue if you need all fields or multiple get/set operation.
For BMiner answer.
Third option is actually really fun, for dataset with max(id) < has-max-ziplist-value this solution has O(N) complexity, because, surprise, Reddis store small hashes as array-like container of length/key/value objects!
But many times hashes contain just a few fields. When hashes are small we can instead just encode them in an O(N) data structure, like a linear array with length-prefixed key value pairs. Since we do this only when N is small, the amortized time for HGET and HSET commands is still O(1): the hash will be converted into a real hash table as soon as the number of elements it contains will grow too much
But you should not worry, you'll break hash-max-ziplist-entries very fast and there you go you are now actually at solution number 1.
Second option will most likely go to the fourth solution under a hood because as question states:
Keep in mind that if I use a hash, the value length isn't predictable. They're not all short such as the bio example above.
And as you already said: the fourth solution is the most expensive +70 byte per each attribute for sure.
My suggestion how to optimize such dataset:
You've got two options:
If you cannot guarantee max size of some user attributes than you go for first solution and if memory matter is crucial than compress user json before store in redis.
If you can force max size of all attributes. Than you can set hash-max-ziplist-entries/value and use hashes either as one hash per user representation OR as hash memory optimization from this topic of a Redis guide: https://redis.io/topics/memory-optimization and store user as json string. Either way you may also compress long user attributes.
This answer is unrelated, but if you wanted to get rid of warning and get following warning from requests:
InsecurePlatformWarning
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
You can disable it by adding the following line to your python code:
requests.packages.urllib3.disable_warnings()
I think this is a simple way for beginners:
using System;
using System.Numerics;
public class PrimeChecker
{
public static void Main()
{
// Input
Console.WriteLine("Enter number to check is it prime: ");
BigInteger n = BigInteger.Parse(Console.ReadLine());
bool prime = false;
// Logic
if ( n==0 || n==1)
{
Console.WriteLine(prime);
}
else if ( n==2 )
{
prime = true;
Console.WriteLine(prime);
}
else if (n>2)
{
IsPrime(n, prime);
}
}
// Method
public static void IsPrime(BigInteger n, bool prime)
{
bool local = false;
for (int i=2; i<=(BigInteger)Math.Sqrt((double)n); i++)
{
if (n % i == 0)
{
local = true;
break;
}
}
if (local)
{
Console.WriteLine(prime);
}
else
{
prime = true;
Console.WriteLine(prime);
}
}
}
This is a topic I'm very interested in. There are many purists who say that you shouldn't test technologies such as EF and NHibernate. They are right, they're already very stringently tested and as a previous answer stated it's often pointless to spend vast amounts of time testing what you don't own.
However, you do own the database underneath! This is where this approach in my opinion breaks down, you don't need to test that EF/NH are doing their jobs correctly. You need to test that your mappings/implementations are working with your database. In my opinion this is one of the most important parts of a system you can test.
Strictly speaking however we're moving out of the domain of unit testing and into integration testing but the principles remain the same.
The first thing you need to do is to be able to mock your DAL so your BLL can be tested independently of EF and SQL. These are your unit tests. Next you need to design your Integration Tests to prove your DAL, in my opinion these are every bit as important.
There are a couple of things to consider:
There are two main approaches to setting up your database, the first is to run a UnitTest create DB script. This ensures that your unit test database will always be in the same state at the beginning of each test (you may either reset this or run each test in a transaction to ensure this).
Your other option is what I do, run specific setups for each individual test. I believe this is the best approach for two main reasons:
Unfortunately your compromise here is speed. It takes time to run all these tests, to run all these setup/tear down scripts.
One final point, it can be very hard work to write such a large amount of SQL to test your ORM. This is where I take a very nasty approach (the purists here will disagree with me). I use my ORM to create my test! Rather than having a separate script for every DAL test in my system I have a test setup phase which creates the objects, attaches them to the context and saves them. I then run my test.
This is far from the ideal solution however in practice I find it's a LOT easier to manage (especially when you have several thousand tests), otherwise you're creating massive numbers of scripts. Practicality over purity.
I will no doubt look back at this answer in a few years (months/days) and disagree with myself as my approaches have changed - however this is my current approach.
To try and sum up everything I've said above this is my typical DB integration test:
[Test]
public void LoadUser()
{
this.RunTest(session => // the NH/EF session to attach the objects to
{
var user = new UserAccount("Mr", "Joe", "Bloggs");
session.Save(user);
return user.UserID;
}, id => // the ID of the entity we need to load
{
var user = LoadMyUser(id); // load the entity
Assert.AreEqual("Mr", user.Title); // test your properties
Assert.AreEqual("Joe", user.Firstname);
Assert.AreEqual("Bloggs", user.Lastname);
}
}
The key thing to notice here is that the sessions of the two loops are completely independent. In your implementation of RunTest you must ensure that the context is committed and destroyed and your data can only come from your database for the second part.
Edit 13/10/2014
I did say that I'd probably revise this model over the upcoming months. While I largely stand by the approach I advocated above I've updated my testing mechanism slightly. I now tend to create the entities in in the TestSetup and TestTearDown.
[SetUp]
public void Setup()
{
this.SetupTest(session => // the NH/EF session to attach the objects to
{
var user = new UserAccount("Mr", "Joe", "Bloggs");
session.Save(user);
this.UserID = user.UserID;
});
}
[TearDown]
public void TearDown()
{
this.TearDownDatabase();
}
Then test each property individually
[Test]
public void TestTitle()
{
var user = LoadMyUser(this.UserID); // load the entity
Assert.AreEqual("Mr", user.Title);
}
[Test]
public void TestFirstname()
{
var user = LoadMyUser(this.UserID);
Assert.AreEqual("Joe", user.Firstname);
}
[Test]
public void TestLastname()
{
var user = LoadMyUser(this.UserID);
Assert.AreEqual("Bloggs", user.Lastname);
}
There are several reasons for this approach:
I feel this makes the test class simpler and the tests more granular (single asserts are good)
Edit 5/3/2015
Another revision on this approach. While class level setups are very helpful for tests such as loading properties they are less useful where the different setups are required. In this case setting up a new class for each case is overkill.
To help with this I now tend to have two base classes SetupPerTest
and SingleSetup
. These two classes expose the framework as required.
In the SingleSetup
we have a very similar mechanism as described in my first edit. An example would be
public TestProperties : SingleSetup
{
public int UserID {get;set;}
public override DoSetup(ISession session)
{
var user = new User("Joe", "Bloggs");
session.Save(user);
this.UserID = user.UserID;
}
[Test]
public void TestLastname()
{
var user = LoadMyUser(this.UserID); // load the entity
Assert.AreEqual("Bloggs", user.Lastname);
}
[Test]
public void TestFirstname()
{
var user = LoadMyUser(this.UserID);
Assert.AreEqual("Joe", user.Firstname);
}
}
However references which ensure that only the correct entites are loaded may use a SetupPerTest approach
public TestProperties : SetupPerTest
{
[Test]
public void EnsureCorrectReferenceIsLoaded()
{
int friendID = 0;
this.RunTest(session =>
{
var user = CreateUserWithFriend();
session.Save(user);
friendID = user.Friends.Single().FriendID;
} () =>
{
var user = GetUser();
Assert.AreEqual(friendID, user.Friends.Single().FriendID);
});
}
[Test]
public void EnsureOnlyCorrectFriendsAreLoaded()
{
int userID = 0;
this.RunTest(session =>
{
var user = CreateUserWithFriends(2);
var user2 = CreateUserWithFriends(5);
session.Save(user);
session.Save(user2);
userID = user.UserID;
} () =>
{
var user = GetUser(userID);
Assert.AreEqual(2, user.Friends.Count());
});
}
}
In summary both approaches work depending on what you are trying to test.
I had the same issue when my server free disk space available was 0
You can use the command (there must be ample space for the mysql files)
REPAIR TABLE `<table name>`;
for repairing individual tables
The two other answers given are for mkdir(1)
and not mkdir(2)
like you ask for, but you can look at the source code for that program and see how it implements the -p
options which calls mkdir(2)
repeatedly as needed.
to get the text from a
<option value="1" data-sigla="AC">Acre</option>
uf = $("#selectestado option:selected").attr('data-sigla');
Even simpler:
$get = @mysql_query("SELECT money FROM players WHERE username = '" . $_SESSION['username'] . "'");
note the quotes around username in the $_SESSION reference.
They can be considered as equivalent. The limits in size are the same:
There is also the DBCLOBs, for double byte characters.
References:
To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.
If you have image in the form of bitmap then use
imageview.setImageBitmap(bm);
If you have image in the form of drawable then use
imageview.setImageDrawable(drawable);
If you have image in your resource example if image is present in drawable folder then use
imageview.setImageResource(R.drawable.image);
If you have path of image then use
imageview.setImageURI(Uri.parse("pathofimage"));
You can directly export the query result with export option in the result grig. This export has various options to export. I think this will work.
You'd obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.
There are a couple of ways to address your problem, however this is probably the most straightforward:
Your main
method is static, so it does not have access to instance members (isLeapYear
field and isLeapYear
method. One approach to rectify this is to make both the field and the method static as well:
static boolean isLeapYear;
/* (snip) */
public static boolean isLeapYear(int year)
{
/* (snip) */
}
Lastly, you're not actually calling your isLeapYear
method (which is why you're not seeing any results). Add this line after int year = kboard.nextInt();
:
isLeapYear(year);
That should be a start. There are some other best practices you could follow but for now just focus on getting your code to work; you can refactor later.
Or, KISS.
DIRS=build build/bins
...
$(shell mkdir -p $(DIRS))
This will create all the directories after the Makefile is parsed.
Search and destroy (or move cautiously) any my.ini files (windows or program files), which is affecting the mysql service failure. also check port 3306 is used by using either netstat or portqry tool. this should help. Also if there is a file system issue you can run check disk.
I had the same problem and I solved it using the lib
option in tsconfig.json
. As said by basarat in his answer, a .d.ts
file is implicitly included by TypeScript depending on the compile target
option but this behaviour can be changed with the lib
option.
You can specify additional definition files to be included without changing the targeted JS version. For examples this is part of my current compilerOptions
for [email protected] and it adds support for es2015
features without installing anything else:
"compilerOptions": {
"experimentalDecorators": true,
"lib": ["es5", "dom", "es6", "dom.iterable", "scripthost"],
"module": "commonjs",
"moduleResolution": "node",
"noLib": false,
"target": "es5",
"types": ["node"]
}
For the complete list of available options check the official doc.
Note also that I added "types": ["node"]
and installed npm install @types/node
to support require('some-module')
in my code.
~/Library/Developer/Xcode/DerivedData
is now the default.
You can set the prefs in Xcode to allow projects to specify their build directories.
In my case it was that the C: drive was out of space. Ensure that you have enough space available.
VAR=$VAR"$VARTOADD(STRING)"
echo $VAR
Swift 5.0, 4.0, 3.0 Updated Solution
Insert at Bottom
self.yourArray.append(msg)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: self.yourArray.count-1, section: 0)], with: .automatic)
self.tblView.endUpdates()
Insert at Top of TableView
self.yourArray.insert(msg, at: 0)
self.tblView.beginUpdates()
self.tblView.insertRows(at: [IndexPath.init(row: 0, section: 0)], with: .automatic)
self.tblView.endUpdates()
SJLJ (setjmp/longjmp): – available for 32 bit and 64 bit – not “zero-cost”: even if an exception isn’t thrown, it incurs a minor performance penalty (~15% in exception heavy code) – allows exceptions to traverse through e.g. windows callbacks
DWARF (DW2, dwarf-2) – available for 32 bit only – no permanent runtime overhead – needs whole call stack to be dwarf-enabled, which means exceptions cannot be thrown over e.g. Windows system DLLs.
SEH (zero overhead exception) – will be available for 64-bit GCC 4.8.
source: https://wiki.qt.io/MinGW-64-bit
You just have to include following script.
<script language="javascript" type="text/javascript">
var xmlHttp
function showState(str)
{
//if you want any text box value you can get it like below line.
//just make sure you have specified its "id" attribute
var name=document.getElementById("id_attr").value;
if (typeof XMLHttpRequest != "undefined")
{
xmlHttp= new XMLHttpRequest();
}
var url="forwardPage.jsp";
url +="?count1=" +str+"&count2="+name";
xmlHttp.onreadystatechange = stateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function stateChange()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("div_id").innerHTML=xmlHttp.responseText
}
}
</script>
So if you got the code, let me tell you, div_id will be id of div tag where you have to show your result. By using this code, you are passing parameters to another page. Whatever the processing is done there will be reflected in div tag whose id is "div_id". You can call showState(this.value) on "onChange" event of any control or "onClick" event of button not submit. Further queries will be appreciated.
The .Elements operation returns a LIST of XElements - but what you really want is a SINGLE element. Add this:
XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node")
where xml2.Element("ID").Value == variable
select xml2).FirstOrDefault();
This way, you tell LINQ to give you the first (or NULL, if none are there) from that LIST of XElements you're selecting.
Marc
Using SQL Management Studio Express:
In the Object Explorer tree drill down under Management to "Activity Monitor" (if you cannot find it there then right click on the database server and select "Activity Monitor"). Opening the Activity Monitor, you can view all process info. You should be able to find the locks for the database you're interested in and kill those locks, which will also kill the connection.
You should be able to rename after that.
You can use the index of the array element to remove it from the array, the next time you use the $list
variable, you will see that the array is changed.
Try something like this
foreach($list as $itemIndex => &$item) {
if($item['status'] === false) {
unset($list[$itemIndex]);
}
}
This matches everything up to ".txt" (without including it):
^.*(?=(\.txt))
Check that you have both ngModel and name
attributes in your select. Also Select is a form component and not the entire form so more logical declaration of local reference will be:-
<div class="form-group">
<label for="actionType">Action Type</label>
<select
ngControl="actionType"
===> #actionType="ngModel"
ngModel // You can go with 1 or 2 way binding as well
name="actionType"
id="actionType"
class="form-control"
required>
<option value=""></option>
<option *ngFor="let actionType of actionTypes" value="{{ actionType.label }}">
{{ actionType.label }}
</option>
</select>
</div>
One more Important thing is make sure you import either FormsModule
in the case of template driven approach or ReactiveFormsModule
in the case of Reactive approach. Or you can import both which is also totally fine.
Try this, it worked for me.
mongod --storageEngine=mmpav1
In my case, I don't have control over server setting, but I know it's expecting "application/json" for "Content-Type". I did this on the iOS client side:
manager.requestSerializer = [AFJSONRequestSerializer serializer];
There are a number of ways to handle this.
My favorite way is to install http://pamsshagentauth.sourceforge.net/ on the remote systems and also your own public key. (Figure out a way to get these installed on the VM, somehow you got an entire Unix system installed, what's a couple more files?)
With your ssh agent forwarded, you can now log in to every system without a password.
And even better, that pam module will authenticate for sudo with your ssh key pair so you can run with root (or any other user's) rights as needed.
You don't need to worry about the host key interaction. If the input is not a terminal then ssh will just limit your ability to forward agents and authenticate with passwords.
You should also look into packages like Capistrano. Definitely look around that site; it has an introduction to remote scripting.
Individual script lines might look something like this:
ssh remote-system-name command arguments ... # so, for exmaple,
ssh target.mycorp.net sudo puppet apply
Yes, you can add padding by adding padding.
android:padding=5dp
for i in range(10,0,-1):
print i,
The range() function will include the first value and exclude the second.
An easy way to achieve this would be:
1.Make a custom background resource (like a rectangle shape) with rounded corners.
2.set this custom background using the command -
cardView = view.findViewById(R.id.card_view2);
cardView.setBackgroundResource(R.drawable.card_view_bg);
this worked for me.
The XML
layout I made with top left and bottom right radius.
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white" />
<corners android:topLeftRadius="18dp" android:bottomRightRadius="18dp" />
</shape>
In your case, you need to change only topLeftRadius as well as topRightRadius.
If you have a layout that overlaps with the corners of the card view and has a different color maybe, then you might need a different background resource file for the layout and in the xml set this background resource to your layout.
I tried and tested the above method. Hope this helps you.
Simplest command to get the last 10 users logged in to the machine is last|head
. To get all the users, simply use last
command
While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE
Let check the parameter value.
If in Case it is :
SQL> show parameter resource_limit
NAME TYPE VALUE
------------------------------------ ----------- ---------
resource_limit boolean FALSE
Its mean resource limit is off,we ist have to enable it.
Use the ALTER SYSTEM statement to turn on resource limits.
SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.
The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..
<asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
AutoPostBack="True" AppendDataBoundItems="true">
<asp:DropDownList ID="DropDownList2" runat="server"
onselectedindexchanged="DropDownList2_SelectedIndexChanged">
</asp:DropDownList>
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList2
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
//Load DropDownList3
}
Here's the intended way to convert a String to a Date:
String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);
Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.
I try to solve here is my code.
first add dependency in build.gradle(app).
dependencies {
compile 'com.android.support:design:23.1.1'
}
Create PagerAdapter.class
public class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
Log.i("PosTabItem",""+position);
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
Log.i("PosTab",""+position);
return mFragmentTitleList.get(position);
}
}
create activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@id/tab_layout" />
</RelativeLayout>
create MainActivity.class
public class MainActivity extends AppCompatActivity {
Pager pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
pager = new Pager(getSupportFragmentManager());
pager.addFragment(new FragmentOne(), "One");
viewPager.setAdapter(pager);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setSmoothScrollingEnabled(true);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
and finally create fragment to add in viewpager
crate fragment_one.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="Location"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Create FragmentOne.class
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container,false);
return view;
}
}
if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...
You have to edit the PHP configuration file. Find the line
error_reporting = E_ALL
and replace it with:
error_reporting = E_ALL ^ E_DEPRECATED
If you don't have access to the configuration file you can add this line to the PHP WordPress file (maybe headers.php):
error_reporting(E_ALL ^ E_DEPRECATED);
Are you using position: relative
?
Try to set position: relative
and then z-index because you want this div has a z-index in relation with other div.
By the way, your browser is important to check if it working or not. Neither IE or Firefox is a good one.
From the Microsoft documentation: Command prompt (Cmd. exe) command-line string limitation
On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters.
I have read all answers above. That is all correct but i found a more easy solution as below:
Saving String List in shared-preference>>
public static void setSharedPreferenceStringList(Context pContext, String pKey, List<String> pData) {
SharedPreferences.Editor editor = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit();
editor.putInt(pKey + "size", pData.size());
editor.commit();
for (int i = 0; i < pData.size(); i++) {
SharedPreferences.Editor editor1 = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).edit();
editor1.putString(pKey + i, (pData.get(i)));
editor1.commit();
}
}
and for getting String List from Shared-preference>>
public static List<String> getSharedPreferenceStringList(Context pContext, String pKey) {
int size = pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getInt(pKey + "size", 0);
List<String> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(pContext.getSharedPreferences(Constants.APP_PREFS, Activity.MODE_PRIVATE).getString(pKey + i, ""));
}
return list;
}
Here Constants.APP_PREFS
is the name of the file to open; can not contain path separators.
If you are using Python 2, the following will be the solution:
import io
for line in io.open("u.item", encoding="ISO-8859-1"):
# Do something
Because the encoding
parameter doesn't work with open()
, you will be getting the following error:
TypeError: 'encoding' is an invalid keyword argument for this function
Well the syntax is almost the same but they rely on different frameworks so the only way to convert is by getting someone who knows both languages and convert the code :) the answer to your question is no there is no "effective" tool to convert c# to java
Compiling the last answers into one:
If you're on Windows, use chocolatey:
choco install ffmpeg
If you are on Mac, use Brew:
brew install ffmpeg
If you are on a Debian Linux distribution, use apt:
sudo apt-get install ffmpeg
And make sure Youtube-dl is updated:
youtube-dl -U
You can try this:
$('#modal').on('hidden.bs.modal', function() {
$(this).removeData('bs.modal');
});
Use the css property overflow . For example:
.item{
width : 100px;
overflow:hidden;
}
The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.
I hope this helps.
Here is step-by-step instruction for Tomcat configuration in IntellijIdea:
1) Create IntellijIdea project via WebApplication template. Idea should be Ultimate version, not Community edition
2) Go to Run-Edit configutaion and set up Tomcat location folder, so Idea will know about your tomcat server
3) Go to Deployment tab and select Artifact. Apply
4) In src folder put your servlet (you can try my example for testing purpose)
5) Go to web.xml file and link your's servlet like this
6) In web folder put your's .jsp files (for example hey.jsp)
7) Now you can start you app via IntellijIdea. Run(Shift+F10) and enjoy your app in browser:
- to jsp files: http://localhost:8080/hey.jsp (or index.jsp by default)
- to servlets via virtual link you set in web.xml : http://localhost:8080/st
This is not intended to be "the good answer", as this question ask explicitly for ObjectiveC. As Apple introduced Swift at the WWDC14, I'd like to share the different ways to use block (or closures) in Swift.
You have many ways offered to pass a block equivalent to function in Swift.
I found three.
To understand this I suggest you to test in playground this little piece of code.
func test(function:String -> String) -> String
{
return function("test")
}
func funcStyle(s:String) -> String
{
return "FUNC__" + s + "__FUNC"
}
let resultFunc = test(funcStyle)
let blockStyle:(String) -> String = {s in return "BLOCK__" + s + "__BLOCK"}
let resultBlock = test(blockStyle)
let resultAnon = test({(s:String) -> String in return "ANON_" + s + "__ANON" })
println(resultFunc)
println(resultBlock)
println(resultAnon)
As Swift is optimized for asynchronous development, Apple worked more on closures. The first is that function signature can be inferred so you don't have to rewrite it.
let resultShortAnon = test({return "ANON_" + $0 + "__ANON" })
let resultShortAnon2 = test({myParam in return "ANON_" + myParam + "__ANON" })
This special case works only if the block is the last argument, it's called trailing closure
Here is an example (merged with inferred signature to show Swift power)
let resultTrailingClosure = test { return "TRAILCLOS_" + $0 + "__TRAILCLOS" }
Finally:
Using all this power what I'd do is mixing trailing closure and type inference (with naming for readability)
PFFacebookUtils.logInWithPermissions(permissions) {
user, error in
if (!user) {
println("Uh oh. The user cancelled the Facebook login.")
} else if (user.isNew) {
println("User signed up and logged in through Facebook!")
} else {
println("User logged in through Facebook!")
}
}
All of these answers seem to assume that the user is generating the bad XML, rather than receiving it from gSOAP, which should know better!
Try this it will work --
if($('#EventStartTimeMin').val() === " ") {
alert("Please enter start time!");
}
Django has some documentation about that on their website, see: Saving changes to objects. To summarize:
.. to save changes to an object that's already in the database, use
save()
.
You have to convert string formate to required date format as following and then you can get your required result.
hive> select * from salesdata01 where from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') >= from_unixtime(unix_timestamp('2010-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') and from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') <= from_unixtime(unix_timestamp('2011-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') limit 10;
OK
1 3 13-10-2010 Low 6.0 261.54 0.04 Regular Air -213.25 38.94
80 483 10-07-2011 High 30.0 4965.7593 0.08 Regular Air 1198.97 195.99
97 613 17-06-2011 High 12.0 93.54 0.03 Regular Air -54.04 7.3
98 613 17-06-2011 High 22.0 905.08 0.09 Regular Air 127.7 42.76
103 643 24-03-2011 High 21.0 2781.82 0.07 Express Air -695.26 138.14
127 807 23-11-2010 Medium 45.0 196.85 0.01 Regular Air -166.85 4.28
128 807 23-11-2010 Medium 32.0 124.56 0.04 Regular Air -14.33 3.95
160 995 30-05-2011 Medium 46.0 1815.49 0.03 Regular Air 782.91 39.89
229 1539 09-03-2011 Low 33.0 511.83 0.1 Regular Air -172.88 15.99
230 1539 09-03-2011 Low 38.0 184.99 0.05 Regular Air -144.55 4.89
Time taken: 0.166 seconds, Fetched: 10 row(s)
hive> select * from salesdata01 where from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') >= from_unixtime(unix_timestamp('2010-09-01', 'yyyy-MM-dd'),'yyyy-MM-dd') and from_unixtime(unix_timestamp(Order_date, 'dd-MM-yyyy'),'yyyy-MM-dd') <= from_unixtime(unix_timestamp('2010-12-01', 'yyyy-MM-dd'),'yyyy-MM-dd') limit 10;
OK
1 3 13-10-2010 Low 6.0 261.54 0.04 Regular Air -213.25 38.94
127 807 23-11-2010 Medium 45.0 196.85 0.01 Regular Air -166.85 4.28
128 807 23-11-2010 Medium 32.0 124.56 0.04 Regular Air -14.33 3.95
256 1792 08-11-2010 Low 28.0 370.48 0.04 Regular Air -5.45 13.48
381 2631 23-09-2010 Low 27.0 1078.49 0.08 Regular Air 252.66 40.96
656 4612 19-09-2010 Medium 9.0 89.55 0.06 Regular Air -375.64 4.48
769 5506 07-11-2010 Critical 22.0 129.62 0.05 Regular Air 4.41 5.88
1457 10499 16-11-2010 Not Specified 29.0 6250.936 0.01 Delivery Truck 31.21 262.11
1654 11911 10-11-2010 Critical 25.0 397.84 0.0 Regular Air -14.75 15.22
2323 16741 30-09-2010 Medium 6.0 157.97 0.01 Regular Air -42.38 22.84
Time taken: 0.17 seconds, Fetched: 10 row(s)
((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");
Per JamieL's answer to another post:
Since Express.js 3x the response object has a json() method which sets all the headers correctly for you.
Example:
res.json({"foo": "bar"});
I tried all above, but none working
Finally tried this my own
getBaseActivity().getFragmentManager()
and is working .. :)
In Java 8:
Customer findCustomerByid(int id) {
return this.customers.stream()
.filter(customer -> customer.getId().equals(id))
.findFirst().get();
}
It might also be better to change the return type to Optional<Customer>
.
Just use the &&
operator like you would with any other statement that you need to do boolean logic.
if (useAdditionalClauses)
{
results = results.Where(
o => o.OrderStatus == OrderStatus.Open
&& o.CustomerID == customerID)
}
$('input[name=hidden_field_name]').val('newVal');
worked for me, when neither
$('input[id=hidden_field_id]').val('newVal');
nor
$('#hidden_field_id').val('newVal');
did.
Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
a = 5
makes the variable name a
to refer to the integer 5. Later, a = "hello"
makes the variable name a
to refer to a string containing "hello". Static typed languages would have you declare int a
and then a = 5
, but assigning a = "hello"
would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a
refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.a = "5"
(the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5
to get "hello5"
.Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...
class Countries < ActiveRecord::Base
self.table_name = "cc"
end
class Countries < ActiveRecord::Base
self.set_table_name "cc"
...
end
\usepackage{array}
in the preamble
then this:
\begin{tabular}{| >{\centering\arraybackslash}m{1in} | >{\centering\arraybackslash}m{1in} |}
note that the "m" for fixed with column is provided by the array package, and will give you vertical centering (if you don't want this just go back to "p"
None of the answers here satisfies my needs.
The answer from Muno is wrong because it lists ONLY the USB ports.
The answer from code4life is wrong because it lists all EXCEPT the USB ports. (Nevertheless it has 44 up-votes!!!)
I have an EPSON printer simulation port on my computer which is not listed by any of the answers here. So I had to write my own solution. Additionally I want to display more information than just the caption string. I also need to separate the port name from the description.
My code has been tested on Windows XP, Windows 7 and Windows 10.
The Port Name (like "COM1") must be read from the registry because WMI does not give this information for all COM ports (EPSON).
If you use my code you do not need SerialPort.GetPortNames()
anymore. My function returns the same ports, but with additional details. Why did Microsoft not implement such a function into the framework??
using System.Management;
using Microsoft.Win32;
using (ManagementClass i_Entity = new ManagementClass("Win32_PnPEntity"))
{
foreach (ManagementObject i_Inst in i_Entity.GetInstances())
{
Object o_Guid = i_Inst.GetPropertyValue("ClassGuid");
if (o_Guid == null || o_Guid.ToString().ToUpper() != "{4D36E978-E325-11CE-BFC1-08002BE10318}")
continue; // Skip all devices except device class "PORTS"
String s_Caption = i_Inst.GetPropertyValue("Caption") .ToString();
String s_Manufact = i_Inst.GetPropertyValue("Manufacturer").ToString();
String s_DeviceID = i_Inst.GetPropertyValue("PnpDeviceID") .ToString();
String s_RegPath = "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\" + s_DeviceID + "\\Device Parameters";
String s_PortName = Registry.GetValue(s_RegPath, "PortName", "").ToString();
int s32_Pos = s_Caption.IndexOf(" (COM");
if (s32_Pos > 0) // remove COM port from description
s_Caption = s_Caption.Substring(0, s32_Pos);
Console.WriteLine("Port Name: " + s_PortName);
Console.WriteLine("Description: " + s_Caption);
Console.WriteLine("Manufacturer: " + s_Manufact);
Console.WriteLine("Device ID: " + s_DeviceID);
Console.WriteLine("-----------------------------------");
}
}
I tested the code with a lot of COM ports. This is the Console output:
Port Name: COM29
Description: CDC Interface (Virtual COM Port) for USB Debug
Manufacturer: GHI Electronics, LLC
Device ID: USB\VID_1B9F&PID_F003&MI_01\6&3009671A&0&0001
-----------------------------------
Port Name: COM28
Description: Teensy USB Serial
Manufacturer: PJRC.COM, LLC.
Device ID: USB\VID_16C0&PID_0483\1256310
-----------------------------------
Port Name: COM25
Description: USB-SERIAL CH340
Manufacturer: wch.cn
Device ID: USB\VID_1A86&PID_7523\5&2499667D&0&3
-----------------------------------
Port Name: COM26
Description: Prolific USB-to-Serial Comm Port
Manufacturer: Prolific
Device ID: USB\VID_067B&PID_2303\5&2499667D&0&4
-----------------------------------
Port Name: COM1
Description: Comunications Port
Manufacturer: (Standard port types)
Device ID: ACPI\PNP0501\1
-----------------------------------
Port Name: COM999
Description: EPSON TM Virtual Port Driver
Manufacturer: EPSON
Device ID: ROOT\PORTS\0000
-----------------------------------
Port Name: COM20
Description: EPSON COM Emulation USB Port
Manufacturer: EPSON
Device ID: ROOT\PORTS\0001
-----------------------------------
Port Name: COM8
Description: Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID: BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&000F\8&3ADBDF90&0&001DA568988B_C00000000
-----------------------------------
Port Name: COM9
Description: Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID: BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\8&3ADBDF90&0&000000000000_00000002
-----------------------------------
Port Name: COM30
Description: Arduino Uno
Manufacturer: Arduino LLC (www.arduino.cc)
Device ID: USB\VID_2341&PID_0001\74132343530351F03132
-----------------------------------
COM1 is a COM port on the mainboard.
COM 8 and 9 are Buetooth COM ports.
COM 25 and 26 are USB to RS232 adapters.
COM 28 and 29 and 30 are Arduino-like boards.
COM 20 and 999 are EPSON ports.
As @nos pointed out in the comments of the currently accepted answer to this question, the accepted answer is incorrect.
Yes, there IS a difference between using %
and localhost
for the user account host when connecting via a socket connect instead of a standard TCP/IP connect.
A host value of %
does not include localhost
for sockets and thus must be specified if you want to connect using that method.
You could take a look at the DateTimeFormat property which contains the culture specific formats.
I'll add an important feature that all of the other answers have overlooked: cancellation.
One of the big things in TPL is cancellation support, and console apps have a method of cancellation built in (CTRL+C). It's very simple to bind them together. This is how I structure all of my async console apps:
static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
System.Console.CancelKeyPress += (s, e) =>
{
e.Cancel = true;
cts.Cancel();
};
MainAsync(args, cts.Token).GetAwaiter.GetResult();
}
static async Task MainAsync(string[] args, CancellationToken token)
{
...
}
Rebooting the PC was the only thing that worked for me. It worked when I had this problem with an Android 2.2 phone, and also an Android 3.1 tablet.
('.cat').hover(
function () {
$(this).show();
},
function () {
$(this).hide();
}
);
It's the same for the others.
For the smooth fade in you can use fadeIn
and fadeOut
The mistake I made that coerced this error was attempting to rename a column in a loop that I was no longer selecting in my SQL. This could also be caused by trying to do the same thing in a column that you were planning to select. Make sure the column that you are trying to change actually exists.
You can also look into pandas.Timestamp
, which includes methods like .now
and .today
.
Unlike pandas.to_datetime('now')
, pandas.Timestamp.now()
won't default to UTC:
import pandas as pd
pd.Timestamp.now() # will return California time
# Timestamp('2018-12-19 09:17:07.693648')
pd.to_datetime('now') # will return UTC time
# Timestamp('2018-12-19 17:17:08')
Using linear algebra, there exist algorithms that achieve better complexity than the naive O(n3). Solvay Strassen algorithm achieves a complexity of O(n2.807) by reducing the number of multiplications required for each 2x2 sub-matrix from 8 to 7.
The fastest known matrix multiplication algorithm is Coppersmith-Winograd algorithm with a complexity of O(n2.3737). Unless the matrix is huge, these algorithms do not result in a vast difference in computation time. In practice, it is easier and faster to use parallel algorithms for matrix multiplication.
Curt makes a good point: the second version is clearer and will fail at load time rather than later, and unexpectedly.
Normally I don't worry about the efficiency of loading modules, since it's (a) pretty fast, and (b) mostly only happens at startup.
If you have to load heavyweight modules at unexpected times, it probably makes more sense to load them dynamically with the __import__
function, and be sure to catch ImportError
exceptions, and handle them in a reasonable manner.
Put this formula in cell d31 and copy down to d39
=iferror(vlookup(b31,$f$3:$g$12,2,0),"")
Here's what is going on. VLOOKUP:
As you know, the last argument of VLOOKUP sets the match type, with FALSE or 0 indicating an exact match.
Finally, IFERROR handles the #N/A when VLOOKUP does not find a match.
If you are on a unixoid operating system and want to extract just a single file you can try the following. The structure of the chrome://cache
pages is URL, parsed HTTP header, hex dump of the HTTP header and then hex dump of the payload.
To extract a file copy all payload lines from a Chrome cache page to the clipboard (starting at the second 00000000: ...
line), paste them into a text editor and save them as a plain text file (e.g. file.txt
). If the payload is a gzipped WOFF file use xxd -r file.txt > file.woff.gz
to convert it back to a binary file and gunzip file.woff.gz
for decompression.
You can then use woff2otf to convert WOFF files to the OTF format or woff2 to convert WOFF 2.0 files to the TTF format. For batch processing this workflow should obviously be scripted.
You could use .each()
with .children()
and a selector within the parenthesis:
//Grab Each Instance of Box.
$(".box").each(function(i){
//For Each Instance, grab a child called .something1. Fade It Out.
$(this).children(".something1").fadeOut();
});
Got same error in this line
Object temp = range.Cells[i][0].Value;
Solved with non-zero based index
Object temp = range.Cells[i][1].Value;
How is it possible that the guys who created this library thought it was a good idea to use non-zero based indexing?
Try below code snippet
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
/* This is one ajax call */
}
Rather than learning un-Official websites learn from oracle website
link follows:Click here
*You can find Initialization as well as declaration with full description *
int n; // size of array here 10
int[] a = new int[n];
for (int i = 0; i < a.length; i++)
{
a[i] = Integer.parseInt(s.nextLine()); // using Scanner class
}
Input: 10//array size 10 20 30 40 50 60 71 80 90 91
Displaying data:
for (int i = 0; i < a.length; i++)
{
System.out.println(a[i] + " ");
}
Output: 10 20 30 40 50 60 71 80 90 91
Here's a super-simple example with basic authentication, headers, and exception handling...
private HttpHeaders createHttpHeaders(String user, String password)
{
String notEncoded = user + ":" + password;
String encodedAuth = "Basic " + Base64.getEncoder().encodeToString(notEncoded.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", encodedAuth);
return headers;
}
private void doYourThing()
{
String theUrl = "http://blah.blah.com:8080/rest/api/blah";
RestTemplate restTemplate = new RestTemplate();
try {
HttpHeaders headers = createHttpHeaders("fred","1234");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
}
catch (Exception eek) {
System.out.println("** Exception: "+ eek.getMessage());
}
}
You can use
display: flex;
CSS property, as mentioned before by @Ayan, but I've created a working example: https://jsfiddle.net/d2kjxd51/
We are using an inhouse developed solution that is basicly a procedure with arguments of what you want included in the comparision (SP's, Full SP code, table structure, defaults, indices, triggers.. etc)
Depending on your needs and budget, it might be a good way to go for you as well.
It is quite easily developed as well, then we just redirect output of procedure to textfiles and do text comparisions between the files.
One good thing about it is that its possible to save the output in source control.
/B
"Oops. Those three commits could be just one."
So, undo the last 3 (or whatever) commits (without affecting the index nor working directory). Then commit all the changes as one.
> git add -A; git commit -m "Start here."
> git add -A; git commit -m "One"
> git add -A; git commit -m "Two"
> git add -A' git commit -m "Three"
> git log --oneline --graph -4 --decorate
> * da883dc (HEAD, master) Three
> * 92d3eb7 Two
> * c6e82d3 One
> * e1e8042 Start here.
> git reset --soft HEAD~3
> git log --oneline --graph -1 --decorate
> * e1e8042 Start here.
Now all your changes are preserved and ready to be committed as one.
Are these two commands really the same (reset --soft
vs commit --amend
)?
Any reason to use one or the other in practical terms?
commit --amend
to add/rm files from the very last commit or to change its message. reset --soft <commit>
to combine several sequential commits into a new one.And more importantly, are there any other uses for reset --soft
apart from amending a commit?
The following might be general knowledge I was just simply lacking, but eh. Some time ago, we had a bug case which included virtual properties. Abstracting the context a bit, consider the following code, and apply breakpoint to specified area :
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
d.Property = "AWESOME";
}
}
class Base
{
string _baseProp;
public virtual string Property
{
get
{
return "BASE_" + _baseProp;
}
set
{
_baseProp = value;
//do work with the base property which might
//not be exposed to derived types
//here
Console.Out.WriteLine("_baseProp is BASE_" + value.ToString());
}
}
}
class Derived : Base
{
string _prop;
public override string Property
{
get { return _prop; }
set
{
_prop = value;
base.Property = value;
} //<- put a breakpoint here then mouse over BaseProperty,
// and then mouse over the base.Property call inside it.
}
public string BaseProperty { get { return base.Property; } private set { } }
}
While in the Derived
object context, you can get the same behavior when adding base.Property
as a watch, or typing base.Property
into the quickwatch.
Took me some time to realize what was going on. In the end I was enlightened by the Quickwatch. When going into the Quickwatch and exploring the Derived
object d (or from the object's context, this
) and selecting the field base
, the edit field on top of the Quickwatch displays the following cast:
((TestProject1.Base)(d))
Which means that if base is replaced as such, the call would be
public string BaseProperty { get { return ((TestProject1.Base)(d)).Property; } private set { } }
for the Watches, Quickwatch and the debugging mouse-over tooltips, and it would then make sense for it to display "AWESOME"
instead of "BASE_AWESOME"
when considering polymorphism. I'm still unsure why it would transform it into a cast, one hypothesis is that call
might not be available from those modules' context, and only callvirt
.
Anyhow, that obviously doesn't alter anything in terms of functionality, Derived.BaseProperty
will still really return "BASE_AWESOME"
, and thus this was not the root of our bug at work, simply a confusing component. I did however find it interesting how it could mislead developpers which would be unaware of that fact during their debug sessions, specially if Base
is not exposed in your project but rather referenced as a 3rd party DLL, resulting in Devs just saying :
"Oi, wait..what ? omg that DLL is like, ..doing something funny"
I use Chrome dev tools' Timeline tab, instantiate increasingly large amounts of objects, and get good estimates like that. You can use html like this one below, as boilerplate, and modify it to better simulate the characteristics of your objects (number and types of properties, etc...). You may want to click the trash bit icon at the bottom of that dev tools tab, before and after a run.
<html>
<script>
var size = 1000*100
window.onload = function() {
document.getElementById("quantifier").value = size
}
function scaffold()
{
console.log("processing Scaffold...");
a = new Array
}
function start()
{
size = document.getElementById("quantifier").value
console.log("Starting... quantifier is " + size);
console.log("starting test")
for (i=0; i<size; i++){
a[i]={"some" : "thing"}
}
console.log("done...")
}
function tearDown()
{
console.log("processing teardown");
a.length=0
}
</script>
<body>
<span style="color:green;">Quantifier:</span>
<input id="quantifier" style="color:green;" type="text"></input>
<button onclick="scaffold()">Scaffold</button>
<button onclick="start()">Start</button>
<button onclick="tearDown()">Clean</button>
<br/>
</body>
</html>
Instantiating 2 million objects of just one property each (as in this code above) leads to a rough calculation of 50 bytes per object, on my Chromium, right now. Changing the code to create a random string per object adds some 30 bytes per object, etc. Hope this helps.
Clearing a session removes the values that were stored there, but you still can add new ones there. After destroying the session you cannot add new values there.
I tried to update a field with
$table->update(['field' => 'val']);
But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)
Go to your db -> structure and do empty in required table. See here:
There could be many reasons for this. A few that come up quickly to my mind:
InitializeComponent()
?It may be possible that there is no other application running. It is possible that the socket wasn't cleanly shutdown from a previous session in which case you may have to wait for a while before the TIME_WAIT expires on that socket. Unfortunately, you won't be able to use the port till that socket expires. If you can start your server after waiting for a while (a few minutes) then the problem is not due to some other application running on port 8080.
ex: url/:id
var sample= app.controller('sample', function ($scope, $routeParams) {
$scope.init = function () {
var qa_id = $routeParams.qa_id;
}
});
I recently found this library that converts an Excel workbook file into a DataSet: Excel Data Reader
In this question:
1.Casting double to integer is very easy task.
2.But it's not rounding double value to the nearest decimal. Therefore casting can be done like this:
double d=99.99999999;
int i=(int)d;
System.out.println(i);
and it will print 99
, but rounding hasn't been done.
Thus for rounding we can use,
double d=99.99999999;
System.out.println( Math.round(d));
This will print the output of 100
.
An alternative to the usual methods is to hook into the drawing of the view.
OnPreDrawListener
is called many times when displaying a view, so there is no specific iteration where your view has valid measured width or height. This requires that you continually verify (view.getMeasuredWidth() <= 0
) or set a limit to the number of times you check for a measuredWidth
greater than zero.
There is also a chance that the view will never be drawn, which may indicate other problems with your code.
final View view = [ACQUIRE REFERENCE]; // Must be declared final for inner class
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
if (view.getMeasuredWidth() > 0) {
view.getViewTreeObserver().removeOnPreDrawListener(this);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
//Do something with width and height here!
}
return true; // Continue with the draw pass, as not to stop it
}
});
You can also use react router dom library useHistory;
`
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
`
Currently, ExplorerCanvas is the only option to emulate HTML5 canvas for IE6, 7, and 8. You're also right about its performance, which is pretty poor.
I found a particle simulatior that benchmarks the difference between true HTML5 canvas handling in Google Chrome, Safari, and Firefox, vs ExplorerCanvas in IE. The results show that the major browsers that do support the canvas tag run about 20 to 30 times faster than the emulated HTML5 in IE with ExplorerCanvas.
I doubt that anyone will go through the effort of creating an alternative because 1) excanvas.js is about as cleanly coded as it gets and 2) when IE9 is released all of the major browsers will finally support the canvas object. Hopefully, We'll get IE9 within a year
Eric @ www.webkrunk.com
Have you tried using str.splitlines()
method?:
From the docs:
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless
keepends
is given and true.
For example:
>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']
>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']
This method uses the universal newlines approach to splitting lines.
The main difference between Python 2.X
and Python 3.X
is that the former uses the universal newlines approach to splitting lines, so "\r"
, "\n"
, and "\r\n"
are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:
\v
or \x0b
: Line Tabulation (added in Python 3.2
).\f
or \x0c
: Form Feed (added in Python 3.2
).\x1c
: File Separator.\x1d
: Group Separator.\x1e
: Record Separator.\x85
: Next Line (C1 Control Code).\u2028
: Line Separator.\u2029
: Paragraph Separator.Unlike
str.split()
when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:
>>> ''.splitlines()
[]
>>> 'Line 1\n'.splitlines()
['Line 1']
While str.split('\n')
returns:
>>> ''.split('\n')
['']
>>> 'Line 1\n'.split('\n')
['Line 1', '']
If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines()
, you could use str.splitlines()
together with str.strip()
:
>>> [str.strip() for str in 'Line 1 \n \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']
Lastly, if you want to filter out the empty strings from the resulting list, you could use filter()
:
>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']
>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']
As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function
Some more info for Browser window : http://www.w3schools.com/js/js_window.asp?output=print
How about some recursion:
private static string ReturnSize(double size, string sizeLabel)
{
if (size > 1024)
{
if (sizeLabel.Length == 0)
return ReturnSize(size / 1024, "KB");
else if (sizeLabel == "KB")
return ReturnSize(size / 1024, "MB");
else if (sizeLabel == "MB")
return ReturnSize(size / 1024, "GB");
else if (sizeLabel == "GB")
return ReturnSize(size / 1024, "TB");
else
return ReturnSize(size / 1024, "PB");
}
else
{
if (sizeLabel.Length > 0)
return string.Concat(size.ToString("0.00"), sizeLabel);
else
return string.Concat(size.ToString("0.00"), "Bytes");
}
}
Then you call it:
return ReturnSize(size, string.Empty);
public abstract class Metadata
{
}
// extend abstract Metadata class
public class Metadata<DataType> : Metadata where DataType : struct
{
private DataType mDataType;
}
I was having a problem on Ubuntu 18.04 on Mysql. When I needed to create a new user, the policy was always high.
The way I figured out how to disable, for future colleagues who come to investigate, was set to low.
Login to the mysql server as root
mysql -h localhost -u root -p
Set the new type of validation
SET GLOBAL validate_password_policy=0; //For Low
Restart mysql
sudo service mysql restart
The GetHashCode
function is specifically designed to create a well distributed range of integers with a low probability of collision, so for this use case is likely to be the best you can do.
But, as I'm sure you're aware, hashing 128 bits of information into 32 bits of information throws away a lot of data, so there will almost certainly be collisions if you have a sufficiently large number of GUIDs.
Here are three steps: A command that you can call inside your terminal and change branch name.
git branch -m old_branch new_branch # Rename branch locally
git push origin :old_branch # Delete the old branch
git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote
If you need more: step-by-step, How To Change Git Branch Name is a good article about that.
If you see the man page of logger:
$ man logger
LOGGER(1) BSD General Commands Manual LOGGER(1)
NAME logger — a shell command interface to the syslog(3) system log module
SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]
DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.
It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.
The simplest way:
import time
#Your code here
time.sleep(60)
#end of code (and console shut down)
this will leave the code up for 1 minute then close it.
You were correct to use WaitForSeconds. But I suspect that you tried using it without coroutines. That's how it should work:
public void SomeMethod()
{
StartCoroutine(SomeCoroutine());
}
private IEnumerator SomeCoroutine()
{
TextUI.text = "Welcome to Number Wizard!";
yield return new WaitForSeconds (3);
TextUI.text = ("The highest number you can pick is " + max);
yield return new WaitForSeconds (3);
TextUI.text = ("The lowest number you can pick is " + min);
}
Maybe I'm missing something, but a lot of these answers seem overly complicated. You should be able to just set the columns within a single list:
Column to the front:
df = df[ ['Mid'] + [ col for col in df.columns if col != 'Mid' ] ]
Or if instead, you want to move it to the back:
df = df[ [ col for col in df.columns if col != 'Mid' ] + ['Mid'] ]
Or if you wanted to move more than one column:
cols_to_move = ['Mid', 'Zsore']
df = df[ cols_to_move + [ col for col in df.columns if col not in cols_to_move ] ]
You need Ajax to make it happen. Something like this:
$(document).ready(function(){
$("#myform").on('submit', function(){
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var contact = $("#contact").val();
var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
if(name=='' || email=='' || password=='' || contact=='')
{
alert("Please fill in all fields");
}
else
{
// Ajax code to submit form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
First of all, you don't need to use a layout inflater to create a simple Button. You can just use:
button = new Button(context);
If you want to style the button you have 2 choices: the simplest one is to just specify all the elements in code, like many of the other answers suggest:
button.setTextColor(Color.RED);
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
The other option is to define the style in XML, and apply it to the button. In the general case, you can use a ContextThemeWrapper
for this:
ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext, R.style.MyStyle);
button = new Button(newContext);
To change the text-related attributes on a TextView (or its subclasses like Button) there is a special method:
button.setTextAppearance(R.style.MyTextStyle);
Or, if you need to support devices pre API-23 (Android 6.0)
button.setTextAppearance(context, R.style.MyTextStyle);
This method cannot be used to change all attributes; for example to change padding you need to use a ContextThemeWrapper
. But for text color, size, etc. you can use setTextAppearance
.
NOTE: you can use NVM software to do this in a more nodejs fashionway. However i got issues in one machine that didn't let me use NVM. So i have to look for an alternative ;-)
You can manually download and install.
go to nodejs > download > other releases http://nodejs.org/dist/
choose the version you are looking for http://nodejs.org/dist/v0.8.18/
choose distro files corresponding your environmment and download (take care of 32bits/64bits version). Example: http://nodejs.org/dist/v0.8.18/node-v0.8.18-linux-x64.tar.gz
Extract files and follow instructions on README.md :
To build:
Prerequisites (Unix only):
* Python 2.6 or 2.7 * GNU Make 3.81 or newer * libexecinfo (FreeBSD and OpenBSD only)
Unix/Macintosh:
./configure make make install
If your python binary is in a non-standard location or has a non-standard name, run the following instead:
export PYTHON=/path/to/python $PYTHON ./configure make make install
Windows:
vcbuild.bat
To run the tests:
Unix/Macintosh:
make test
Windows:
vcbuild.bat test
To build the documentation:
make doc
To read the documentation:
man doc/node.1
Maybe you want to (must to) move the folder to a more apropiate place like /usr/lib/nodejs/node-v0.8.18/ then create a Symbolic Lynk on /usr/bin to get acces to your install from anywhere.
sudo mv /extracted/folder/node-v0.8.18 /usr/lib/nodejs/node-v0.8.18
sudo ln -s /usr/lib/nodejs/node-v0.8.18/bin/node /usr/bin/node
And if you want different release in the same machine you can use debian alternatives. Proceed in the same way posted before to download a second release. For example the latest release.
http://nodejs.org/dist/latest/ -> http://nodejs.org/dist/latest/node-v0.10.28-linux-x64.tar.gz
Move to your favorite destination, the same of the rest of release you want to install.
sudo mv /extracted/folder/node-v0.10.28 /usr/lib/nodejs/node-v0.10.28
Follow instructions of the README.md file. Then update the alternatives, for each release you have dowload install the alternative with.
sudo update-alternatives --install genname symlink altern priority [--slave genname symlink altern]
Add a group of alternatives to the system. genname is the
generic name for the master link, symlink is the name of its
symlink in the alternatives directory, and altern is the
alternative being introduced for the master link. The arguments
after --slave are the generic name, symlink name in the
alternatives directory and alternative for a slave link. Zero
or more --slave options, each followed by three arguments, may
be specified.
If the master symlink specified exists already in the
alternatives system’s records, the information supplied will be
added as a new set of alternatives for the group. Otherwise, a
new group, set to automatic mode, will be added with this
information. If the group is in automatic mode, and the newly
added alternatives’ priority is higher than any other installed
alternatives for this group, the symlinks will be updated to
point to the newly added alternatives.
for example:
sudo update-alternatives --install /usr/bin/node node /usr/lib/nodejs/node-v0.10.28 0 --slave /usr/share/man/man1/node.1.gz node.1.gz /usr/lib/nodejs/node-v0.10.28/share/man/man1/node.1
Then you can use update-alternatives --config node
to choose between any number of releases instaled in your machine.
The only issue I see are relative links and templates not being properly loaded because of this.
from the docs regarding HTML5 mode
Relative links
Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (
<base href="/my-base">
) or you must use absolute urls (starting with/
) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.
In your case you can add a forward slash /
in href
attributes ($location.path
does this automatically) and also to templateUrl
when configuring routes. This avoids routes like example.com/tags/another
and makes sure templates load properly.
Here's an example that works:
<div>
<a href="/">Home</a> |
<a href="/another">another</a> |
<a href="/tags/1">tags/1</a>
</div>
<div ng-view></div>
And
app.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/partials/template1.html',
controller: 'ctrl1'
})
.when('/tags/:tagId', {
templateUrl: '/partials/template2.html',
controller: 'ctrl2'
})
.when('/another', {
templateUrl: '/partials/template1.html',
controller: 'ctrl1'
})
.otherwise({ redirectTo: '/' });
});
If using Chrome you will need to run this from a server.
Update in July 2020:
During the last 16 months, maybe the most notable change in the React community is React hooks.
According to what I observe, in order to gain better compatibility with functional components and hooks, projects (even those large ones) would tend to use:
useQuery
useMutation
In comparison, redux-saga
doesn't really provide significant benefit in most normal cases of API calls comparing to the above approaches for now, while increasing project complexity by introducing many saga files/generators (also because the last release v1.1.1 of redux-saga
was on 18 Sep 2019, which was a long time ago).
But still, redux-saga
provides some unique features such as racing effect and parallel requests. Therefore, if you need these special functionalities, redux-saga
is still a good choice.
Original post in March 2019:
Just some personal experience:
For coding style and readability, one of the most significant advantages of using redux-saga in the past is to avoid callback hell in redux-thunk — one does not need to use many nesting then/catch anymore. But now with the popularity of async/await thunk, one could also write async code in sync style when using redux-thunk, which may be regarded as an improvement in redux-thunk.
One may need to write much more boilerplate codes when using redux-saga, especially in Typescript. For example, if one wants to implement a fetch async function, the data and error handling could be directly performed in one thunk unit in action.js with one single FETCH action. But in redux-saga, one may need to define FETCH_START, FETCH_SUCCESS and FETCH_FAILURE actions and all their related type-checks, because one of the features in redux-saga is to use this kind of rich “token” mechanism to create effects and instruct redux store for easy testing. Of course one could write a saga without using these actions, but that would make it similar to a thunk.
In terms of the file structure, redux-saga seems to be more explicit in many cases. One could easily find an async related code in every sagas.ts, but in redux-thunk, one would need to see it in actions.
Easy testing may be another weighted feature in redux-saga. This is truly convenient. But one thing that needs to be clarified is that redux-saga “call” test would not perform actual API call in testing, thus one would need to specify the sample result for the steps which may be used after the API call. Therefore before writing in redux-saga, it would be better to plan a saga and its corresponding sagas.spec.ts in detail.
Redux-saga also provides many advanced features such as running tasks in parallel, concurrency helpers like takeLatest/takeEvery, fork/spawn, which are far more powerful than thunks.
In conclusion, personally, I would like to say: in many normal cases and small to medium size apps, go with async/await style redux-thunk. It would save you many boilerplate codes/actions/typedefs, and you would not need to switch around many different sagas.ts and maintain a specific sagas tree. But if you are developing a large app with much complex async logic and the need for features like concurrency/parallel pattern, or have a high demand for testing and maintenance (especially in test-driven development), redux-sagas would possibly save your life.
Anyway, redux-saga is not more difficult and complex than redux itself, and it does not have a so-called steep learning curve because it has well-limited core concepts and APIs. Spending a small amount of time learning redux-saga may benefit yourself one day in the future.
First thing to do is run this:
SHOW GRANTS;
You will quickly see you were assigned the anonymous user to authenticate into mysql.
Instead of logging into mysql with
mysql
login like this:
mysql -uroot
By default, root@localhost has all rights and no password.
If you cannot login as root without a password, do the following:
Step 01) Add the two options in the mysqld section of my.ini:
[mysqld]
skip-grant-tables
skip-networking
Step 02) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 03) Connect to mysql
mysql
Step 04) Create a password from root@localhost
UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit
Step 05) Restart mysql
net stop mysql
<wait 10 seconds>
net start mysql
Step 06) Login as root with password
mysql -u root -p
You should be good from there.
You can iterate through JavaScript objects this way:
for(var attributename in myobject){
console.log(attributename+": "+myobject[attributename]);
}
myobject could be your json.data
Java supports closures just fine. It just doesn't support functions, so the syntax you're used to for closures is much more awkward and bulky: you have to wrap everything up in a class with a method. For example,
public Runnable foo(final int x) {
return new Runnable() {
public void run() {
System.out.println(x);
}
};
}
Will return a Runnable object whose run()
method "closes over" the x
passed in, just like in any language that supports first-class functions and closures.
In some cases margin="0 auto" won't cut the mustard when center aligning a html email in Outlook 2007, 2010, 2013.
Try the following:
Wrap your content in another table with style="table-layout: fixed;" and align=“center”.
<!-- WRAPPING TABLE -->
<table cellpadding="0" cellspacing="0" border="0" style="table-layout: fixed;" align="center">
<tr>
<td>
<!-- YOUR TABLES AND EMAIL CONTENT GOES HERE -->
</td>
</tr>
</table>
Bootstrap v4.1 uses new classnames for hiding columns on their grid system.
For hiding columns depending on the screen width, use d-none
class or any of the d-{sm,md,lg,xl}-none
classes.
To show columns on certain screen sizes, combine the above mentioned classes with d-block
or d-{sm,md,lg,xl}-block
classes.
Examples are:
<div class="d-lg-none">hide on screens wider than lg</div>_x000D_
<div class="d-none d-lg-block">hide on screens smaller than lg</div>
_x000D_
More of these here.
You should add System.configuration dll as reference and use System.Configuration.ConfigurationManager.AppSettings["configFile"].ToString
Don't forget to add using
statement at the beginning. Hope it will help.
If its a 32 bit COM/Active X, use version 32 bit of cscript.exe/wscript.exe located in C:\Windows\SysWOW64\
An IEnumerator
is a thing that can enumerate: it has the Current
property and the MoveNext
and Reset
methods (which in .NET code you probably won't call explicitly, though you could).
An IEnumerable
is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator
.
Which do you use? The only reason to use IEnumerator
is if you have something that has a nonstandard way of enumerating (that is, of returning its various elements one-by-one), and you need to define how that works. You'd create a new class implementing IEnumerator
. But you'd still need to return that IEnumerator
in an IEnumerable
class.
For a look at what an enumerator (implementing IEnumerator<T>
) looks like, see any Enumerator<T>
class, such as the ones contained in List<T>
, Queue<T>,
or Stack<T>
. For a look at a class implementing IEnumerable
, see any standard collection class.
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
Maybe someone can use it. Find all files which were modified within a certain time frame recursively, just run:
find . -type f -newermt "2013-06-01" \! -newermt "2013-06-20"
I get this every time I want to create an application in VC++.
Right-click the project, select Properties then under 'Configuration properties | C/C++ | Code Generation', select "Multi-threaded Debug (/MTd)" for Debug configuration.
Note that this does not change the setting for your Release configuration - you'll need to go to the same location and select "Multi-threaded (/MT)" for Release.
For money: decimal
. It costs a little more memory, but doesn't have rounding troubles like double
sometimes has.
Set the following registry value:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion!EnableLog] (DWORD) to 1
To disable, set to 0 or delete the value.
[edit ]:Save the following text to a file, e.g FusionEnableLog.reg, in Windows Registry Editor Format:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion]
"EnableLog"=dword:00000001
Then run the file from windows explorer and ignore the warning about possible damage.
I am using the new EF & Identity Core and I have the same issue, with the addition that I've got this error:
The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked.
With the new DI model I added the constructor's Controller the context to the DB.
I tried to see what are the conflict with _conext.ChangeTracker.Entries()
and adding AsNoTracking()
to my calls without success.
I only need to change the state of my object (in this case Identity)
_context.Entry(user).State = EntityState.Modified;
var result = await _userManager.UpdateAsync(user);
And worked without create another store or object and mapping.
I hope someone else is useful my two cents.
Use timeit. http://docs.python.org/library/timeit.html
What is this for and why would I use @":\" instead of ":\"?
Because when you have a long string with many \
you don't need to escape them all and the \n
, \r
and \f
won't work too.
Use JSON.stringify() to wrap your json
var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
$http.post(url, parameter).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
You need to use sqlite's prepared statements interface. Basically, the idea is that you prepare a statement with a placeholder for your blob, then use one of the bind calls to "bind" your data...
I wrote a small bash script that you can run from your command line, so long as you update your PATH to include its directory (or you can place it in a directory that is already contained in the PATH).
Usage: $ pinch filename start-line end-line
#!/bin/bash
# Display line number ranges of a file to the terminal.
# Usage: $ pinch filename start-line end-line
# By Evan J. Coon
FILENAME=$1
START=$2
END=$3
ERROR="[PINCH ERROR]"
# Check that the number of arguments is 3
if [ $# -lt 3 ]; then
echo "$ERROR Need three arguments: Filename Start-line End-line"
exit 1
fi
# Check that the file exists.
if [ ! -f "$FILENAME" ]; then
echo -e "$ERROR File does not exist. \n\t$FILENAME"
exit 1
fi
# Check that start-line is not greater than end-line
if [ "$START" -gt "$END" ]; then
echo -e "$ERROR Start line is greater than End line."
exit 1
fi
# Check that start-line is positive.
if [ "$START" -lt 0 ]; then
echo -e "$ERROR Start line is less than 0."
exit 1
fi
# Check that end-line is positive.
if [ "$END" -lt 0 ]; then
echo -e "$ERROR End line is less than 0."
exit 1
fi
NUMOFLINES=$(wc -l < "$FILENAME")
# Check that end-line is not greater than the number of lines in the file.
if [ "$END" -gt "$NUMOFLINES" ]; then
echo -e "$ERROR End line is greater than number of lines in file."
exit 1
fi
# The distance from the end of the file to end-line
ENDDIFF=$(( NUMOFLINES - END ))
# For larger files, this will run more quickly. If the distance from the
# end of the file to the end-line is less than the distance from the
# start of the file to the start-line, then start pinching from the
# bottom as opposed to the top.
if [ "$START" -lt "$ENDDIFF" ]; then
< "$FILENAME" head -n $END | tail -n +$START
else
< "$FILENAME" tail -n +$START | head -n $(( END-START+1 ))
fi
# Success
exit 0
Just do:
$object = new stdClass();
$object->name = "My name";
$myArray[] = $object;
You need to create the object first (the new
line) and then push it onto the end of the array (the []
line).
You can also do this:
$myArray[] = (object) ['name' => 'My name'];
However I would argue that's not as readable, even if it is more succinct.
I found a very good explanation in
http://www.programmerinterview.com/index.php/database-sql/find-nth-highest-salary-sql/
This query should give nth
highest salary
SELECT *
FROM Employee Emp1
WHERE (N-1) = (
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)
I used simple hack, asking windows to use cmd commands , and send it to null.
// Class for Different hacks for better CMD Display
import java.io.IOException;
public class CMDWindowEffets
{
public static void getch() throws IOException, InterruptedException
{
new ProcessBuilder("cmd", "/c", "pause > null").inheritIO().start().waitFor();
}
}
I had a simular need. Here is what I did:
<script type="text/javascript" language="javascript">
function convertEnterToTab() {
if(event.keyCode==13) {
event.keyCode = 9;
}
}
document.onkeydown = convertEnterToTab;
</script>
This is an old question (2008) so there are many more options now than there were then:
UPDATES (projects still active in 2020):
A caveat on picking HTTP/REST clients. Make sure to check what your framework stack is using for an HTTP client, how it does threading, and ideally use the same client if it offers one. That is if your using something like Vert.x or Play you may want to try to use its backing client to participate in whatever bus or reactor loop the framework provides... otherwise be prepared for possibly interesting threading issues.
If I put stdlib.h or stdio.h, I don't have to link those but I have to link when I compile:
stdlib.h
, stdio.h
are the header files. You include them for your convenience. They only forecast what symbols will become available if you link in the proper library. The implementations are in the library files, that's where the functions really live.
Including math.h
is only the first step to gaining access to all the math functions.
Also, you don't have to link against libm
if you don't use it's functions, even if you do a #include <math.h>
which is only an informational step for you, for the compiler about the symbols.
stdlib.h
, stdio.h
refer to functions available in libc
, which happens to be always linked in so that the user doesn't have to do it himself.
I found that the only option that worked for me was
font-size:0;
I was also using overflow
and white-space: nowrap;
float: left;
seems to mess things up
In Python:
con = sqlite3.connect('database.db')
cursor = con.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall())
Watch out for my other answer. There is a much faster way using pandas.
It is very simple. You can use
.fill .map
{
min-height: 100vh;
}
You can change height according to your requirement.
Here's my implementation of Dan Tao's answer, allowing for a predicate:
public static bool IsEmpty<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null) throw new ArgumentNullException();
if (IsCollectionAndEmpty(source)) return true;
return !source.Any(predicate);
}
public static bool IsEmpty<TSource>(this IEnumerable<TSource> source)
{
if (source == null) throw new ArgumentNullException();
if (IsCollectionAndEmpty(source)) return true;
return !source.Any();
}
private static bool IsCollectionAndEmpty<TSource>(IEnumerable<TSource> source)
{
var genericCollection = source as ICollection<TSource>;
if (genericCollection != null) return genericCollection.Count == 0;
var nonGenericCollection = source as ICollection;
if (nonGenericCollection != null) return nonGenericCollection.Count == 0;
return false;
}
select count(*) from dbo.tablename where address_line_1 LIKE '%[\'']%' {eSCAPE'\'}
I had to use nl2br to display the carriage returns correctly and it worked for me:
<?php
echo nl2br(file_get_contents( "filename.php" )); // get the contents, and echo it out.
?>
My reading of the docs is that HttpConnection itself is not treated as thread safe, and hence MultiThreadedHttpConnectionManager provides a reusable pool of HttpConnections, you have a single MultiThreadedHttpConnectionManager shared by all threads and initialised exactly once. So you need a couple of small refinements to option A.
MultiThreadedHttpConnectionManager connman = new MultiThreadedHttpConnectionManag
Then each thread should be using the sequence for every request, getting a conection from the pool and putting it back on completion of its work - using a finally block may be good. You should also code for the possibility that the pool has no available connections and process the timeout exception.
HttpConnection connection = null
try {
connection = connman.getConnectionWithTimeout(
HostConfiguration hostConfiguration, long timeout)
// work
} catch (/*etc*/) {/*etc*/} finally{
if ( connection != null )
connman.releaseConnection(connection);
}
As you are using a pool of connections you won't actually be closing the connections and so this should not hit the TIME_WAIT problem. This approach does assuume that each thread doesn't hang on to the connection for long. Note that conman itself is left open.
To say it differently: When you insert a key-value-pair into a HashMap where the key already exists (in a sense hashvalue() gives the same value und equal() is true, but the two objects can still differ in several ways), the key isn't replaced but the value is overwritten. The key is just used to get the hashvalue() and find the value in the table with it. Since HashSet uses the keys of a HashMap and sets arbitrary values which don't really matter (to the user) as a result the Elements of the Set aren't replaced either.