Cluster differs from Cloud and Grid in that a cluster is a group of computers connected by a local area network (LAN), whereas cloud and grid are more wide scale and can be geographically distributed. Another way to put it is to say that a cluster is tightly coupled, whereas a Grid or a cloud is loosely coupled. Also, clusters are made up of machines with similar hardware, whereas clouds and grids are made up of machines with possibly very different hardware configurations.
To know more about cloud computing, I recommend reading this paper: «Above the Clouds: A Berkeley View of Cloud Computing», Michael Armbrust, Armando Fox, Rean Griffith, Anthony D. Joseph, Randy H. Katz, Andrew Konwinski, Gunho Lee, David A. Patterson, Ariel Rabkin, Ion Stoica and Matei Zaharia. The following is an abstract from the above paper:
Cloud Computing refers to both the applications delivered as services over the Internet and the hardware and systems software in the datacenters that provide those services. The services themselves have long been referred to as Software as a Service (SaaS). The datacenter hardware and software is what we call a Cloud. When a Cloud is made available in a pay-as-you-go manner to the general public, we call it a Public Cloud; the service being sold is Utility Computing. We use the term Private Cloud to refer to internal datacenters of a business or other organization, not made available to the general public. Thus, Cloud Computing is the sum of SaaS and Utility Computing, but does not include Private Clouds. People can be users or providers of SaaS, or users or providers of Utility Computing.
The difference between a cloud and a grid can be expressed as below:
Resource distribution: Cloud computing is a centralized model whereas grid computing is a decentralized model where the computation could occur over many administrative domains.
Ownership: A grid is a collection of computers which is owned by multiple parties in multiple locations and connected together so that users can share the combined power of resources. Whereas a cloud is a collection of computers usually owned by a single party.
Examples of Clouds: Amazon Web Services (AWS), Google App Engine.
Examples of Grids: FutureGrid.
Examples of cloud computing services: Dropbox, Gmail, Facebook, Youtube, RapidShare.
Grid computing is where more than one computer coordinates to solve a problem together. Often used for problems involving a lot of number crunching, which can be easily parallelisable.
Cloud computing is where an application doesn't access resources it requires directly, rather it accesses them through something like a service. So instead of talking to a specific hard drive for storage, and a specific CPU for computation, etc. it talks to some service that provides these resources. The service then maps any requests for resources to its physical resources, in order to provide for the application. Usually the service has access to a large amount of physical resources, and can dynamically allocate them as they are needed.
In this way, if an application requires only a small amount of some resource, say computation, then the service only allocates a small amount, say on a single physical CPU (that may be shared with some other application using the service). If the application requires a large amount of some resource, then the service allocates that large amount, say a grid of CPUs. The application is relatively oblivious to this, and all the complex handling and coordination is performed by the service, not the application. In this way the application can scale well.
For example a web site written "on the cloud" may share a server with many other web sites while it has a low amount of traffic, but may be moved to its own dedicated server, or grid of servers, if it ever has massive amounts of traffic. This is all handled by the cloud service, so the application shouldn't have to be modified drastically to cope.
A cloud would usually use a grid. A grid is not necessarily a cloud or part of a cloud.
Wikipedia articles: Grid computing, Cloud computing.
$responseInfo = curl_getinfo($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$body = substr($response, $header_size);
$result=array();
$result['httpCode']=$httpCode;
$result['body']=json_decode($body);
$result['responseInfo']=$responseInfo;
print_r($httpCode);
print_r($result['body']); exit;
curl_close($ch);
if($httpCode == 403)
{
print_r("Access denied");
exit;
}
else
{
//catch more errors
}
Please read the following carefully. It should remove all your doubts regarding the difference between null
and undefined
in JavaScript. Also, you can use the utility function at the end of this answer to get more specific types of variables.
In JavaScript we can have the following types of variables:
undefined
null
undefined
or null
The following explains each of these cases one by one:
Undeclared Variables
typeof
operator which returns string 'undefined'== undefined
), let alone the strict equality operator ( === undefined
),? :
) — these throw Reference ErrorsDeclared but Unassigned Variables
typeof
returns string 'undefined'==
check with null
returns true
==
check with undefined
returns true
===
check with null
returns false
===
check with undefined
returns true
? :
)Variables assigned with literal undefined
These variables are treated exactly the same as Declared But Unassigned Variables.
Variables assigned with literal null
typeof
returns string 'object'==
check with null
returns true
==
check with undefined
returns true
===
check with null
returns true
===
check with undefined
returns false
? :
)Variables assigned with anything other than undefined
or null
Following provides the algorithm for correct type checking of a variable:
typeof
our variable and return it if it isn't 'object'null
, as typeof null
returns 'object' as wellObject
's toString
method returns strings that look like '[object ConstructorName]' for native/host objects. For all other objects (user-defined objects), it always returns '[object Object]'true
, it will try to get the name of the constructor by toString
-ing it and extracting the name from there. If the constructor can't be reached, 'object' is returned as usual. If the string doesn't contain its name, 'anonymous' is returned(supports all types up to ECMAScript 2020)
function TypeOf(o, returnConstructorBoolean) {
const type = typeof o
if (type !== 'object') return type
if (o === null) return 'null'
const toString = Object.prototype.toString.call(o)
switch (toString) {
// Value types: 6
case '[object BigInt]': return 'bigint'
case '[object Boolean]': return 'boolean'
case '[object Date]': return 'date'
case '[object Number]': return 'number'
case '[object String]': return 'string'
case '[object Symbol]': return 'symbol'
// Error types: 7
case '[object Error]': return 'error'
case '[object EvalError]': return 'evalerror'
case '[object RangeError]': return 'rangeerror'
case '[object ReferenceError]': return 'referenceerror'
case '[object SyntaxError]': return 'syntaxerror'
case '[object TypeError]': return 'typeerror'
case '[object URIError]': return 'urierror'
// Indexed Collection and Helper types: 13
case '[object Array]': return 'array'
case '[object Int8Array]': return 'int8array'
case '[object Uint8Array]': return 'uint8array'
case '[object Uint8ClampedArray]': return 'uint8clampedarray'
case '[object Int16Array]': return 'int16array'
case '[object Uint16Array]': return 'uint16array'
case '[object Int32Array]': return 'int32array'
case '[object Uint32Array]': return 'uint32array'
case '[object Float32Array]': return 'float32array'
case '[object Float64Array]': return 'float64array'
case '[object ArrayBuffer]': return 'arraybuffer'
case '[object SharedArrayBuffer]': return 'sharedarraybuffer'
case '[object DataView]': return 'dataview'
// Keyed Collection types: 2
case '[object Map]': return 'map'
case '[object WeakMap]': return 'weakmap'
// Set types: 2
case '[object Set]': return 'set'
case '[object WeakSet]': return 'weakset'
// Operation types: 3
case '[object RegExp]': return 'regexp'
case '[object Proxy]': return 'proxy'
case '[object Promise]': return 'promise'
// Plain objects
case '[object Object]':
if (!returnConstructorBoolean)
return type
const _prototype = Object.getPrototypeOf(o)
if (!_prototype)
return type
const _constructor = _prototype.constructor
if (!_constructor)
return type
const matches = Function.prototype.toString.call(_constructor).match(/^function\s*([^\s(]+)/)
return matches ? matches[1] : 'anonymous'
default: return toString.split(' ')[1].slice(0, -1)
}
}
As per Pipeline plugin tutorial:
If you have configured your pipeline to accept parameters when it is built — Build with Parameters — they are accessible as Groovy variables of the same name.
So try to access the variable directly, e.g.:
node()
{
print "DEBUG: parameter foo = " + foo
print "DEBUG: parameter bar = ${bar}"
}
A relatively short path to specifying a Powershell script to execute at startup in Windows could be:
shell:startup
Create a new shortcut by rightclick and in context menu choose menu item: New=>Shortcut
Create a shortcut to your script, e.g:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "C:\Users\someuser\Documents\WindowsPowerShell\Scripts\somesscript.ps1"
Note the use of -NoProfile In case you put a lot of initializing in your $profile file, it is inefficient to load this up to just run a Powershell script. The -NoProfile will skip loading your profile file and is smart to specify, if it is not necessary to run it before the Powershell script is to be executed.
Here you see such a shortcut created (.lnk file with a Powershell icon with shortcut glyph):
Here is a well tested function which i used for my projects with detailed self explanatory comments
There are many times when the ports other than 80 are blocked by server firewall so the code appears to be working fine on localhost but not on the server
function get_page($url){
global $proxy;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_HEADER, 0); // return headers 0 no 1 yes
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return page 1:yes
curl_setopt($ch, CURLOPT_TIMEOUT, 200); // http request timeout 20 seconds
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects, need this if the url changes
curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //if http server gives redirection responce
curl_setopt($ch, CURLOPT_USERAGENT,
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt"); // cookies storage / here the changes have been made
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // false for https
curl_setopt($ch, CURLOPT_ENCODING, "gzip"); // the page encoding
$data = curl_exec($ch); // execute the http request
curl_close($ch); // close the connection
return $data;
}
Another way (worked for 2015) is open "Install/remove programs" (Apps & features), find Visual Studio, select Modify. In opened window, press Modify, check
Languages -> Visual C++ -> Common tools for Visual C++
Windows and web development -> Tools for universal windows apps -> Tools (1.4.1)
and Windows 10 SDK ([version])
Windows and web development -> Tools for universal windows apps -> Windows 10 SDK ([version])
and install. Then right click on solution -> Re-target and it will compile
I did manage to figure it out:
$order_meta = get_post_meta($order_id);
$email = $order_meta["_shipping_email"][0] ?: $order_meta["_billing_email"][0];
I do know know for sure if the shipping email is part of the metadata, but if so I would rather have it than the billing email - at least for my purposes.
This is absolutely possible. Although you shouldn't do it unless you know what you are dealing with. Took me about 2 days to figure it out. Here is a stored procedure where i enter: ---database name (schema name is "_" for readability) ---table name ---column ---column data type (column added is always null, otherwise you won't be able to insert) ---the position of the new column.
Since I'm working with tables from SAM toolkit (and some of them have > 80 columns) , the typical variable won't be able to contain the query. That forces the need of external file. Now be careful where you store that file and who has access on NTFS and network level.
Cheers!
USE [master]
GO
/****** Object: StoredProcedure [SP_Set].[TrasferDataAtColumnLevel] Script Date: 8/27/2014 2:59:30 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [SP_Set].[TrasferDataAtColumnLevel]
(
@database varchar(100),
@table varchar(100),
@column varchar(100),
@position int,
@datatype varchar(20)
)
AS
BEGIN
set nocount on
exec ('
declare @oldC varchar(200), @oldCDataType varchar(200), @oldCLen int,@oldCPos int
create table Test ( dummy int)
declare @columns varchar(max) = ''''
declare @columnVars varchar(max) = ''''
declare @columnsDecl varchar(max) = ''''
declare @printVars varchar(max) = ''''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR
select column_name, data_type, character_maximum_length, ORDINAL_POSITION from ' + @database + '.INFORMATION_SCHEMA.COLUMNS where table_name = ''' + @table + '''
OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos WHILE @@FETCH_STATUS = 0 BEGIN
if(@oldCPos = ' + @position + ')
begin
exec(''alter table Test add [' + @column + '] ' + @datatype + ' null'')
end
if(@oldCDataType != ''timestamp'')
begin
set @columns += @oldC + '' , ''
set @columnVars += ''@'' + @oldC + '' , ''
if(@oldCLen is null)
begin
if(@oldCDataType != ''uniqueidentifier'')
begin
set @printVars += '' print convert('' + @oldCDataType + '',@'' + @oldC + '')''
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
end
else
begin
set @printVars += '' print convert(varchar(50),@'' + @oldC + '')''
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + '', ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + '' null'')
end
end
else
begin
if(@oldCLen < 0)
begin
set @oldCLen = 4000
end
set @printVars += '' print @'' + @oldC
set @columnsDecl += ''@'' + @oldC + '' '' + @oldCDataType + ''('' + convert(character,@oldCLen) + '') , ''
exec(''alter table Test add ['' + @oldC + ''] '' + @oldCDataType + ''('' + @oldCLen + '') null'')
end
end
if exists (select column_name from INFORMATION_SCHEMA.COLUMNS where table_name = ''Test'' and column_name = ''dummy'')
begin
alter table Test drop column dummy
end
FETCH NEXT FROM MY_CURSOR INTO @oldC, @oldCDataType, @oldCLen, @oldCPos END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR
set @columns = reverse(substring(reverse(@columns), charindex('','',reverse(@columns)) +1, len(@columns)))
set @columnVars = reverse(substring(reverse(@columnVars), charindex('','',reverse(@columnVars)) +1, len(@columnVars)))
set @columnsDecl = reverse(substring(reverse(@columnsDecl), charindex('','',reverse(@columnsDecl)) +1, len(@columnsDecl)))
set @columns = replace(replace(REPLACE(@columns, '' '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnVars = replace(replace(REPLACE(@columnVars, '' '', ''''), char(9) + char(9),'' ''), char(9), '''')
set @columnsDecl = replace(replace(REPLACE(@columnsDecl, '' '', ''''), char(9) + char(9),'' ''),char(9), '''')
set @printVars = REVERSE(substring(reverse(@printVars), charindex(''+'',reverse(@printVars))+1, len(@printVars)))
create table query (id int identity(1,1), string varchar(max))
insert into query values (''declare '' + @columnsDecl + ''
DECLARE MY_CURSOR CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY FOR '')
insert into query values (''select '' + @columns + '' from ' + @database + '._.' + @table + ''')
insert into query values (''OPEN MY_CURSOR FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' WHILE @@FETCH_STATUS = 0 BEGIN '')
insert into query values (@printVars )
insert into query values ( '' insert into Test ('')
insert into query values (@columns)
insert into query values ( '') values ( '' + @columnVars + '')'')
insert into query values (''FETCH NEXT FROM MY_CURSOR INTO '' + @columnVars + '' END CLOSE MY_CURSOR DEALLOCATE MY_CURSOR'')
declare @path varchar(100) = ''C:\query.sql''
declare @query varchar(500) = ''bcp "select string from query order by id" queryout '' + @path + '' -t, -c -S '' + @@servername + '' -T''
exec master..xp_cmdshell @query
set @query = ''sqlcmd -S '' + @@servername + '' -i '' + @path
EXEC xp_cmdshell @query
set @query = ''del '' + @path
exec xp_cmdshell @query
drop table ' + @database + '._.' + @table + '
select * into ' + @database + '._.' + @table + ' from Test
drop table query
drop table Test ')
END
You need to use cp -t /home/shantanu/tosend
in order to tell it that the argument is the target directory and not a source. You can then change it to -exec ... +
in order to get cp
to copy as many files as possible at once.
The answer was surprisingly simple. I had to add a Content-Type
header in the POST
request with a value of application/json
. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON)
annotation)!
You can use like this, it works!
WebProxy proxy = new WebProxy
{
Address = new Uri(""),
Credentials = new NetworkCredential("", "")
};
HttpClientHandler httpClientHandler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true
};
HttpClient client = new HttpClient(httpClientHandler);
HttpResponseMessage response = await client.PostAsync("...");
If you have an AVD, this might help.
Open the AVD Manager from Android Studio. Choose the dropdown in the right most of your device row. Then do Wipe Data. Restart your virtual device, and ADB will work.
function CurFocus()
{
$('.txtEmail').focus();
}
function pageLoad()
{
setTimeout(CurFocus(),3000);
}
window.onload = pageLoad;
You can access any DGV cell as follows :
dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;
But usually it's better to use databinding : you bind the DGV to a data source (DataTable
, collection...) through the DataSource
property, and only work on the data source itself. The DataGridView
will automatically reflect the changes, and changes made on the DataGridView
will be reflected on the data source
It leaves blank pages so that a new part or chapter start on the right-hand side. You can fix this with the "openany" option for the document class. ;)
You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources
will throw the exception :
// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");
// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception
Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");
Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.
By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.
Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.
Hope that helps.
Regards
JSDoc 3 allows you to annotate your functions with the @access private
(previously the @private
tag) which is also useful for broadcasting your intent to other developers - http://usejsdoc.org/tags-access.html
For your first array example use,
a = numpy.arange(5)
To initialize big_array, use
big_array = numpy.zeros((10,4))
This assumes you want to initialize with zeros, which is pretty typical, but there are many other ways to initialize an array in numpy.
Edit:
If you don't know the size of big_array in advance, it's generally best to first build a Python list using append, and when you have everything collected in the list, convert this list to a numpy array using numpy.array(mylist)
. The reason for this is that lists are meant to grow very efficiently and quickly, whereas numpy.concatenate would be very inefficient since numpy arrays don't change size easily. But once everything is collected in a list, and you know the final array size, a numpy array can be efficiently constructed.
Not sure what you're trying to select in the query, but keep in mind that UNIX_TIMESTAMP()
without arguments returns the time now. You should probably provide a valid time as argument, or change the condition.
EDIT:
Here is an example of a time bound query based on the question:
PreparedStatement statement = con
.prepareStatement("select * from orders where status='Q' AND date > ?");
Date date = new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2000");
statement.setDate(1, new java.sql.Date(date.getTime()));
EDIT: timestamp column
In case of timestamp use java.sql.Timestamp
and PreparedStatement.setTimestamp(), ie:
PreparedStatement statement = con
.prepareStatement("select * from orders where status='Q' AND date > ?");
Date date = new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2000");
Timestamp timestamp = new Timestamp(date.getTime());
statement.setTimestamp(1, timestamp);
The size()
method returns the number of elements in the ArrayList. The index values of the elements are 0
through (size()-1)
, so you would use myArrayList.get(myArrayList.size()-1)
to retrieve the last element.
describe
may give you everything you want otherwise you can perform aggregations using groupby and pass a list of agg functions: http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once
In [43]:
df.describe()
Out[43]:
shopper_num is_martian number_of_items count_pineapples
count 14.0000 14 14.000000 14
mean 7.5000 0 3.357143 0
std 4.1833 0 6.452276 0
min 1.0000 False 0.000000 0
25% 4.2500 0 0.000000 0
50% 7.5000 0 0.000000 0
75% 10.7500 0 3.500000 0
max 14.0000 False 22.000000 0
[8 rows x 4 columns]
Note that some columns cannot be summarised as there is no logical way to summarise them, for instance columns containing string data
As you prefer you can transpose the result if you prefer:
In [47]:
df.describe().transpose()
Out[47]:
count mean std min 25% 50% 75% max
shopper_num 14 7.5 4.1833 1 4.25 7.5 10.75 14
is_martian 14 0 0 False 0 0 0 False
number_of_items 14 3.357143 6.452276 0 0 0 3.5 22
count_pineapples 14 0 0 0 0 0 0 0
[4 rows x 8 columns]
Another approach is to create an association table that contains columns for each potential resource type. In your example, each of the two existing owner types has their own table (which means you have something to reference). If this will always be the case you can have something like this:
CREATE TABLE dbo.Group
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.User
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.Ticket
(
ID int NOT NULL,
Owner_ID int NOT NULL,
Subject varchar(50) NULL
)
CREATE TABLE dbo.Owner
(
ID int NOT NULL,
User_ID int NULL,
Group_ID int NULL,
{{AdditionalEntity_ID}} int NOT NULL
)
With this solution, you would continue to add new columns as you add new entities to the database and you would delete and recreate the foreign key constraint pattern shown by @Nathan Skerl. This solution is very similar to @Nathan Skerl but looks different (up to preference).
If you are not going to have a new Table for each new Owner type then maybe it would be good to include an owner_type instead of a foreign key column for each potential Owner:
CREATE TABLE dbo.Group
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.User
(
ID int NOT NULL,
Name varchar(50) NOT NULL
)
CREATE TABLE dbo.Ticket
(
ID int NOT NULL,
Owner_ID int NOT NULL,
Owner_Type string NOT NULL, -- In our example, this would be "User" or "Group"
Subject varchar(50) NULL
)
With the above method, you could add as many Owner Types as you want. Owner_ID would not have a foreign key constraint but would be used as a reference to the other tables. The downside is that you would have to look at the table to see what the owner types there are since it isn't immediately obvious based upon the schema. I would only suggest this if you don't know the owner types beforehand and they won't be linking to other tables. If you do know the owner types beforehand, I would go with a solution like @Nathan Skerl.
Sorry if I got some SQL wrong, I just threw this together.
ctrl != super on windows and linux machines.
If the F12 version of "Goto Definition" produces results of several files, the "ctrl + shift + click" version might not work well. I found that bug when viewing golang project with GoSublime package.
I want to handle passing multiple lists, integer values and strings.
Helpful link => How to pass a Bash variable to Python?
def main(args):
my_args = []
for arg in args:
if arg.startswith("[") and arg.endswith("]"):
arg = arg.replace("[", "").replace("]", "")
my_args.append(arg.split(","))
else:
my_args.append(arg)
print(my_args)
if __name__ == "__main__":
import sys
main(sys.argv[1:])
Order is not important. If you want to pass a list just do as in between "["
and "]
and seperate them using a comma.
Then,
python test.py my_string 3 "[1,2]" "[3,4,5]"
Output => ['my_string', '3', ['1', '2'], ['3', '4', '5']]
, my_args
variable contains the arguments in order.
There are numerous caveats in the javadoc for the toFront() method which may be causing your problem.
But I'll take a guess anyway, when "only the tab in the taskbar flashes", has the application been minimized? If so the following line from the javadoc may apply:
"If this Window is visible, brings this Window to the front and may make it the focused Window."
Install mysysgit. (Same as Greg Hewgill's answer.)
Install Tortoisegit. (Tortoisegit requires mysysgit or something similiar like Cygwin.)
After TortoiseGit is installed, right-click on a folder, select Git Clone..., then enter the Url of the repository, then click Ok.
This answer is not any better than just installing mysysgit, but you can avoid the dreaded command line. :)
Simple answer is :
$('#first').select2().val()
and you can write by this way also:
$('#first').val()
If you're trying to get the integers from the command line args, you'll need something like this:
public static void main(String[] args) {
int[] nums = new int[args.length];
for(int i = 0; i < args.length; i++) {
try {
nums[i] = Integer.parseInt(args[i]);
}
catch(NumberFormatException nfe) {
System.err.println("Invalid argument");
}
}
// averaging code here
}
As for the actual averaging code, others have suggested how you can tweak that (so I won't repeat what they've said).
Edit: actually it's probably better to just put it inside the above loop and not use the nums
array at all
By combining all the given answers, this method should work on all environments:
public static void clearConsole() {
try {
if (System.getProperty("os.name").contains("Windows")) {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
else {
System.out.print("\033\143");
}
} catch (IOException | InterruptedException ex) {}
}
public void addNotification()
{
NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(MainActivity.this);
mBuilder.setSmallIcon(R.drawable.email);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi,This notification for you let me check");
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent conPendingIntent = PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(conPendingIntent);
NotificationManager manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0,mBuilder.build());
Toast.makeText(MainActivity.this, "Notification", Toast.LENGTH_SHORT).show();
}
You need to provide a candidate for autowire. That means that an instance of PasswordHint must be known to spring in a way that it can guess that it must reference it.
Please provide the class head of PasswordHint and/or the spring bean definition of that class for further assistance.
Try changing the name of
PasswordHintAction action;
to
PasswordHintAction passwordHintAction;
so that it matches the bean definition.
Both answers were good so I moved them in to a directive so that it is reusable and a second scope variable doesn't have to be defined.
Here is the fiddle if you want to see it implemented
Below is the directive:
var uniqueItems = function (data, key) {
var result = [];
for (var i = 0; i < data.length; i++) {
var value = data[i][key];
if (result.indexOf(value) == -1) {
result.push(value);
}
}
return result;
};
myApp.filter('groupBy',
function () {
return function (collection, key) {
if (collection === null) return;
return uniqueItems(collection, key);
};
});
Then it can be used as follows:
<div ng-repeat="team in players|groupBy:'team'">
<b>{{team}}</b>
<li ng-repeat="player in players | filter: {team: team}">{{player.name}}</li>
</div>
The following SQL lists all object dependencies across all databases and servers:
IF(OBJECT_ID('tempdb..#Obj_Dep_Details') IS NOT NULL)
BEGIN
DROP TABLE #Obj_Dep_Details
END
CREATE TABLE #Obj_Dep_Details
(
[Database] nvarchar(128)
,[Schema] nvarchar(128)
,dependent_object nvarchar(128)
,dependent_object_type nvarchar(60)
,referenced_server_name nvarchar(128)
,referenced_database_name nvarchar(128)
,referenced_schema_name nvarchar(128)
,referenced_entity_name nvarchar(128)
,referenced_id int
,referenced_object_db nvarchar(128)
,referenced_object_type nvarchar(60)
,referencing_id int
,SchemaDep nvarchar(128)
)
EXEC sp_MSForEachDB @command1='USE [?];
INSERT INTO #Obj_Dep_Details
SELECT DISTINCT
DB_NAME() AS [Database]
,SCHEMA_NAME(od.[schema_id]) AS [Schema]
,OBJECT_NAME(d1.referencing_id) AS dependent_object
,od.[type_desc] AS dependent_object_type
,COALESCE(d1.referenced_server_name, @@SERVERNAME) AS referenced_server_name
,COALESCE(d1.referenced_database_name, DB_NAME()) AS referenced_database_name
,COALESCE(d1.referenced_schema_name, SCHEMA_NAME(ro.[schema_id])) AS referenced_schema_name
,d1.referenced_entity_name
,d1.referenced_id
,DB_NAME(ro.parent_object_id) AS referenced_object_db
,ro.[type_desc] AS referenced_object_type
,d1.referencing_id
,SCHEMA_NAME(od.[schema_id]) AS SchemaDep
FROM sys.sql_expression_dependencies d1
LEFT OUTER JOIN sys.all_objects od
ON d1.referencing_id = od.[object_id]
LEFT OUTER JOIN sys.objects ro
ON d1.referenced_id = ro.[object_id]'
SELECT [Database] AS [Dep_Object_DB]
,[Schema] AS [Dep_Object_Schema]
,dependent_object AS [Dep_Object_Name]
,LOWER(REPLACE(dependent_object_type, '_', ' ')) AS [Dep_Object_Type]
,referenced_server_name AS [Ref_Object_Server_Name]
,referenced_database_name AS [Ref_Object_DB]
,referenced_schema_name AS [Ref_Object_Schema]
,referenced_entity_name AS [Ref_Object_Name]
,referenced_id AS [Ref_Object_ID]
,LOWER(REPLACE(referenced_object_type, '_', ' ')) AS [Ref_Object_Type]
,referencing_id AS [Dep_Object_ID]
FROM #Obj_Dep_Details WITH(NOLOCK)
WHERE referenced_entity_name = 'TableName'
ORDER BY [Dep_Object_DB]
,[Dep_Object_Name]
,[Ref_Object_Name]
,[Ref_Object_DB]
Yes, you'll need to use pseudo elements AND pseudo selectors: http://jsfiddle.net/cYky9/
See the mysql manual, Unicode Character Sets section:
For any Unicode character set, operations performed using the _general_ci collation are faster than those for the _unicode_ci collation. For example, comparisons for the utf8_general_ci collation are faster, but slightly less correct, than comparisons for utf8_unicode_ci. The reason for this is that utf8_unicode_ci supports mappings such as expansions; that is, when one character compares as equal to combinations of other characters. For example, in German and some other languages “ß” is equal to “ss”. utf8_unicode_ci also supports contractions and ignorable characters. utf8_general_ci is a legacy collation that does not support expansions, contractions, or ignorable characters. It can make only one-to-one comparisons between characters.
So to summarize, utf_general_ci uses a smaller and less correct (according to the standard) set of comparisons than utf_unicode_ci which should implement the entire standard. The general_ci set will be faster because there is less computation to do.
int
is a primitive data type while Integer
is a Reference or Wrapper Type (Class) in Java.
after java 1.5
which introduce the concept of autoboxing and unboxing you can initialize both int
or Integer
like this.
int a= 9
Integer a = 9 // both valid After Java 1.5.
why
Integer.parseInt("1");
but notint.parseInt("1");
??
Integer
is a Class defined in jdk
library and parseInt()
is a static method belongs to Integer
Class
So, Integer.parseInt("1");
is possible in java. but int
is primitive type (assume like a keyword) in java. So, you can't call parseInt()
with int
.
I like sehe's answer, but it does not use deferred execution (the input sequences are eagerly enumerated by the calls to ToLookup). So after looking at the .NET sources for LINQ-to-objects, I came up with this:
public static class LinqExtensions
{
public static IEnumerable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
this IEnumerable<TLeft> left,
IEnumerable<TRight> right,
Func<TLeft, TKey> leftKeySelector,
Func<TRight, TKey> rightKeySelector,
Func<TLeft, TRight, TKey, TResult> resultSelector,
IEqualityComparer<TKey> comparator = null,
TLeft defaultLeft = default(TLeft),
TRight defaultRight = default(TRight))
{
if (left == null) throw new ArgumentNullException("left");
if (right == null) throw new ArgumentNullException("right");
if (leftKeySelector == null) throw new ArgumentNullException("leftKeySelector");
if (rightKeySelector == null) throw new ArgumentNullException("rightKeySelector");
if (resultSelector == null) throw new ArgumentNullException("resultSelector");
comparator = comparator ?? EqualityComparer<TKey>.Default;
return FullOuterJoinIterator(left, right, leftKeySelector, rightKeySelector, resultSelector, comparator, defaultLeft, defaultRight);
}
internal static IEnumerable<TResult> FullOuterJoinIterator<TLeft, TRight, TKey, TResult>(
this IEnumerable<TLeft> left,
IEnumerable<TRight> right,
Func<TLeft, TKey> leftKeySelector,
Func<TRight, TKey> rightKeySelector,
Func<TLeft, TRight, TKey, TResult> resultSelector,
IEqualityComparer<TKey> comparator,
TLeft defaultLeft,
TRight defaultRight)
{
var leftLookup = left.ToLookup(leftKeySelector, comparator);
var rightLookup = right.ToLookup(rightKeySelector, comparator);
var keys = leftLookup.Select(g => g.Key).Union(rightLookup.Select(g => g.Key), comparator);
foreach (var key in keys)
foreach (var leftValue in leftLookup[key].DefaultIfEmpty(defaultLeft))
foreach (var rightValue in rightLookup[key].DefaultIfEmpty(defaultRight))
yield return resultSelector(leftValue, rightValue, key);
}
}
This implementation has the following important properties:
These properties are important, because they are what someone new to FullOuterJoin but experienced with LINQ will expect.
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
You might try following function:
<script type="text/javascript">
function open(url)
{
var popup = window.open(url, "_blank", "width=200, height=200") ;
popup.location = URL;
}
</script>
The HTML code for execution:
<a href="#" onclick="open('http://www.google.com')">google search</a>
There are also new kids on the block!
If you need a more in-depth comparison please read this and you may end up using docopt or click. Thanks to Kyle Purdon!
You can create your own JSONObject
then toString()
.
Remember run it in the background thread like doInBackground
in AsyncTask
.
OkHttp version > 4:
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build()
var response: Response? = null
try {
response = client.newCall(request).execute()
val resStr = response.body!!.string()
} catch (e: IOException) {
e.printStackTrace()
}
OkHttp version 3:
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// put your json here
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
Use the following command before defining them:
cmd.Parameters.Clear()
Think of it like an archive. MyDB.Bak contains MyDB.mdf and MyDB.ldf.
Restore with Move to say HerDB basically grabs MyDB.mdf (and ldf) from the back up, and copies them as HerDB.mdf and ldf.
So if you already had a MyDb on the server instance you are restoring to it wouldn't be touched.
put this in your php page.
ini_set("error_reporting", E_ALL & ~E_DEPRECATED);
In Python 3, this question doesn't apply. The plain int
type is unbounded.
However, you might actually be looking for information about the current interpreter's word size, which will be the same as the machine's word size in most cases. That information is still available in Python 3 as sys.maxsize
, which is the maximum value representable by a signed word. Equivalently, it's the size of the largest possible list or in-memory sequence.
Generally, the maximum value representable by an unsigned word will be sys.maxsize * 2 + 1
, and the number of bits in a word will be math.log2(sys.maxsize * 2 + 2)
. See this answer for more information.
In Python 2, the maximum value for plain int
values is available as sys.maxint
:
>>> sys.maxint
9223372036854775807
You can calculate the minimum value with -sys.maxint - 1
as shown here.
Python seamlessly switches from plain to long integers once you exceed this value. So most of the time, you won't need to know it.
If you're using node:
values.js
:export let someValues = {
value1: 0
}
Then just import it as needed at the top of each file it's used in (e.g., file.js
):
import { someValues } from './values'
console.log(someValues);
After "AND" and after "OR" the QUERY has forgotten what it is all about.
I would also not know that it is about in any SQL / programming language.
if(SOMETHING equals "X" or SOMETHING equals "Y")
COLUMN NOT LIKE "A%" AND COLUMN NOT LIKE "B%"
You can use replace
instead of gsub
.
"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
Slightly more than just displaying the function, how about getting the edit in-place facility as well.
\ef <function_name>
is very handy. It will open the source code of the function in editable format.
You will not only be able to view it, you can edit and execute it as well.
Just \ef
without function_name will open editable CREATE FUNCTION template.
For further reference -> https://www.postgresql.org/docs/9.6/static/app-psql.html
You can find the answer here: http://www.dorusomcutean.com/how-to-install-php-7-2-on-windows/
In that blog post, I'm showing how to install PHP on Windows and how to enable extensions. Hope that it helps anyone who encounters this problem again.
I don't know if this is still a current issue or not but I just encountered the same problem and used the CSS display: inline-block;
tag.
Wrapping these in a div so that they can be positioned appropriately.
<div>
<div style="display: inline-block;">Content1</div>
<div style="display: inline-block;">Content2</div>
</div>
Note that the use of the inline style attribute was only used for the succinctness of this example of course these used be moved to an external CSS file.
Use crosstab()
from the tablefunc module.
SELECT * FROM crosstab(
$$SELECT user_id, user_name, rn, email_address
FROM (
SELECT u.user_id, u.user_name, e.email_address
, row_number() OVER (PARTITION BY u.user_id
ORDER BY e.creation_date DESC NULLS LAST) AS rn
FROM usr u
LEFT JOIN email_tbl e USING (user_id)
) sub
WHERE rn < 4
ORDER BY user_id
$$
, 'VALUES (1),(2),(3)'
) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);
I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:
Detailed explanation and instructions here:
And in particular, for "extra columns":
The special difficulties here are:
The lack of key names.
-> We substitute with row_number()
in a subquery.
The varying number of emails.
-> We limit to a max. of three in the outer SELECT
and use crosstab()
with two parameters, providing a list of possible keys.
Pay attention to NULLS LAST
in the ORDER BY
.
Try this:
<input type="number" max="???" min="???" step="0.5" id="myInput"/>
$("#myInput").attr({
"max" : 10,
"min" : 2
});
Note:This will set max and min value only to single input
Try with below logic
driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");
List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));
for(WebElement ele :allElements) {
System.out.println("Name + Number===>"+ele.getText());
String s=ele.getText();
s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
System.out.println("Number==>"+s);
}
====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemedelské objekty (5)
Number==>5
Name + Number===>Komercní objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22
you cannot disable a link, if you want that click event should not fire then simply Remove
the action
from that link.
$(td).find('a').attr('href', '');
For More Info :- Elements that can be Disabled
You could try this:
git reset --hard HEAD
git pull
(from How do I force "git pull" to overwrite local files?)
Another idea would be to delete the entire git and make a new clone.
<div id="normal>text..</div>
<div id="small1" class="smallDiv"></div>
<div id="small2" class="smallDiv"></div>
<div id="small3" class="smallDiv"></div>
css:
.smallDiv { height: 150px; width: 150px; }
try {
InputStream connInputStream = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
int size = connInputStream.available();
int available () Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.
VB.net, Desktop application. If you need lapsed time in milliseconds:
Dim starts As Integer = My.Computer.Clock.TickCount
Dim ends As Integer = My.Computer.Clock.TickCount
Dim lapsed As Integer = ends - starts
You get "close existing connections to destination database" option only in "Databases context >> Restore Wizard" and NOT ON context of any particular database.
Right Click on the Databases under your Server-Name as shown below:
and select the option: "Restore Database..." from it.
In the "Restore Database" wizard,
Here you can find the checkbox saying, "close existing connections to destination database"
Just check it, and you can proceed for the restore operation.
It automatically will resume all connections after completion of the Restore.
Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede), go to
Window->Preferences->Java->Editor->Content Assist
and check the checkbox for Use static imports (only 1.5 or higher).
This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (CTRL + 1) on the line it will give you the option to add the static import which is good enough.
There are multiple possible causes for this error:
1) When you put the property 'x' inside brackets you are trying to bind to it. Therefore first thing to check is if the property 'x' is defined in your component with an Input()
decorator
Your html file:
<body [x]="...">
Your class file:
export class YourComponentClass {
@Input()
x: string;
...
}
(make sure you also have the parentheses)
2) Make sure you registered your component/directive/pipe classes in NgModule:
@NgModule({
...
declarations: [
...,
YourComponentClass
],
...
})
See https://angular.io/guide/ngmodule#declare-directives for more details about declare directives.
3) Also happens if you have a typo in your angular directive. For example:
<div *ngif="...">
^^^^^
Instead of:
<div *ngIf="...">
This happens because under the hood angular converts the asterisk syntax to:
<div [ngIf]="...">
Also struggled with this issue, trying to upload .csv data into AWS RDS instance from my local machine using MySQL Workbench on Windows.
The addition I needed was adding OPT_LOCAL_INFILE=1
in: Connection > Advanced > Others. Note CAPS was required.
I found this answer by PeterMag in AWS Developer Forums.
For further info:
SHOW VARIABLES LIKE 'local_infile';
already returned ON
and the query was:
LOAD DATA LOCAL INFILE 'filepath/file.csv'
INTO TABLE `table_name`
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
Copying from the answer source referenced above:
Apparently this is a bug in MYSQL Workbench V8.X. In addition to the configurations shown earlier in this thread, you also need to change the MYSQL Connection in Workbench as follows:
- Go to the Welcome page of MYSQL which displays all your connections
- Select Manage Server Connections (the little spanner icon)
- Select your connection
- Select Advanced tab
- In the Others box, add OPT_LOCAL_INFILE=1
Now I can use the LOAD DATA LOCAL INFILE query on MYSQL RDS. It seems that the File_priv permission is not required.*
To Print key-value pair, for example:
players = {
'lebron': 'lakers',
'giannis': 'milwakee bucks',
'durant': 'brooklyn nets',
'kawhi': 'clippers',
}
for player,club in players.items():
print(f"\n{player.title()} is the leader of {club}")
The above code, key-value pair:
'lebron': 'lakers', - Lebron is key and lakers is value
for loop - specify key, value in dictionary.item():
Now Print (Player Name is the leader of club).
the Output is:
#Lebron is the leader of lakers
#Giannis is the leader of milwakee bucks
#Durant is the leader of brooklyn nets
#Kawhi is the leader of clippers
I have wrote my own library on Python to expand variables being loaded from directories with a hierarchy like:
/root
|
+- /proj1
|
+- config.yaml
|
+- /proj2
|
+- config.yaml
|
... and so on ...
The key difference here is that the expansion must be applied only after all the config.yaml
files is loaded, where the variables from the next file can override the variables from the previous, so the pseudocode should look like this:
env = YamlEnv()
env.load('/root/proj1/config.yaml')
env.load('/root/proj1/proj2/config.yaml')
...
env.expand()
As an additional option the xonsh
script can export the resulting variables into environment variables (see the yaml_update_global_vars
function).
The scripts:
https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/cmdoplib.yaml.py https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/cmdoplib.yaml.xsh
Pros:
${MYUNDEFINEDVAR}
-> *$/{MYUNDEFINEDVAR}
)${env:MYVAR}
)\\
to /
in a path variable (${env:MYVAR:path}
)Cons:
${MYSCOPE.MYVAR}
is not implemented)Or use JodaTime:
DateTime lastWeek = new DateTime().minusDays(7);
You can use the built in divider, this will work for both orientations.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="?android:attr/listDivider"
android:orientation="horizontal"
android:showDividers="middle">
Here is an AngularJS solution using ng-keyup if anyone has the same issue using AngularJS.
ng-keyup="$event.keyCode == 13 && !$event.shiftKey && myFunc()"
if (version_compare(phpversion(), '5.4.0', '<')) {
if(session_id() == '') {
session_start();
}
}
else
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
Here I've created a second empty array and used for
loop with the first array which is having duplicates. It will run as many time as the count of the first array. Then compared with the position of the array with the first array and matched that it has this item already or not by using in_array
. If not then it'll add that item to second array with array_push
.
$a = array(1,2,3,1,3,4,5);
$count = count($a);
$b = [];
for($i=0; $i<$count; $i++){
if(!in_array($a[$i], $b)){
array_push($b, $a[$i]);
}
}
print_r ($b);
Actually, as far as I know, nginx would show an empty message and it wouldn't actually restart if the configuration is bad.
The only way to screw it up is by doing an nginx stop and then start again. It would succeed to stop, but fail to start.
In codeigniter you can't pass parameters in the url as you are doing in core php.So remove the "?" and "product_id" and simply pass the id.If you want more security you can encrypt the id and pass it.
foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"
This works because the #
operator computes the length of the list. The empty list has length 0, etc.
If you're using Lua 5.3+, then you can do almost exactly what you wanted:
foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"
Expressions are not statements in Lua and they need to be used somehow.
By default, android will match the progress color of your slider to
`<item name="colorAccent">`
value in your styles.xml. Then, to set a custom slider thumb image, just use this code in your SeekBar xml layout's block:
android:thumb="@drawable/slider"
Install package : Microsoft.AspNet.WebApi.Cors
go to : App_Start --> WebApiConfig
Add :
var cors = new EnableCorsAttribute("http://localhost:4200", "", ""); config.EnableCors(cors);
Note : If you add '/' as end of the particular url not worked for me.
It depends on how the code in the first file is structured.
If it's just a bunch of functions, like:
# first.py
def foo(): print("foo")
def bar(): print("bar")
Then you could import it and use the functions as follows:
# second.py
import first
first.foo() # prints "foo"
first.bar() # prints "bar"
or
# second.py
from first import foo, bar
foo() # prints "foo"
bar() # prints "bar"
or, to import all the names defined in first.py:
# second.py
from first import *
foo() # prints "foo"
bar() # prints "bar"
Note: This assumes the two files are in the same directory.
It gets a bit more complicated when you want to import names (functions, classes, etc) from modules in other directories or packages.
I am beginner to iOS development so I would like to share whole info I got in this section.
First from image assets (images.xcassets) create image set .
According to Documentation here is all sizes need to create background image.
For iPhone 5:
640 x 1136
For iPhone 6:
750 x 1334 (@2x) for portrait
1334 x 750 (@2x) for landscape
For iPhone 6 Plus:
1242 x 2208 (@3x) for portrait
2208 x 1242 (@3x) for landscape
iPhone 4s (@2x)
640 x 960
iPad and iPad mini (@2x)
1536 x 2048 (portrait)
2048 x 1536 (landscape)
iPad 2 and iPad mini (@1x)
768 x 1024 (portrait)
1024 x 768 (landscape)
iPad Pro (@2x)
2048 x 2732 (portrait)
2732 x 2048 (landscape)
call the image background we can call image from image assets by using this method UIImage(named: "background")
here is full code example
override func viewDidLoad() {
super.viewDidLoad()
assignbackground()
// Do any additional setup after loading the view.
}
func assignbackground(){
let background = UIImage(named: "background")
var imageView : UIImageView!
imageView = UIImageView(frame: view.bounds)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
imageView.image = background
imageView.center = view.center
view.addSubview(imageView)
self.view.sendSubviewToBack(imageView)
}
I couldn't find a way to inject and use the $routeParams
service (which I would assume would be a better solution) I tried this thinking it might work:
angular.module('myApp', []).
config(function ($routeProvider, $routeParams) {
$routeProvider.when('/:primaryNav/:secondaryNav', {
templateUrl: 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html'
});
});
Which yielded this error:
Unknown provider: $routeParams from myApp
If something like that isn't possible you can change your templateUrl
to point to a partial HTML file that just has ng-include
and then set the URL in your controller using $routeParam
s like this:
angular.module('myApp', []).
config(function ($routeProvider) {
$routeProvider.when('/:primaryNav/:secondaryNav', {
templateUrl: 'resources/angular/templates/nav/urlRouter.html',
controller: 'RouteController'
});
});
function RouteController($scope, $routeParams) {
$scope.templateUrl = 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html';
}
With this as your urlRouter.html
<div ng-include src="templateUrl"></div>
Flexbox is a modern alternative that lets you do this without fixed heights or JavaScript.
Setting display: flex; flex-direction: column;
on the container and flex-shrink: 0;
on the header and footer divs does the trick:
HTML:
<div id="body">
<div id="head">
<p>Dynamic size without scrollbar</p>
<p>Dynamic size without scrollbar</p>
<p>Dynamic size without scrollbar</p>
</div>
<div id="content">
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
<p>Dynamic size with scrollbar</p>
</div>
<div id="foot">
<p>Fixed size without scrollbar</p>
<p>Fixed size without scrollbar</p>
</div>
</div>
CSS:
#body {
position: absolute;
top: 150px;
left: 150px;
height: 300px;
width: 500px;
border: black dashed 2px;
display: flex;
flex-direction: column;
}
#head {
border: green solid 1px;
flex-shrink: 0;
}
#content{
border: red solid 1px;
overflow-y: auto;
/*height: 100%;*/
}
#foot {
border: blue solid 1px;
height: 50px;
flex-shrink: 0;
}
You can use the REST-API's "Item last modified". From the docs, it retuns something like this:
GET /api/storage/libs-release-local/org/acme?lastModified
{
"uri": "http://localhost:8081/artifactory/api/storage/libs-release-local/org/acme/foo/1.0-SNAPSHOT/foo-1.0-SNAPSHOT.pom",
"lastModified": ISO8601
}
Example:
# Figure out the URL of the last item modified in a given folder/repo combination
url=$(curl \
-H 'X-JFrog-Art-Api: XXXXXXXXXXXXXXXXXXXX' \
'http://<artifactory-base-url>/api/storage/<repo>/<folder>?lastModified' | jq -r '.uri')
# Figure out the name of the downloaded file
downloaded_filename=$(echo "${url}" | sed -e 's|[^/]*/||g')
# Download the file
curl -L -O "${url}"
FYI, I needed to update the color of the calendar icon which didn't seem possible with properties like color
, fill
, etc.
I did eventually figure out that some filter
properties will adjust the icon so while i did not end up figuring out how to make it any color, luckily all I needed was to make it so the icon was visible on a dark background so I was able to do the following:
body { background: black; }_x000D_
_x000D_
input[type="date"] { _x000D_
background: transparent;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
filter: invert(100%);_x000D_
}
_x000D_
<body>_x000D_
<input type="date" />_x000D_
</body>
_x000D_
Hopefully this helps some people as for the most part chrome even directly says this is impossible.
The simplest approach would be to edit the webserver, most likely an Apache2 installation, configuration and give phpmyadmin a different name.
A second approach would be to limit the IP addresses from where phpmyadmin may be accessed (e.g. only local lan or localhost).
I tried all of these suggestions and more, just so I could git clone from my AWS instance. Nothing worked. I finally cheated out of desperation: I copied the contents of id_rsa.pub on my local machine and appended it to ~/.ssh/known_hosts on my AWS instance.
If you want to keep the height of the DIV absolute, regardless of the amount of text inside use the following:
overflow: hidden;
From the source code (decompiled) :
public String trim()
{
int i = this.count;
int j = 0;
int k = this.offset;
char[] arrayOfChar = this.value;
while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
++j;
while ((j < i) && (arrayOfChar[(k + i - 1)] <= ' '))
--i;
return (((j > 0) || (i < this.count)) ? substring(j, i) : this);
}
The two while
that you can see mean all the characters whose unicode is below the space character's, at beginning and end, are removed.
Using the SQL CASE statement with the dplyr and sqldf packages:
Data
df <-structure(list(idnat = structure(c(2L, 2L, 2L, 1L), .Label = c("foreign",
"french"), class = "factor"), idbp = structure(c(3L, 1L, 4L,
2L), .Label = c("colony", "foreign", "mainland", "overseas"), class = "factor")), .Names = c("idnat",
"idbp"), class = "data.frame", row.names = c(NA, -4L))
sqldf
library(sqldf)
sqldf("SELECT idnat, idbp,
CASE
WHEN idbp IN ('colony', 'overseas') THEN 'overseas'
ELSE idbp
END AS idnat2
FROM df")
dplyr
library(dplyr)
df %>%
mutate(idnat2 = case_when(.$idbp == 'mainland' ~ "mainland",
.$idbp %in% c("colony", "overseas") ~ "overseas",
TRUE ~ "foreign"))
Output
idnat idbp idnat2
1 french mainland mainland
2 french colony overseas
3 french overseas overseas
4 foreign foreign foreign
As I happened to be poorly satisfied by dos2unix, I rolled out my own simple utility. Apart of a few advantages in speed and predictability, the syntax is also a bit simpler :
endlines unix *
And if you want it to go down into subdirectories (skipping hidden dirs and non-text files) :
endlines unix -r .
endlines
is available here https://github.com/mdolidon/endlines
<%= f.submit 'name of button here', :class => 'submit_class_name_here' %>
This should do. If you're getting an error, chances are that you're not supplying the name.
Alternatively, you can style the button without a class:
form#form_id_here input[type=submit]
Try that, as well.
Contacts.add(objt.Data(name, address, contact));
This is not a perfect way to call a constructor. The constructor is called at the time of object creation automatically. If there is no constructor java class creates its own constructor.
The correct way is:
// object creation.
Data object1 = new Data(name, address, contact);
// adding Data object to ArrayList object Contacts.
Contacts.add(object1);
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
Gmail: OAuth
Client ID
and Secret ID
. Finally click OK to close the credentials pop up.Google API
. Click on Overview in the left pane.Google API
under Social APIs section.That’s all from the Google part.
Come back to your application, open App_start/Startup.Auth.cs
and uncomment the following snippet
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "",
ClientSecret = ""
});
Update the ClientId
and ClientSecret
with the values from Google API
credentials which you have created already.
Gmail
id.Gmail
id into your application database.This is a long-standing "feature" of the list controls in .NET in my experience. Personally, I would just bind to the on change of the SelectedValue property and write whatever additional code is necessary to workaround this "feature" (such as having two properties, binding to one for SelectedValue, and then, on the set of that property, updating the value from SelectedItem in your custom code).
Anyway, I hope that helps =D
What about WebMatrix: http://www.microsoft.com/web/webmatrix/ ?
A little more readable :)
public static <T> ArrayList<T> reverse(ArrayList<T> list) {
int length = list.size();
ArrayList<T> result = new ArrayList<T>(length);
for (int i = length - 1; i >= 0; i--) {
result.add(list.get(i));
}
return result;
}
When using MVC in .NET with Angular you can always use OrderByDecending() when doing your db query like this:
var reversedList = dbContext.GetAll().OrderByDecending(x => x.Id).ToList();
Then on the Angular side, it will already be reversed in some browsers (IE). When supporting Chrome and FF, you would then need to add orderBy:
<tr ng-repeat="item in items | orderBy:'-Id'">
In this example, you'd be sorting in descending order on the .Id property. If you're using paging, this gets more complicated because only the first page would be sorted. You'd need to handle this via a .js filter file for your controller, or in some other way.
@model AdventureWork.CRUD.WebApp4.Models.EmployeeViewModel
@{
ViewBag.Title = "Detalle";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Ingresar Usuario</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonType, labelText: "Tipo de Persona", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.PersonType, new List<SelectListItem>
{
new SelectListItem{ Text= "SC", Value = "SC" },
new SelectListItem{ Text= "VC", Value = "VC" },
new SelectListItem{ Text= "IN", Value = "IN" },
new SelectListItem{ Text= "EM", Value = "EM" },
new SelectListItem{ Text= "SP", Value = "SP" },
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.PersonType, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeGender, labelText: "Genero", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.EmployeeGender, new List<SelectListItem>
{
new SelectListItem{ Text= "Masculino", Value = "M" },
new SelectListItem{ Text= "Femenino", Value = "F" }
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.EmployeeGender, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonTitle, labelText: "Titulo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonFirstName, labelText: "Primer Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonFirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonFirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonMiddleName, labelText: "Segundo Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonMiddleName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonMiddleName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonLastName, labelText: "Apellido", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonLastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonLastName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonSuffix, labelText: "Sufijo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonSuffix, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonSuffix, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.DepartmentID, labelText: "Departamento", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.DepartmentID, new SelectList(Model.ListDepartment, "DepartmentID", "DepartmentName"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.DepartmentID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeMaritalStatus, labelText: "Estado Civil", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.EmployeeMaritalStatus, new List<SelectListItem>
{
new SelectListItem{ Text= "Soltero", Value = "S" },
new SelectListItem{ Text= "Casado", Value = "M" }
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.EmployeeMaritalStatus, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.ShiftId, labelText: "Turno", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.ShiftId, new SelectList(Model.ListShift, "ShiftId", "ShiftName"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.ShiftId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeLoginId, labelText: "Login", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeLoginId, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeLoginId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeNationalIDNumber, labelText: "Identificacion Nacional", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeNationalIDNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeNationalIDNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeJobTitle, labelText: "Cargo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeJobTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeJobTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeBirthDate, labelText: "Fecha Nacimiento", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeBirthDate, new { htmlAttributes = new { @class = "form-control datepicker" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeBirthDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeSalariedFlag, labelText: "Asalariado", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeSalariedFlag, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeSalariedFlag, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Guardar" class="btn btn-default" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10" style="color:green">
@ViewBag.Message
</div>
<div class="col-md-offset-2 col-md-10" style="color:red">
@ViewBag.ErrorMessage
</div>
</div>
</div>
}
I was able to fix this issue by changing the mail settings in the system.net portion of my web.config:
<mailSettings>
<smtp deliveryMethod="Network">
<network host="yourserver" defaultCredentials="true"/>
</smtp>
</mailSettings>
Styling file inputs are notoriously difficult, as most browsers will not change the appearance from either CSS or javascript.
Even the size of the input will not respond to the likes of:
<input type="file" style="width:200px">
Instead, you will need to use the size attribute:
<input type="file" size="60" />
For any styling more sophisticated than that (e.g. changing the look of the browse button) you will need to look at the tricksy approach of overlaying a styled button and input box on top of the native file input. The article already mentioned by rm at www.quirksmode.org/dom/inputfile.html is the best one I've seen.
UPDATE
Although it's difficult to style an <input>
tag directly, this is easily possible with the help of a <label>
tag. See answer below from @JoshCrozier: https://stackoverflow.com/a/25825731/10128619
Another option is to create a shortcut with the following properties:
Target should be:
"%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login
Start in is the folder you wish your Git Bash prompt to launch into.
We can make a plugin pretty easily:
$.fn.filterData = function(key, value) {
return this.filter(function() {
return $(this).data(key) == value;
});
};
Usage (checking a radio button):
$('input[name=location_id]').filterData('my-data','data-val').prop('checked',true);
Here, I have two options. The first one shows the concept of an array of arrays or pointer of pointers. I prefer the second one because the addresses are contiguous, as you can see in the image.
#include <iostream>
using namespace std;
int main(){
int **arr_01,**arr_02,i,j,rows=4,cols=5;
//Implementation 1
arr_01=new int*[rows];
for(int i=0;i<rows;i++)
arr_01[i]=new int[cols];
for(i=0;i<rows;i++){
for(j=0;j<cols;j++)
cout << arr_01[i]+j << " " ;
cout << endl;
}
for(int i=0;i<rows;i++)
delete[] arr_01[i];
delete[] arr_01;
cout << endl;
//Implementation 2
arr_02=new int*[rows];
arr_02[0]=new int[rows*cols];
for(int i=1;i<rows;i++)
arr_02[i]=arr_02[0]+cols*i;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++)
cout << arr_02[i]+j << " " ;
cout << endl;
}
delete[] arr_02[0];
delete[] arr_02;
return 0;
}
SET @pos := 0;
UPDATE TABLE_NAME SET Roll_No = ( SELECT @pos := @pos + 1 ) ORDER BY First_Name ASC;
In the above example query simply update the student Roll_No column depending on the student Frist_Name column. From 1 to No_of_records in the table. I hope it's clear now.
Web Browser control might work. http://ryanfarley.com/blog/archive/2004/12/23/1330.aspx
Also a bunch of pdf open source c# projects here http://csharp-source.net/open-source/pdf-libraries
PYSPARK
In the below code, df
is the name of dataframe. 1st parameter is to show all rows in the dataframe dynamically rather than hardcoding a numeric value. The 2nd parameter will take care of displaying full column contents since the value is set as False
.
df.show(df.count(),False)
SCALA
In the below code, df
is the name of dataframe. 1st parameter is to show all rows in the dataframe dynamically rather than hardcoding a numeric value. The 2nd parameter will take care of displaying full column contents since the value is set as false
.
df.show(df.count().toInt,false)
You can have a view with Background color as black and set alpha for the view as 0.7 or whatever as per your requirement.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/onboardingimg1">
<View
android:id="@+id/opacityFilter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
android:layout_alignParentBottom="true"
android:alpha="0.7">
</View>
</RelativeLayout>
Here is my dark theme (based on Darcula IntelliJ Theme):
https://github.com/mervick/Qt-Creator-Darcula
Simply prevent the default browser action:
window.addEventListener("keydown", function(e) {
// space and arrow keys
if([32, 37, 38, 39, 40].indexOf(e.code) > -1) {
e.preventDefault();
}
}, false);
If you need to support Internet Explorer or other older browsers, use e.keyCode
instead of e.code
, but keep in mind that keyCode
is deprecated.
I used the following function in my own game:
var keys = {};
window.addEventListener("keydown",
function(e){
keys[e.code] = true;
switch(e.code){
case 37: case 39: case 38: case 40: // Arrow keys
case 32: e.preventDefault(); break; // Space
default: break; // do not block other keys
}
},
false);
window.addEventListener('keyup',
function(e){
keys[e.code] = false;
},
false);
The magic happens in e.preventDefault();
. This will block the default action of the event, in this case moving the viewpoint of the browser.
If you don't need the current button states you can simply drop keys
and just discard the default action on the arrow keys:
var arrow_keys_handler = function(e) {
switch(e.code){
case 37: case 39: case 38: case 40: // Arrow keys
case 32: e.preventDefault(); break; // Space
default: break; // do not block other keys
}
};
window.addEventListener("keydown", arrow_keys_handler, false);
Note that this approach also enables you to remove the event handler later if you need to re-enable arrow key scrolling:
window.removeEventListener("keydown", arrow_keys_handler, false);
window.addEventListener
window.removeEventListener
KeyboardEvent.code
interfaceApparently, the system I was using had the docker-ce not Docker. Thus, running below command did the trick.
sudo apt-get purge docker-ce
sudo rm -rf /var/lib/docker
hope it helps
You need to change the sshd_config
file in the remote server (probably in /etc/ssh/sshd_config
).
Change
PasswordAuthentication no
to
PasswordAuthentication yes
And then restart the sshd
daemon.
An easy workaround, at least to get the running port, is to add the parameter javax.servlet.HttpServletRequest in the signature of one of the controller's methods. Once you have the HttpServletRequest instance is straightforward to get the baseUrl with this: request.getRequestURL().toString()
Have a look at this code:
@PostMapping(value = "/registration" , produces = "application/json")
public StringResponse register(@RequestBody RequestUserDTO userDTO,
HttpServletRequest request) {
request.getRequestURL().toString();
//value: http://localhost:8080/registration
------
return "";
}
You can also use ngrok: https://ngrok.com/. I use it all the time to have a public server running on my localhost. Hope this helps.
Another options which even provides your own custom domain for free are serveo.net and https://localtunnel.github.io/www/
For a concrete example of accessing the SMS/MMS database, take a look at gTalkSMS.
Below command worked on 16.4 Ubuntu
This issue comes when your .sh file is corrupt or not formatted as per unix protocols.
dos2unix converts the .sh file to Unix format!
sudo apt-get install dos2unix -y
dos2unix test.sh
sudo chmod u+x test.sh
sudo ./test.sh
The files selected are stored in an array: [input].files
For example, you can access the items
// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
For jQuery-comfortable people, it's similarly easy
// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;
for (var i = 0; i < files.length; i++)
{
alert(files[i].name);
}
For small changes, I have used hexedit:
http://rigaux.org/hexedit.html
Simple but fast and useful.
To recap (and for newbies). It's not that painful. Just add the protocol, then add the functions you need for detection.
In the view (class) that contains the UIScrolView, add the protocol, then added any the functions from here to your view (class).
// --------------------------------
// In the "h" file:
// --------------------------------
@interface myViewClass : UIViewController <UIScrollViewDelegate> // <-- Adding the protocol here
// Scroll view
@property (nonatomic, retain) UIScrollView *myScrollView;
@property (nonatomic, assign) BOOL isScrolling;
// Protocol functions
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView;
// --------------------------------
// In the "m" file:
// --------------------------------
@implementation BlockerViewController
- (void)viewDidLoad {
CGRect scrollRect = self.view.frame; // Same size as this view
self.myScrollView = [[UIScrollView alloc] initWithFrame:scrollRect];
self.myScrollView.delegate = self;
self.myScrollView.contentSize = CGSizeMake(scrollRect.size.width, scrollRect.size.height);
self.myScrollView.contentInset = UIEdgeInsetsMake(0.0,22.0,0.0,22.0);
// Allow dragging button to display outside the boundaries
self.myScrollView.clipsToBounds = NO;
// Prevent buttons from activating scroller:
self.myScrollView.canCancelContentTouches = NO;
self.myScrollView.delaysContentTouches = NO;
[self.myScrollView setBackgroundColor:[UIColor darkGrayColor]];
[self.view addSubview:self.myScrollView];
// Add stuff to scrollview
UIImage *myImage = [UIImage imageNamed:@"foo.png"];
[self.myScrollView addSubview:myImage];
}
// Protocol functions
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
NSLog(@"start drag");
_isScrolling = YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
NSLog(@"end decel");
_isScrolling = NO;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
NSLog(@"end dragging");
if (!decelerate) {
_isScrolling = NO;
}
}
// All of the available functions are here:
// https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIScrollViewDelegate_Protocol/Reference/UIScrollViewDelegate.html
OSError: [WinError 193] %1 is not a valid Win32 application
This error is most probably due to this line import subprocess
I had the same issue and had solved it by uninstalling and reinstalling python and anaconda then i used jupyter and wrote pip install numpy this gave me the whole path where it was getting my site-packages from i deleted my site-packages folder and then the error dissappeared. Actually because i had 2 folders for site-packages one with anaconda and other somewhere in app data(which had some issues in it), since i deleted that site-package folder then it automatically started taking my libraries from site-package folder which was with anaconda hence the problem was solved.
If you want to confirm if focus is with an element then
if ($('#inputId').is(':focus')) {
//your code
}
The javadoc for refEq mentioned that the equality check is shallow! You can find more details at the link below:
"shallow equality" issue cannot be controlled when you use other classes which don't implement .equals() method,"DefaultMongoTypeMapper" class is an example where .equals() method is not implemented.
org.springframework.beans.factory.support offers a method that can generate a bean definition instead of creating an instance of the object, and it can be used to git rid of Comparison Failure.
genericBeanDefinition(DefaultMongoTypeMapper.class)
.setScope(SCOPE_SINGLETON)
.setAutowireMode(AUTOWIRE_CONSTRUCTOR)
.setLazyInit(false)
.addConstructorArgValue(null)
.getBeanDefinition()
**"The bean definition is only a description of the bean, not a bean itself. the bean descriptions properly implement equals() and hashCode(), so rather than creating a new DefaultMongoTypeMapper() we provide a definition that tells spring how it should create one"
In your example, you can do somethong like this
Mockito.verify(mockedObject)
.doSoething(genericBeanDefinition(YourClass.class).setA("a")
.getBeanDefinition());
The best method is what Mark Byers explains:
s = s.substring(0, s.length() - 1)
For example, if we want to replace \ to space " " with ReplaceAll, it doesn't work fine
String.replaceAll("\\", "");
or
String.replaceAll("\\$", ""); //if it is a path
This is in response to a number of comments as my reputation isn't high enough to comment directly.
You can specify the profile at runtime as long as the application context has not yet been loaded.
// Previous answers incorrectly used "spring.active.profiles" instead of
// "spring.profiles.active" (as noted in the comments).
// Use AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME to avoid this mistake.
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, environment);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml");
If storing less then 1 mil records, and high performance is not an issue go for varchar(20)/char(20) otherwise I've found that for storing even 100 milion global business phones or personal phones, int is best. Reason : smaller key -> higher read/write speed, also formatting can allow for duplicates.
1 phone in char(20) = 20 bytes vs 8 bytes bigint
(or 10 vs 4 bytes int
for local phones, up to 9 digits) , less entries can enter the index block => more blocks => more searches, see this for more info (writen for Mysql but it should be true for other Relational Databases).
Here is an example of phone tables:
CREATE TABLE `phoneNrs` (
`internationalTelNr` bigint(20) unsigned NOT NULL COMMENT 'full number, no leading 00 or +, up to 19 digits, E164 format',
`format` varchar(40) NOT NULL COMMENT 'ex: (+NN) NNN NNN NNN, optional',
PRIMARY KEY (`internationalTelNr`)
)
DEFAULT CHARSET=ascii
DEFAULT COLLATE=ascii_bin
or with processing/splitting before insert (2+2+4+1 = 9 bytes)
CREATE TABLE `phoneNrs` (
`countryPrefix` SMALLINT unsigned NOT NULL COMMENT 'countryCode with no leading 00 or +, up to 4 digits',
`countyPrefix` SMALLINT unsigned NOT NULL COMMENT 'countyCode with no leading 0, could be missing for short number format, up to 4 digits',
`localTelNr` int unsigned NOT NULL COMMENT 'local number, up to 9 digits',
`localLeadingZeros` tinyint unsigned NOT NULL COMMENT 'used to reconstruct leading 0, IF(localLeadingZeros>0;LPAD(localTelNr,localLeadingZeros+LENGTH(localTelNr),'0');localTelNr)',
PRIMARY KEY (`countryPrefix`,`countyPrefix`,`localLeadingZeros`,`localTelNr`) -- ordered for fast inserts
)
DEFAULT CHARSET=ascii
DEFAULT COLLATE=ascii_bin
;
Also "the phone number is not a number", in my opinion is relative to the type of phone numbers. If we're talking of an internal mobile phoneBook, then strings are fine, as the user may wish to store GSM Hash Codes. If storing E164 phones, bigint is the best option.
try with following code. make elements with class name page-scroll and keep id name to href
of corresponding links
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
After hours of finding ways on how to get the data from the row selected on a WPF DataGrid Control, as I was using MongoDB. I found this post and used Tony's answer. I revised the code to be relevant to my project. Maybe someone can use this to get an idea.
private void selectionChanged(object sender, SelectionChangedEventArgs e)
{
facultyData row = (facultyData)facultyDataGrid.SelectedItem;
facultyID_Textbox.Text = row.facultyID;
lastName_TextBox.Text = row.lastName;
firstName_TextBox.Text = row.firstName;
middleName_TextBox.Text = row.middleName;
age_TextBox.Text = row.age.ToString();
}
}
class facultyData
{
public ObjectId _id { get; set; }
public string facultyID { get; set; }
public string acadYear { get; set; }
public string program { get; set; }
}
You might need to change your path by:
import os
path=os.chdir(str('Here should be the path to your file')) #This command changes directory
This is what worked for me at least! Hope it works for you too!
If you have used chmod command already then check the difference of file, It shows previous file mode and current file mode such as:
new mode : 755
old mode : 644
set old mode of all files using below command
sudo chmod 644 .
now set core.fileMode to false in config file either using command or manually.
git config core.fileMode false
then apply chmod command to change the permissions of all files such as
sudo chmod 755 .
and again set core.fileMode to true.
git config core.fileMode true
For best practises don't Keep core.fileMode false always.
I try lots of ways and finally try this:
def db_persist(func):
def persist(*args, **kwargs):
func(*args, **kwargs)
try:
session.commit()
logger.info("success calling db func: " + func.__name__)
return True
except SQLAlchemyError as e:
logger.error(e.args)
session.rollback()
return False
return persist
and :
@db_persist
def insert_or_update(table_object):
return session.merge(table_object)
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
@echo off
title Test
echo Select a language. (de/en)
set /p language=
IF /i "%language%"=="de" goto languageDE
IF /i "%language%"=="en" goto languageEN
echo Not found.
goto commonexit
:languageDE
echo German
goto commonexit
:languageEN
echo English
goto commonexit
:commonexit
pause
The point is that batch simply continues through instructions, line by line until it reaches a goto
, exit
or end-of-file. It has no concept of sections
to control flow.
Hence, entering de
would jump to :languagede
then simply continue executing instructions until the file ends, showing de
then en
then not found
.
$insertation = "INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIMESTAMP(), '$comments')";
You can use this Query. CURRENT_TIMESTAMP
Remember to use the parenthesis CURRENT_TIMESTAMP()
You have to put div with single quotation around it. ' '
the Div
must be in the middle of single quotation . i'm gonna clear it with one example :
<?php
echo '<div id="output">'."Identify".'<br>'.'<br>';
echo 'Welcome '."$name";
echo "<br>";
echo 'Web Mail: '."$email";
echo "<br>";
echo 'Department of '."$dep";
echo "<br>";
echo "$maj";
'</div>'
?>
hope be useful.
If you're hoping to use background-image: url(...);
, I don't think you can. However, if you want to play with layering, you can do something like this:
<img class="bg" src="..." />
And then some CSS:
.bg
{
width: 100%;
z-index: 0;
}
You can now layer content above the stretched image by playing with z-indexes and such. One quick note, the image can't be contained in any other elements for the width: 100%;
to apply to the whole page.
Here's a quick demo if you can't rely on background-size
: http://jsfiddle.net/bB3Uc/
GCC compilers always try to compile your program if this is at all possible. However, in some
cases, the C and C++ standards specify that certain extensions are forbidden. Conforming compilers
such as gcc or g++ must issue a diagnostic when these extensions are encountered. For example,
the gcc compiler’s -pedantic option causes gcc to issue warnings in such cases. Using the stricter
-pedantic-errors
option converts such diagnostic warnings into errors that will cause compilation
to fail at such points. Only those non-ISO constructs that are required to be flagged by a conforming
compiler will generate warnings or errors.
The argument to remove()
is a filter document, so passing in an empty document means 'remove all':
db.user.remove({})
However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove()
call vs the drop()
call.
More details in the docs.
in oracle SQL you would do this:
SELECT
DATA_TYPE
FROM
all_tab_columns
WHERE
table_name = 'TABLE NAME' -- in uppercase
AND column_name = 'COLUMN NAME' -- in uppercase
use code=>generate=>getter() and setter() dialog ,select all the variables ,generate all the getter(),setter() methods at one time.
Additional to the jQuery thing treated in the other answers there is another meaning in JavaScript - as prefix for the RegExp properties representing matches, for example:
"test".match( /t(e)st/ );
alert( RegExp.$1 );
will alert "e"
But also here it's not "magic" but simply part of the properties name
If you need only display the trimmed value then I'd suggest against manipulating the original string and using a filter instead.
app.filter('trim', function () {
return function(value) {
if(!angular.isString(value)) {
return value;
}
return value.replace(/^\s+|\s+$/g, ''); // you could use .trim, but it's not going to work in IE<9
};
});
And then
<span>{{ foo | trim }}</span>
<execute-test-successful-condition> if <test> else <execute-test-fail-condition>
with your code-snippet it would become,
count = 0 if count == N else N + 1
g++ does not check for array bounds, and you may be overwriting something with 3,4 but nothing really important, if you try with higher numbers you'll get a crash.
You are just overwriting parts of the stack that are not used, you could continue till you reach the end of the allocated space for the stack and it'd crash eventually
EDIT: You have no way of dealing with that, maybe a static code analyzer could reveal those failures, but that's too simple, you may have similar(but more complex) failures undetected even for static analyzers
+=
is the in-place addition operator.
It's the same as doing cnt = cnt + 1
. For example:
>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44
The operator is often used in a similar fashion to the ++
operator in C-ish languages, to increment a variable by one in a loop (i += 1
)
There are similar operator for subtraction/multiplication/division/power and others:
i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4
The +=
operator also works on strings, for example:
>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there
People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs:
- If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.
The str.join() method refers to doing the following:
mysentence = []
for x in range(100):
mysentence.append("test")
" ".join(mysentence)
..instead of the more obvious:
mysentence = ""
for x in range(100):
mysentence += " test"
The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)
If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()
'ing it.
use Request.Form
to get the Data
Controller:
[HttpPost]
public ActionResult Index(int? id)
{
string jsonData= Request.Form[0]; // The data from the POST
}
I write this to try
View:
<input type="button" value="post" id="btnPost" />
<script type="text/javascript">
$(function () {
var test = {
number: 456,
name: "Ryu"
}
$("#btnPost").click(function () {
$.post('@Url.Action("Index", "Home")', JSON.stringify(test));
});
});
</script>
and write Request.Form[0]
or Request.Params[0]
in controller can get the data.
I don't write <form> tag
in view.
You can also call any controller from JavaScript/jQuery. Say you have a controller returning 404 or some other usercontrol/page. Then, on some action, from your client code, you can call some address that will fire your controller and return the result in HTML format your client code can take this returned result and put it wherever you want in you your page...
Use iconv - see Best way to convert text files between character sets?
If you want to iterate the inserted actors data:
for i in range(n):
if len(nams[i]) > 3:
do_something
if len(nams[i]) > 4:
do_something_else
When its comes to a relevantly big project we may need something re-usable. This is something I came with with help of SO.
<!-- Modal Dialog -->
<div class="modal fade" id="confirmDelete" role="dialog" aria-labelledby="confirmDeleteLabel"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title">Delete Parmanently</h4>
</div>
<div class="modal-body" style="height: 75px">
<p>Are you sure about this ?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-danger" id="confirm-delete-ok">Ok
</button>
</div>
</div>
</div>
<script type="text/javascript">
var url_for_deletion = "#";
var success_redirect = window.location.href;
$('#confirmDelete').on('show.bs.modal', function (e) {
var message = $(e.relatedTarget).attr('data-message');
$(this).find('.modal-body p').text(message);
var title = $(e.relatedTarget).attr('data-title');
$(this).find('.modal-title').text(title);
if (typeof $(e.relatedTarget).attr('data-url') != 'undefined') {
url_for_deletion = $(e.relatedTarget).attr('data-url');
}
if (typeof $(e.relatedTarget).attr('data-success-url') != 'undefined') {
success_redirect = $(e.relatedTarget).attr('data-success-url');
}
});
<!-- Form confirm (yes/ok) handler, submits form -->
$('#confirmDelete').find('.modal-footer #confirm-delete-ok').on('click', function () {
$.ajax({
method: "delete",
url: url_for_deletion,
}).success(function (data) {
window.location.href = success_redirect;
}).fail(function (error) {
console.log(error);
});
$('#confirmDelete').modal('hide');
return false;
});
<script/>
<a href="#" class="table-link danger"
data-toggle="modal"
data-target="#confirmDelete"
data-title="Delete Something"
data-message="Are you sure you want to inactivate this something?"
data-url="client/32"
id="delete-client-32">
</a>
<!-- jQuery should come before this -->
<%@ include file="../some/path/confirmDelete.jsp" %>
Note: This uses http delete method for delete request, you can change it from javascript or, can send it using a data-attribute as in data-title or data-url etc, for support any request.
The PackageInfo.sharedUserId
field will show the user Id assigned in the manifest.
If you want two applications to have the same userId, so they can see each other's data and run in the same process, then assign them the same userId in the manifest:
android:sharedUserId="string"
The two packages with the same sharedUserId need to have the same signature too.
I would also recommend reading here for a nudge in the right direction.
@RequestMapping
has a String[]
value parameter, so you should be able to specify multiple values like this:
@RequestMapping(value={"", "/", "welcome"})
(months later) a tiny real example where lambda is useful, partial not:
say you want various 1-dimensional cross-sections through a 2-dimensional function,
like slices through a row of hills.
quadf( x, f )
takes a 1-d f
and calls it for various x
.
To call it for vertical cuts at y = -1 0 1 and horizontal cuts at x = -1 0 1,
fx1 = quadf( x, lambda x: f( x, 1 ))
fx0 = quadf( x, lambda x: f( x, 0 ))
fx_1 = quadf( x, lambda x: f( x, -1 ))
fxy = parabola( y, fx_1, fx0, fx1 )
f_1y = quadf( y, lambda y: f( -1, y ))
f0y = quadf( y, lambda y: f( 0, y ))
f1y = quadf( y, lambda y: f( 1, y ))
fyx = parabola( x, f_1y, f0y, f1y )
As far as I know, partial
can't do this --
quadf( y, partial( f, x=1 ))
TypeError: f() got multiple values for keyword argument 'x'
(How to add tags numpy, partial, lambda to this ?)
If you're on Windows, try findstr
. Third-party tools are not needed:
findstr /V /L "searchstring" inputfile.txt > outputfile.txt
It supports regex's too! Just read the tool's help findstr /?
.
P.S. If you want to work with big, huge files (like 400 MB log files) a text editor is not very memory-efficient, so, as someone already pointed out, command-line tools are the way to go. But there's no grep on Windows, so...
I just ran this on a 1 GB log file, and it literally took 3 seconds.
(Make sure to install react-router using npm!)
To use react-router, you do the following:
Create a file with routes defined using Route, IndexRoute components
Inject the Router (with 'r'!) component as the top-level component for your app, passing the routes defined in the routes file and a type of history (hashHistory, browserHistory)
Step 1 routes.js
import React from 'react';
import { Route, IndexRoute } from 'react-router';
/**
* Import all page components here
*/
import App from './components/App';
import MainPage from './components/MainPage';
import SomePage from './components/SomePage';
import SomeOtherPage from './components/SomeOtherPage';
/**
* All routes go here.
* Don't forget to import the components above after adding new route.
*/
export default (
<Route path="/" component={App}>
<IndexRoute component={MainPage} />
<Route path="/some/where" component={SomePage} />
<Route path="/some/otherpage" component={SomeOtherPage} />
</Route>
);
Step 2 entry point (where you do your DOM injection)
// You can choose your kind of history here (e.g. browserHistory)
import { Router, hashHistory as history } from 'react-router';
// Your routes.js file
import routes from './routes';
ReactDOM.render(
<Router routes={routes} history={history} />,
document.getElementById('your-app')
);
Step 3 The App component (props.children)
In the render for your App component, add {this.props.children}:
render() {
return (
<div>
<header>
This is my website!
</header>
<main>
{this.props.children}
</main>
<footer>
Your copyright message
</footer>
</div>
);
}
Step 4 Use Link for navigation
Anywhere in your component render function's return JSX value, use the Link component:
import { Link } from 'react-router';
(...)
<Link to="/some/where">Click me</Link>
Here s what I suggest without using any other dependency , just node and express, use app.locals, here s an example :
app.get("/", function(req, res) {
var context = req.app.locals.specialContext;
req.app.locals.specialContext = null;
res.render("home.jade", context);
// or if you are using ejs
res.render("home", {context: context});
});
function middleware(req, res, next) {
req.app.locals.specialContext = * your context goes here *
res.redirect("/");
}
This question is a duplicate of Make a div fill the height of the remaining screen space and the correct answer is to use the flexbox model.
All major browsers and IE11+ support Flexbox. For IE 10 or older, or Android 4.3 and older, you can use the FlexieJS shim.
Note how simple the markup and the CSS are. No table hacks or anything.
html, body {
height: 100%;
margin: 0; padding: 0; /* to avoid scrollbars */
}
#wrapper {
display: flex; /* use the flex model */
min-height: 100%;
flex-direction: column; /* learn more: http://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ */
}
#header {
background: yellow;
height: 100px; /* can be variable as well */
}
#body {
flex: 1;
border: 1px solid orange;
}
#footer{
background: lime;
}
<div id="wrapper">
<div id="header">Title</div>
<div id="body">Body</div>
<div id="footer">
Footer<br/>
of<br/>
variable<br/>
height<br/>
</div>
</div>
In the CSS above, the flex property shorthands the flex-grow, flex-shrink, and flex-basis properties to establish the flexibility of the flex items. Mozilla has a good introduction to the flexible boxes model.
Since pip 20.1b1, which was released on 21 April 2020 and "added pip cache
command for inspecting/managing pip’s wheel cache", it is possible to issue this command:
pip cache purge
The reference guide is here:
https://pip.pypa.io/en/stable/reference/pip_cache/
The corresponding pull request is here.
Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)
dt.Columns.Add("MyRow", typeof(System.Int32));
dt.Columns["MyRow"].Expression = "'0'";
And for now, here is https://github.com/google/go-cmp which
is intended to be a more powerful and safer alternative to
reflect.DeepEqual
for comparing whether two values are semantically equal.
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
func main() {
a := []byte{1, 2, 3}
b := []byte{1, 2, 3}
fmt.Println(cmp.Equal(a, b)) // true
}
Yes, you can just change the port to to any number. For instance change Listen 80
to Listen 81
in the httpd.conf
file. Now try with http://localhost:81
and it will respond on port 81!!
Modified code of Tapas's answer:
Dim searcher As New ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem")
Dim collection As ManagementObjectCollection = searcher.[Get]()
Dim username As String
For Each oReturn As ManagementObject In collection
username = oReturn("UserName")
Next
This is the way that I did it for a uni project, works fine, prob not safe tho
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$title = $_POST['title'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$pass = $_POST['password'];
$cpass = $_POST['cpassword'];
$check = 1;
if (){
}
else{
$check = 1;
}
if ($check == 1){
require_once('website_data_collecting/db.php');
$sel_user = "SELECT * FROM users WHERE user_email='$email'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if ($check_user > 0){
echo '<div style="margin: 0 0 10px 20px;">Email already exists!</br>
<a href="recover.php">Recover Password</a></div>';
}
else{
$users_tb = "INSERT INTO users ".
"(user_name, user_email, user_password) ".
"VALUES('$name','$email','$pass')";
$users_info_tb = "INSERT INTO users_info".
"(user_title, user_surname)".
"VALUES('$title', '$surname')";
mysql_select_db('dropbox');
$run_users_tb = mysql_query( $users_tb, $conn );
$run_users_info_tb = mysql_query( $users_info_tb, $conn );
if(!$run_users_tb || !$run_users_info_tb){
die('Could not enter data: ' . mysql_error());
}
else{
echo "Entered data successfully\n";
}
mysql_close($conn);
}
}
use this code in manifest.xml
<uses-sdk
android:minSdkVersion="16"
android:maxSdkVersion="17"
tools:overrideLibrary="x"/>
this Func may help you . it add every list object to grid view
private void show_data()
{
BindingSource Source = new BindingSource();
for (int i = 0; i < CC.Contects.Count; i++)
{
Source.Add(CC.Contects.ElementAt(i));
};
Data_View.DataSource = Source;
}
I write this for simple database app
Or second solution
you can try to connect using Direct not TNS by providing host and port in the connect screen of Toad
SQL> DECLARE
2 a integer;
3 b integer;
4 BEGIN
5 a:=&a;
6 b:=&b;
7 dbms_output.put_line('The a value is : ' || a);
8 dbms_output.put_line('The b value is : ' || b);
9 END;
10 /
In MVC 4 If you want maxlenght in input type text ? You can !
@Html.TextBoxFor(model => model.Item3.ADR_ZIP, new { @class = "gui-input ui-oblig", @maxlength = "5" })
Can't load library: /home/tom/.swt/lib/linux/x86_64/libswt-gtk-3740.so Can't load library: /home/tom/.swt/lib/linux/x86_64/libswt-gtk.so
looks like the libraries should be at .swt/lib/linux/x86_64/ if there are not there you can try this command:
locate libswt-gtk.so
this should find the libraries copy the entire directory to /home/tom/.swt/lib/linux/x86_64
The error is clear, isn't it?
You've not added the path where sqljdbc_auth.dll is present. Find out in the system where the DLL is and add that to your classpath.
And if that also doesn't work, add the folder where the DLL is present (I'm assuming \Microsoft SQL Server JDBC Driver 3.0\sqljdbc_3.0\enu\auth\x86) to your PATH variable.
Again if you're going via ant or cmd you have to explicitly mention the path using -Djava.library.path=[path to MS_SQL_AUTH_DLL]
There's a public Web-accessible version of the Lambda-enabled Java 8 JavaDocs, linked from http://lambdafaq.org/lambda-resources. (This should obviously be a comment on Joachim Sauer's answer, but I can't get into my SO account with the reputation points I need to add a comment.) The lambdafaq site (I maintain it) answers this and a lot of other Java-lambda questions.
NB This answer was written before the Java 8 GA documentation became publicly available. I've left in place, though, because the Lambda FAQ might still be useful to people learning about features introduced in Java 8.
This code will do what you're looking for. It's based on examples found here and here.
The autofmt_xdate()
call is particularly useful for making the x-axis labels readable.
import numpy as np
from matplotlib import pyplot as plt
fig = plt.figure()
width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)
fig.autofmt_xdate()
plt.savefig("figure.pdf")
However this seems inefficient to me, as the filter will scan the whole list
No it won't - it will "break" as soon as the first element satisfying the predicate is found. You can read more about laziness in the stream package javadoc, in particular (emphasis mine):
Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, "find the first String with three consecutive vowels" need not examine all the input strings. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy.
Just to build on VisioN's answer above, if you are using the jQuery validation plugin you could use this:
$(document).ready(function() {
$.validator.addMethod('integer', function(value, element, param) {
return (value >>> 0 === parseFloat(value) && value > 0);
}, 'Please enter a non zero integer value!');
}
Then you could use in your normal rules set or add it dynamically this way:
$("#positiveIntegerField").rules("add", {required:true, integer:true});
You can perform it, this way:
$('input[id=ans]').is(':checked');
If the bandwidth is far higher than the bitrate, I would recommend TCP for unicast live video streaming.
Case 1: Consecutive packets are lost for a duration of several seconds. => live video will stop on the client side whatever the transport layer is (TCP or UDP). When the network recovers: - if TCP is used, client video player can choose to restart the stream at the first packet lost (timeshift) OR to drop all late packets and to restart the video stream with no timeshift. - if UDP is used, there is no choice on the client side, video restart live without any timeshift. => TCP equal or better.
Case 2: some packets are randomly and often lost on the network. - if TCP is used, these packets will be immediately retransmitted and with a correct jitter buffer, there will be no impact on the video stream quality/latency. - if UDP is used, video quality will be poor. => TCP much better
In Visual Studio Code, this lets me run/debug only one Jest test, with breakpoints: Debugging tests in Visual Studio Code
My launch.json
file has this inside:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Jest All",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["--runInBand"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest",
}
},
{
"type": "node",
"request": "launch",
"name": "Jest Current File",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["${relativeFile}"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest",
}
}
]
}
And this in file package.json
:
"scripts": {
"test": "jest"
}
test
(or it
) to test.only
(or it.only
). To run one test suite (several tests), change describe
to describe.only
.You can easily auto increase versionName and versionCode programmatically.
For Android add this to your gradle script and also create a file version.properties with VERSION_CODE=555
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
def versionPropsFile = file('version.properties')
if (versionPropsFile.canRead()) {
def Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
def code = versionProps['VERSION_CODE'].toInteger() + 1
versionProps['VERSION_CODE'] = code.toString()
versionProps.store(versionPropsFile.newWriter(), null)
defaultConfig {
applicationId "app.umanusorn.playground"
minSdkVersion 29
targetSdkVersion 30
versionCode code
versionName code.toString()
Closing a SpringApplication
basically means closing the underlying ApplicationContext
. The SpringApplication#run(String...)
method gives you that ApplicationContext
as a ConfigurableApplicationContext
. You can then close()
it yourself.
For example,
@SpringBootApplication
public class Example {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
// ...determine it's time to shut down...
ctx.close();
}
}
Alternatively, you can use the static
SpringApplication.exit(ApplicationContext, ExitCodeGenerator...)
helper method to do it for you. For example,
@SpringBootApplication
public class Example {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
// ...determine it's time to stop...
int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
@Override
public int getExitCode() {
// no errors
return 0;
}
});
// or shortened to
// int exitCode = SpringApplication.exit(ctx, () -> 0);
System.exit(exitCode);
}
}
It works for me for opening small text file... I didn't try in other file
protected void viewhelper(Intent intent) {
Uri a = intent.getData();
if (!a.toString().startsWith("content:")) {
return;
}
//Ok Let's do it
String content = readUri(a);
//do something with this content
}
here is the readUri(Uri uri) method
private String readUri(Uri uri) {
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(uri);
if (inputStream != null) {
byte[] buffer = new byte[1024];
int result;
String content = "";
while ((result = inputStream.read(buffer)) != -1) {
content = content.concat(new String(buffer, 0, result));
}
return content;
}
} catch (IOException e) {
Log.e("receiver", "IOException when reading uri", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
Log.e("receiver", "IOException when closing stream", e);
}
}
}
return null;
}
I got it from this repository https://github.com/zhutq/android-file-provider-demo/blob/master/FileReceiver/app/src/main/java/com/demo/filereceiver/MainActivity.java
I modified some code so that it work.
Manifest file:
<activity android:name=".MainActivity">
<intent-filter >
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
</activity>
You need to add
@Override
protected void onCreate(Bundle savedInstanceState) {
/*
* Your OnCreate
*/
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
//VIEW"
if (Intent.ACTION_VIEW.equals(action) && type != null) {
viewhelper(intent); // Handle text being sent
}
}
Too late, just in case some one is looking for another way:
void Main()
{
string jsonString = @"{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}";
Product product = new Product();
//Serializing to Object
Product obj = JObject.Parse(jsonString).SelectToken("$.Manufacturers[?(@.Name == 'Acme Co' && @.Name != 'Contoso')]").ToObject<Product>();
Console.WriteLine(obj);
}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
For chat applications or any other application that is in constant conversation with the server, WebSockets
are the best option. However, you can only use WebSockets
with a server that supports them, so that may limit your ability to use them if you cannot install the required libraries. In which case, you would need to use Long Polling
to obtain similar functionality.
Building on the previous, my preferred approach (since this is a frequently performed action) is to wrap the wait cursor code in an IDisposable helper class so it can be used with using() (one line of code), take optional parameters, run the code within, then clean up (restore cursor) afterwards.
public class CursorWait : IDisposable
{
public CursorWait(bool appStarting = false, bool applicationCursor = false)
{
// Wait
Cursor.Current = appStarting ? Cursors.AppStarting : Cursors.WaitCursor;
if (applicationCursor) Application.UseWaitCursor = true;
}
public void Dispose()
{
// Reset
Cursor.Current = Cursors.Default;
Application.UseWaitCursor = false;
}
}
Usage:
using (new CursorWait())
{
// Perform some code that shows cursor
}
this work for me, thanks. I want change text size only not change font name.
var fontSizeButtonBig:Int = 30
btnMenu9.titleLabel?.font = .systemFont(ofSize: CGFloat(fontSizeButtonBig))
Click on servers tab in eclipse and then double click on the server listed there. Select the port tab in the config page opened.Change the port to any other ports.Restart the server.
The simplest method is to use dir(objectname)
. It will display all the methods available for that object. Cool trick.
I did this once for my project, to close one application and open another application.
System.Threading.Thread newThread;
Form1 frmNewForm = new Form1;
newThread = new System.Threading.Thread(new System.Threading.ThreadStart(frmNewFormThread));
this.Close();
newThread.SetApartmentState(System.Threading.ApartmentState.STA);
newThread.Start();
And add the following Method. Your newThread.Start will call this method.
public void frmNewFormThread)()
{
Application.Run(frmNewForm);
}
The following simple test:
C++ Array vs Vector performance test explanation
contradicts the conclusions from "Comparison of assembly code generated for basic indexing, dereferencing, and increment operations on vectors and arrays/pointers."
There must be a difference between the arrays and vectors. The test says so... just try it, the code is there...
This is in VB.NET, just translate to C# if you need it:
<Extension()>
Public Function FindControlInRepeaterHeader(Of T As Control)(obj As Repeater, ControlName As String) As T
Dim ctrl As T = TryCast((From item As RepeaterItem In obj.Controls
Where item.ItemType = ListItemType.Header).SingleOrDefault.FindControl(ControlName),T)
Return ctrl
End Function
And use it easy:
Dim txt as string = rptrComentarios.FindControlInRepeaterHeader(Of Label)("lblVerTodosComentarios").Text
Try to make it work with footer, and items controls too =)
A multidimensional array creates a nice linear memory layout while a jagged array implies several extra levels of indirection.
Looking up the value jagged[3][6]
in a jagged array var jagged = new int[10][5]
works like this: Look up the element at index 3 (which is an array) and look up the element at index 6 in that array (which is a value). For each dimension in this case, there's an additional look up (this is an expensive memory access pattern).
A multidimensional array is laid out linearly in memory, the actual value is found by multiplying together the indexes. However, given the array var mult = new int[10,30]
, the Length
property of that multidimensional array returns the total number of elements i.e. 10 * 30 = 300.
The Rank
property of a jagged array is always 1, but a multidimensional array can have any rank. The GetLength
method of any array can be used to get the length of each dimension. For the multidimensional array in this example mult.GetLength(1)
returns 30.
Indexing the multidimensional array is faster. e.g. given the multidimensional array in this example mult[1,7]
= 30 * 1 + 7 = 37, get the element at that index 37. This is a better memory access pattern because only one memory location is involved, which is the base address of the array.
A multidimensional array therefore allocates a continuous memory block, while a jagged array does not have to be square, e.g. jagged[1].Length
does not have to equal jagged[2].Length
, which would be true for any multidimensional array.
Performance wise, multidimensional arrays should be faster. A lot faster, but due to a really bad CLR implementation they are not.
23.084 16.634 15.215 15.489 14.407 13.691 14.695 14.398 14.551 14.252
25.782 27.484 25.711 20.844 19.607 20.349 25.861 26.214 19.677 20.171
5.050 5.085 6.412 5.225 5.100 5.751 6.650 5.222 6.770 5.305
The first row are timings of jagged arrays, the second shows multidimensional arrays and the third, well that's how it should be. The program is shown below, FYI this was tested running mono. (The windows timings are vastly different, mostly due to the CLR implementation variations).
On windows, the timings of the jagged arrays are greatly superior, about the same as my own interpretation of what multidimensional array look up should be like, see 'Single()'. Sadly the windows JIT-compiler is really stupid, and this unfortunately makes these performance discussions difficult, there are too many inconsistencies.
These are the timings I got on windows, same deal here, the first row are jagged arrays, second multidimensional and third my own implementation of multidimensional, note how much slower this is on windows compared to mono.
8.438 2.004 8.439 4.362 4.936 4.533 4.751 4.776 4.635 5.864
7.414 13.196 11.940 11.832 11.675 11.811 11.812 12.964 11.885 11.751
11.355 10.788 10.527 10.541 10.745 10.723 10.651 10.930 10.639 10.595
Source code:
using System;
using System.Diagnostics;
static class ArrayPref
{
const string Format = "{0,7:0.000} ";
static void Main()
{
Jagged();
Multi();
Single();
}
static void Jagged()
{
const int dim = 100;
for(var passes = 0; passes < 10; passes++)
{
var timer = new Stopwatch();
timer.Start();
var jagged = new int[dim][][];
for(var i = 0; i < dim; i++)
{
jagged[i] = new int[dim][];
for(var j = 0; j < dim; j++)
{
jagged[i][j] = new int[dim];
for(var k = 0; k < dim; k++)
{
jagged[i][j][k] = i * j * k;
}
}
}
timer.Stop();
Console.Write(Format,
(double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
}
Console.WriteLine();
}
static void Multi()
{
const int dim = 100;
for(var passes = 0; passes < 10; passes++)
{
var timer = new Stopwatch();
timer.Start();
var multi = new int[dim,dim,dim];
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
for(var k = 0; k < dim; k++)
{
multi[i,j,k] = i * j * k;
}
}
}
timer.Stop();
Console.Write(Format,
(double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
}
Console.WriteLine();
}
static void Single()
{
const int dim = 100;
for(var passes = 0; passes < 10; passes++)
{
var timer = new Stopwatch();
timer.Start();
var single = new int[dim*dim*dim];
for(var i = 0; i < dim; i++)
{
for(var j = 0; j < dim; j++)
{
for(var k = 0; k < dim; k++)
{
single[i*dim*dim+j*dim+k] = i * j * k;
}
}
}
timer.Stop();
Console.Write(Format,
(double)timer.ElapsedTicks/TimeSpan.TicksPerMillisecond);
}
Console.WriteLine();
}
}
In MinGW, I had to install the following things:
Basic Setup -> mingw32-base
Basic Setup -> mingw32-gcc-g++
Basic Setup -> msys-base
And in Eclipse, go to
Windows -> Preferences -> C/C++ -> Build -> Environment
And set the following environment variables (with "Append variables to native environment" option set):
MINGW_HOME C:\MinGW
PATH C:\MinGW\bin;C:\MinGW\msys\1.0\bin
Click "Apply" and then "OK".
This worked for me, as far as I can tell.
You can also use Eclipse's keyboard shortcuts: just go on preferences > keymap and choose Eclipse from the drop-down menu. And all your Eclipse shortcuts will be used in here.
For enums, I test them only when they actually have methods in them. If it's a pure value-only enum like your example, I'd say don't bother.
But since you're keen on testing it, going with your second option is much better than the first. The problem with the first is that if you use an IDE, any renaming on the enums would also rename the ones in your test class.
You can use a plugin available here..
https://plugins.jquery.com/cookie/
and then to write a cookie do
$.cookie("test", 1);
to access the set cookie do
$.cookie("test");
After reading your previous comments, it's clear that you misunderstood the Hash::make function. Hash::make uses bcrypt hashing. By design, this means that every time you run Hash::make('password'), the result will be different (due to random salting). That's why you can't verify the password by simply checking the hashed password against the hashed input.
The proper way to validate a hash is by using:
Hash::check($passwordToCheck, $hashedPassword);
So, for example, your login function would be implemented like this:
public static function login($email, $password) {
$user = User::whereEmail($email)->first();
if ( !$user ) return null; //check if user exists
if ( Hash::check($password, $user->password) ) {
return $user;
} else return null;
}
And then you'd call it like this:
$user = User::login('[email protected]', 'password');
if ( !$user ) echo "Invalid credentials.";
else echo "First name: $user->firstName";
I recommend reviewing the Laravel security documentation, as functions already exist in Laravel to perform this type of authorization.
Furthermore, if your custom-made hashing algorithm generates the same hash every time for a given input, it's a security risk. A good one-way hashing algorithm should use random salting.
>>> dic0 = {'dic0':0}
>>> dic1 = {'dic1':1}
>>> ndic = dict(dic0.items() + dic1.items())
>>> ndic
{'dic0': 0, 'dic1': 1}
>>>
a reduce helper can do the trick (without type checking) -
const cleanObj = Object.entries(objToClean).reduce((acc, [key, value]) => {
if (value) {
acc[key] = value;
}
return acc;
}, {});
The Bitmap class is an implementation of the Image class. The Image class is an abstract class;
The Bitmap class contains 12 constructors that construct the Bitmap object from different parameters. It can construct the Bitmap from another bitmap, and the string address of the image.
See more in this comprehensive sample.
Here is a snippet that gets the default newline character for the current platform.
Use
System.getProperty("os.name")
and
System.getProperty("os.version").
Example:
public static String getSystemNewline(){
String eol = null;
String os = System.getProperty("os.name").toLowerCase();
if(os.contains("mac"){
int v = Integer.parseInt(System.getProperty("os.version"));
eol = (v <= 9 ? "\r" : "\n");
}
if(os.contains("nix"))
eol = "\n";
if(os.contains("win"))
eol = "\r\n";
return eol;
}
Where eol is the newline
For those looking for a modern solution that works in IE, Firefox, AND Chrome:
None of these solutions that use a hyperlink element will work the same in chrome. If you pass an invalid (or blank) url to chrome, it will always return the host where the script is called from. So in IE you will get blank, whereas in Chrome you will get localhost (or whatever).
If you are trying to look at the referrer, this is deceitful. You will want to make sure that the host you get back was in the original url to deal with this:
function getHostNameFromUrl(url) {
// <summary>Parses the domain/host from a given url.</summary>
var a = document.createElement("a");
a.href = url;
// Handle chrome which will default to domain where script is called from if invalid
return url.indexOf(a.hostname) != -1 ? a.hostname : '';
}