The problem with all suggested approaches: all RegEx is validating
All RegEx -based code is over-engineered: it will find only valid URLs! As a sample, it will ignore anything starting with "http://" and having non-ASCII characters inside.
Even more: I have encountered 1-2-seconds processing times (single-threaded, dedicated) with Java RegEx package (filtering Email addresses from text) for very small and simple sentences, nothing specific; possibly bug in Java 6 RegEx...
Simplest/Fastest solution would be to use StringTokenizer to split text into tokens, to remove tokens starting with "http://" etc., and to concatenate tokens into text again.
If you want to filter Emails from text (because later on you will do NLP staff etc) - just remove all tokens containing "@" inside.
This is simple text where RegEx of Java 6 fails. Try it in divverent variants of Java. It takes about 1000 milliseconds per RegEx call, in a long running single threaded test application:
pattern = Pattern.compile("[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})", Pattern.CASE_INSENSITIVE);
"Avalanna is such a sweet little girl! It would b heartbreaking if cancer won. She's so precious! #BeliebersPrayForAvalanna");
"@AndySamuels31 Hahahahahahahahahhaha lol, you don't look like a girl hahahahhaahaha, you are... sexy.";
Do not rely on regular expressions if you only need to filter words with "@", "http://", "ftp://", "mailto:"; it is huge engineering overhead.
If you really want to use RegEx with Java, try Automaton
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
This code will effectively make the element(s) blink without touching the layout (like fadeIn().fadeOut()
will do) by just acting on the opacity ; There you go, blinking text ; usable for both good and evil :)
setInterval(function() {
$('.blink').animate({ opacity: 1 }, 400).animate({ opacity: 0 }, 600);
}, 800);
You can do:
getMap(locations.toArray(new WorldLocation[locations.size()]));
or
getMap(locations.toArray(new WorldLocation[0]));
or
getMap(new WorldLocation[locations.size()]);
@SuppressWarnings("unchecked")
is needed to remove the ide warning.
The following is an answer to the question "What version of Java does Android support?" which is different from "What version of Java can I use to run Android Studio?" which is I believe what was actually being asked. For those looking to answer the 2nd question, you might find Using Android Studio with Java 1.7 helpful.
Also: See http://developer.android.com/sdk/index.html#latest for Android Studio system requirements. JDK8 is actually a requirement for PC and linux (as of 5/14/16).
Because I'd assume this question will start popping up soon with the release yesterday: As of right now, there's no set date for when Android will support Java 8.
Here's a discussion over at /androiddev - http://www.reddit.com/r/androiddev/comments/22mh0r/does_android_have_any_plans_for_java_8/
If you really want lambda support, you can checkout Retrolambda - https://github.com/evant/gradle-retrolambda. I've never used it, but it seems fairly promising.
Android now supports Java 7 (minus try-with-resource feature). You can read more about the Java 7 features here: https://stackoverflow.com/a/13550632/413254. If you're using gradle, you can add the following in your build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
Older response
I'm using Java 7 with Android Studio without any problems (OS X - 10.8.4). You need to make sure you drop the project language level down to 6.0 though. See the screenshot below.
What tehawtness said below makes sense, too. If they're suggesting JDK 6, it makes sense to just go with JDK 6. Either way will be fine.
Update: See this SO post -- https://stackoverflow.com/a/9567402/413254
Use forward declaration when possible.
Suppose you want to define a new class B
that uses objects of class A
.
B
only uses references or pointers to A
. Use forward declaration then you don't need to include <A.h>
. This will in turn speed a little bit the compilation.
class A ;
class B
{
private:
A* fPtrA ;
public:
void mymethod(const& A) const ;
} ;
B
derives from A
or B
explicitely (or implicitely) uses objects of class A
. You then need to include <A.h>
#include <A.h>
class B : public A
{
};
class C
{
private:
A fA ;
public:
void mymethod(A par) ;
}
something like this?
#sticky-sidebar {_x000D_
position:fixed;_x000D_
max-width: 20%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-xs-4">_x000D_
<div class="col-xs-12" id="sticky-sidebar">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
</div>_x000D_
<div class="col-xs-8" id="main">_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</div>_x000D_
</div>_x000D_
</div
_x000D_
String to byte array: "FooBar".split('').map(c => c.charCodeAt(0));
Byte array to string: [102, 111, 111, 98, 97, 114].map(c => String.fromCharCode(c)).join('');
Why are you combining GET and POST? Use one or the other.
$.ajax({
type: 'post',
data: {
timestamp: timestamp,
uid: uid
...
}
});
php:
$uid =$_POST['uid'];
Or, just format your request properly (you're missing the ampersands for the get parameters).
url:"getdata.php?timestamp="+timestamp+"&uid="+id+"&uname="+name,
Try this:
grep -rl 'SearchString' ./ | xargs sed -i 's/REPLACESTRING/WITHTHIS/g'
grep -rl
will recursively search for the SEARCHSTRING
in the directories ./
and will replace the strings using sed
.
Ex:
Replacing a name TOM
with JERRY
using search string as SWATKATS
in directory CARTOONNETWORK
grep -rl 'SWATKATS' CARTOONNETWORK/ | xargs sed -i 's/TOM/JERRY/g'
This will replace TOM
with JERRY
in all the files and subdirectories under CARTOONNETWORK
wherever it finds the string SWATKATS
.
I got this error while trying to run my unit tests in a submodule. What I have done is:
Change the simulator => Clean the project => Build the project => Run unit tests.
After this, my unit tests ran without any issue.
-DBL_MAX
in ANSI C, which is defined in float.h.
Here is an example using a recursive directive: http://jsfiddle.net/n8dPm/ Taken from https://groups.google.com/forum/#!topic/angular/vswXTes_FtM
module.directive("tree", function($compile) {
return {
restrict: "E",
scope: {family: '='},
template:
'<p>{{ family.name }}</p>'+
'<ul>' +
'<li ng-repeat="child in family.children">' +
'<tree family="child"></tree>' +
'</li>' +
'</ul>',
compile: function(tElement, tAttr) {
var contents = tElement.contents().remove();
var compiledContents;
return function(scope, iElement, iAttr) {
if(!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope, function(clone, scope) {
iElement.append(clone);
});
};
}
};
});
Tested with PyCharm 4.0.6 (OSX 10.10.3) following this steps:
Problem solved!
Take a look at this article on Simple-talk.com by Pop Rivett. It walks you through creating a generic trigger that will log the OLDVALUE and the NEWVALUE for all updated columns. The code is very generic and you can apply it to any table you want to audit, also for any CRUD operation i.e. INSERT, UPDATE and DELETE. The only requirement is that your table to be audited should have a PRIMARY KEY (which most well designed tables should have anyway).
Here's the code relevant for your GUESTS Table.
IF NOT EXISTS
(SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Audit]')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE Audit
(Type CHAR(1),
TableName VARCHAR(128),
PK VARCHAR(1000),
FieldName VARCHAR(128),
OldValue VARCHAR(1000),
NewValue VARCHAR(1000),
UpdateDate datetime,
UserName VARCHAR(128))
GO
CREATE TRIGGER TR_GUESTS_AUDIT ON GUESTS FOR UPDATE
AS
DECLARE @bit INT ,
@field INT ,
@maxfield INT ,
@char INT ,
@fieldname VARCHAR(128) ,
@TableName VARCHAR(128) ,
@PKCols VARCHAR(1000) ,
@sql VARCHAR(2000),
@UpdateDate VARCHAR(21) ,
@UserName VARCHAR(128) ,
@Type CHAR(1) ,
@PKSelect VARCHAR(1000)
--You will need to change @TableName to match the table to be audited.
-- Here we made GUESTS for your example.
SELECT @TableName = 'GUESTS'
-- date and user
SELECT @UserName = SYSTEM_USER ,
@UpdateDate = CONVERT (NVARCHAR(30),GETDATE(),126)
-- Action
IF EXISTS (SELECT * FROM inserted)
IF EXISTS (SELECT * FROM deleted)
SELECT @Type = 'U'
ELSE
SELECT @Type = 'I'
ELSE
SELECT @Type = 'D'
-- get list of columns
SELECT * INTO #ins FROM inserted
SELECT * INTO #del FROM deleted
-- Get primary key columns for full outer join
SELECT @PKCols = COALESCE(@PKCols + ' and', ' on')
+ ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
-- Get primary key select for insert
SELECT @PKSelect = COALESCE(@PKSelect+'+','')
+ '''<' + COLUMN_NAME
+ '=''+convert(varchar(100),
coalesce(i.' + COLUMN_NAME +',d.' + COLUMN_NAME + '))+''>'''
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
WHERE pk.TABLE_NAME = @TableName
AND CONSTRAINT_TYPE = 'PRIMARY KEY'
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
IF @PKCols IS NULL
BEGIN
RAISERROR('no PK on table %s', 16, -1, @TableName)
RETURN
END
SELECT @field = 0,
@maxfield = MAX(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName
WHILE @field < @maxfield
BEGIN
SELECT @field = MIN(ORDINAL_POSITION)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND ORDINAL_POSITION > @field
SELECT @bit = (@field - 1 )% 8 + 1
SELECT @bit = POWER(2,@bit - 1)
SELECT @char = ((@field - 1) / 8) + 1
IF SUBSTRING(COLUMNS_UPDATED(),@char, 1) & @bit > 0
OR @Type IN ('I','D')
BEGIN
SELECT @fieldname = COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName
AND ORDINAL_POSITION = @field
SELECT @sql = '
insert Audit ( Type,
TableName,
PK,
FieldName,
OldValue,
NewValue,
UpdateDate,
UserName)
select ''' + @Type + ''','''
+ @TableName + ''',' + @PKSelect
+ ',''' + @fieldname + ''''
+ ',convert(varchar(1000),d.' + @fieldname + ')'
+ ',convert(varchar(1000),i.' + @fieldname + ')'
+ ',''' + @UpdateDate + ''''
+ ',''' + @UserName + ''''
+ ' from #ins i full outer join #del d'
+ @PKCols
+ ' where i.' + @fieldname + ' <> d.' + @fieldname
+ ' or (i.' + @fieldname + ' is null and d.'
+ @fieldname
+ ' is not null)'
+ ' or (i.' + @fieldname + ' is not null and d.'
+ @fieldname
+ ' is null)'
EXEC (@sql)
END
END
GO
It's not an official term. I guess it means knowledge of the Java language itself and the most important parts of the standard API (java.lang, java.io, java.utils packages, basically), as opposed to the multitude of specialzed APIs and frameworks (J2EE, JPA, JNDI, JSTL, ...) that are often required for Java jobs.
None of these solutions worked for me. I had to uninstall Android Studio all together, then remove all Android Studio related files (user files), then reinstall it again.
You can use the new Bootstrap cards:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Link: Click here
regards,
I know this thread is a little old but it came in handy for a specific scenario I had and I thought it worth while to note that there is another reason why System.Threading.Timer
might be a good approach.
When you have to periodically execute a Job that might take a long time and you want to ensure that the entire waiting period is used between jobs or if you don't want the job to run again before the previous job has finished in the case where the job takes longer than the timer period.
You could use the following:
using System;
using System.ServiceProcess;
using System.Threading;
public partial class TimerExampleService : ServiceBase
{
private AutoResetEvent AutoEventInstance { get; set; }
private StatusChecker StatusCheckerInstance { get; set; }
private Timer StateTimer { get; set; }
public int TimerInterval { get; set; }
public CaseIndexingService()
{
InitializeComponent();
TimerInterval = 300000;
}
protected override void OnStart(string[] args)
{
AutoEventInstance = new AutoResetEvent(false);
StatusCheckerInstance = new StatusChecker();
// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate =
new TimerCallback(StatusCheckerInstance.CheckStatus);
// Create a timer that signals the delegate to invoke
// 1.CheckStatus immediately,
// 2.Wait until the job is finished,
// 3.then wait 5 minutes before executing again.
// 4.Repeat from point 2.
Console.WriteLine("{0} Creating timer.\n",
DateTime.Now.ToString("h:mm:ss.fff"));
//Start Immediately but don't run again.
StateTimer = new Timer(timerDelegate, AutoEventInstance, 0, Timeout.Infinite);
while (StateTimer != null)
{
//Wait until the job is done
AutoEventInstance.WaitOne();
//Wait for 5 minutes before starting the job again.
StateTimer.Change(TimerInterval, Timeout.Infinite);
}
//If the Job somehow takes longer than 5 minutes to complete then it wont matter because we will always wait another 5 minutes before running again.
}
protected override void OnStop()
{
StateTimer.Dispose();
}
}
class StatusChecker
{
public StatusChecker()
{
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Start Checking status.",
DateTime.Now.ToString("h:mm:ss.fff"));
//This job takes time to run. For example purposes, I put a delay in here.
int milliseconds = 5000;
Thread.Sleep(milliseconds);
//Job is now done running and the timer can now be reset to wait for the next interval
Console.WriteLine("{0} Done Checking status.",
DateTime.Now.ToString("h:mm:ss.fff"));
autoEvent.Set();
}
}
None of these suggestions above worked for me as-is. I had to use the following to center a checkbox with the label text displayed to the right of the box:
<style>
.checkboxes {
display: flex;
justify-content: center;
align-items: center;
vertical-align: middle;
word-wrap: break-word;
}
</style>
<label for="checkbox1" class="checkboxes"><input type="checkbox" id="checkbox1" name="checked" value="yes" class="checkboxes"/>
Check the box.</label>
I think using the fact that the keys can be treated as a set is the nicest way if you're on python 3:
def remove_keys(d, keys):
to_remove = set(keys)
filtered_keys = d.keys() - to_remove
filtered_values = map(d.get, filtered_keys)
return dict(zip(filtered_keys, filtered_values))
Example:
>>> remove_keys({'k1': 1, 'k3': 3}, ['k1', 'k2'])
{'k3': 3}
sed can do this:
sed 's/[\t ]/,/g' input.file
That will send to the console,
sed -i 's/[\t ]/,/g' input.file
will edit the file in-place
Consider using the decorator pattern http://en.wikipedia.org/wiki/Decorator_pattern
You can change the decorator at runtime with one that has different properties when an event occurs.
I solved it by renaming my function.
Changed
function editForm(value)
to
function editTheForm(value)
Works perfectly.
One can catch that you may change it through windows registry key
(SQLEXPRESS instance):
"Software\Microsoft\Microsoft SQL Server\SQLEXPRESS\LoginMode" = 2
... and restart service
Generally, you should only catch the exceptions you can actually handle. That means be as specific as possible when catching exceptions. Catching all exceptions is rarely a good idea and ignoring all exceptions is almost always a very bad idea.
I can only think of a few instances where an empty catch block has some meaningful purpose. If whatever specific exception, you are catching is "handled" by just reattempting the action there would be no need to do anything in the catch block. However, it would still be a good idea to log the fact that the exception occurred.
Another example: CLR 2.0 changed the way unhandled exceptions on the finalizer thread are treated. Prior to 2.0 the process was allowed to survive this scenario. In the current CLR the process is terminated in case of an unhandled exception on the finalizer thread.
Keep in mind that you should only implement a finalizer if you really need one and even then you should do a little as possible in the finalizer. But if whatever work your finalizer must do could throw an exception, you need to pick between the lesser of two evils. Do you want to shut down the application due to the unhandled exception? Or do you want to proceed in a more or less undefined state? At least in theory the latter may be the lesser of two evils in some cases. In those case the empty catch block would prevent the process from being terminated.
you try this way
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
})
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
};
and
useEffect(() => {
fetchBusinesses();
});
it's work for you. But my suggestion is try this way also work for you. It's better than before way. I use this way:
useEffect(() => {
const fetchBusinesses = () => {
return fetch("theURL", {method: "GET"}
)
.then(res => normalizeResponseErrors(res))
.then(res => {
return res.json();
})
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
};
fetchBusinesses();
}, []);
if you get data on the base of specific id then add in callback useEffect [id]
then cannot show you warning
React Hook useEffect has a missing dependency: 'any thing'. Either include it or remove the dependency array
You have to first convert your object literal to a Prototype Hash:
// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}
// Iterate like so. The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
alert(pair.key);
alert(pair.value);
});
#!/bin/bash
current_usage=$( df -h | grep 'gfsvg-gfslv' | awk {'print $5'} )
echo $current_usage
critical_usage=6%
warning_usage=3%
if [[ ${current_usage%?} -lt ${warning_usage%?} ]]; then
echo OK current usage is $current_usage
elif [[ ${current_usage%?} -ge ${warning_usage%?} ]] && [[ ${current_usage%?} -lt ${critical_usage%?} ]]; then
echo Warning $current_usage
else
echo Critical $current_usage
fi
Little Edit
Try adding
return new JavascriptResult() { Script = "alert('Successfully registered');" };
in place of
return RedirectToAction("Index");
This answer support the @ macrocosme suggestion.
I am using heat map as hist2d plot. Additionally I use cmin=0.5 for no count value and cmap for color, r represent the reverse of given color.
# np.arange(data.min(), data.max()+binwidth, binwidth)
bin_x = np.arange(0.6, 7 + 0.3, 0.3)
bin_y = np.arange(12, 58 + 3, 3)
plt.hist2d(data=fuel_econ, x='displ', y='comb', cmin=0.5, cmap='viridis_r', bins=[bin_x, bin_y]);
plt.xlabel('Dispalcement (1)');
plt.ylabel('Combine fuel efficiency (mpg)');
plt.colorbar();
I've a workaround for NullPointerException
when remove fragment in on DestoryView
, Just put your code in onStop()
not onDestoryView
. It works fine!
@Override
public void onStop() {
super.onStop();
if (mMap != null) {
MainActivity.fragmentManager.beginTransaction()
.remove(MainActivity.fragmentManager.findFragmentById(R.id.location_map)).commit();
mMap = null;
}
}
Here is how I solved the same problem using the Oracle.DataAccess.Client
Namespace.
using Oracle.DataAccess.Client;
string strConnection = ConfigurationManager.ConnectionStrings["oConnection"].ConnectionString;
dataConnection = new OracleConnectionStringBuilder(strConnection);
OracleConnection oConnection = new OracleConnection(dataConnection.ToString());
oConnection.Open();
OracleCommand tmpCommand = oConnection.CreateCommand();
tmpCommand.Parameters.Add("user", OracleDbType.Varchar2, txtUser.Text, ParameterDirection.Input);
tmpCommand.CommandText = "SELECT USER, PASS FROM TB_USERS WHERE USER = :1";
try
{
OracleDataReader tmpReader = tmpCommand.ExecuteReader(CommandBehavior.SingleRow);
if (tmpReader.HasRows)
{
// PT: IMPLEMENTE SEU CÓDIGO
// ES: IMPLEMENTAR EL CÓDIGO
// EN: IMPLEMENT YOUR CODE
}
}
catch(Exception e)
{
// PT: IMPLEMENTE SEU CÓDIGO
// ES: IMPLEMENTAR EL CÓDIGO
// EN: IMPLEMENT YOUR CODE
}
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
Running a different copy of Python is as easy as starting the correct executable. You mention that you've started a python instance, from the command line, by simply typing python
.
What this does under Windows, is to trawl the %PATH%
environment variable, checking for an executable, either batch file (.bat
), command file (.cmd
) or some other executable to run (this is controlled by the PATHEXT
environment variable), that matches the name given. When it finds the correct file to run the file is being run.
Now, if you've installed two python versions 2.5 and 2.6, the path will have both of their directories in it, something like PATH=c:\python\2.5;c:\python\2.6
but Windows will stop examining the path when it finds a match.
What you really need to do is to explicitly call one or both of the applications, such as c:\python\2.5\python.exe
or c:\python\2.6\python.exe
.
The other alternative is to create a shortcut to the respective python.exe
calling one of them python25
and the other python26
; you can then simply run python25
on your command line.
If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...
import com.ximpleware.*;
public class queryText {
public static void main(String[] s) throws VTDException{
VTDGen vg = new VTDGen();
if (!vg.parseFile("input.xml", true))
return;
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
// first manually navigate
if(vn.toElement(VTDNav.FC,"tag")){
int i= vn.getText();
if (i!=-1){
System.out.println("text ===>"+vn.toString(i));
}
if (vn.toElement(VTDNav.NS,"tag")){
i=vn.getText();
System.out.println("text ===>"+vn.toString(i));
}
}
// second version use XPath
ap.selectXPath("/add/tag/text()");
int i=0;
while((i=ap.evalXPath())!= -1){
System.out.println("text node ====>"+vn.toString(i));
}
}
}
I've thought of another—slightly unusual, but very effective—way to do this that doesn't require decorator functions or classes. Instead it just uses a mutable keyword argument, which ought to work in most versions of Python. Most of the time these are something to be avoided since normally you wouldn't want a default argument value to change from call-to-call—but that ability can be leveraged in this case and used as a cheap storage mechanism. Here's how that would work:
def my_function1(_has_run=[]):
if _has_run: return
print("my_function1 doing stuff")
_has_run.append(1)
def my_function2(_has_run=[]):
if _has_run: return
print("my_function2 doing some other stuff")
_has_run.append(1)
for i in range(10):
my_function1()
my_function2()
print('----')
my_function1(_has_run=[]) # Force it to run.
Output:
my_function1 doing stuff
my_function2 doing some other stuff
----
my_function1 doing stuff
This could be simplified a little further by doing what @gnibbler suggested in his answer and using an iterator (which were introduced in Python 2.2):
from itertools import count
def my_function3(_count=count()):
if next(_count): return
print("my_function3 doing something")
for i in range(10):
my_function3()
print('----')
my_function3(_count=count()) # Force it to run.
Output:
my_function3 doing something
----
my_function3 doing something
I fixed my problem by switching to the latest .Net Framework. So your target Framework sets your Security Protocol.
when you have this in Web.config
<system.web>
<httpRuntime targetFramework="4.5"/>
</system.web>
you will get this by default:
ServicePointManager.SecurityProtocol = Ssl3 | Tls
when you have this in Web.config
<system.web>
<httpRuntime targetFramework="4.6.1"/>
</system.web>
you will get this by default:
ServicePointManager.SecurityProtocol = Tls12 | Tls11 | Tls
You can disable it with -Wno-reorder
.
On Websphere Application Server, in the same situation, it helped deleting the Temp folders while the server was stopped.
I ran into the situation when the package of the service changed.
Using advanced wheres:
CabRes::where('m__Id', 46)
->where('t_Id', 2)
->where(function($q) {
$q->where('Cab', 2)
->orWhere('Cab', 4);
})
->get();
Or, even better, using whereIn()
:
CabRes::where('m__Id', 46)
->where('t_Id', 2)
->whereIn('Cab', $cabIds)
->get();
Your first variable declartion must start with a ?
while any additional must be concatenated with a &
single variable URL
multiple variable URL
typed mongod and getting error
Errors:
exception in initAndListen: NonExistentPath: Data directory /data/db not found., terminating
shuts down with Code 100
Then try with (create data and db folder with all permission)
mongod --dbpath=/data
use new tab and type mongo.
If still you are facing prob then you can check for mac catalina: (https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x-tarball/)
for windows: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows-unattended/
In my case I was developing a framework and had a test application inside it, what was missing is inside the test application target -> build settings -> Framework Search Paths:
Also, inside the test application target -> Build Phases -> Link Binary With Libraries:
An idea would be that display:flex;
with flex-direction: row;
is filling the container
div with .flex-1
and .flex-2
, but that does not mean that .flex-2
has a default height:100%;
, even if it is extended to full height.
And to have a child element (.flex-2-child
) with height:100%;
, you'll need to set the parent to height:100%;
or use display:flex;
with flex-direction: row;
on the .flex-2
div too.
From what I know, display:flex
will not extend all your child elements height to 100%.
A small demo, removed the height from .flex-2-child
and used display:flex;
on .flex-2
:
http://jsfiddle.net/2ZDuE/3/
Be careful using the answer provide by @DevNG. Arrays.asList() returns internal implementation of ArrayList that doesn't implement some useful methods like add(), delete(), etc. If you call them an UnsupportedOperationException will be thrown. In order to get real ArrayList instance you need to write something like this:
List<Video> = new ArrayList<>(Arrays.asList(videoArray));
Note that the ansible
command doesn't collect facts, but the ansible-playbook
command does. When running ansible -m setup
, the setup module happens to run the fact collection so you get the facts, but running ansible -m command
does not. Therefore the facts aren't available. This is why the other answers include playbook YAML files and indicate the lookup works.
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
How to end the request?
Try other solution, just:
return StatusCode(418);
You could use StatusCode(???)
to return any HTTP status code.
Also, you can use dedicated results:
Success:
return Ok()
? Http status code 200return Created()
? Http status code 201return NoContent();
? Http status code 204Client Error:
return BadRequest();
? Http status code 400return Unauthorized();
? Http status code 401return NotFound();
? Http status code 404
More details:
You are trying access a non-static class in a static way. Change Builder
to static class Builder
and it should work.
The example usage you give fails because there is no instance of Builder
present. A static class for all practical purposes is always instantiated. If you don't make it static, you'd need to say:
Widget = new Widget.Builder(10).setparm1(1).setparm2(3).build();
Because you would need to construct a new Builder
every time.
You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the messageTotal integer:
NSDictionary* userInfo = @{@"total": @(messageTotal)};
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];
On the receiving end you can access the userInfo dictionary as follows:
-(void) receiveTestNotification:(NSNotification*)notification
{
if ([notification.name isEqualToString:@"TestNotification"])
{
NSDictionary* userInfo = notification.userInfo;
NSNumber* total = (NSNumber*)userInfo[@"total"];
NSLog (@"Successfully received test notification! %i", total.intValue);
}
}
INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count
FROM batch
WHERE NOT EXISTS (
SELECT * FROM target t2, batch b2
WHERE t2.userid = b2.userid
-- ... other keyfields ...
)
;
BTW: if you want the whole batch to fail in case of a duplicate, then (given a primary key constraint)
INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count
FROM batch
;
will do exactly what you want: either it succeeds, or it fails.
There are two ways we can convert String to InputStream in Java,
Example :-
String str = "String contents";
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
Example:-
String str = "String contents"
InputStream is = IOUtils.toInputStream(str, StandardCharsets.UTF_8);
Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected, like in the case of INFINITY.
Below is the function for handling unexpected behaviour.
function cleanInt(x) {
x = Number(x);
return x >= 0 ? Math.floor(x) : Math.ceil(x);
}
See results of below test cases.
console.log("CleanInt: ", cleanInt('xyz'), " ParseInt: ", parseInt('xyz'));
console.log("CleanInt: ", cleanInt('123abc'), " ParseInt: ", parseInt('123abc'));
console.log("CleanInt: ", cleanInt('234'), " ParseInt: ", parseInt('234'));
console.log("CleanInt: ", cleanInt('-679'), " ParseInt: ", parseInt('-679'));
console.log("CleanInt: ", cleanInt('897.0998'), " ParseInt: ", parseInt('897.0998'));
console.log("CleanInt: ", cleanInt('Infinity'), " ParseInt: ", parseInt('Infinity'));
result:
CleanInt: NaN ParseInt: NaN
CleanInt: NaN ParseInt: 123
CleanInt: 234 ParseInt: 234
CleanInt: -679 ParseInt: -679
CleanInt: 897 ParseInt: 897
CleanInt: Infinity ParseInt: NaN
Make sure upload
plugin implements this.each
in it so that it will execute the logic for all the matching elements. It should ideally work
$("#upload_link,#upload_link2,#upload_link3").upload(function(){ });
We ended up realising that our one server that was experiencing this had busted fpm config resulting in php errors/warnings/notices that'd normally be logged to disk were being sent over the FCGI socket. It looks like there's a parsing bug when part of the header gets split across the buffer chunks.
So setting php_admin_value[error_log]
to something actually writeable and restarting php-fpm was enough to fix the problem.
We could reproduce the problem with a smaller script:
<?php
for ($i = 0; $i<$_GET['iterations']; $i++)
error_log(str_pad("a", $_GET['size'], "a"));
echo "got here\n";
Raising the buffers made the 502s harder to hit but not impossible, e.g native:
bash-4.1# for it in {30..200..3}; do for size in {100..250..3}; do echo "size=$size iterations=$it $(curl -sv "http://localhost/debug.php?size=$size&iterations=$it" 2>&1 | egrep '^< HTTP')"; done; done | grep 502 | head
size=121 iterations=30 < HTTP/1.1 502 Bad Gateway
size=109 iterations=33 < HTTP/1.1 502 Bad Gateway
size=232 iterations=33 < HTTP/1.1 502 Bad Gateway
size=241 iterations=48 < HTTP/1.1 502 Bad Gateway
size=145 iterations=51 < HTTP/1.1 502 Bad Gateway
size=226 iterations=51 < HTTP/1.1 502 Bad Gateway
size=190 iterations=60 < HTTP/1.1 502 Bad Gateway
size=115 iterations=63 < HTTP/1.1 502 Bad Gateway
size=109 iterations=66 < HTTP/1.1 502 Bad Gateway
size=163 iterations=69 < HTTP/1.1 502 Bad Gateway
[... there would be more here, but I piped through head ...]
fastcgi_buffers 16 16k; fastcgi_buffer_size 32k;
:
bash-4.1# for it in {30..200..3}; do for size in {100..250..3}; do echo "size=$size iterations=$it $(curl -sv "http://localhost/debug.php?size=$size&iterations=$it" 2>&1 | egrep '^< HTTP')"; done; done | grep 502 | head
size=223 iterations=69 < HTTP/1.1 502 Bad Gateway
size=184 iterations=165 < HTTP/1.1 502 Bad Gateway
size=151 iterations=198 < HTTP/1.1 502 Bad Gateway
So I believe the correct answer is: fix your fpm config so it logs errors to disk.
I figured out another way that works with most istreams, including std::cin!
std::string readFile()
{
stringstream str;
ifstream stream("Hello_World.txt");
if(stream.is_open())
{
while(stream.peek() != EOF)
{
str << (char) stream.get();
}
stream.close();
return str.str();
}
}
You can use String#replaceAll()
with a pattern of ^\"|\"$
for this.
E.g.
string = string.replaceAll("^\"|\"$", "");
To learn more about regular expressions, have al ook at http://regular-expression.info.
That said, this smells a bit like that you're trying to invent a CSV parser. If so, I'd suggest to look around for existing libraries, such as OpenCSV.
If you use the java keyword abstract
you cannot provide an implementation.
Sometimes this idea comes from having a background in C++ and mistaking the virtual
keyword in C++ as being "almost the same" as the abstract
keyword in Java.
In C++ virtual
indicates that a method can be overridden and polymorphism will follow, but abstract
in Java is not the same thing. In Java abstract
is more like a pure virtual
method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual
from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.
Now to protect a method from being overridden, Java uses the keyword final
in coordination with the method declaration to indicate that subclasses cannot override the method.
Try using the Worksheet.Protect
method, like so:
Sub ProtectActiveSheet()
Dim ws As Worksheet
Set ws = ActiveSheet
ws.Protect DrawingObjects:=True, Contents:=True, _
Scenarios:=True, Password="SamplePassword"
End Sub
You should, however, be concerned about including the password in your VBA code. You don't necessarily need a password if you're only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.
Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That's a good way to get started in VBA.
This was once written for Gradle 2.x / 3.x in 2016 and is far outdated!! Please have a look at the documented solutions in Gradle 4 and up
To sum up both old answers (get best and minimum viable of both worlds):
some warm words first:
first, we need to define the sourceSet
:
sourceSets {
integrationTest
}
next we expand the sourceSet
from test
, therefor we use the test.runtimeClasspath
(which includes all dependenciess from test
AND test
itself) as classpath for the derived sourceSet
:
sourceSets {
integrationTest {
compileClasspath += sourceSets.test.runtimeClasspath
runtimeClasspath += sourceSets.test.runtimeClasspath // ***)
}
}
sourceSets.integrationTest.runtimeClasspath
is needed, but should be irrelevant since runtimeClasspath
always expands output + runtimeSourceSet
, don't get itwe define a dedicated task for just running integration tests:
task integrationTest(type: Test) {
}
Configure the integrationTest
test classes and classpaths use. The defaults from the java
plugin use the test
sourceSet
task integrationTest(type: Test) {
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
}
(optional) auto run after test
integrationTest.dependsOn test
(optional) add dependency from check
(so it always runs when build
or check
are executed)
tasks.check.dependsOn(tasks.integrationTest)
(optional) add java,resources to the sourceSet
to support auto-detection and create these "partials" in your IDE. i.e. IntelliJ IDEA will auto create sourceSet
directories java and resources for each set if it doesn't exist:
sourceSets {
integrationTest {
java
resources
}
}
tl;dr
apply plugin: 'java'
// apply the runtimeClasspath from "test" sourceSet to the new one
// to include any needed assets: test, main, test-dependencies and main-dependencies
sourceSets {
integrationTest {
// not necessary but nice for IDEa's
java
resources
compileClasspath += sourceSets.test.runtimeClasspath
// somehow this redeclaration is needed, but should be irrelevant
// since runtimeClasspath always expands compileClasspath
runtimeClasspath += sourceSets.test.runtimeClasspath
}
}
// define custom test task for running integration tests
task integrationTest(type: Test) {
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
}
tasks.integrationTest.dependsOn(tasks.test)
referring to:
Unfortunatly, the example code on github.com/gradle/gradle/subprojects/docs/src/samples/java/customizedLayout/build.gradle or …/gradle/…/withIntegrationTests/build.gradle seems not to handle this or has a different / more complex / for me no clearer solution anyway!
Your code could look more like:
<?php
session_start(); $username = $password = $userError = $passError = '';
if(isset($_POST['sub'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:wherever.php'); die();
}
if($username !== 'admin')$userError = 'Invalid Username';
if($password !== 'password')$passError = 'Invalid Password';
}
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<style type='text.css'>
@import common.css;
</style>
</head>
<body>
<form name='input' action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
<label for='username'></label><input type='text' value='<?php echo $username;?>' id='username' name='username' />
<div class='error'><?php echo $userError;?></div>
<label for='password'></label><input type='password' value='<?php echo $password;?>' id='password' name='password' />
<div class='error'><?php echo $passError;?></div>
<input type='submit' value='Home' name='sub' />
</form>
<script type='text/javascript' src='common.js'></script>
</body>
</html>
the OOP way to do this in ES5 is to make that variable into a property using the this keyword.
function first(){
this.nameContent=document.getElementById('full_name').value;
}
function second() {
y=new first();
alert(y.nameContent);
}
SELECT *
FROM Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND (isnull(@Value,1) <> 2
OR I.RecurringCharge = @Total
OR @Total is NULL )
AND (isnull(@Value,2) <> 3
OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
OR @Total is NULL )
Basically, your condition was
if (@Value=2)
TEST FOR => (I.RecurringCharge=@Total or @Total is NULL )
flipped around,
AND (isnull(@Value,1) <> 2 -- A
OR I.RecurringCharge = @Total -- B
OR @Total is NULL ) -- C
When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2
, which is the original intention.
You can set the CORS in the cloud function like this
response.set('Access-Control-Allow-Origin', '*');
No need to import the cors
package
int is a binary representation of a whole number, double is a double-precision floating point number.
You can do this by using the --prefix
flag and the --global
* flag.
pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
[email protected] /Users/pje/foo/vendor/node_modules/bower
*Even though this is a "global" installation, installed bins won't be accessible through the command line unless ~/foo/vendor/node_modules
exists in PATH
.
Every configurable attribute of npm
can be set in any of six different places. In order of priority:
--prefix ./vendor/node_modules
NPM_CONFIG_PREFIX=./vendor/node_modules
$HOME/.npmrc
or userconfig
param$PREFIX/etc/npmrc
or userconfig
parampath/to/npm/itself/npmrc
By default, locally-installed packages go into ./node_modules
. global ones go into the prefix
config variable (/usr/local
by default).
You can run npm config list
to see your current config and npm config edit
to change it.
In general, npm
's documentation is really helpful. The folders section is a good structural overview of npm and the config section answers this question.
Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)
function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
Hi Jack,
your function design is fine, but this function always misses the first dataset in the array. I tested that.
Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.
The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.
You can avoid that by moving the if condition above the second foreach loop like this:
function display_data($data) {
$output = "<table>";
foreach($data as $key => $var) {
//$output .= '<tr>';
if($key===0) {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= "<td>" . $col . '</td>';
}
$output .= '</tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
else {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
}
$output .= '</table>';
echo $output;
}
Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016
and another update that removes redundant code blocks that hurt maintainability of the code.
function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
I almost always use the standard formating ShortDateString, because I want the user to be in control of the actual output of the date.
Dim d As DateTime = Now
Debug.WriteLine(d.ToLongDateString)
Debug.WriteLine(d.ToShortDateString)
Debug.WriteLine(d.ToString("d"))
Debug.WriteLine(d.ToString("yyyy-MM-dd"))
Wednesday, December 10, 2008
12/10/2008
12/10/2008
2008-12-10
Note that these results will vary depending on the culture settings on your computer.
def closest(list, Number):
aux = []
for valor in list:
aux.append(abs(Number-valor))
return aux.index(min(aux))
This code will give you the index of the closest number of Number in the list.
The solution given by KennyTM is the best overall, but in the cases you cannot use it (like brython), this function will do the work
A not very direct trick:
Use pyautogui hotkey:
Import pyautogui
pyautogui.hotkey('ctrl', 'v')
Therefore, you can paste the clipboard data as you like.
Encrypt:
openssl enc -in infile.txt -out encrypted.dat -e -aes256 -k symmetrickey
Decrypt:
openssl enc -in encrypted.dat -out outfile.txt -d -aes256 -k symmetrickey
For details, see the openssl(1)
docs.
Just use exception.ToString()
http://msdn.microsoft.com/en-us/library/system.exception.tostring.aspx
The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. If any of these members is null, its value is not included in the returned string.
If there is no error message or if it is an empty string (""), then no error message is returned. The name of the inner exception and the stack trace are returned only if they are not null.
exception.ToString() will also call .ToString() on that exception's inner exception, and so on...
You should supply the SqlParameter instances in the following way:
context.Database.SqlQuery<myEntityType>(
"mySpName @param1, @param2, @param3",
new SqlParameter("param1", param1),
new SqlParameter("param2", param2),
new SqlParameter("param3", param3)
);
Since 2011a, the recommended way is:
booleanIndex = strcmp('KU', strs)
If you want to get the integer index (which you often don't need), you can use:
integerIndex = find(booleanIndex);
strfind
is deprecated, so try not to use it.
I think i understand your problem, because i have a similar.
So the tag <label>
have the atribute for, you can use this atribute to link your input with type="file".
But if you don't want to activate this using this label because some rule of your layout, you can do like this.
$(document).ready(function(){_x000D_
var reference = $(document).find("#main");_x000D_
reference.find(".js-btn-upload").attr({_x000D_
formenctype: 'multipart/form-data'_x000D_
});_x000D_
_x000D_
reference.find(".js-btn-upload").click(function(){_x000D_
reference.find("label").trigger("click");_x000D_
});_x000D_
_x000D_
});
_x000D_
.hide{_x000D_
overflow: hidden;_x000D_
visibility: hidden;_x000D_
/*Style for hide the elements, don't put the element "out" of the screen*/_x000D_
}_x000D_
_x000D_
.btn{_x000D_
/*button style*/_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<div id="main">_x000D_
<form enctype"multipart/formdata" id="form-id" class="hide" method="post" action="your-action">_x000D_
<label for="input-id" class="hide"></label>_x000D_
<input type="file" id="input-id" class="hide"/>_x000D_
</form>_x000D_
_x000D_
<button class="btn js-btn-upload">click me</button>_x000D_
</div>
_x000D_
Of course you will adapt this for your own purpose and layout, but that's the more easily way i know to make it work!!
Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for/path/to/repo.git
andfoo
forhost.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
The simplest way is with the pkill
command.
In your case:
pkill -9 -t pts/6
pkill -9 -t pts/9
pkill -9 -t pts/10
Regarding tty sessions, the commands below are always useful:
w
- shows active terminal sessions
tty
- shows your current terminal session (so you won't close it by accident)
last | grep logged
- shows currently logged users
Sometimes we want to close all sessions of an idle user (ie. when connections are lost abruptly).
pkill -u username
- kills all sessions of 'username' user.
And sometimes when we want to kill all our own sessions except the current one, so I made a script for it. There are some cosmetics and some interactivity (to avoid accidental running on the script).
#!/bin/bash
MYUSER=`whoami`
MYSESSION=`tty | cut -d"/" -f3-`
OTHERSESSIONS=`w $MYUSER | grep "^$MYUSER" | grep -v "$MYSESSION" | cut -d" " -f2`
printf "\e[33mCurrent session\e[0m: $MYUSER[$MYSESSION]\n"
if [[ ! -z $OTHERSESSIONS ]]; then
printf "\e[33mOther sessions:\e[0m\n"
w $MYUSER | egrep "LOGIN@|^$MYUSER" | grep -v "$MYSESSION" | column -t
echo ----------
read -p "Do you want to force close all your other sessions? [Y]Yes/[N]No: " answer
answer=`echo $answer | tr A-Z a-z`
confirm=("y" "yes")
if [[ "${confirm[@]}" =~ "$answer" ]]; then
for SESSION in $OTHERSESSIONS
do
pkill -9 -t $SESSION
echo Session $SESSION closed.
done
fi
else
echo "There are no other sessions for the user '$MYUSER'".
fi
It seems all you can't get is to show the error at the end of editText. Set your editText width to match that of the parent layout enveloping. Will work just fine.
check for any process running on the same port by entering the command:
sudo ps -ef
You can find the process running on the respective node port, then kill the node by
kill -9 <node id>
If the problem still remains then just kill all the node
killall node
Not a barplot
solution but using lattice
and barchart
:
library(lattice)
barchart(Species~Reason,data=Reasonstats,groups=Catergory,
scales=list(x=list(rot=90,cex=0.8)))
You can not use DATEDIFF
but you can use this (if columns are not date type):
SELECT
to_date('2008-08-05','YYYY-MM-DD')-to_date('2008-06-05','YYYY-MM-DD')
AS DiffDate from dual
with open('test.txt', 'r') as inf, open('test1.txt', 'w') as outf:
for line in inf:
line = line.strip()
if line:
try:
outf.write(str(int(line, 16)))
outf.write('\n')
except ValueError:
print("Could not parse '{0}'".format(line))
declare @sexo as char(1)
select @sexo='F'
select * from pessoa
where isnull(Sexo,0) =isnull(@Sexo,0)
If you're not completely attached to using "from" and "to" as your option names, it's fairly easy to implement this using getopts:
while getopts f:t: opts; do
case ${opts} in
f) FROM_VAL=${OPTARG} ;;
t) TO_VAL=${OPTARG} ;;
esac
done
getopts
is a program that processes command line arguments and conveniently parses them for you.
f:t:
specifies that you're expecting 2 parameters that contain values (indicated by the colon). Something like f:t:v
says that -v
will only be interpreted as a flag.
opts
is where the current parameter is stored. The case
statement is where you will process this.
${OPTARG}
contains the value following the parameter. ${FROM_VAL}
for example will get the value /home/kristoffer/test.png
if you ran your script like:
ocrscript.sh -f /home/kristoffer/test.png -t /home/kristoffer/test.txt
As the others are suggesting, if this is your first time writing bash scripts you should really read up on some basics. This was just a quick tutorial on how getopts
works.
In my case, I was missing a "name" attribute on my input element.
let arr=[1,2,3,3,4,5,5,6,7,7]
let obj={}
for(var i=0;i<arr.length;i++){
obj[arr[i]]=obj[arr[i]]!=null ?obj[arr[i]]+1:1 //stores duplicate in an obj
}
console.log(obj)
//returns object {1:1,:1,3:2,.....}
To add to the above, if you want to search within the selected folder, right click on the folder and click "Find in Folder" or default key binding:
Alt+Shift+F
As already mentioned, to search all folders in your project, click Edit > "Find in Files" or:
Ctrl+Shift+F
When I try:
<input type="button" id="moreFields" onclick="alert('The text will be show!!'); return false;" value="Give me more fields!" />
It's worked well. So I think the problem is position of moreFields() function. Ensure that function will be define before your input tag.
Pls try:
<script type="text/javascript">
function moreFields() {
alert("The text will be show");
}
</script>
<input type="button" id="moreFields" onclick="moreFields()" value="Give me more fields!" />
Hope it helped.
We can also focus webelement using below code:
public focusElement(WebElement element){
String javaScript = "var evObj = document.createEvent('MouseEvents');"
+ "evObj.initMouseEvent(\"mouseover\",true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);"
+ "arguments[0].dispatchEvent(evObj);";
((JavascriptExecutor) getDriver()).executeScript(javaScript, element);
}
Hope it helps :)
Here is the way works for me.
mysql> show databases ;
ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
mysql> uninstall plugin validate_password;
ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
mysql> alter user 'root'@'localhost' identified by 'root';
Query OK, 0 rows affected (0.01 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.03 sec)
On UNIX / Linux / Mac OS X you can copy and override files, can't you? So how about this solution:
cp /dev/null /var/mail/root
In my case solution was on iframe class adding:
display: block;
margin-right: auto;
margin-left: auto;
add following property in your hibernate.cfg.xml file
<property name="hibernate.hbm2ddl.auto">update</property>
BTW, in your Entity class, you must define your @Id filed like this:
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "id")
private long id;
if you use the following definition, it maybe not work:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
long dateTime = DateTime.Now.Ticks;
Console.WriteLine(dateTime);
Console.WriteLine(new DateTime(dateTime));
Console.ReadKey();
Considering you want to check for ASCII Alphanumeric characters, Try this:
"^[a-zA-Z0-9]*$"
. Use this RegEx in String.matches(Regex)
, it will return true if the string is alphanumeric, else it will return false.
public boolean isAlphaNumeric(String s){
String pattern= "^[a-zA-Z0-9]*$";
return s.matches(pattern);
}
If it will help, read this for more details about regex: http://www.vogella.com/articles/JavaRegularExpressions/article.html
You can also use Rest Assured library. For a demo with sample script, refer to http://artoftesting.com/automationTesting/restAPIAutomationGetRequest.html
Another portable POSIX
compliant way to do in bash
, which can be defined as a function in .bashrc
for all the arithmetic operators of convenience.
addNumbers () {
local IFS='+'
printf "%s\n" "$(( $* ))"
}
and just call it in command-line as,
addNumbers 1 2 3 4 5 100
115
The idea is to use the Input-Field-Separator(IFS), a special variable in bash
used for word splitting after expansion and to split lines into words. The function changes the value locally to use word-splitting character as the sum operator +
.
Remember the IFS
is changed locally and does NOT take effect on the default IFS
behaviour outside the function scope. An excerpt from the man bash
page,
The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly , the default, then sequences of , , and at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words.
The "$(( $* ))"
represents the list of arguments passed to be split by +
and later the sum value is output using the printf
function. The function can be extended to add scope for other arithmetic operations also.
The Use of Razor code @Html.Hidden or @Html.HiddenFor is similar to the following Html code
<input type="hidden"/>
And also refer the following link
Simply,
SELECT TIME(column_name), DATE(column_name)
You can't do that. It's not possible to resize an array. You have to create a new array and copy the data to it:
bArray = addByteToArray(bArray, newByte);
code:
public byte[] addByteToArray(byte[] bArray, byte newByte)
{
byte[] newArray = new byte[bArray.Length + 1];
bArray.CopyTo(newArray, 1);
newArray[0] = newByte;
return newArray;
}
The size of the pointer may be something different than that of int
. Also an implementation could produce better than simple hex value representation of the address when you use %p
.
In real life where you encounter systems already written and adding indexes to tables then drastically slows down the data loading of a 14gig data table, you are sometime forced to used WITH NOLOCK on your reports and end of month proessing so that the aggregate funtions (sum, count etc) do not do row, page, table locking and deteriate the overall performance. Easy to say in a new system never use WITH NOLOCK and use indexes - but adding indexes severly downgrades data loading, and when I'm then told, well, alter the code base to delete indexes, then bulk load then recreate the indexes - which is all well and good, if you are developing a new system. But Not when you have a system already in place.
The problem is you either haven't closed your if
or you need an elseif
:
create procedure checando(
in nombrecillo varchar(30),
in contrilla varchar(30),
out resultado int)
begin
if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
set resultado = 0;
elseif exists (select * from compas where nombre = nombrecillo) then
set resultado = -1;
else
set resultado = -2;
end if;
end;
We need to detect whether ellipsis is really applied, then to show a tooltip to reveal full text. It is not enough by only comparing "this.offsetWidth < this.scrollWidth
" when the element nearly holding its content but only lacking one or two more pixels in width, especially for the text of full-width Chinese/Japanese/Korean characters.
Here is an example: http://jsfiddle.net/28r5D/5/
I found a way to improve ellipsis detection:
this.offsetWidth < this.scrollWidth
" first, continue step #2 if failed.Here is my improvement: http://jsfiddle.net/28r5D/6/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Library
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "INSERT INTO [Table] (BookName , AuthorName , Category) VALUES('" + textBox1.Text.ToString() + "' , '" + textBox2.Text.ToString() + "' , '" + textBox3.Text.ToString() + "')";
SqlCommand com = new SqlCommand(query, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
MessageBox.Show("Entry Added");
}
private void button3_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "' OR AuthorName='" + textBox2.Text.ToString() + "'";
string query1 = "SELECT BookStatus FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
string query2 = "SELECT DateOfReturn FROM [Table] where BookName='" + textBox1.Text.ToString() + "'";
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr, dr1,dr2;
con.Open();
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
dr1 = com1.ExecuteReader();
dr1.Read();
string i = dr1["BookStatus"].ToString();
if (i =="1" )
{
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
dr2 = com2.ExecuteReader();
dr2.Read();
MessageBox.Show("This book is already issued\n " + "Book will be available by "+ dr2["DateOfReturn"] );
}
else
{
con.Close();
con.Open();
dr = com.ExecuteReader();
dr.Read();
MessageBox.Show("BookFound\n" + "BookName=" + dr["BookName"] + "\n AuthorName=" + dr["AuthorName"]);
}
con.Close();
}
else
{
MessageBox.Show("This Book is not available in the library");
}
}
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query = "SELECT * FROM [TABLE] WHERE BookName='" + textBox1.Text.ToString() + "'";
string dateofissue1 = DateTime.Today.ToString("dd-MM-yyyy");
string dateofreturn = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
string query1 = "update [Table] set BookStatus=1,DateofIssue='"+ dateofissue1 +"',DateOfReturn='"+ dateofreturn +"' where BookName='" + textBox1.Text.ToString() + "'";
con.Open();
SqlCommand com = new SqlCommand(query, con);
SqlDataReader dr;
com.ExecuteNonQuery();
dr = com.ExecuteReader();
if (dr.Read())
{
con.Close();
con.Open();
string dateofissue = DateTime.Today.ToString("dd-MM-yyyy");
textBox4.Text = dateofissue;
textBox5.Text = DateTime.Today.AddDays(15).ToString("dd-MM-yyyy");
SqlCommand com1 = new SqlCommand(query1, con);
com1.ExecuteNonQuery();
MessageBox.Show("Book Isuued");
}
else
{
MessageBox.Show("Book Not Found");
}
con.Close();
}
private void button4_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\NIKHIL R\Documents\Library.mdf;Integrated Security=True;Connect Timeout=30");
string query1 = "update [Table] set BookStatus=0 WHERE BookName='"+textBox1.Text.ToString()+"'";
con.Open();
SqlCommand com = new SqlCommand(query1, con);
com.ExecuteNonQuery();
string today = DateTime.Today.ToString("dd-MM-yyyy");
DateTime today1 = DateTime.Parse(today);
string query = "SELECT dateofReturn from [Table] where BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlDataReader dr;
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
dr = cmd.ExecuteReader();
dr.Read();
string DOR = dr["DateOfReturn"].ToString();
DateTime dor = DateTime.Parse(DOR);
TimeSpan ts = today1.Subtract(dor);
string query2 = "update [Table] set DateOfIssue=NULL, DateOfReturn=NULL WHERE BookName='" + textBox1.Text.ToString() + "'";
con.Close();
con.Open();
SqlCommand com2 = new SqlCommand(query2, con);
com2.ExecuteNonQuery();
int x = int.Parse(ts.Days.ToString());
if (x > 0)
{
int fine = x * 5;
textBox6.Text = fine.ToString();
MessageBox.Show("Book Received\nFine=" + fine);
}
else
{
textBox6.Text = "0";
MessageBox.Show("Book Received\nFine=0");
}
con.Close();
}
}
}
gcc -I/path -L/path
-I /path
path to include, gcc will find .h files in this path
-L /path
contains library files, .a
, .s
o
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
All aforementioned suggestions use %s
placeholder for subject. I'll recommend to use %B
because %s
formatting preserves new lines and multiple lines commit message appears squashed.
git log --pretty=format:"%h%x09%an%x09%ai%x09%B"
Check whether you are actually under a github repo.
So, listing of .git/ should give you results..otherwise you may be some level outside your repo.
Now, cd to your repo and you are good to go.
Three libraries for accessing and manipulating dates and times, namely datetime, arrow and pendulum, all make these items available in namedtuples whose elements are accessible either by name or index. Moreover, the items are accessible in precisely the same way. (I suppose if I were more intelligent I wouldn't be surprised.)
>>> YEARS, MONTHS, DAYS, HOURS, MINUTES = range(5)
>>> import datetime
>>> import arrow
>>> import pendulum
>>> [datetime.datetime.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [arrow.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 15]
>>> [pendulum.now().timetuple()[i] for i in [YEARS, MONTHS, DAYS, HOURS, MINUTES]]
[2017, 6, 16, 19, 16]
If you have array like:
$runners = ["1","2","3","4"];
And if you want to covert them into integers and keep within array, following should do the job:
$newArray = array_map( create_function('$value', 'return (int)$value;'),
$runners);
Best option to do this according to WP Codex is as follow.
Use the global variable $post:
<?php
global $post;
$post_slug = $post->post_name;
?>
It's not possible to run a java class from a WAR file. WAR files have a different structure to Jar files.
To find the related java classes, export (preferred way to use ant) them as Jar put it in your web app lib.
Then you can use the jar file as normal to run java program. The same jar was also referred in web app (if you put this jar in web app lib)
With the use of concat:
In [128]: df
Out[128]:
col_1 col_2
0 0 4
1 1 5
2 2 6
3 3 7
In [129]: pd.concat([df, pd.DataFrame(columns = [ 'column_new_1', 'column_new_2','column_new_3'])])
Out[129]:
col_1 col_2 column_new_1 column_new_2 column_new_3
0 0.0 4.0 NaN NaN NaN
1 1.0 5.0 NaN NaN NaN
2 2.0 6.0 NaN NaN NaN
3 3.0 7.0 NaN NaN NaN
Not very sure of what you wanted to do with [np.nan, 'dogs',3]
. Maybe now set them as default values?
In [142]: df1 = pd.concat([df, pd.DataFrame(columns = [ 'column_new_1', 'column_new_2','column_new_3'])])
In [143]: df1[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs', 3]
In [144]: df1
Out[144]:
col_1 col_2 column_new_1 column_new_2 column_new_3
0 0.0 4.0 NaN dogs 3
1 1.0 5.0 NaN dogs 3
2 2.0 6.0 NaN dogs 3
3 3.0 7.0 NaN dogs 3
scut, a cut-like utility (smarter but slower I made) that can use any perl regex as a breaking token. Breaking on whitespace is the default, but you can also break on multi-char regexes, alternative regexes, etc.
scut -f='6 2 8 7' < input.file > output.file
so the above command would break columns on whitespace and extract the (0-based) cols 6 2 8 7 in that order.
You could use this PHP, hope it helps.
<?php if(basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>
So a list would be like the below.
<ul>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="home"><i class="fa fa-dashboard"></i> <span>Home</span></a></li>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'listings' ) { ?> class="active" <?php } else { ?> <?php }?>><a href="other"><i class="fa fa-th-list"></i> <span>Other</span></a></li>
</ul>
Try using OPENDATASOURCE The syntax is like this:
select * from OPENDATASOURCE ('SQLNCLI', 'Data Source=192.168.6.69;Initial Catalog=AnotherDatabase;Persist Security Info=True;User ID=sa;Password=AnotherDBPassword;MultipleActiveResultSets=true;' ).HumanResources.Department.MyTable
If you are using PHP's password_hash()
with the PASSWORD_DEFAULT
algorithm to generate the bcrypt hash (which I would assume is a large percentage of people reading this question) be sure to keep in mind that in the future password_hash()
might use a different algorithm as the default and this could therefore affect the length of the hash (but it may not necessarily be longer).
From the manual page:
Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).
Using bcrypt, even if you have 1 billion users (i.e. you're currently competing with facebook) to store 255 byte password hashes it would only ~255 GB of data - about the size of a smallish SSD hard drive. It is extremely unlikely that storing the password hash is going to be the bottleneck in your application. However in the off chance that storage space really is an issue for some reason, you can use PASSWORD_BCRYPT
to force password_hash()
to use bcrypt, even if that's not the default. Just be sure to stay informed about any vulnerabilities found in bcrypt and review the release notes every time a new PHP version is released. If the default algorithm is ever changed it would be good to review why and make an informed decision whether to use the new algorithm or not.
None of the above worked for me. What I had to do was: In SQL Server Management Studio on the login screen, select Options >> In the Network section change the Network protocol to Named Pipes.
Also, what I had to do to make it work with the <default>
setting was to disable the wireless network (the machine was also connected to the wired lan).
Unless you can get PHP to label that element with a class you are better to use jQuery.
jQuery(document).ready(function () {
$count = jQuery("ul li").size() - 1;
alert($count);
jQuery("ul li:nth-child("+$count+")").css("color","red");
});
Note: This solution only works for Webkit browsers, which incorrectly apply pseudo-elements to self-closing tags.
As an addendum to above answers it is worth noting that in some cases one needs to insert a space instead of merely ignoring <br>
:
For instance the above answers will turn
Monday<br>05 August
to
Monday05 August
as I had verified while I tried to format my weekly event calendar. A space after "Monday" is preferred to be inserted. This can be done easily by inserting the following in the CSS:
br {
content: ' '
}
br:after {
content: ' '
}
This will make
Monday<br>05 August
look like
Monday 05 August
You can change the content
attribute in br:after
to ', '
if you want to separate by commas, or put anything you want within ' '
to make it the delimiter! By the way
Monday, 05 August
looks neat ;-)
See here for a reference.
As in the above answers, if you want to make it tag-specific, you can. As in if you want this property to work for tag <h3>
, just add a h3
each before br
and br:after
, for instance.
It works most generally for a pseudo-tag.
I know that you're currently using jQuery, but what if you defined the onclick handler inline. Then you could do:
<a href='/link/for/non-js-users.htm' onclick='loadContent(5);return false;'>
Article 5</a>
I was not able to resolve this error by either refresh or by turning on "native polling" workspace feature. Turned out my project was also opened in two instances of eclipse. Once I closed the other instance, the error went away. So make sure your project is only opened at one place if you are seeing this error.
All above solutions make table header scroll too... If you want to scroll tbody only then apply this:
tbody {
height: 100px !important;
overflow: scroll;
display:block;
}
compareTo()
is from the Comparable
interface.
compare()
is from the Comparator
interface.
Both methods do the same thing, but each interface is used in a slightly different context.
The Comparable interface is used to impose a natural ordering on the objects of the implementing class. The compareTo()
method is called the natural comparison method. The Comparator interface is used to impose a total ordering on the objects of the implementing class. For more information, see the links for exactly when to use each interface.
Here's a method using display:flex
:
.container {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
display: flex;_x000D_
position: fixed;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>centered text!</div>_x000D_
</div>
_x000D_
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
You can get numpy version using Terminal or a Python code.
In a Terminal (bash) using Ubuntu:
pip list | grep numpy
In python 3.6.7, this code shows the numpy version:
import numpy
print (numpy.version.version)
If you insert this code in the file shownumpy.py, you can compile it:
python shownumpy.py
or
python3 shownumpy.py
I've got this output:
1.16.1
Laravel 5.7 introduced the following functionality:
Auth::routes(['register' => false]);
The currently possible options here are:
Auth::routes([
'register' => false, // Registration Routes...
'reset' => false, // Password Reset Routes...
'verify' => false, // Email Verification Routes...
]);
For older Laravel versions just override showRegistrationForm()
and register()
methods in
AuthController
for Laravel 5.0 - 5.4Auth/RegisterController.php
for Laravel 5.5public function showRegistrationForm()
{
return redirect('login');
}
public function register()
{
}
The problem by using stream().forEach(..)
with a call to add
or put
inside the forEach
(so you mutate the external myMap
or myList
instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.
One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.
Map<Boolean, List<Map.Entry<K, V>>> partitions =
animalMap.entrySet()
.stream()
.collect(partitioningBy(e -> e.getValue() == null));
Map<K, V> myMap =
partitions.get(false)
.stream()
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
List<K> myList =
partitions.get(true)
.stream()
.map(Map.Entry::getKey)
.collect(toList());
... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2>
class exists, you can create your own), e.g:
public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
return Collector.of(
() -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
(pair, entry) -> {
if(entry.getValue() == null) {
pair._2.add(entry.getKey());
} else {
pair._1.put(entry.getKey(), entry.getValue());
}
},
(p1, p2) -> {
p1._1.putAll(p2._1);
p1._2.addAll(p2._2);
return p1;
});
}
with its usage:
Tuple2<Map<K, V>, List<K>> pair =
animalMap.entrySet().parallelStream().collect(customCollector());
You can tune it more if you want, for example by providing a predicate as parameter.
$('input[type=file]').change(function(e){
$(this).parents('.parent-selector').find('.element-to-paste-filename').text(e.target.files[0].name);
});
This code will not show C:\fakepath\
before file name in Google Chrome in case of using .val()
.
To just get a list of the commit hashes use git rev-list
git rev-list HEAD <filename>
Output:
b7c4f0d7ebc3e4c61155c76b5ebc940e697600b1
e3920ac6c08a4502d1c27cea157750bd978b6443
ea62422870ea51ef21d1629420c6441927b0d3ea
4b1eb462b74c309053909ab83451e42a7239c0db
4df2b0b581e55f3d41381f035c0c2c9bd31ee98d
which means 5 commits have touched this file. It's reverse chronological order, so the first commit in the list b7c4f0d7
is the most recent one.
I never really did get to the bottom of what was causing it for me. I think somewhere I must have been missing some files. I got the error after publishing to a new server. Eventually I copied the site from working site. Then the site worked and so did further publishes to the new server.
You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.
For example, add an empty file called .gitkeep
to the folder you want to keep, then in your .gitignore
file write:
# exclude everything
somefolder/*
# exception to the rule
!somefolder/.gitkeep
Commit your .gitignore
and .gitkeep
files and this should resolve your issue.
blazeroni already made it pretty clear, I just want to add few points.
<merge>
is used for optimizing layouts.It is used for reducing unnecessary nesting. <merge>
tag is added into another layout,the <merge>
node is removed and its child view is added directly to the new parent.Xcode provides CFNetwork Diagnostic Logging. Apple doc
To enable it, add CFNETWORK_DIAGNOSTICS=3
in the Environment Variable section:
This will show requests from the App with its headers & body. Note that OS_ACTIVITY_MODE
must be set to enable
as shown. Otherwise no output will be shown on the Console.
You could just pass a static value (or a variable from *ngFor
or whatever)
<button (click)="toggle(1)" class="someclass">
<button (click)="toggle(2)" class="someclass">
git stash pop
will get everything back in place
as suggested in the comments, you can use git stash branch newbranch
to apply the stash to a new branch, which is the same as running:
git checkout -b newbranch
git stash pop
I created a folder named a in /home/prasanth and copied your code to a file named A.java. I compiled from /home/prasanth as javac a/A.java
and run javac a.A
. I got output as
a!
How to sum array of object using Javascript
const traveler = [
{ description: 'Senior', Amount: 50},
{ description: 'Senior', Amount: 50},
{ description: 'Adult', Amount: 75},
{ description: 'Child', Amount: 35},
{ description: 'Infant', Amount: 25 }
];
const traveler = [_x000D_
{ description: 'Senior', Amount: 50},_x000D_
{ description: 'Senior', Amount: 50},_x000D_
{ description: 'Adult', Amount: 75},_x000D_
{ description: 'Child', Amount: 35},_x000D_
{ description: 'Infant', Amount: 25 },_x000D_
];_x000D_
function sum(arrayData, key){_x000D_
return arrayData.reduce((a,b) => {_x000D_
return {Amount : a.Amount + b.Amount}_x000D_
})_x000D_
}_x000D_
console.log(sum(traveler))
_x000D_
it worked for me using this line of code:
<a id="LinkTest" title="Any Title" href="#" onclick="Function(); return false; ">text</a>
When your certificate expires, it simply disappears from the ‘Certificates, Identifier & Profiles’ section of Member Center. There is no ‘Renew’ button that allows you to renew your certificate. You can revoke a certificate and generate a new one before it expires. Or you can wait for it to expire and disappear, then generate a new certificate. In Apple's App Distribution Guide:
Replacing Expired Certificates
When your development or distribution certificate expires, remove it and request a new certificate in Xcode.
When your certificate expires or is revoked, any provisioning profile that made use of the expired/revoked certificate will be reflected as ‘Invalid’. You cannot build and sign any app using these invalid provisioning profiles. As you can imagine, I'd rather revoke and regenerate a certificate before it expires.
Q: If I do that then will all my live apps be taken down?
Apps that are already on the App Store continue to function fine. Again, in Apple's App Distribution Guide:
Important: Re-creating your development or distribution certificates doesn’t affect apps that you’ve submitted to the store nor does it affect your ability to update them.
So…
Q: How to I properly renew it?
As mentioned above, there is no renewing of certificates. Follow the steps below to revoke and regenerate a new certificate, along with the affected provisioning profiles. The instructions have been updated for Xcode 8.3 and Xcode 9.
Login to Member Center > Certificates, Identifiers & Profiles, select the expiring certificate. Take note of the expiry date of the certificate, and click the ‘Revoke’ button.
Optionally, if you don't want to have the revoked certificate lying around in your system, you can delete them from your system. Unfortunately, the ‘Delete Certificate’ function in Xcode > Preferences > Accounts > [Apple ID] > Manage Certificates… seems to be always disabled, so we have to delete them manually using Keychain Access.app (/Applications/Utilities/Keychain Access.app).
Filter by ‘login’ Keychains and ‘Certificates’ Category. Locate the certificate that you've just revoked in Step 1.
Depending on the certificate that you've just revoked, search for either ‘Mac’ or ‘iPhone’. Mac App Store distribution certificates begin with “3rd Party Mac Developer”, and iOS App Store distribution certificates begin with “iPhone Distribution”.
You can locate the revoked certificate based on the team name, the type of certificate (Mac or iOS) and the expiry date of the certificate you've noted down in Step 1.
Under Xcode > Preferences > Accounts > [Apple ID] > Manage Certificates…, click on the ‘+’ button on the lower left, and select the same type of certificate that you've just revoked to let Xcode request a new one for you.
After which, head back to Member Center > Certificates, Identifiers & Profiles > Provisioning Profiles > All. You'll notice that any provisioning profile that made use of the revoked certificate is now reflected as ‘Invalid’.
Click on any profile that are now ‘Invalid’, click ‘Edit’, then choose the newly created certificate, then click on ‘Generate’. Repeat this until all provisioning profiles are regenerated with the new certificate.
Tip: Before you download the new profiles using Xcode, you may want to clear any existing and possibly invalid provisioning profiles from your Mac. You can do so by removing all the profiles from ~/Library/MobileDevice/Provisioning Profiles
Back in Xcode > Preferences > Accounts > [Apple ID], click on the ‘Download All Profiles’ button to ask Xcode to download all the provisioning profiles from your developer account.
In vi, J
(that's Shift + J) or :join
should do what you want, for the most part. Note that they adjust whitespace. In particular, you'll end up with a space between the two joined lines in many cases, and if the second line is indented that indentation will be removed prior to joining.
In Vim you can also use gJ
(G, then Shift + J) or :join!
. These will join lines without doing any whitespace adjustments.
In Vim, see :help J
for more information.
This problem usually happen if eclipse accidentally compile the main.xml incorrectly. The easiest solution is to delete R.java inside gen directory. Once we delete, than eclipse will generate the new R.java base on the latest main.xml
SELECT CAST(FLOOR(CAST(GETDATE() AS float)) as datetime)
or
SELECT CONVERT(datetime,FLOOR(CONVERT(float,GETDATE())))
Try this:
tableView.backgroundColor = .black
tableView.reloadData()
DispatchQueue.main.async(execute: {
tableView.backgroundColor = .green
})
The tableView color will changed from black to green only after the reloadData()
function completes.
document.getElementById("placehere").appendChild(elem);
not
document.getElementById("placehere").appendChild("elem");
and use the below to set the source
elem.src = 'images/hydrangeas.jpg';
select OrderId, (
select max([Price]) from (
select NegotiatedPrice [Price]
union all
select SuggestedPrice
) p
) from [Order]
"Z" doesn't stand for "Zulu"
I don't have any more information than the Wikipedia article cited by the two existing answers, but I believe the interpretation that "Z" stands for "Zulu" is incorrect. UTC time is referred to as "Zulu time" because of the use of Z to identify it, not the other way around. The "Z" seems to have been used to mark the time zone as the "zero zone", in which case "Z" unsurprisingly stands for "zero" (assuming the following information from Wikipedia is accurate):
Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications — zones M and Y have the same clock time but differ by 24 hours: a full day). These can be vocalized using the NATO phonetic alphabet which pronounces the letter Z as Zulu, leading to the use of the term "Zulu Time" for Greenwich Mean Time, or UT1 from January 1, 1972 onward.
I lost some days with this problem.... until I found that in some file I was importing one static file, a built file. It make the build to never end. Something like:
import PropTypes from "../static/build/prop-types";
Fixing to the real source solved all the problem.
Sharing my solution. :)
What about the size of the image? If I use the img tag, the browser scales the image. If I use css background, the browser just cuts a chunk from the larger image.
http://en.wikibooks.org/wiki/LaTeX/Formatting
use \alltt
environment instead. Then set size using the same commands as outside verbatim environment.
Create a File
object, passing the directory path to the constructor. Use the listFiles()
to retrieve an array of File
objects for each file in the directory, and then call the getName()
method to get the filename.
List<String> results = new ArrayList<String>();
File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null.
for (File file : files) {
if (file.isFile()) {
results.add(file.getName());
}
}
In react router v4. I follow this two way to route programmatically.
1. this.props.history.push("/something/something")
2. this.props.history.replace("/something/something")
Number two
Replaces the current entry on the history stack
To get history in props you may have to wrap your component with
My tested version
Sub PrintArray(RowPrint, ColPrint, ArrayName, WorkSheetName)
Sheets(WorkSheetName).Range(Cells(RowPrint, ColPrint), _
Cells(RowPrint + UBound(ArrayName, 2) - 1, _
ColPrint + UBound(ArrayName, 1) - 1)) = _
WorksheetFunction.Transpose(ArrayName)
End Sub
CURL OPERATION BETWEEN SERVER TO SERVER WITHOUT HTML FORM IN PHP USING MULTIPART/FORM-DATA
// files to upload
$filename = "https://example.s3.amazonaws.com/0.jpg";
// URL to upload to (Destination server)
$url = "https://otherserver/image";
AND
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
//CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents($filename),
CURLOPT_HTTPHEADER => array(
//"Authorization: Bearer $TOKEN",
"Content-Type: multipart/form-data",
"Content-Length: " . strlen(file_get_contents($filename)),
"API-Key: abcdefghi" //Optional if required
),
));
$response = curl_exec($curl);
$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";
//print_r($info['request_header']);
var_dump($response);
$err = curl_error($curl);
echo "error";
var_dump($err);
curl_close($curl);
Do you perhaps have one too many here?
describe "when name is too long" do
before { @user.name = "a" * 51 }
it { should_not be_valid }
end
end
in my case,
dev@Dev-007:~$ mysql -u root -p
Enter password:
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
I am sure my password was correct otherwise error code would be ERROR 1045 (28000): Access denied for user
so i relogin using sudo,
dev@Dev-007:~$ sudo mysql -u root -p
this time it worked for me . see the docs
and then change root password,
mysql> alter user 'root'@'%' identified with mysql_native_password by 'me123';
Query OK, 0 rows affected (0.14 sec)
mysql>
then restart server using sudo /etc/init.d/mysql restart
After trying the options described here, I found this post from Forester in r-bloggers . I think it is a clean option to consider.
I put his code here:
From command line
$ R CMD BATCH --no-save --no-restore '--args a=1 b=c(2,5,6)' test.R test.out &
Test.R
##First read in the arguments listed at the command line
args=(commandArgs(TRUE))
##args is now a list of character vectors
## First check to see if arguments are passed.
## Then cycle through each element of the list and evaluate the expressions.
if(length(args)==0){
print("No arguments supplied.")
##supply default values
a = 1
b = c(1,1,1)
}else{
for(i in 1:length(args)){
eval(parse(text=args[[i]]))
}
}
print(a*2)
print(b*3)
In test.out
> print(a*2)
[1] 2
> print(b*3)
[1] 6 15 18
Thanks to Forester!
I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project
Made it into a function. You can now call splitCsv <Filename> [chunkSize]
splitCsv() {
HEADER=$(head -1 $1)
if [ -n "$2" ]; then
CHUNK=$2
else
CHUNK=1000
fi
tail -n +2 $1 | split -l $CHUNK - $1_split_
for i in $1_split_*; do
sed -i -e "1i$HEADER" "$i"
done
}
Found on: http://edmondscommerce.github.io/linux/linux-split-file-eg-csv-and-keep-header-row.html
In the most latest android, we implement card view like this:
build.gradle file:
dependencies {
...
compile 'com.android.support:cardview-v7:24.0.0'
}
and in the xml file its referenced as:
<androidx.cardview.widget.CardView
…>
…
</androidx.cardview.widget.CardView>
this means its class has changed to:
androidx.cardview.widget.CardView
I would just use..
try:
float(element)
except ValueError:
print "Not a float"
..it's simple, and it works. Note that it will still throw OverflowError if element is e.g. 1<<1024.
Another option would be a regular expression:
import re
if re.match(r'^-?\d+(?:\.\d+)$', element) is None:
print "Not float"
You'd use REGEXP_REPLACE
in order to remove all non-digit characters from a string:
select regexp_replace(column_name, '[^0-9]', '')
from mytable;
or
select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;
Of course you can write a function extract_number
. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.
create function extract_number(in_number varchar2) return varchar2 is
begin
return regexp_replace(in_number, '[^[:digit:]]', '');
end;
curl -u username:password http://
curl -u username http://
From the documentation page:
-u, --user <user:password>
Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.
If you simply specify the user name, curl will prompt for a password.
The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.
When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.
When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.
To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.
If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.
http://curl.haxx.se/docs/manpage.html#-u
Note that you do not need --basic
flag as it is the default.
That is exactly how you do it in C#, but the feature was first added in .NET 4.0
<!-- Install jQuery and underscore -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<!-- Create your template -->
<script type="foo/bar" id='usageList'>
<table cellspacing='0' cellpadding='0' border='1' >
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<%
// repeat items
_.each(items,function(item,key,list){
// create variables
var f = item.name.split("").shift().toLowerCase();
%>
<tr>
<!-- use variables -->
<td><%= key %></td>
<td class="<%= f %>">
<!-- use %- to inject un-sanitized user input (see 'Demo of XSS hack') -->
<h3><%- item.name %></h3>
<p><%- item.interests %></p>
</td>
</tr>
<%
});
%>
</tbody>
</table>
</script>
<!-- Create your target -->
<div id="target"></div>
<!-- Write some code to fetch the data and apply template -->
<script type="text/javascript">
var items = [
{name:"Alexander", interests:"creating large empires"},
{name:"Edward", interests:"ha.ckers.org <\nBGSOUND SRC=\"javascript:alert('XSS');\">"},
{name:"..."},
{name:"Yolando", interests:"working out"},
{name:"Zachary", interests:"picking flowers for Angela"}
];
var template = $("#usageList").html();
$("#target").html(_.template(template,{items:items}));
</script>
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
To create a composite unique key on table
ALTER TABLE [TableName] ADD UNIQUE ([Column1], [Column2], [column3]);
For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.
However, if you had multiple rules like this:
#foo > ul > li > ul > li > a:nth-child(3n+1) {
color: red;
}
#foo > ul > li > ul > li > a:nth-child(3n+2) {
color: green;
}
#foo > ul > li > ul > li > a:nth-child(3n+3) {
color: blue;
}
You could condense them to one of the following:
/* Sass */
#foo > ul > li > ul > li
> a:nth-child(3n+1)
color: red
> a:nth-child(3n+2)
color: green
> a:nth-child(3n+3)
color: blue
/* SCSS */
#foo > ul > li > ul > li {
> a:nth-child(3n+1) { color: red; }
> a:nth-child(3n+2) { color: green; }
> a:nth-child(3n+3) { color: blue; }
}
These are all a matter of convenience.
Basically, if the question were 'Do we need to use body-parser
?' The answer is 'No'. We can come up with the same information from the client-post-request using a more circuitous route that will generally be less flexible and will increase the amount of code we have to write to get the same information.
This is kind of the same as asking 'Do we need to use express
to begin with?' Again, the answer there is no, and again, really it all comes down to saving us the hassle of writing more code to do the basic things that express comes with 'built-in'.
On the surface - body-parser
makes it easier to get at the information contained in client requests in a variety of formats instead of making you capture the raw data streams and figuring out what format the information is in, much less manually parsing that information into useable data.
Note: if you're just looking for the names of changed files (without the line numbers for lines that were changed), that's easy, click this link to another answer here.
There's no built-in option for this (and I don't think it's all that useful either), but it is possible to do this in git, with the help of an "external diff" script.
Here's a pretty crappy one; it will be up to you to fix up the output the way you would like it.
#! /bin/sh
#
# run this with:
# GIT_EXTERNAL_DIFF=<name of script> git diff ...
#
case $# in
1) "unmerged file $@, can't show you line numbers"; exit 1;;
7) ;;
*) echo "I don't know what to do, help!"; exit 1;;
esac
path=$1
old_file=$2
old_hex=$3
old_mode=$4
new_file=$5
new_hex=$6
new_mode=$7
printf '%s: ' $path
diff $old_file $new_file | grep -v '^[<>-]'
For details on "external diff" see the description of GIT_EXTERNAL_DIFF
in the git manual page (around line 700, pretty close to the end).
Use the SimpleDateFormat
class:
private Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(date);
}
Usage:
Date date = parseDate("19/05/2009", "dd/MM/yyyy");
For efficiency, you would want to store your formatters in a hashmap. The hashmap is a static member of your util class.
private static Map<String, SimpleDateFormat> hashFormatters = new HashMap<String, SimpleDateFormat>();
public static Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = hashFormatters.get(format);
if (formatter == null)
{
formatter = new SimpleDateFormat(format);
hashFormatters.put(format, formatter);
}
return formatter.parse(date);
}
Actually, when we want this, we want to change the action depending on which submit button we press.
Here you do not need even assign name
or id
to the form. Just use the form
property of the clicked element:
<form action = "/default/page" >
<input type=submit onclick='this.form.action="/this/page";' value="Save">
<input type=submit onclick='this.form.action="/that/page";' value="Cancel">
</form>
Nevermind, the answer is raw triple-quoted strings:
r"""what"ever"""
Also WebClient doesn't have timeout property. And that's the problem, because dafault value is 100 seconds and that's too much to indicate if there's no Internet connection.
Workaround for that problem is here https://stackoverflow.com/a/3052637/1303422
match
returns an array.
The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:
var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);
I had a similar issue, because of my replication binary logs.
If this is the case, just create a cronjob to run this query every day:
PURGE BINARY LOGS BEFORE DATE_SUB( NOW(), INTERVAL 2 DAY );
This will remove all binary logs older than 2 days.
I found this solution here.
private Map<Integer, Set<Integer>> nobreaks = new HashMap();
nobreaks.put(1, new HashSet(Arrays.asList(new int[]{2, 4, 5})));
System.out.println("expected size is 3: " +nobreaks.get(1).size());
the output is
expected size is 3: 1
change it to
nobreaks.put(1, new HashSet(Arrays.asList( 2, 4, 5 )));
the output is
expected size is 3: 3
right click on project->properties->android->select target name --set target-- click ok
I surprise no one had mentioned this possible easy approach in visual studio code.
Install VS Code and Apache maven ( just as mentioned by @Steve Chambers)
After installing this extension vscode:extension/vscjava.vscode-java-pack
In the java overview page , there is a an option which reads 'Create Maven Project' which further takes to a simple wizard to generate maven project.
Its pretty quick which is intutitive enough, even newbies can very well start with a Maven project.
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
I can change ActionBar text color by using titleTextColor
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="titleTextColor">#333333</item>
</style>
For a popup javascript is required. Put this in your header:
<script>
function myFunction()
{
alert("I am an alert box!"); // this is the message in ""
}
</script>
And this in your body:
<input type="button" onclick="myFunction()" value="Show alert box">
When the button is pressed a box pops up with the message set in the header.
This can be put in any html or php file without the php tags.
-----EDIT-----
To display it using php try this:
<?php echo '<script>myfunction()</script>'; ?>
It may not be 100% correct but the principle is the same.
To display different messages you can either create lots of functions or you can pass a variable in to the function when you call it.
No, that is not a valid production according to the "credentials" definition in RFC 2617. You give a valid auth-scheme, but auth-param values must be of the form token "=" ( token | quoted-string )
(see section 1.2), and your example doesn't use "=" that way.
Encode the response content with a common enum that allows the client to switch on it and fork logic accordingly. I'm not sure how your client would distinguish the difference between a "data not found" 404 and a "web resource not found" 404? You don;t want someone to browse to userZ/9 and have the client wonder off as if the request was valid but there was no data returned.
I had to go another route for an assignment but this is what I ended up with.
my_array += ([x] * repeated_times)
You can download recent packages manually from these pages:
Then, install it by running dpkg
:
dpkg -i *.deb
Hey guys so i think i found a fix. This is working for me on iphone and android at the moment. Its a mash up of hours upon hours of searching, reading and testing. So if you see parts of your code in here credit goes to you lol.
@media only screen and (max-device-width:768px){
body.modal-open {
// block scroll for mobile;
// causes underlying page to jump to top;
// prevents scrolling on all screens
overflow: hidden;
position: fixed;
}
}
body.viewport-lg {
// block scroll for desktop;
// will not jump to top;
// will not prevent scroll on mobile
position: absolute;
}
body {
overflow-x: hidden;
overflow-y: scroll !important;
}
The reason the media specific is on there is on a desktop i was having issues with when the modal would open all content on the page would shift from centered to left. Looked like crap. So this targets up to tablet size devices where you would need to scroll. There is still a slight shift on mobile and tablet but its really not much. Let me know if this works for you guys. Hopefully this puts the nail in the coffin
When I were trying install librosa
package with pip
(pip install librosa
), this error were appeared:
ERROR: Cannot uninstall 'llvmlite'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.
I tried to remove llvmlite
, but pip uninstall
could not remove it. So, I used capability of ignore
of pip
by this code:
pip install librosa --ignore-installed llvmlite
Indeed, you can use this rule for ignoring a package you don't want to consider:
pip install {package you want to install} --ignore-installed {installed package you don't want to consider}
Google has released a Native Development Kit (NDK) (according to http://www.youtube.com/watch?v=Z5whfaLH1-E at 00:07:30).
Hopefully the information will be updated on the google groups page (http://groups.google.com/group/android-ndk), as it says it hasn't been released yet.
I'm not sure where to get a simple download for it, but I've heard that you can get a copy of the NDK from Google's Git repository under the donut branch.
there is no selector in RecyclerView like ListView and GridView but you try below thing it worked for me
create a selector drawable as below
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="@color/blue" />
</shape>
</item>
<item android:state_pressed="false">
<shape>
<solid android:color="@android:color/transparent" />
</shape>
</item>
</selector>
then set this drawable as background of your RecyclerView row layout as
android:background="@drawable/selector"
ieshims.dll
is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as CreateProcess
) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. wer.dll
is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.
I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway.
ssh-keygen -f private.pem -y > public.pub
when referencing images in CSS or in an IMG tag, use image-name.jpg
while the image is really located under ./assets/images/image-name.jpg
suppose we take a integer in string.
String s="100"; int i=Integer.parseInt(s); or int i=Integer.valueOf(s);
but in your question the number you are trying to do the change is the whole number
String s="10.00";
double d=Double.parseDouble(s);
int i=(int)d;
This way you get the answer of the value which you are trying to get it.
import sys
sys.dont_write_bytecode = True
I believe using --no-index
is what you're looking for:
git diff [<options>] --no-index [--] <path> <path>
as mentioned in the git manual:
This form is to compare the given two paths on the filesystem. You can omit the
--no-index
option when running the command in a working tree controlled by Git and at least one of the paths points outside the working tree, or when running the command outside a working tree controlled by Git.